def ffmpeg_resize(video,output,size): """ resizes ``video`` to new size ``size`` and write the result in file ``output``. """ cmd= ["ffmpeg", "-i", video, "-vf", "scale=%d:%d"%(res[0], res[1]), output] subprocess_call(cmd)
def ffmpeg_resize(video,output,size): """ resizes ``video`` to new size ``size`` and write the result in file ``output``. """ cmd= [get_setting("FFMPEG_BINARY"), "-i", video, "-vf", "scale=%d:%d"%(size[0], size[1]), output] subprocess_call(cmd)
def gif_to_directory(gif_file,dirName=None): """ Stores all the frames of the given .gif file into the directory ``dirName``. If ``dirName`` is not provided, the directory has the same name as the .gif file. Supports transparency. Returns the directory name. Example: >>> d = gif_to_directory("animated-earth.gif") >>> clip = DirectoryClip(d,fps=3) """ if dirName is None: name, ext = os.path.splitext(gif_file) dirName = name try: os.mkdir(dirName) except: pass subprocess_call(["convert", "-coalesce", gif_file, os.path.join(dirName,"%04d.png")])
def ffmpeg_merge_video_audio(video,audio,output, vcodec='copy', acodec='copy', ffmpeg_output=False): """ merges video file ``video`` and audio file ``audio`` into one movie file ``output``. """ cmd = ["ffmpeg", "-y", "-i", audio,"-i", video, "-vcodec", vcodec, "-acodec", acodec, output] subprocess_call(cmd, stdin=None, stdout=None)
def __init__(self, txt, size=None, color='black', bg_color='transparent', fontsize=None, font='Courier', stroke_color=None, stroke_width=1, method='label', kerning=None, align='center', interline=None, tempfile='temp.png', temptxt='temp.txt', transparent=True, remove_temp=True, print_cmd=False): if not txt.startswith('@'): temptxt = 'temp.txt' with open(temptxt, 'w+') as f: f.write(txt) txt = '@temp.txt' else: txt = "'%s'"%txt if size != None: size = ('' if size[0] is None else str(size[0]), '' if size[1] is None else str(size[1])) cmd = ( ["convert", "-background", bg_color, "-fill", color, "-font", font]) if fontsize !=None: cmd += ["-pointsize", "%d"%fontsize] if kerning != None: cmd += ["-kerning", "%0.1f"%kerning] if stroke_color != None: cmd += ["-stroke", stroke_color, "-strokewidth", "%.01f"%stroke_width] if size != None: cmd += ["-size", "%sx%s"%(size[0], size[1])] if align != None: cmd += ["-gravity",align] if interline != None: cmd += ["-interline-spacing", "%d"%interline] cmd += ["%s:%s" %(method, txt), "-type", "truecolormatte", "PNG32:%s"%tempfile] if print_cmd: print( " ".join(cmd) ) subprocess_call(cmd, verbose=False ) ImageClip.__init__(self, tempfile, transparent=transparent) self.txt = txt self.color = color self.stroke_color = stroke_color if remove_temp: os.remove(tempfile) try: os.remove(temptxt) except: pass
def ffmpeg_merge_video_audio(video,audio,output, vcodec='copy', acodec='copy', ffmpeg_output=False, verbose = True): """ merges video file ``video`` and audio file ``audio`` into one movie file ``output``. """ cmd = [FFMPEG_BINARY, "-y", "-i", audio,"-i", video, "-vcodec", vcodec, "-acodec", acodec, output] subprocess_call(cmd, verbose = verbose)
def ffmpeg_merge_video_audio(video,audio,output, vcodec='copy', acodec='copy', ffmpeg_output=False, logger = 'bar'): """ merges video file ``video`` and audio file ``audio`` into one movie file ``output``. """ cmd = [get_setting("FFMPEG_BINARY"), "-y", "-i", audio,"-i", video, "-vcodec", vcodec, "-acodec", acodec, output] subprocess_call(cmd, logger = logger)
def download_webfile(url, filename, overwrite=False): """ Small utility to download the file at 'url' under name 'filename'. If url is a youtube video ID like z410eauCnH it will download the video using youtube-dl (install youtube-dl first !). If the filename already exists and overwrite=False, nothing will happen. """ if os.path.exists(filename) and not overwrite: return if '.' in url: urlretrieve(url, filename) else: subprocess_call(['youtube-dl', url, '-o', filename])
def ffmpeg_merge_video_audio(video, audio, output, vcodec='copy', acodec='copy', ffmpeg_output=False): """ merges video file ``video`` and audio file ``audio`` into one movie file ``output``. """ cmd = [ "ffmpeg", "-y", "-i", audio, "-i", video, "-vcodec", vcodec, "-acodec", acodec, output ] subprocess_call(cmd, stdin=None, stdout=None)
def concat(person, clips): """ Concatenates the the input clips into an output video for a given person Parameters -------------------- clips -- Array of clip names excluding filetype as we assume them to be .mp4 Returns -------------------- returns nothing but creates an output video """ #create workspace for less clutter if os.path.exists("workspacets"): shutil.rmtree("workspacets") #clear workspace and remake it os.makedirs("workspacets") else: os.makedirs("workspacets") #ffmpeg setup and calls concat_param = "concat:" first = True for clip in clips: cmd = [ get_setting("FFMPEG_BINARY"), "-y", "-i", clips_path + "/" + person + "/" + clip + "/1.mp4", "-c", "copy", "-bsf:v", "h264_mp4toannexb", "-f", "mpegts", "workspacets/" + clip + ".ts" ] try: subprocess_call(cmd, False, False) except: print("Oops! " + person.title() + " doesn't know the word '" + clip + "'") return clip if first: concat_param = concat_param + "workspacets/" + clip + ".ts" first = False else: concat_param = concat_param + "|" + "workspacets/" + clip + ".ts" fcmd = [ get_setting("FFMPEG_BINARY"), "-y", "-i", concat_param, "-c", "copy", "-bsf:a", "aac_adtstoasc", output_folder + "/tmp.mp4" ] subprocess_call(fcmd, False) return ""
def ffmpeg_movie_from_frames(filename, folder, fps, digits=6): """ Writes a movie out of the frames (picture files) in a folder. Almost deprecated. """ s = "%" + "%02d" % digits + "d.png" cmd = ["ffmpeg", "-y", "-f","image2", "-r", "%d"%fps, "-i", os.path.join(folder,folder) + '/' + s, "-b", "%dk"%bitrate, "-r", "%d"%self.fps, filename] subprocess_call(cmd, stdin=None, stdout=None)
def ffmpeg_extract_audio(inputfile, output, bitrate=3000, fps=44100): """ extract the sound from a video file and save it in ``output`` """ cmd = [ FFMPEG_BINARY, "-y", "-i", inputfile, "-ab", "%dk" % bitrate, "-ar", "%d" % fps, output, ] subprocess_call(cmd)
def ffmpeg_movie_from_frames(filename, folder, fps, digits=6): """ Writes a movie out of the frames (picture files) in a folder. Almost deprecated. """ s = "%" + "%02d" % digits + "d.png" cmd = [get_setting("FFMPEG_BINARY"), "-y", "-f","image2", "-r", "%d"%fps, "-i", os.path.join(folder,folder) + '/' + s, "-b", "%dk"%bitrate, "-r", "%d"%self.fps, filename] subprocess_call(cmd)
def ffmpeg_movie_from_frames(filename, folder, fps, digits=6, bitrate='v'): """ Writes a movie out of the frames (picture files) in a folder. Almost deprecated. """ s = "%" + "%02d" % digits + "d.png" cmd = [get_setting("FFMPEG_BINARY"), "-y", "-f","image2", "-r", "%d"%fps, "-i", os.path.join(folder,folder) + '/' + s, "-b", "%dk"%bitrate, "-r", "%d"%fps, filename] subprocess_call(cmd)
def ffmpeg_concatenate_subclips(file1, file2, targetname): temp = open("temp.txt", "w+") try: temp.writelines("file '" + os.path.abspath(file1) + "'\n") temp.writelines("file '" + os.path.abspath(file2) + "'") temp.close() cmd = [ get_setting("FFMPEG_BINARY"), "-safe", "0", "-f", "concat", "-i", os.path.abspath(temp.name), "-c", "copy", targetname, '-y' ] subprocess_call(cmd) finally: os.remove(temp.name)
def ffmpeg_merge_video_audio(video, audio, output, vcodec='copy', acodec='copy', ffmpeg_output=False, logger='bar'): """ merges video file ``video`` and audio file ``audio`` into one movie file ``output``. """ cmd = [ get_setting("FFMPEG_BINARY"), "-y", "-i", audio, "-i", video, "-vcodec", vcodec, "-acodec", acodec, output ] subprocess_call(cmd, logger=logger)
def ffmpeg_extract_subclip(filename, t1, t2, targetname=None): """ Makes a new video file playing video file ``filename`` between the times ``t1`` and ``t2``. """ name, ext = os.path.splitext(filename) if not targetname: T1, T2 = [int(1000*t) for t in [t1, t2]] targetname = "%sSUB%d_%d.%s" % (name, T1, T2, ext) cmd = [get_setting("FFMPEG_BINARY"),"-y", "-ss", "%0.2f"%t1, "-i", filename, "-t", "%0.2f"%(t2-t1), "-vcodec", "copy", "-acodec", "copy", targetname] subprocess_call(cmd)
def ffmpeg_merge_video_audio(video, audio, output, vcodec='copy', acodec='copy', ffmpeg_output=False, verbose=True): """ merges video file ``video`` and audio file ``audio`` into one movie file ``output``. """ cmd = [ FFMPEG_BINARY, "-y", "-i", audio, "-i", video, "-vcodec", vcodec, "-acodec", acodec, output ] subprocess_call(cmd, verbose=verbose)
def ffmpeg_extract_subclip(filename, t1, t2, targetname=None): """ Makes a new video file playing video file ``filename`` between the times ``t1`` and ``t2``. """ name, ext = os.path.splitext(filename) if not targetname: T1, T2 = [int(1000 * t) for t in [t1, t2]] targetname = "%sSUB%d_%d.%s" % (name, T1, T2, ext) cmd = [ get_setting("FFMPEG_BINARY"), "-y", "-ss", "%0.2f" % t1, "-i", filename, "-t", "%0.2f" % (t2 - t1), "-vcodec", "copy", "-acodec", "copy", targetname ] subprocess_call(cmd)
def ffmpeg_merge_video_audio(video_file_name, audio_file_name, output_file_name): """ run this command $ ffmpeg -i video.mp4 -i audio.wav -c:v copy -c:a aac output.mp4 video.mp4 -> video_file_name audio.wav -> audio_file_name output.mp4 -> output_file_name """ cmd = [ get_setting("FFMPEG_BINARY"), "-y", "-i", video_file_name, "-i", audio_file_name, "-c:v", "copy", "-c:a", "aac", output_file_name ] subprocess_call(cmd) #from moviepy
def ffmpeg_merge_video_without_reencoding(subclip_list, output_file_name): #ffmpeg -f concat -safe 0 -i vidlist.txt -c copy output contents = "" for name in subclip_list: contents += "file '{}'\n".format(name) tmp_video_list_file = "tmp_subclips.txt" with open(tmp_video_list_file, "w") as f: f.write(contents) cmd = [ get_setting("FFMPEG_BINARY"), "-y", "-f", "concat", "-safe", "0", "-i", tmp_video_list_file, "-c", "copy", output_file_name ] subprocess_call(cmd) os.remove(tmp_video_list_file)
def download_webfile(url, filename, overwrite=False): """Small utility to download the file at ``url`` under name ``filename``. Parameters ---------- url : str If url is a youtube video ID like z410eauCnH it will download the video using youtube-dl. Requires youtube-dl (pip install youtube-dl). filename : str Path to the new downloaded file location. overwrite : bool, optional If the filename already exists and overwrite=False, nothing will happen. Use it to force destination file overwriting. Examples -------- >>> from moviepy.io.downloader import download_website >>> >>> download_website( ... "http://localhost:8000/media/chaplin.mp4", ... "media/chaplin-copy.mp4", ... ) >>> """ if os.path.exists(filename) and not overwrite: # pragma: no cover return if "." in url: with urllib.request.urlopen(url) as req, open(filename, "wb") as f: shutil.copyfileobj(req, f, 128) else: try: subprocess_call(["youtube-dl", url, "-o", filename]) except OSError as e: raise OSError( ( "Error running youtube-dl.\n%sA possible reason is that" " youtube-dl is not installed on your computer. Install it " " with 'pip install youtube_dl'." ) % ((e.message + "\n" if hasattr(e, "message") else "")) )
def ffmpeg_compress_audio(self, file: str, output: str): threshold = self.compressor_settings["threshold"] ratio = self.compressor_settings["ratio"] attack = self.compressor_settings["attack"] release = self.compressor_settings["release"] cmd = [ "ffmpeg", "-i", file, "-c:v", "copy", # Copy video to avoid re-encoding "-af", f"acompressor=threshold={threshold}:ratio={ratio}:attack={attack}:release={release}", output, ] subprocess_call(cmd)
def ffmpeg_extract_subclip( inputfile, start_time, end_time, outputfile=None, logger="bar" ): """Makes a new video file playing video file between two times. Parameters ---------- inputfile : str Path to the file from which the subclip will be extracted. start_time : float Moment of the input clip that marks the start of the produced subclip. end_time : float Moment of the input clip that marks the end of the produced subclip. outputfile : str, optional Path to the output file. Defaults to ``<inputfile_name>SUB<start_time>_<end_time><ext>``. """ if not outputfile: name, ext = os.path.splitext(inputfile) t1, t2 = [int(1000 * t) for t in [start_time, end_time]] outputfile = "%sSUB%d_%d%s" % (name, t1, t2, ext) cmd = [ FFMPEG_BINARY, "-y", "-ss", "%0.2f" % start_time, "-i", inputfile, "-t", "%0.2f" % (end_time - start_time), "-map", "0", "-vcodec", "copy", "-acodec", "copy", "-copyts", outputfile, ] subprocess_call(cmd, logger=logger)
def download_webfile(url, filename, overwrite=False): """ Small utility to download the file at 'url' under name 'filename'. If url is a youtube video ID like z410eauCnH it will download the video using youtube-dl (install youtube-dl first !). If the filename already exists and overwrite=False, nothing will happen. """ if os.path.exists(filename) and not overwrite: return if '.' in url: urlretrieve(url, filename) else: try: subprocess_call(['youtube-dl', url, '-o', filename]) except OSError as e: raise OSError(e.message + '\n A possible reason is that youtube-dl' ' is not installed on your computer. Install it with ' ' "pip install youtube-dl"')
def test_6(): ''' Tests subprocess_call for operation. the process sleep should run for a given time in seconds. This checks that the process has deallocated from the stack on completion of the called process ''' process = tools.subprocess_call(["sleep", '1']) time.sleep(1) assert process is None
def cut(scene_list, video_list, vid, time, fps, read): #function that cut shots during the cut&combine part # calls the function statfile_cut to get a precise cut src = video_list[vid] # regex time sec = float(re.search('[0-9]+\.([0-9]{1})', str(time)).group(0)) #choosing best frame to cut cut_time = statfile_cut(scene_list, vid, sec, fps, read) #calulating absolute frame for updating scene list frame_in_shot = seconds_to_frame(cut_time, fps) frame_offset = scene_list[vid] frame = frame_offset + frame_in_shot #regex name reg = video_target_name + "(.+)\." name = re.search(reg, src).group(1) target1 = video_path + video_target_name + name + "(1)" + video_target_format target2 = video_path + video_target_name + name + "(2)" + video_target_format cmd = [ "ffmpeg", "-i", project_path + src, "-c:av", "copy", "-ss", str(cut_time), "-y", project_path + target2 ] subprocess_call(cmd) cmd = [ "ffmpeg", "-i", project_path + src, "-c:av", "copy", "-ss", "0.0", "-t", str(cut_time), "-y", project_path + target1 ] subprocess_call(cmd) video_list.pop(vid) video_list.insert(vid, target2) video_list.insert(vid, target1) #udating scene_list scene_list.insert(vid + 1, frame) update_scenes(scene_list, fps, read) return video_list
def ffmpeg_extarct_subclip_audio(filename, output_path='./', isfolder=False, sr=22050, output_format='wav'): """ Extact Audio files(.WAV) from Video files(.MP4) filename : 가져올 파일 or 폴더 이름 output_path : 저장할 경로 isfolder : 폴더 유무를 판단하는 함수 sr : sample rate(default : 22050) output_format : 출력할 형식 """ ffmpeg_path = "D:/ffmpeg-4.2-win64-static/bin/ffmpeg.exe" ## ffmpeg 주소 saved_path = output_path if saved_path[-1] != "/": saved_path += "/" if isfolder: file_list = [f for f in os.listdir(filename)] command = [[ ffmpeg_path, '-y', '-i', filename + file, saved_path + os.path.splitext(file)[0] + '.' + output_format ] for file in file_list] else: command = [ ffmpeg_path, '-y', '-i', filename, saved_path + os.path.splitext(filename)[0].split('/')[-1] + '.' + output_format ] for cmd in command: try: if type(cmd) != list: subprocess_call(command) return subprocess_call(cmd) print("Convert Completes") except OSError: print("Don't exist File or Audio in File") print("Please check the file") return
def ffmpeg_merge_video_audio( videofile, audiofile, outputfile, video_codec="copy", audio_codec="copy", logger="bar", ): """Merges video file and audio file into one movie file. Parameters ---------- videofile : str Path to the video file used in the merge. audiofile : str Path to the audio file used in the merge. outputfile : str Path to the output file. video_codec : str, optional Video codec used by FFmpeg in the merge. audio_codec : str, optional Audio codec used by FFmpeg in the merge. """ cmd = [ FFMPEG_BINARY, "-y", "-i", audiofile, "-i", videofile, "-vcodec", video_codec, "-acodec", audio_codec, outputfile, ] subprocess_call(cmd, logger=logger)
def normalize(clip): """ Normalizes the audio of the the input clip into an output video Parameters -------------------- clips -- Array of clip names excluding filetype as we assume them to be .mp4 Returns -------------------- returns nothing but creates an output video """ cmd = ["ffmpeg-normalize", "-fu", "--format", "mp4", clip] subprocess_call(cmd, False) if os.path.exists(output_folder + "/they-say.mp4"): os.remove(output_folder + "/they-say.mp4") os.rename(output_folder + "/normalized-tmp.mp4", output_folder + "/they-say.mp4") os.remove(output_folder + "/tmp.mp4")
def split(self): for t in self._r: video_file = "vid.part" + str(t) + "." + self._file audio_file = "aud.part" + str(t) + "." + self._file + ".wav" ffmpeg_extract_subclip(self._file, t, t + self._segment_duration, targetname=video_file) # pyAudioAnalysis accepts mono -> refactor ffmpeg_extract_audio # bitrate = 3000 fps = 44100 cmd = [ get_setting("FFMPEG_BINARY"), "-y", "-i", video_file, "-ac", "1", "-ab", "%dk" % bitrate, "-ar", "%d" % fps, audio_file ] subprocess_call(cmd) return self._r
def video_subclip_ffmpeg(filename, t1, t2, targetname=None, reencode=False): """ makes a new video file playing video file ``filename`` between the times ``t1`` and ``t2``. """ if not reencode: ffmpeg_extract_subclip(filename=filename, t1=t1, t2=t2, targetname=targetname) else: name, ext = os.path.splitext(filename) if not targetname: T1, T2 = [int(1000 * t) for t in [t1, t2]] targetname = name + "%sSUB%d_%d.%s" % (name, T1, T2, ext) cmd = [ get_setting("FFMPEG_BINARY"), "-y", "-i", filename, "-ss", "%0.2f" % t1, "-t", "%0.2f" % (t2 - t1), "-c:v", "libx264", "-c:a", "aac", "-b:a", "64k", "-strict", "experimental", targetname ] subprocess_call(cmd)
def optimize_gif(path, file): image_magick = os.getenv("MAGICK_PATH") base_name = os.path.splitext(os.path.basename(file))[0] cmd = [ image_magick, "convert", os.path.join(path, file), "-layers", "coalesce", "-fuzz", "25%", "-layers", "remove-dups", "+delete", os.path.join(path, f"{base_name}.optimized.gif") ] try: subprocess_call(cmd) except: pass
def download_webfile(url, filename, overwrite=False): """Small utility to download the file at 'url' under name 'filename'. - If url is a youtube video ID like z410eauCnH it will download the video using youtube-dl. Requires youtube-dl (pip install youtube-dl). - If the filename already exists and overwrite=False, nothing will happen. """ if os.path.exists(filename) and not overwrite: return if "." in url: with urllib.request.urlopen(url) as req, open(filename, "wb") as f: shutil.copyfileobj(req, f, 128) else: try: subprocess_call(["youtube-dl", url, "-o", filename]) except OSError as e: raise OSError( e.message + "\n A possible reason is that youtube-dl" " is not installed on your computer. Install it with " ' "pip install youtube_dl"')
def ffmpeg_split(list, filename, fps, read): # function that allows the cutting of the video in different shots, that were found just after the PySceneDetect process #convert mkv file to mp4 input_name = project_path + video_path + video_target_temp + video_target_format cmd = [ "ffmpeg", "-i", project_path + video_path + filename, "-c:v", "copy", "-an", "-y", input_name ] subprocess_call(cmd) #input_name = project_path+video_path+filename # discard first scene(0) and add last read for computing purpose/ at the end add/remove these elements list.pop(0) list.append(read) media_name_list = [] begin = 0 for current in list: t2 = current - begin t1 = frames_to_second(begin, fps) t2 = frames_to_second(t2, fps) tar = video_path + video_target_name + str(begin) + video_target_format media_name_list.append(tar) tar = project_path + tar cmd = [ "ffmpeg", "-i", input_name, "-c:av", "copy", "-ss", str(t1), "-t", str(t2), "-y", tar ] subprocess_call(cmd) begin = current list.pop(-1) list.insert(0, 0) return media_name_list
def download_webfile(url, filename, overwrite=False): """ Small utility to download the file at 'url' under name 'filename'. If url is a youtube video ID like z410eauCnH it will download the video using youtube-dl (install youtube-dl first !). If the filename already exists and overwrite=False, nothing will happen. """ if os.path.exists(filename) and not overwrite: return if '.' in url: r = requests.get(url, stream=True) with open(filename, 'wb') as fd: for chunk in r.iter_content(chunk_size=128): fd.write(chunk) else: try: subprocess_call(['youtube-dl', url, '-o', filename]) except OSError as e: raise OSError( e.message + '\n A possible reason is that youtube-dl' ' is not installed on your computer. Install it with ' ' "pip install youtube_dl"')
def download_webfile(url, filename, overwrite=False): """ Small utility to download the file at 'url' under name 'filename'. If url is a youtube video ID like z410eauCnH it will download the video using youtube-dl (install youtube-dl first !). If the filename already exists and overwrite=False, nothing will happen. """ if os.path.exists(filename) and not overwrite: return if "." in url: r = requests.get(url, stream=True) with open(filename, "wb") as fd: for chunk in r.iter_content(chunk_size=128): fd.write(chunk) else: try: subprocess_call(["youtube-dl", url, "-o", filename]) except OSError as e: raise OSError( e.message + "\n A possible reason is that youtube-dl" " is not installed on your computer. Install it with " ' "pip install youtube_dl"')
def combine(scene_list, video_list, to_combine_list, fps, read): #function that allows the combine of two or more shots in one shot while len(to_combine_list) >= 2: index1 = video_list.index(to_combine_list[0]) index2 = video_list.index(to_combine_list[1]) if abs(index1 - index2) > 1: to_combine_list.pop(0) else: a = project_path + to_combine_list[0] b = project_path + to_combine_list[1] #regex reg = video_target_name + "(.+)\." num1 = re.search(reg, a).group(1) num2 = re.search(reg, b).group(1) target = video_path + video_target_name + str(num1) + "-" + str( num2) + video_target_format arg = '[0:v:0] [1:v:0] concat=n=2:v=1 [v]' cmd = [ "ffmpeg", "-i", a, "-i", b, "-filter_complex", arg, "-map", "[v]", "-y", project_path + target ] subprocess_call(cmd) video_list.pop(index2) video_list.pop(index1) video_list.insert(index1, target) to_combine_list.pop(0) to_combine_list.pop(0) to_combine_list.insert(0, target) #updating scene_list scene_list.pop(index2) update_scenes(scene_list, fps, read) return video_list
def _ffmpeg_extract_subclip(self, filename, t1, t2, targetname=None): """ makes a new video file playing video file ``filename`` between the times ``t1`` and ``t2``. :param filename: path of video file :type filename: str, required :param t1: time from where video to clip :type t1: float, required :param t2: time to which video to clip :type t2: float, required :param targetname: path where clipped file to be stored :type targetname: str, optional :return: None """ name, ext = os.path.splitext(filename) if not targetname: T1, T2 = [int(1000 * t) for t in [t1, t2]] targetname = name + "{0}SUB{1}_{2}.{3}".format(name, T1, T2, ext) cmd = [ get_setting("FFMPEG_BINARY"), "-y", "-i", filename, "-ss", "%0.2f" % t1, "-t", "%0.2f" % (t2 - t1), "-vcodec", "copy", "-acodec", "copy", targetname, ] subprocess_call(cmd, logger=None, errorprint=True)
def write_gif_with_tempfiles(clip, filename, fps=None, program='ImageMagick', opt="OptimizeTransparency", fuzz=1, verbose=True, loop=0, dispose=False, colors=None, tempfiles=False): """ Write the VideoClip to a GIF file. Converts a VideoClip into an animated GIF using ImageMagick or ffmpeg. Does the same as write_gif (see this one for more docstring), but writes every frame to a file instead of passing them in the RAM. Useful on computers with little RAM. """ fileName, fileExtension = os.path.splitext(filename) tt = np.arange(0, clip.duration, 1.0 / fps) tempfiles = [] verbose_print( verbose, "\nMoviePy: building GIF file %s\n" % filename + 40 * "-" + "\n") verbose_print(verbose, "Generating GIF frames.\n") total = int(clip.duration * fps) + 1 for i, t in tqdm(enumerate(tt), total=total): name = "%s_GIFTEMP%04d.png" % (fileName, i + 1) tempfiles.append(name) clip.save_frame(name, t, savemask=True) verbose_print(verbose, "Done generating GIF frames.\n") delay = int(100.0 / fps) if program == "ImageMagick": cmd = [ get_setting("IMAGEMAGICK_BINARY"), '-delay', '%d' % delay, "-dispose", "%d" % (2 if dispose else 1), "-loop", "%d" % loop, "%s_GIFTEMP*.png" % fileName, "-coalesce", "-layers", "%s" % opt, "-fuzz", "%02d" % fuzz + "%", ] + (["-colors", "%d" % colors] if colors is not None else []) + [filename] elif program == "ffmpeg": cmd = [ get_setting("FFMPEG_BINARY"), '-y', '-f', 'image2', '-r', str(fps), '-i', fileName + '_GIFTEMP%04d.png', '-r', str(fps), filename ] try: subprocess_call(cmd, verbose=verbose) except (IOError, OSError) as err: error = ("MoviePy Error: creation of %s failed because " "of the following error:\n\n%s.\n\n." % (filename, str(err))) if program == "ImageMagick": error = error + ( "This error can be due to the fact that " "ImageMagick is not installed on your computer, or " "(for Windows users) that you didn't specify the " "path to the ImageMagick binary in file conf.py.") raise IOError(error) for f in tempfiles: os.remove(f)
def __init__( self, text=None, filename=None, size=None, color="black", bg_color="transparent", font_size=None, font="Courier", stroke_color=None, stroke_width=1, method="label", kerning=None, align="center", interline=None, tempfilename=None, temptxt=None, transparent=True, remove_temp=True, print_cmd=False, ): if text is not None: if temptxt is None: temptxt_fd, temptxt = tempfile.mkstemp(suffix=".txt") try: # only in Python3 will this work os.write(temptxt_fd, bytes(text, "UTF8")) except TypeError: # oops, fall back to Python2 os.write(temptxt_fd, text) os.close(temptxt_fd) text = "@" + temptxt else: # use a file instead of a text. text = "@%" + filename if size is not None: size = ( "" if size[0] is None else str(size[0]), "" if size[1] is None else str(size[1]), ) cmd = [ IMAGEMAGICK_BINARY, "-background", bg_color, "-fill", color, "-font", font, ] if font_size is not None: cmd += ["-pointsize", "%d" % font_size] if kerning is not None: cmd += ["-kerning", "%0.1f" % kerning] if stroke_color is not None: cmd += [ "-stroke", stroke_color, "-strokewidth", "%.01f" % stroke_width ] if size is not None: cmd += ["-size", "%sx%s" % (size[0], size[1])] if align is not None: cmd += ["-gravity", align] if interline is not None: cmd += ["-interline-spacing", "%d" % interline] if tempfilename is None: tempfile_fd, tempfilename = tempfile.mkstemp(suffix=".png") os.close(tempfile_fd) cmd += [ "%s:%s" % (method, text), "-type", "truecolormatte", "PNG32:%s" % tempfilename, ] if print_cmd: print(" ".join(cmd)) try: subprocess_call(cmd, logger=None) except (IOError, OSError) as err: error = ( f"MoviePy Error: creation of {filename} failed because of the " f"following error:\n\n{err}.\n\n." "This error can be due to the fact that ImageMagick " "is not installed on your computer, or (for Windows " "users) that you didn't specify the path to the " "ImageMagick binary. Check the documentation.") raise IOError(error) ImageClip.__init__(self, tempfilename, transparent=transparent) self.text = text self.color = color self.stroke_color = stroke_color if remove_temp: if tempfilename is not None and os.path.exists(tempfilename): os.remove(tempfilename) if temptxt is not None and os.path.exists(temptxt): os.remove(temptxt)
def __init__(self, txt=None, filename=None, size=None, color='black', bg_color='transparent', fontsize=None, font='Courier', stroke_color=None, stroke_width=1, method='label', kerning=None, align='center', interline=None, tempfilename=None, temptxt=None, transparent=True, remove_temp=True, shadow=None, antialias=4, print_cmd=False): import tempfile import subprocess as sp from moviepy.tools import subprocess_call from moviepy.config import get_setting # from moviepy.video.VideoClip import * aa_factor= 1 if not antialias else antialias if txt is not None: if temptxt is None: temptxt_fd, temptxt = tempfile.mkstemp(suffix='.txt') try: # only in Python3 will this work os.write(temptxt_fd, bytes(txt, 'UTF8')) except TypeError: # oops, fall back to Python2 os.write(temptxt_fd, txt) os.close(temptxt_fd) txt = '@' + temptxt else: # use a file instead of a text. txt = "@%" + filename if size is not None: size = ('' if size[0] is None else size[0], '' if size[1] is None else size[1]) if shadow is not None: shadow = (80 if shadow[0] is None else shadow[0], 1 if shadow[1] is None else shadow[1], 2 if shadow[2] is None else shadow[2], 2 if shadow[3] is None else shadow[3]) cmd = ( [get_setting("IMAGEMAGICK_BINARY"), "-density", str(aa_scale(72, aa_factor)), "-background", bg_color, "-fill", color, "-font", font]) if fontsize is not None: cmd += ["-pointsize", "%d" % fontsize] if kerning is not None: cmd += ["-kerning", "%0.1f" % aa_scale(kerning, aa_factor)] if stroke_color is not None: cmd += ["-stroke", stroke_color, "-strokewidth", "%.01f" % aa_scale(stroke_width, aa_factor)] if size is not None: cmd += ["-size", "%sx%s" % aa_scale(size, aa_factor)] if align is not None: cmd += ["-gravity", align] if interline is not None: cmd += ["-interline-spacing", "%d" % interline] if tempfilename is None: tempfile_fd, tempfilename = tempfile.mkstemp(suffix='.png') os.close(tempfile_fd) if shadow is not None: shadow_cmd = ( ["(", "+clone", "-shadow", "%sx%s+%s+%s" % (tuple([shadow[0]]) + aa_scale(shadow[1:], aa_factor)), ")", "-compose", "DstOver", "-flatten"]) cmd += ["%s:%s" % (method, txt)] cmd += shadow_cmd cmd += ["-resample", "72"] cmd += ["-type", "truecolormatte", "PNG32:%s" % tempfilename] if print_cmd: print( " ".join(cmd) ) try: subprocess_call(cmd, verbose=verbose) except (IOError,OSError) as err: error = ("MoviePy Error: creation of %s failed because " "of the following error:\n\n%s.\n\n."%(filename, str(err)) + ("This error can be due to the fact that " "ImageMagick is not installed on your computer, or " "(for Windows users) that you didn't specify the " "path to the ImageMagick binary in file conf.py, or." "that the path you specified is incorrect" )) raise IOError(error) ImageClip.__init__(self, tempfilename, transparent=transparent) self.txt = txt self.color = color self.stroke_color = stroke_color if remove_temp: if os.path.exists(tempfilename): os.remove(tempfilename) if os.path.exists(temptxt): os.remove(temptxt)
def write_gif_with_tempfiles(clip, filename, fps=None, program= 'ImageMagick', opt="OptimizeTransparency", fuzz=1, verbose=True, loop=0, dispose=True, colors=None): """ Write the VideoClip to a GIF file. Converts a VideoClip into an animated GIF using ImageMagick or ffmpeg. Does the same as write_gif (see this one for more docstring), but writes every frame to a file instead of passing them in the RAM. Useful on computers with little RAM. """ fileName, fileExtension = os.path.splitext(filename) tt = np.arange(0,clip.duration, 1.0/fps) tempfiles = [] verbose_print(verbose, "\n[MoviePy] Building file %s\n"%filename +40*"-"+"\n") verbose_print(verbose, "[MoviePy] Generating GIF frames...\n") total = int(clip.duration*fps)+1 for i, t in tqdm(enumerate(tt), total=total): name = "%s_GIFTEMP%04d.png"%(fileName, i+1) tempfiles.append(name) clip.save_frame(name, t, withmask=True) delay = int(100.0/fps) if program == "ImageMagick": verbose_print(verbose, "[MoviePy] Optimizing GIF with ImageMagick... ") cmd = [get_setting("IMAGEMAGICK_BINARY"), '-delay' , '%d'%delay, "-dispose" ,"%d"%(2 if dispose else 1), "-loop" , "%d"%loop, "%s_GIFTEMP*.png"%fileName, "-coalesce", "-layers", "%s"%opt, "-fuzz", "%02d"%fuzz + "%", ]+(["-colors", "%d"%colors] if colors is not None else [])+[ filename] elif program == "ffmpeg": cmd = [get_setting("FFMPEG_BINARY"), '-y', '-f', 'image2', '-r',str(fps), '-i', fileName+'_GIFTEMP%04d.png', '-r',str(fps), filename] try: subprocess_call( cmd, verbose = verbose ) verbose_print(verbose, "[MoviePy] GIF %s is ready."%filename) except (IOError,OSError) as err: error = ("MoviePy Error: creation of %s failed because " "of the following error:\n\n%s.\n\n."%(filename, str(err))) if program == "ImageMagick": error = error + ("This error can be due to the fact that " "ImageMagick is not installed on your computer, or " "(for Windows users) that you didn't specify the " "path to the ImageMagick binary in file conf.py." ) raise IOError(error) for f in tempfiles: os.remove(f)
def ffmpeg_extract_audio(inputfile,output,bitrate=3000,fps=44100): """ extract the sound from a video file and save it in ``output`` """ cmd = ["ffmpeg", "-y", "-i", inputfile, "-ab", "%dk"%bitrate, "-ar", "%d"%fps, output] subprocess_call(cmd, stdin=None, stdout=None)
def ffmpeg_extract_audio(inputfile,output,bitrate=3000,fps=44100): """ extract the sound from a video file and save it in ``output`` """ cmd = [get_setting("FFMPEG_BINARY"), "-y", "-i", inputfile, "-ab", "%dk"%bitrate, "-ar", "%d"%fps, output] subprocess_call(cmd)
def to_gif(self, filename, fps=None, program= 'ImageMagick', opt="OptimizeTransparency", fuzz=1, verbose=True, loop=0, dispose=False): """ Write the VideoClip to a GIF file Converts a VideoClip into an animated GIF using ImageMagick or ffmpeg. Parameters ----------- filename Name of the resulting gif file. fps Number of frames per second (see note below). If it isn't provided, then the function will look for the clip's ``fps`` attribute (VideoFileClip, for instance, have one). program Software to use for the conversion, either 'ImageMagick' or 'ffmpeg'. opt (ImageMagick only) optimalization to apply, either 'optimizeplus' or 'OptimizeTransparency'. fuzz (ImageMagick only) Compresses the GIF by considering that the colors that are less than fuzz% different are in fact the same. Notes ----- The gif will be playing the clip in real time (you can only change the frame rate). If you want the gif to be played slower than the clip you will use :: >>> # slow down clip 50% and make it a gif >>> myClip.speedx(0.5).to_gif('myClip.gif') """ def verbose_print(s): if verbose: sys_write_flush(s) if fps is None: fps = self.fps fileName, fileExtension = os.path.splitext(filename) tt = np.arange(0,self.duration, 1.0/fps) tempfiles = [] verbose_print("\nMoviePy: building GIF file %s\n"%filename +40*"-"+"\n") verbose_print("Generating GIF frames.\n") total = int(self.duration/fps)+1 for i, t in tqdm(enumerate(tt), total=total): name = "%s_GIFTEMP%04d.png"%(fileName, i+1) tempfiles.append(name) self.save_frame(name, t, savemask=True) verbose_print("Done generating GIF frames.\n") delay = int(100.0/fps) if program == "ImageMagick": cmd = [IMAGEMAGICK_BINARY, '-delay' , '%d'%delay, "-dispose" ,"%d"%(2 if dispose else 1), "-loop" , "%d"%loop, "%s_GIFTEMP*.png"%fileName, "-coalesce", "-fuzz", "%02d"%fuzz + "%", "-layers", "%s"%opt, "%s"%filename] elif program == "ffmpeg": cmd = [FFMPEG_BINARY, '-y', '-f', 'image2', '-i', fileName+'_GIFTEMP%04d.png', '-r',str(fps), filename] subprocess_call( cmd, verbose = verbose ) for f in tempfiles: os.remove(f)
def __init__(self, txt, size=None, color='black', bg_color='transparent', fontsize=None, font='Courier', stroke_color=None, stroke_width=1, method='label', kerning=None, align='center', interline=None, tempfilename=None, temptxt=None, transparent=True, remove_temp=True, print_cmd=False): if not txt.startswith('@'): if temptxt is None: temptxt_fd, temptxt = tempfile.mkstemp(suffix='.txt') os.write(temptxt_fd, txt) os.close(temptxt_fd) txt = '@'+temptxt else: txt = "'%s'"%txt if size != None: size = ('' if size[0] is None else str(size[0]), '' if size[1] is None else str(size[1])) cmd = ( [IMAGEMAGICK_BINARY, "-background", bg_color, "-fill", color, "-font", font]) if fontsize !=None: cmd += ["-pointsize", "%d"%fontsize] if kerning != None: cmd += ["-kerning", "%0.1f"%kerning] if stroke_color != None: cmd += ["-stroke", stroke_color, "-strokewidth", "%.01f"%stroke_width] if size != None: cmd += ["-size", "%sx%s"%(size[0], size[1])] if align != None: cmd += ["-gravity",align] if interline != None: cmd += ["-interline-spacing", "%d"%interline] if tempfilename is None: tempfile_fd, tempfilename = tempfile.mkstemp(suffix='.png') os.close(tempfile_fd) cmd += ["%s:%s" %(method, txt), "-type", "truecolormatte", "PNG32:%s"%tempfilename] if print_cmd: print( " ".join(cmd) ) subprocess_call(cmd, verbose=False ) ImageClip.__init__(self, tempfilename, transparent=transparent) self.txt = txt self.color = color self.stroke_color = stroke_color if remove_temp: if os.path.exists(tempfilename): os.remove(tempfilename) if os.path.exists(temptxt): os.remove(temptxt)
def write_gif_with_tempfiles( clip, filename, fps=None, program="ImageMagick", opt="OptimizeTransparency", fuzz=1, loop=0, dispose=True, colors=None, logger="bar", pix_fmt=None, ): """Write the VideoClip to a GIF file. Converts a VideoClip into an animated GIF using ImageMagick or ffmpeg. Does the same as write_gif (see this one for more docstring), but writes every frame to a file instead of passing them in the RAM. Useful on computers with little RAM. """ logger = proglog.default_bar_logger(logger) fileName, ext = os.path.splitext(filename) tt = np.arange(0, clip.duration, 1.0 / fps) tempfiles = [] logger(message="MoviePy - Building file %s\n" % filename) logger(message="MoviePy - - Generating GIF frames") for i, t in logger.iter_bar(t=list(enumerate(tt))): name = "%s_GIFTEMP%04d.png" % (fileName, i + 1) tempfiles.append(name) clip.save_frame(name, t, withmask=True) delay = int(100.0 / fps) if clip.mask is None: withmask = False if program == "ImageMagick": if not pix_fmt: pix_fmt = "RGBA" if withmask else "RGB" logger(message="MoviePy - - Optimizing GIF with ImageMagick...") cmd = ([ IMAGEMAGICK_BINARY, "-delay", "%d" % delay, "-dispose", "%d" % (2 if dispose else 1), "-loop", "%d" % loop, "%s_GIFTEMP*.png" % fileName, "-coalesce", "-fuzz", "%02d" % fuzz + "%", "-layers", "%s" % opt, "-set", "colorspace", pix_fmt, ] + (["-colors", "%d" % colors] if colors is not None else []) + [filename]) elif program == "ffmpeg": if not pix_fmt: pix_fmt = "rgba" if withmask else "rgb24" cmd = [ FFMPEG_BINARY, "-y", "-f", "image2", "-r", str(fps), "-i", fileName + "_GIFTEMP%04d.png", "-r", str(fps), filename, "-pix_fmt", (pix_fmt), ] try: subprocess_call(cmd, logger=logger) logger(message="MoviePy - GIF ready: %s." % filename) except (IOError, OSError) as err: error = ("MoviePy Error: creation of %s failed because " "of the following error:\n\n%s.\n\n." % (filename, str(err))) if program == "ImageMagick": error += ( "This error can be due to the fact that " "ImageMagick is not installed on your computer, or " "(for Windows users) that you didn't specify the " "path to the ImageMagick binary. Check the documentation.") raise IOError(error) for f in tempfiles: os.remove(f)