WriteGear handles various powerful Video-Writer Tools that provide us the freedom to do almost anything imaginable with multimedia data.
WriteGear API provides a complete, flexible, and robust wrapper around FFmpeg, a leading multimedia framework. WriteGear can process real-time frames into a lossless compressed video-file with any suitable specification (such as bitrate, codec, framerate, resolution, subtitles, etc.). It is powerful enough to perform complex tasks such as Live-Streaming (such as for Twitch) and Multiplexing Video-Audio with real-time frames in way fewer lines of code.
Best of all, WriteGear grants users the complete freedom to play with any FFmpeg parameter with its exclusive Custom Commands function without relying on any third-party API.
In addition to this, WriteGear also provides flexible access to OpenCV's VideoWriter API tools for video-frames encoding without compression.
Modes of Operation
WriteGear primarily operates in following modes:
Compression Mode: In this mode, WriteGear utilizes powerful FFmpeg inbuilt encoders to encode lossless multimedia files. This mode provides us the ability to exploit almost any parameter available within FFmpeg, effortlessly and flexibly, and while doing that it robustly handles all errors/warnings quietly.
Non-Compression Mode: In this mode, WriteGear utilizes basic OpenCV's inbuilt VideoWriter API tools. This mode also supports all parameters manipulation available within VideoWriter API, but it lacks the ability to manipulate encoding parameters and other important features like video compression, audio encoding, etc.
classWriteGear:""" WriteGear handles various powerful Video-Writer Tools that provide us the freedom to do almost anything imaginable with multimedia data. WriteGear API provides a complete, flexible, and robust wrapper around FFmpeg, a leading multimedia framework. WriteGear can process real-time frames into a lossless compressed video-file with any suitable specification (such as bitrate, codec, framerate, resolution, subtitles, etc.). It is powerful enough to perform complex tasks such as Live-Streaming (such as for Twitch) and Multiplexing Video-Audio with real-time frames in way fewer lines of code. Best of all, WriteGear grants users the complete freedom to play with any FFmpeg parameter with its exclusive Custom Commands function without relying on any third-party API. In addition to this, WriteGear also provides flexible access to OpenCV's VideoWriter API tools for video-frames encoding without compression. ??? tip "Modes of Operation" WriteGear primarily operates in following modes: * **Compression Mode**: In this mode, WriteGear utilizes powerful **FFmpeg** inbuilt encoders to encode lossless multimedia files. This mode provides us the ability to exploit almost any parameter available within FFmpeg, effortlessly and flexibly, and while doing that it robustly handles all errors/warnings quietly. * **Non-Compression Mode**: In this mode, WriteGear utilizes basic **OpenCV's inbuilt VideoWriter API** tools. This mode also supports all parameters manipulation available within VideoWriter API, but it lacks the ability to manipulate encoding parameters and other important features like video compression, audio encoding, etc. """def__init__(self,output:str="",compression_mode:bool=True,custom_ffmpeg:str="",logging:bool=False,**output_params:dict):""" This constructor method initializes the object state and attributes of the WriteGear class. Parameters: output (str): sets the valid filename/path/URL for encoding. compression_mode (bool): selects the WriteGear's Primary Mode of Operation. custom_ffmpeg (str): assigns the location of custom path/directory for custom FFmpeg executables. logging (bool): enables/disables logging. output_params (dict): provides the flexibility to control supported internal parameters and FFmpeg properties. """# enable logging if specifiedself.__logging=loggingifisinstance(logging,bool)elseFalse# print current versionlogcurr_vidgear_ver(logging=self.__logging)# check if user not using depreciated `output_filename` parameterassert(not"output_filename"inoutput_params),"[WriteGear:ERROR] :: The `output_filename` parameter has been renamed to `output`. Refer Docs for more info."# assign parameter values to class variables# enables compression if enabledself.__compression=(compression_modeifisinstance(compression_mode,bool)elseFalse)# specifies if machine in-use is running Windows OS or notself.__os_windows=Trueifos.name=="nt"elseFalse# initialize various important class variablesself.__output_parameters={}# handles output parametersself.__inputheight=None# handles input frames heightself.__inputwidth=None# handles input frames widthself.__inputchannels=None# handles input frames channelsself.__inputdtype=None# handles input frames dtypeself.__process=None# handles Encoding class/processself.__ffmpeg=""# handles valid FFmpeg binaries locationself.__initiate_process=(True# handles initiate one-time process for generating pipeline)self.__ffmpeg_window_disabler_patch=(False# handles disabling window for ffmpeg subprocess on Windows)self.__out_file=None# handles outputgstpipeline_mode=False# handles GStreamer Pipeline Mode# handles outputifnotoutput:# raise error otherwiseraiseValueError("[WriteGear:ERROR] :: Kindly provide a valid `output` value. Refer Docs for more info.")else:# validate output is a system file/directory# and Whether WriteGear has the write rights# to specified file/directory or notabs_path=os.path.abspath(output)ifcheck_WriteAccess(os.path.dirname(abs_path),is_windows=self.__os_windows,logging=self.__logging,):# check if given path is directoryifos.path.isdir(abs_path):# then, auto-assign valid name and adds it to pathabs_path=os.path.join(abs_path,"VidGear-{}.mp4".format(time.strftime("%Y%m%d-%H%M%S")),)# assign output file absolute# path to class variable if validself.__out_file=abs_pathelse:# log note otherwiselogger.info("`{}` isn't a valid system path or directory. Skipped!".format(output))# cleans and reformat output parametersself.__output_parameters={str(k).strip():(v.strip()ifisinstance(v,str)elsev)fork,vinoutput_params.items()}# log it if specifiedself.__loggingandlogger.debug("Output Parameters: `{}`".format(self.__output_parameters))# handles FFmpeg binaries validity# in Compression modeifself.__compression:# log it if specifiedself.__loggingandlogger.debug("Compression Mode is enabled therefore checking for valid FFmpeg executable.")# handles where to save the downloaded FFmpeg Static Binaries# on Windows(if specified)__ffmpeg_download_path=self.__output_parameters.pop("-ffmpeg_download_path","")# check if value is validifnotisinstance(__ffmpeg_download_path,(str)):# reset improper values__ffmpeg_download_path=""# handle user-defined output resolution (must be a tuple or list)# in Compression Mode only.self.__output_dimensions=self.__output_parameters.pop("-output_dimensions",None)# check if value is validifnotisinstance(self.__output_dimensions,(list,tuple)):# reset improper valuesself.__output_dimensions=None# handle user defined input framerate of encoding pipeline# in Compression Mode only.self.__inputframerate=self.__output_parameters.pop("-input_framerate",0.0)# check if value is validifnotisinstance(self.__inputframerate,(float,int)):# reset improper valuesself.__inputframerate=0.0else:# must be floatself.__inputframerate=float(self.__inputframerate)# handle user-defined input frames pixel-format in Compression Mode only.self.__inputpixfmt=self.__output_parameters.pop("-input_pixfmt",None)# check if value is validifnotisinstance(self.__inputpixfmt,str):# reset improper valuesself.__inputpixfmt=Noneelse:# must be exactself.__inputpixfmt=self.__inputpixfmt.strip()# handle user-defined FFmpeg command pre-headers(must be a list)# in Compression Mode only.self.__ffmpeg_preheaders=self.__output_parameters.pop("-ffpreheaders",[])# check if value is validifnotisinstance(self.__ffmpeg_preheaders,list):# reset improper valuesself.__ffmpeg_preheaders=[]# handle the special-case of forced-termination (only for Compression mode)disable_force_termination=self.__output_parameters.pop("-disable_force_termination",Falseif("-i"inself.__output_parameters)elseTrue,)# check if value is validifisinstance(disable_force_termination,bool):self.__forced_termination=not(disable_force_termination)else:# handle improper valuesself.__forced_termination=(Trueif("-i"inself.__output_parameters)elseFalse)# handles disabling window for ffmpeg subprocess on Windows OS (only for Compression mode)# this patch prevents ffmpeg creation window from opening when building exe filesffmpeg_window_disabler_patch=self.__output_parameters.pop("-disable_ffmpeg_window",False)# check if value is validifnotself.__os_windowsorlogging:logger.warning("Optional `-disable_ffmpeg_window` flag is only available on Windows OS with `logging=False`. Discarding!")elifisinstance(ffmpeg_window_disabler_patch,bool):self.__ffmpeg_window_disabler_patch=ffmpeg_window_disabler_patchelse:# handle improper valuesself.__ffmpeg_window_disabler_patch=False# validate the FFmpeg path/binaries and returns valid executable FFmpeg# location/path (also auto-downloads static binaries on Windows OS)self.__ffmpeg=get_valid_ffmpeg_path(custom_ffmpeg,self.__os_windows,ffmpeg_download_path=__ffmpeg_download_path,logging=self.__logging,)# check if valid executable FFmpeg location/pathifself.__ffmpeg:# log it if foundself.__loggingandlogger.debug("Found valid FFmpeg executable: `{}`.".format(self.__ffmpeg))else:# otherwise disable Compression Mode# and switch to Non-compression modelogger.warning("Disabling Compression Mode since no valid FFmpeg executable found on this machine!")ifself.__loggingandnotself.__os_windows:logger.debug("Kindly install a working FFmpeg module or provide a valid custom FFmpeg binary path. See docs for more info.")# compression mode disabledself.__compression=Falseelse:# handle GStreamer Pipeline Mode (only for Non-compression mode)if"-gst_pipeline_mode"inself.__output_parameters:# check if value is validifisinstance(self.__output_parameters["-gst_pipeline_mode"],bool):gstpipeline_mode=self.__output_parameters["-gst_pipeline_mode"]andcheck_gstreamer_support(logging=logging)self.__loggingandlogger.debug("GStreamer Pipeline Mode successfully activated!")else:# reset improper valuesgstpipeline_mode=False# log itself.__loggingandlogger.warning("GStreamer Pipeline Mode failed to activate!")# handle output differently in Compression/Non-compression Modesifself.__compressionandself.__ffmpeg:# check if output falls in exclusive casesifself.__out_fileisNone:if(platform.system()=="Linux"andpathlib.Path(output).is_char_device()):# check whether output is a Linux video device path (such as `/dev/video0`)self.__loggingandlogger.debug("Path:`{}` is a valid Linux Video Device path.".format(output))self.__out_file=outputelifis_valid_url(self.__ffmpeg,url=output,logging=self.__logging):# check whether output is a valid URL insteadself.__loggingandlogger.debug("URL:`{}` is valid and successfully configured for streaming.".format(output))self.__out_file=outputelse:# raise error otherwiseraiseValueError("[WriteGear:ERROR] :: output value:`{}` is not supported in Compression Mode.".format(output))# log if forced termination is enabledself.__forced_terminationandlogger.debug("Forced termination is enabled for this FFmpeg process.")# log Compression is enabledself.__loggingandlogger.debug("Compression Mode with FFmpeg backend is configured properly.")else:# raise error if not valid inputifself.__out_fileisNoneandnotgstpipeline_mode:raiseValueError("[WriteGear:ERROR] :: output value:`{}` is not supported in Non-Compression Mode.".format(output))# check if GStreamer Pipeline Mode is enabledifgstpipeline_mode:# enforce GStreamer backendself.__output_parameters["-backend"]="CAP_GSTREAMER"# enforce original output valueself.__out_file=output# log itself.__loggingandlogger.debug("Non-Compression Mode is successfully configured in GStreamer Pipeline Mode.")# log if Compression is disabledlogger.critical("Compression Mode is disabled, Activating OpenCV built-in Writer!")defwrite(self,frame:NDArray,rgb_mode:bool=False)->None:""" Pipelines `ndarray` frames to respective API _(**FFmpeg** in Compression Mode & **OpenCV's VideoWriter API** in Non-Compression Mode)_. Parameters: frame (ndarray): a valid numpy frame rgb_mode (boolean): enable this flag to activate RGB mode _(i.e. specifies that incoming frames are of RGB format(instead of default BGR)_. """ifframeisNone:# None-Type frames will be skippedreturn# get height, width, number of channels, and dtype of current frameheight,width=frame.shape[:2]channels=frame.shape[-1]ifframe.ndim==3else1dtype=frame.dtype# assign values to class variables on first runifself.__initiate_process:self.__inputheight=heightself.__inputwidth=widthself.__inputchannels=channelsself.__inputdtype=dtypeself.__loggingandlogger.debug("InputFrame => Height:{} Width:{} Channels:{} Datatype:{}".format(self.__inputheight,self.__inputwidth,self.__inputchannels,self.__inputdtype,))# validate frame sizeifheight!=self.__inputheightorwidth!=self.__inputwidth:raiseValueError("[WriteGear:ERROR] :: All video-frames must have same size!")# validate number of channels in frameifchannels!=self.__inputchannels:raiseValueError("[WriteGear:ERROR] :: All video-frames must have same number of channels!")# validate frame datatypeifdtype!=self.__inputdtype:raiseValueError("[WriteGear:ERROR] :: All video-frames must have same datatype!")# checks if compression mode is enabledifself.__compression:# initiate FFmpeg process on first runifself.__initiate_process:# start pre-processing of FFmpeg parameters, and initiate processself.__PreprocessFFParams(channels,dtype=dtype,rgb=rgb_mode)# Check status of the processassertself.__processisnotNonetry:# try writing the frame bytes to the subprocess pipelineself.__process.stdin.write(frame.tobytes())except(OSError,IOError):# log if something is wrong!logger.error("BrokenPipeError caught, Wrong values passed to FFmpeg Pipe. Kindly Refer Docs!")raiseValueError# for testing purpose onlyelse:# otherwise initiate OpenCV's VideoWriter Class processifself.__initiate_process:# start VideoWriter Class processself.__start_CVProcess()# Check status of the processassertself.__processisnotNone# log one-time OpenCV warningself.__loggingandlogger.info("RGBA and 16-bit grayscale video frames are not supported by OpenCV yet. Kindly switch on `compression_mode` to use them!")# write frame directly to# VideoWriter Class processself.__process.write(frame)def__PreprocessFFParams(self,channels,dtype=None,rgb=False):""" Internal method that pre-processes FFmpeg Parameters before beginning to pipeline frames. Parameters: channels (int): Number of channels in input frame. dtype (str): Datatype of input frame. rgb (boolean): Whether to activate `RGB mode`? """# turn off initiate flagself.__initiate_process=False# initialize input parametersinput_parameters={}# handle output frames dimensionsdimensions=""ifself.__output_dimensionsisNone:# check if dimensions are givendimensions+="{}x{}".format(self.__inputwidth,self.__inputheight)# auto derive from frameelse:dimensions+="{}x{}".format(self.__output_dimensions[0],self.__output_dimensions[1])# apply if definedinput_parameters["-s"]=str(dimensions)# handles user-defined and auto-assigned input pixel-formatsifnot(self.__inputpixfmtisNone)andself.__inputpixfmtinget_supported_pixfmts(self.__ffmpeg):# assign directly if validinput_parameters["-pix_fmt"]=self.__inputpixfmtelse:# handles pix_fmt based on channels and dtype(HACK)ifdtype.kind=="u"anddtype.itemsize==2:# handle pix_fmt for frames with higher than 8-bit depthpix_fmt=Noneifchannels==1:pix_fmt="gray16"elifchannels==2:pix_fmt="ya16"elifchannels==3:pix_fmt="rgb48"ifrgbelse"bgr48"elifchannels==4:pix_fmt="rgba64"ifrgbelse"bgra64"else:# raise error otherwiseraiseValueError("[WriteGear:ERROR] :: Frames with channels outside range 1-to-4 are not supported!")# Add endianness suffix (w.r.t byte-order)input_parameters["-pix_fmt"]=pix_fmt+("be"ifdtype.byteorder==">"else"le")else:# handle pix_fmt for frames with exactly 8-bit depth(`uint8`)ifchannels==1:input_parameters["-pix_fmt"]="gray"elifchannels==2:input_parameters["-pix_fmt"]="ya8"elifchannels==3:input_parameters["-pix_fmt"]="rgb24"ifrgbelse"bgr24"elifchannels==4:input_parameters["-pix_fmt"]="rgba"ifrgbelse"bgra"else:# raise error otherwiseraiseValueError("[WriteGear:ERROR] :: Frames with channels outside range 1-to-4 are not supported!")# handles user-defined output video framerateifself.__inputframerate>0.0:# assign input framerate if validself.__loggingandlogger.debug("Setting Input framerate: {}".format(self.__inputframerate))input_parameters["-framerate"]=str(self.__inputframerate)# initiate FFmpeg processself.__start_FFProcess(input_params=input_parameters,output_params=self.__output_parameters)def__start_FFProcess(self,input_params,output_params):""" An Internal method that launches FFmpeg subprocess pipeline in Compression Mode for pipelining frames to `stdin`. Parameters: input_params (dict): Input FFmpeg parameters output_params (dict): Output FFmpeg parameters """# convert input parameters to argument listinput_parameters=dict2Args(input_params)# handle output video encoder.# get list of supported video-encoderssupported_vcodecs=get_supported_vencoders(self.__ffmpeg)# dynamically select default encoderdefault_vcodec=[vcodecforvcodecin["libx264","libx265","libxvid","mpeg4"]ifvcodecinsupported_vcodecs][0]or"unknown"# extract any user-defined encoderif"-c:v"inoutput_params:# assign it to the pipelineoutput_params["-vcodec"]=output_params.pop("-c:v",default_vcodec)ifnot"-vcodec"inoutput_params:# auto-assign default video-encoder (if not assigned by user).output_params["-vcodec"]=default_vcodecif(default_vcodec!="unknown"andnotoutput_params["-vcodec"]insupported_vcodecs):# reset to default if not supportedlogger.critical("Provided FFmpeg does not support `{}` video-encoder. Switching to default supported `{}` encoder!".format(output_params["-vcodec"],default_vcodec))output_params["-vcodec"]=default_vcodec# assign optimizations based on selected video encoder(if any)ifoutput_params["-vcodec"]insupported_vcodecs:ifoutput_params["-vcodec"]in["libx265","libx264"]:ifnot"-crf"inoutput_params:output_params["-crf"]="18"ifnot"-preset"inoutput_params:output_params["-preset"]="fast"ifoutput_params["-vcodec"]in["libxvid","mpeg4"]:ifnot"-qscale:v"inoutput_params:output_params["-qscale:v"]="3"else:# raise error otherwiseraiseRuntimeError("[WriteGear:ERROR] :: Provided FFmpeg does not support any suitable/usable video-encoders for compression."" Kindly disable compression mode or switch to another FFmpeg binaries(if available).")# convert output parameters to argument listoutput_parameters=dict2Args(output_params)# format FFmpeg commandcmd=([self.__ffmpeg,"-y"]+self.__ffmpeg_preheaders+["-f","rawvideo","-vcodec","rawvideo"]+input_parameters+["-i","-"]+output_parameters+[self.__out_file])# Launch the process with FFmpeg commandifself.__logging:# log command in logging modelogger.debug("Executing FFmpeg command: `{}`".format(" ".join(cmd)))# In logging modeself.__process=sp.Popen(cmd,stdin=sp.PIPE,stdout=sp.PIPE,stderr=None)else:# In silent modeself.__process=sp.Popen(cmd,stdin=sp.PIPE,stdout=sp.DEVNULL,stderr=sp.STDOUT,creationflags=(# this prevents ffmpeg creation window from opening when building exe files on Windowssp.DETACHED_PROCESSifself.__ffmpeg_window_disabler_patchelse0),)def__enter__(self):""" Handles entry with the `with` statement. See [PEP343 -- The 'with' statement'](https://peps.python.org/pep-0343/). **Returns:** Returns a reference to the WriteGear Class """returnselfdef__exit__(self,exc_type,exc_val,exc_tb):""" Handles exit with the `with` statement. See [PEP343 -- The 'with' statement'](https://peps.python.org/pep-0343/). """self.close()defexecute_ffmpeg_cmd(self,command:List=None)->None:""" Executes user-defined FFmpeg Terminal command, formatted as a python list(in Compression Mode only). Parameters: command (list): inputs list data-type command. """# check if valid commandifcommandisNoneornot(command):logger.warning("Input command is empty, Nothing to execute!")returnelse:ifnot(isinstance(command,list)):raiseValueError("[WriteGear:ERROR] :: Invalid input command datatype! Kindly read docs.")# check if Compression Mode is enabledifnot(self.__compression):# raise error otherwiseraiseRuntimeError("[WriteGear:ERROR] :: Compression Mode is disabled, Kindly enable it to access this function.")# add configured FFmpeg pathcmd=[self.__ffmpeg]+commandtry:# write frames to pipelineifself.__logging:# log command in logging modelogger.debug("Executing FFmpeg command: `{}`".format(" ".join(cmd)))# In logging modesp.run(cmd,stdin=sp.PIPE,stdout=sp.PIPE,stderr=None)else:# In silent modesp.run(cmd,stdin=sp.PIPE,stdout=sp.DEVNULL,stderr=sp.STDOUT)except(OSError,IOError)ase:# re-raise errorifself.__logging:raiseValueError("BrokenPipeError caught, Wrong command passed to FFmpeg Pipe, Kindly Refer Docs!")fromNoneelse:raiseValueError("BrokenPipeError caught, Wrong command passed to FFmpeg Pipe, Kindly Refer Docs!")fromedef__start_CVProcess(self):""" An Internal method that launches OpenCV VideoWriter process in Non-Compression Mode with given settings. """# turn off initiate flagself.__initiate_process=False# initialize essential variablesFPS=0BACKEND=""FOURCC=0COLOR=True# pre-assign default parameters (if not assigned by user).if"-fourcc"notinself.__output_parameters:FOURCC=cv2.VideoWriter_fourcc(*"MJPG")if"-fps"notinself.__output_parameters:FPS=25# auto-assign frame dimensionsHEIGHT=self.__inputheightWIDTH=self.__inputwidth# assign dict parameter values to variablestry:forkey,valueinself.__output_parameters.items():ifkey=="-fourcc":FOURCC=cv2.VideoWriter_fourcc(*(value.upper()))elifkey=="-fps":FPS=int(value)elifkey=="-backend":BACKEND=capPropId(value.upper())elifkey=="-color":COLOR=bool(value)else:passexceptExceptionase:# log and raise error if something is wrongself.__loggingandlogger.exception(str(e))raiseValueError("[WriteGear:ERROR] :: Wrong Values passed to OpenCV Writer, Kindly Refer Docs!")# log values for debuggingself.__loggingandlogger.debug("FILE_PATH: {}, FOURCC = {}, FPS = {}, WIDTH = {}, HEIGHT = {}, BACKEND = {}".format(self.__out_file,FOURCC,FPS,WIDTH,HEIGHT,BACKEND))# start different OpenCV VideoCapture processes# for with and without Backend.ifBACKEND:self.__process=cv2.VideoWriter(self.__out_file,apiPreference=BACKEND,fourcc=FOURCC,fps=FPS,frameSize=(WIDTH,HEIGHT),isColor=COLOR,)else:self.__process=cv2.VideoWriter(self.__out_file,fourcc=FOURCC,fps=FPS,frameSize=(WIDTH,HEIGHT),isColor=COLOR,)# check if OpenCV VideoCapture is opened successfullyassert(self.__process.isOpened()),"[WriteGear:ERROR] :: Failed to initialize OpenCV Writer!"defclose(self)->None:""" Safely terminates various WriteGear process. """# log terminationself.__loggingandlogger.debug("Terminating WriteGear Processes.")# handle termination separatelyifself.__compression:# when Compression Mode is enabledifself.__processisNoneornot(self.__process.poll()isNone):# return if no process initiated# at first placereturn# close `stdin` outputself.__process.stdinandself.__process.stdin.close()# close `stdout` outputself.__process.stdoutandself.__process.stdout.close()# forced termination if specified.self.__forced_terminationandself.__process.terminate()# wait if process is still processingself.__process.wait()else:# when Compression Mode is disabledifself.__processisNone:# return if no process initiated# at first placereturn# close itself.__process.release()# discard processself.__process=None
def__init__(self,output:str="",compression_mode:bool=True,custom_ffmpeg:str="",logging:bool=False,**output_params:dict):""" This constructor method initializes the object state and attributes of the WriteGear class. Parameters: output (str): sets the valid filename/path/URL for encoding. compression_mode (bool): selects the WriteGear's Primary Mode of Operation. custom_ffmpeg (str): assigns the location of custom path/directory for custom FFmpeg executables. logging (bool): enables/disables logging. output_params (dict): provides the flexibility to control supported internal parameters and FFmpeg properties. """# enable logging if specifiedself.__logging=loggingifisinstance(logging,bool)elseFalse# print current versionlogcurr_vidgear_ver(logging=self.__logging)# check if user not using depreciated `output_filename` parameterassert(not"output_filename"inoutput_params),"[WriteGear:ERROR] :: The `output_filename` parameter has been renamed to `output`. Refer Docs for more info."# assign parameter values to class variables# enables compression if enabledself.__compression=(compression_modeifisinstance(compression_mode,bool)elseFalse)# specifies if machine in-use is running Windows OS or notself.__os_windows=Trueifos.name=="nt"elseFalse# initialize various important class variablesself.__output_parameters={}# handles output parametersself.__inputheight=None# handles input frames heightself.__inputwidth=None# handles input frames widthself.__inputchannels=None# handles input frames channelsself.__inputdtype=None# handles input frames dtypeself.__process=None# handles Encoding class/processself.__ffmpeg=""# handles valid FFmpeg binaries locationself.__initiate_process=(True# handles initiate one-time process for generating pipeline)self.__ffmpeg_window_disabler_patch=(False# handles disabling window for ffmpeg subprocess on Windows)self.__out_file=None# handles outputgstpipeline_mode=False# handles GStreamer Pipeline Mode# handles outputifnotoutput:# raise error otherwiseraiseValueError("[WriteGear:ERROR] :: Kindly provide a valid `output` value. Refer Docs for more info.")else:# validate output is a system file/directory# and Whether WriteGear has the write rights# to specified file/directory or notabs_path=os.path.abspath(output)ifcheck_WriteAccess(os.path.dirname(abs_path),is_windows=self.__os_windows,logging=self.__logging,):# check if given path is directoryifos.path.isdir(abs_path):# then, auto-assign valid name and adds it to pathabs_path=os.path.join(abs_path,"VidGear-{}.mp4".format(time.strftime("%Y%m%d-%H%M%S")),)# assign output file absolute# path to class variable if validself.__out_file=abs_pathelse:# log note otherwiselogger.info("`{}` isn't a valid system path or directory. Skipped!".format(output))# cleans and reformat output parametersself.__output_parameters={str(k).strip():(v.strip()ifisinstance(v,str)elsev)fork,vinoutput_params.items()}# log it if specifiedself.__loggingandlogger.debug("Output Parameters: `{}`".format(self.__output_parameters))# handles FFmpeg binaries validity# in Compression modeifself.__compression:# log it if specifiedself.__loggingandlogger.debug("Compression Mode is enabled therefore checking for valid FFmpeg executable.")# handles where to save the downloaded FFmpeg Static Binaries# on Windows(if specified)__ffmpeg_download_path=self.__output_parameters.pop("-ffmpeg_download_path","")# check if value is validifnotisinstance(__ffmpeg_download_path,(str)):# reset improper values__ffmpeg_download_path=""# handle user-defined output resolution (must be a tuple or list)# in Compression Mode only.self.__output_dimensions=self.__output_parameters.pop("-output_dimensions",None)# check if value is validifnotisinstance(self.__output_dimensions,(list,tuple)):# reset improper valuesself.__output_dimensions=None# handle user defined input framerate of encoding pipeline# in Compression Mode only.self.__inputframerate=self.__output_parameters.pop("-input_framerate",0.0)# check if value is validifnotisinstance(self.__inputframerate,(float,int)):# reset improper valuesself.__inputframerate=0.0else:# must be floatself.__inputframerate=float(self.__inputframerate)# handle user-defined input frames pixel-format in Compression Mode only.self.__inputpixfmt=self.__output_parameters.pop("-input_pixfmt",None)# check if value is validifnotisinstance(self.__inputpixfmt,str):# reset improper valuesself.__inputpixfmt=Noneelse:# must be exactself.__inputpixfmt=self.__inputpixfmt.strip()# handle user-defined FFmpeg command pre-headers(must be a list)# in Compression Mode only.self.__ffmpeg_preheaders=self.__output_parameters.pop("-ffpreheaders",[])# check if value is validifnotisinstance(self.__ffmpeg_preheaders,list):# reset improper valuesself.__ffmpeg_preheaders=[]# handle the special-case of forced-termination (only for Compression mode)disable_force_termination=self.__output_parameters.pop("-disable_force_termination",Falseif("-i"inself.__output_parameters)elseTrue,)# check if value is validifisinstance(disable_force_termination,bool):self.__forced_termination=not(disable_force_termination)else:# handle improper valuesself.__forced_termination=(Trueif("-i"inself.__output_parameters)elseFalse)# handles disabling window for ffmpeg subprocess on Windows OS (only for Compression mode)# this patch prevents ffmpeg creation window from opening when building exe filesffmpeg_window_disabler_patch=self.__output_parameters.pop("-disable_ffmpeg_window",False)# check if value is validifnotself.__os_windowsorlogging:logger.warning("Optional `-disable_ffmpeg_window` flag is only available on Windows OS with `logging=False`. Discarding!")elifisinstance(ffmpeg_window_disabler_patch,bool):self.__ffmpeg_window_disabler_patch=ffmpeg_window_disabler_patchelse:# handle improper valuesself.__ffmpeg_window_disabler_patch=False# validate the FFmpeg path/binaries and returns valid executable FFmpeg# location/path (also auto-downloads static binaries on Windows OS)self.__ffmpeg=get_valid_ffmpeg_path(custom_ffmpeg,self.__os_windows,ffmpeg_download_path=__ffmpeg_download_path,logging=self.__logging,)# check if valid executable FFmpeg location/pathifself.__ffmpeg:# log it if foundself.__loggingandlogger.debug("Found valid FFmpeg executable: `{}`.".format(self.__ffmpeg))else:# otherwise disable Compression Mode# and switch to Non-compression modelogger.warning("Disabling Compression Mode since no valid FFmpeg executable found on this machine!")ifself.__loggingandnotself.__os_windows:logger.debug("Kindly install a working FFmpeg module or provide a valid custom FFmpeg binary path. See docs for more info.")# compression mode disabledself.__compression=Falseelse:# handle GStreamer Pipeline Mode (only for Non-compression mode)if"-gst_pipeline_mode"inself.__output_parameters:# check if value is validifisinstance(self.__output_parameters["-gst_pipeline_mode"],bool):gstpipeline_mode=self.__output_parameters["-gst_pipeline_mode"]andcheck_gstreamer_support(logging=logging)self.__loggingandlogger.debug("GStreamer Pipeline Mode successfully activated!")else:# reset improper valuesgstpipeline_mode=False# log itself.__loggingandlogger.warning("GStreamer Pipeline Mode failed to activate!")# handle output differently in Compression/Non-compression Modesifself.__compressionandself.__ffmpeg:# check if output falls in exclusive casesifself.__out_fileisNone:if(platform.system()=="Linux"andpathlib.Path(output).is_char_device()):# check whether output is a Linux video device path (such as `/dev/video0`)self.__loggingandlogger.debug("Path:`{}` is a valid Linux Video Device path.".format(output))self.__out_file=outputelifis_valid_url(self.__ffmpeg,url=output,logging=self.__logging):# check whether output is a valid URL insteadself.__loggingandlogger.debug("URL:`{}` is valid and successfully configured for streaming.".format(output))self.__out_file=outputelse:# raise error otherwiseraiseValueError("[WriteGear:ERROR] :: output value:`{}` is not supported in Compression Mode.".format(output))# log if forced termination is enabledself.__forced_terminationandlogger.debug("Forced termination is enabled for this FFmpeg process.")# log Compression is enabledself.__loggingandlogger.debug("Compression Mode with FFmpeg backend is configured properly.")else:# raise error if not valid inputifself.__out_fileisNoneandnotgstpipeline_mode:raiseValueError("[WriteGear:ERROR] :: output value:`{}` is not supported in Non-Compression Mode.".format(output))# check if GStreamer Pipeline Mode is enabledifgstpipeline_mode:# enforce GStreamer backendself.__output_parameters["-backend"]="CAP_GSTREAMER"# enforce original output valueself.__out_file=output# log itself.__loggingandlogger.debug("Non-Compression Mode is successfully configured in GStreamer Pipeline Mode.")# log if Compression is disabledlogger.critical("Compression Mode is disabled, Activating OpenCV built-in Writer!")
defclose(self)->None:""" Safely terminates various WriteGear process. """# log terminationself.__loggingandlogger.debug("Terminating WriteGear Processes.")# handle termination separatelyifself.__compression:# when Compression Mode is enabledifself.__processisNoneornot(self.__process.poll()isNone):# return if no process initiated# at first placereturn# close `stdin` outputself.__process.stdinandself.__process.stdin.close()# close `stdout` outputself.__process.stdoutandself.__process.stdout.close()# forced termination if specified.self.__forced_terminationandself.__process.terminate()# wait if process is still processingself.__process.wait()else:# when Compression Mode is disabledifself.__processisNone:# return if no process initiated# at first placereturn# close itself.__process.release()# discard processself.__process=None
defwrite(self,frame:NDArray,rgb_mode:bool=False)->None:""" Pipelines `ndarray` frames to respective API _(**FFmpeg** in Compression Mode & **OpenCV's VideoWriter API** in Non-Compression Mode)_. Parameters: frame (ndarray): a valid numpy frame rgb_mode (boolean): enable this flag to activate RGB mode _(i.e. specifies that incoming frames are of RGB format(instead of default BGR)_. """ifframeisNone:# None-Type frames will be skippedreturn# get height, width, number of channels, and dtype of current frameheight,width=frame.shape[:2]channels=frame.shape[-1]ifframe.ndim==3else1dtype=frame.dtype# assign values to class variables on first runifself.__initiate_process:self.__inputheight=heightself.__inputwidth=widthself.__inputchannels=channelsself.__inputdtype=dtypeself.__loggingandlogger.debug("InputFrame => Height:{} Width:{} Channels:{} Datatype:{}".format(self.__inputheight,self.__inputwidth,self.__inputchannels,self.__inputdtype,))# validate frame sizeifheight!=self.__inputheightorwidth!=self.__inputwidth:raiseValueError("[WriteGear:ERROR] :: All video-frames must have same size!")# validate number of channels in frameifchannels!=self.__inputchannels:raiseValueError("[WriteGear:ERROR] :: All video-frames must have same number of channels!")# validate frame datatypeifdtype!=self.__inputdtype:raiseValueError("[WriteGear:ERROR] :: All video-frames must have same datatype!")# checks if compression mode is enabledifself.__compression:# initiate FFmpeg process on first runifself.__initiate_process:# start pre-processing of FFmpeg parameters, and initiate processself.__PreprocessFFParams(channels,dtype=dtype,rgb=rgb_mode)# Check status of the processassertself.__processisnotNonetry:# try writing the frame bytes to the subprocess pipelineself.__process.stdin.write(frame.tobytes())except(OSError,IOError):# log if something is wrong!logger.error("BrokenPipeError caught, Wrong values passed to FFmpeg Pipe. Kindly Refer Docs!")raiseValueError# for testing purpose onlyelse:# otherwise initiate OpenCV's VideoWriter Class processifself.__initiate_process:# start VideoWriter Class processself.__start_CVProcess()# Check status of the processassertself.__processisnotNone# log one-time OpenCV warningself.__loggingandlogger.info("RGBA and 16-bit grayscale video frames are not supported by OpenCV yet. Kindly switch on `compression_mode` to use them!")# write frame directly to# VideoWriter Class processself.__process.write(frame)