1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| import cv2 as cv import time import subprocess as sp import multiprocessing import platform import psutil
class stream_pusher(object): def __init__(self, rtmp_url=None, raw_frame_q=None): self.rtmp_url = rtmp_url self.raw_frame_q = raw_frame_q
fps = 20 width = 640 height = 480
self.command = ['ffmpeg', '-y', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-pix_fmt', 'bgr24', '-s', "{}x{}".format(width, height), '-r', str(fps), '-i', '-', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-preset', 'ultrafast', '-f', 'flv', self.rtmp_url]
def __frame_handle__(self, raw_frame, text, shape1, shape2): return (raw_frame)
def push_frame(self): p = psutil.Process() p.cpu_affinity([0, 1, 2, 3]) p = sp.Popen(self.command, stdin=sp.PIPE)
while True: if not self.raw_frame_q.empty(): raw_frame, text, shape1, shape2 = self.raw_frame_q.get() frame = self.__frame_handle__(raw_frame, text, shape1, shape2)
p.stdin.write(frame.tostring()) else: time.sleep(0.01)
def run(self): push_frame_p = multiprocessing.Process(target=self.push_frame, args=()) push_frame_p.daemon = True push_frame_p.start()
if __name__ == '__main__': if platform.system() == 'Linux': cap = cv.VideoCapture(0) cap.set(3, 640) cap.set(4, 480) elif platform.system() == 'Darwin': cap = cv.VideoCapture(0) cap.set(3, 640) cap.set(4, 480) else: exit(0)
rtmpUrl = "rtmp://127.0.0.1:1935/live/live" raw_q = multiprocessing.Queue()
my_pusher = stream_pusher(rtmp_url=rtmpUrl, raw_frame_q=raw_q) my_pusher.run() while True: _, raw_frame = cap.read() info = (raw_frame, '2', '3', '4') if not raw_q.full(): raw_q.put(info) cv.waitKey(1) cap.release() print('finish')
|