async def main():
    playlists = glob("*.m3u")
    basePath = None
    coros = []

    for file in playlists:
        playlistObj = m3u8.load(file)
        if not playlistObj:
            continue

        for key in playlistObj.keys:
            if key and key.uri:
                basePath = '/'.join(key.uri.split('/')[:-1])

        if basePath:
            break

    for file in playlists:
        playlistObj = m3u8.load(file)
        if not playlistObj:
            continue

        playlistObj.base_path = basePath
        with open(file, "w") as f:
            f.write(playlistObj.dumps())

        ff = ffmpy3.FFmpeg(
            global_options="-protocol_whitelist file,http,https,tcp,tls,crypto",
            inputs={file: "-f hls"},
            outputs={splitext(file)[0] + ".mp3": None})

        coros.append(ff.run_async())

    await asyncio.gather(*coros)
Ejemplo n.º 2
0
def upload(request):
    if request.method == 'POST':
        obj = Video()
        obj.name = request.POST['name']
        obj.videofile = request.FILES['videofile']
        obj.save()
        print(str(obj.videofile))
        s = str(obj.videofile)

        g = os.path.join(settings.MEDIA_ROOT, s)

        ff = ffmpy3.FFmpeg(inputs={g: None},
                           outputs={'outpu11t.mp4': '-c:v hevc_nvenc'})
        ff.run_async()
        #await ff.wait()

        #  ff = ffmpy3.FFmpeg( inputs={'input.mp4': None},  outputs={'output.avi': None} )

        # stream = ffmpeg.input(g)
        # stream = ffmpeg.scale(stream)
        # stream = ffmpeg.output(stream, 'output2.mp4')
        # ffmpeg.run(stream)

        return HttpResponse("<h1>Hello</h1>")

    else:
        return render(request, 'index.html')
Ejemplo n.º 3
0
 def to_wave_with_subsampling(self, sample_rate):
     # HACK: wavを書き出さなくてもできる方法を探す
     ff = ffmpy3.FFmpeg(
         inputs={self.filename: None},
         outputs={SOUND_WAVE: '-ac 1 -ar %d' % sample_rate}
     )
     ff.run()
Ejemplo n.º 4
0
def download(name):
    try:
        print(name)
        print(video[name])
        ffmpy3.FFmpeg(inputs={video[name]: None}, outputs={path+name+'.mp4':None}).run()
    except:
        print('视频下载失败!')
Ejemplo n.º 5
0
def convert_video(page):
    print('convert_video executed')
    currentVideoPath = os.path.join(_DOWNLOAD_HOME, page.av.title, page.title)

    L = []
    root_dir = currentVideoPath

    for file in sorted(os.listdir(root_dir),
                       key=lambda x: int(x[x.rindex("-") + 1:x.rindex(".")])):
        if os.path.splitext(file)[1] == '.flv':
            L.append("file '{}'".format(os.path.join(root_dir, file)))

    tmp_file_path = os.path.join(root_dir, 'tmp.txt')
    tmp_file = open(tmp_file_path, 'w')

    for strs in L:
        tmp_file.write(strs + '\n')
    tmp_file.close()

    output = os.path.join(os.path.join(_DOWNLOAD_HOME, page.av.title),
                          page.title + '.flv')

    ff = ffmpy3.FFmpeg(
        inputs={tmp_file_path: '-f concat -safe 0'},
        outputs={output: '-c copy -y'},
    )

    ff.run()
    if os.path.exists(tmp_file_path):
        os.remove(tmp_file_path)
    print("complete")
Ejemplo n.º 6
0
async def main():
    input_filename = "video.gif"
    output_filename = "video_compat.mp4"

    null_output = os.devnull

    # Turn file into mp4
    ff = ffmpy3.FFmpeg(
        inputs={input_filename: None},
        outputs={output_filename: ffmpegoptions + " -crf " + str(crf)})
    await ff.run_async()
    await ff.wait()

    # If it's over the size limit, do a 2 pass encoding
    if os.path.getsize(output_filename) > limit:
        # Get video duration from ffprobe
        ffprobe = ffmpy3.FFprobe(
            global_options=["-v error"],
            inputs={
                output_filename:
                "-show_entries format=duration -of default=noprint_wrappers=1:nokey=1"
            })
        ffprobe_process = await ffprobe.run_async(
            stdout=asyncio.subprocess.PIPE)
        ffprobe_out = await ffprobe_process.communicate()
        await ffprobe.wait()
        duration = float(ffprobe_out[0].decode('utf-8').strip())
        # 2 pass run
        bitrate = targetsize / duration * 1000000 * 8
        ff1 = ffmpy3.FFmpeg(global_options=["-y"],
                            inputs={input_filename: None},
                            outputs={
                                null_output:
                                ffmpegoptions + " -b:v " + str(bitrate) +
                                " -pass 1 -f mp4"
                            })
        await ff1.run_async()
        await ff1.wait()
        ff2 = ffmpy3.FFmpeg(global_options=["-y"],
                            inputs={input_filename: None},
                            outputs={
                                output_filename:
                                ffmpegoptions + " -b:v " + str(bitrate) +
                                " -pass 2"
                            })
        await ff2.run_async()
        await ff2.wait()
Ejemplo n.º 7
0
def downVideo(url):
    num = search_res[url]
    name = os.path.join(video_dir, '第%03d集.mp4' % num)
    ffmpy3.FFmpeg(inputs={
        url: None
    }, outputs={
        name: None
    }).run()  #通过ffmpeg自动整合ts分段视频,并保存为mp4格式的视频
Ejemplo n.º 8
0
 def combine_ts(self):
     c_ts = 'combine_ts.ts'
     os.remove(c_ts)
     file_list = glob.glob('*.ts')
     file_list.sort()
     with open(c_ts, 'wb') as f:
         for i in file_list:
             f.write(open(i, 'rb').read())
     ffmpy3.FFmpeg(inputs={c_ts: None}, outputs={"combine.mp4": None}).run()
async def convert_to_mp3(input_filename, output_filename):
    print('start converting {}'.format(input_filename))
    ff = ffmpy3.FFmpeg(inputs={input_filename: None},
                       outputs={output_filename: None},
                       global_options=['-y'])
    await ff.run_async(stderr=asyncio.subprocess.PIPE)
    await ff.wait()
    print('sucessfully converting {} to mp3'.format(input_filename))
    os.remove(input_filename)
    return output_filename
Ejemplo n.º 10
0
def extractThumbnail(originalPath, thumbnailPath):
    time = 0.0
    metadata = FFProbe(originalPath)
    for stream in metadata.streams:
        if stream.is_video():
            time = stream.duration_seconds() / 2
    thumbnailTask = ffmpy3.FFmpeg(
        inputs={originalPath: None},
        outputs={thumbnailPath: '-y -ss %d -vframes 1 ' % (time)})
    thumbnailTask.run()
Ejemplo n.º 11
0
 def generate_m4as(self):
     print('Generating m4as')
     for node in self.todo['m4a']:
         node = node.split('.')[0]
         infile = os.path.join(ORIG, self.orig[node])
         outfile = os.path.join(COMPUTED, '{}.m4a'.format(node))
         ff = ffmpy3.FFmpeg(inputs={infile: None},
                            outputs={outfile: "-ar 44100"})
         ff.run()
     self.todo['m4a'] = []
Ejemplo n.º 12
0
    def getAudio(self, input_file, output_file_name):
        dir_path = os.path.join('.\\', self.outputh_path)
        if not os.path.isdir(dir_path):
            os.makedirs(dir_path)

        output_file = os.path.join(dir_path, output_file_name + '.ogg')
        ff = ffmpy3.FFmpeg(inputs={input_file: None},
                           outputs={output_file: ' -vn -f ogg -y'})
        # print(ff.cmd)
        ff.run()
Ejemplo n.º 13
0
 def generate_webms(self):
     print('Generating webms')
     for node in self.todo['webm']:
         node = node.split('.')[0]
         infile = os.path.join(ORIG, self.orig[node])
         outfile = os.path.join(COMPUTED, '{}.webm'.format(node))
         ff = ffmpy3.FFmpeg(inputs=od([(infile, None)]),
                            outputs={outfile: "-an -map 0:v -vf scale=640:360:force_original_aspect_ratio=decrease -b:v 900k -codec:v libvpx -auto-alt-ref 0"})
         ff.run()
     self.todo['webm'] = []
Ejemplo n.º 14
0
 def generate_mp4s(self):
     print('Generating mp4s')
     for node in self.todo['mp4']:
         node = node.split('.')[0]
         infile = os.path.join(ORIG, self.orig[node])
         outfile = os.path.join(COMPUTED, '{}.mp4'.format(node))
         ff = ffmpy3.FFmpeg(inputs=od([(infile, None)]),
                            outputs={outfile: "-an -map 0:v -vf scale=640:360:force_original_aspect_ratio=decrease -b:v 900k -movflags faststart"})
         ff.run()
         print('    {} generated'.format(outfile))
     self.todo['mp4'] = []
Ejemplo n.º 15
0
 def generate_pair_mp4s(self):
     print('Generating pair_mp4s')
     for leftright in self.todo['pair_mp4']:
         left, right = leftright.split('.')[0].split('-')
         lfilm = os.path.join(ORIG, self.orig[left])
         rfilm = os.path.join(ORIG, self.orig[right])
         outfile = os.path.join(COMPUTED, leftright)
         ff = ffmpy3.FFmpeg(inputs=od([(lfilm, None), (rfilm, None)]),
                            outputs={outfile: "-an -s 1280x360 -filter_complex {} -b:v 900k -movflags faststart".format(FILTER)})
         ff.run()
     self.todo['pair_mp4'] = []
Ejemplo n.º 16
0
 async def run(self):
     ff = ffmpy3.FFmpeg(global_options=self.global_options,
                        inputs=self.inputs,
                        outputs=self.outputs)
     ff_process = await ff.run_async(stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
     ff_out = await ff_process.communicate()
     await ff.wait()
     output = ff_out[0].decode('utf-8', errors="replace").strip()
     error = ff_out[1].decode('utf-8', errors="replace").strip()
     return output, error
Ejemplo n.º 17
0
def convert_file(song):
    initial_file = vid_dir + "/" + song
    final_file = audio_dir + "/" + song[:-4] + ".mp3"
    if (os.path.isfile(final_file)):  # avoid converting repeated files
        print("Already Converted " + song + ", skipping")
        return

    print("Converting: " + song)
    ff = ffmpy3.FFmpeg(inputs={initial_file: ["-y"]},
                       outputs={final_file: None})
    # print(ff.cmd)
    ff.run()
Ejemplo n.º 18
0
def download_video(video_url, file_name):
    ff = ffmpy3.FFmpeg(
        inputs={
            video_url:
            '-headers "User-Agent: (Windows NT 10.0; WOW64) PotPlayer/1.7.18495" -y'
        },
        outputs={
            file_name + str(uid) + time.strftime('%Y-%m-%d-%H-%M-%S') + '.flv':
            '-c copy'
        })
    print(ff.cmd)
    ff.run()
Ejemplo n.º 19
0
def main(myblob: func.InputStream, context: func.Context):
    logging.info(f"Python blob trigger function processed blob \n"
                 f"Name: {myblob.name}\n"
                 f"Blob Size: {myblob.length} bytes")

    file = open("input.mp4", "wb")
    file.write(myblob.read())
    file.close()
    ff = ffmpy3.FFmpeg(executable=context.function_directory + '/ffmpeg',
                       inputs={'input.mp4': None},
                       outputs={'output_%d.png': '-y -vf fps=1'})
    ff.run()
Ejemplo n.º 20
0
    def download_movie_by_ffmpeg(self, url):
        mName = ''
        for k in self.search_res:
            if k == url:
                index = self.search_res[k]
                mName = str("第%d集.mp4" % index)
                break

        print(mName + "-----" + url)
        ff = ffmpy3.FFmpeg(inputs={url: None},
                           outputs={os.getcwd() + "\\" + mName: None})
        ff.run()
Ejemplo n.º 21
0
def word2audio(client, word):
    result = client.synthesis(word, 'zh', 1, {'vol': 5, 'per': 3})

    # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
    if not isinstance(result, dict):
        with open('audio/audio.mp3', 'wb') as f:
            f.write(result)

    ff = ffmpy3.FFmpeg(executable='C:\\ffmpeg\\bin\\ffmpeg.exe',
                       inputs={'audio/audio.mp3': None},
                       outputs={'audio/audio.wav': None},
                       global_options='-y')
    ff.run()
Ejemplo n.º 22
0
def lambda_handler(event, context):
    print("Python S3 trigger fired.")

    with open('input.mp4', 'wb') as f:
        s3.download_file(event['Records'][0]['s3']['bucket']['name'],
                         event['Records'][0]['s3']['object']['name'], f)

    ff = ffmpy3.FFmpeg(executable='ffmpeg',
                       inputs={'input.mp4': None},
                       outputs={'output_%d.png': '-y -vf fps=1'})
    ff.run()

    return {'statusCode': 200, 'body': json.dumps('Created output file')}
Ejemplo n.º 23
0
def main():
    html = getSearchResult('鹿鼎记')
    video_name, video_link = parseBody(html)  # 默认返回第一个搜索结果
    video_piece_links = getVideoPicsLink(video_link)

    if os.path.exists(video_name):
        os.system("rm -r {}/".format(video_name))
    os.mkdir(video_name)

    num = 0
    for link in video_piece_links:
        num += 1
        ffmpy3.FFmpeg(inputs={link: None}, outputs={'%s/第%d集.mp4'%(video_name, num):None}).run()
Ejemplo n.º 24
0
    def snap(self, input_file, time_offset, file_name=None):
        dir_path = os.path.join('.\\', self.outputh_path)
        if not os.path.isdir(dir_path):
            os.makedirs(dir_path)

        if file_name == None:
            file_name = time_offset.replace(':', '_')

        output_file = os.path.join(dir_path, file_name + '.jpg')
        ff = ffmpy3.FFmpeg(
            inputs={input_file: '-ss ' + time_offset},
            outputs={output_file: ' -r 1 -vframes 1 -an -f mjpeg -y'})
        # print(ff.cmd)
        ff.run()
Ejemplo n.º 25
0
def changeFormat(inputs, outputsDir, format_):
    try:
        ff = ffmpy3.FFmpeg(
            inputs={inputs: None},
            outputs={
                outputsDir + "/" + extractNewFileName(inputs, format_): None
            })
        ff.run()
        return True
    except:
        return False


#print(changeFormat("F:/from youtube/أبونا فلتاؤس السريانى - بيعمل القهوة للاباء فى القلاية بنفسه.webm" , "F:" , "mp4"))
Ejemplo n.º 26
0
def video_download(name):  # 通过ffmpy3下载
    try:
        if os.path.exists(path + NAME + '/'):
            pass
        else:
            os.makedirs(path + NAME + '/')
        ffmpy3.FFmpeg(inputs={
            download[name]: None
        },
                      outputs={
                          path + NAME + '/' + name + '.mp4': None
                      }).run()
        print('************' + name + '下载成功!' + '************')
    except:
        print('============' + name + '下载失败!' + '============')
Ejemplo n.º 27
0
def KeyFrame(path, dest_path):
    # Get key frames of the film, using FFMPEG.
    # path: Path of the video
    # dest_path: The directory where you want to save the key frames.
    dest_path += '%04d.jpg'
    video = ffmpy3.FFmpeg(
        executable="ffmpeg.exe",
        inputs={path: '-hwaccel dxva2'},
        outputs={
            dest_path:
            '-vf select=\'eq(pict_type\,I)\' -vsync 2 -b:v 5M -s 1920*1080 -f image2'
        })
    print(video.cmd)
    video.run()
    return
Ejemplo n.º 28
0
def job04():
    input_path = 'input'
    input_filename = 'video.mp4'
    input_fullfilename = os.path.join(input_path, input_filename)
    cmd = [
        'ffmpeg', '-i', input_fullfilename, '-c:v', 'h264', '-f', 'h264',
        'pipe:1'
    ]
    input_process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    [input_data, input_err] = input_process.communicate(input=input_process)
    if input_err:
        sys.stderr.write(input_err + "\n")
        return
    print("Got %d Bytes of data" % len(input_data))

    # Simulate a stream buffer
    input_stream = io.BytesIO(input_data)

    time.sleep(0.5)

    # Initiate the FFMPEG Decode Process
    device_height = 1920
    device_width = 1080
    scaling_factor = 0.1
    s_height = int(device_height * scaling_factor)
    s_width = int(device_width * scaling_factor)
    rgb_size_frame = s_height * s_width * 3

    ff = ffmpy3.FFmpeg(
        inputs={'pipe:0': '-c:v h264 -f h264'},
        outputs={
            'pipe:1':
            '-c:v rawvideo -f rawvideo -an -sn -pix_fmt rgb24 -s {}x{}'.format(
                s_height, s_width)
        })

    stdout, stderr = ff.run(input_data=input_stream.read(),
                            stdout=subprocess.PIPE)
    #print(type(stdout))

    rgb_frames = []
    for i in range(0, len(stdout), rgb_size_frame):
        rgb_frame = stdout[i:rgb_size_frame]
        rgb_frames.append(rgb_frame)

    print("Total Frames %d" % len(rgb_frames))
Ejemplo n.º 29
0
    def trim_movie(self, begin_sec, end_sec):
        if end_sec - begin_sec > self.length_sec:
            sys.exit(1)
        else:
            length_sec = end_sec - begin_sec

        cmd1 = "-ss " + str(begin_sec)
        cmd2 = "-t " + str(length_sec)
        out_name = "trim_" + str(self.filename)

        remove_wav(out_name)

        fc = ffmpy3.FFmpeg(
            inputs={self.filename: cmd1},
            outputs={out_name: cmd2}
        )
        fc.run()
Ejemplo n.º 30
0
 def convert_dir(src_dir: AnyStr, dst_dir: AnyStr, file_ext: AnyStr):
     """
     Converts all files in the given directory (src_dir) with the
     output going to the given directory (dst_dir).
     :param src_dir:
         Source directory path.
     :param dst_dir:
         Destination directory path.
     :param file_ext:
         File type to convert all files to (should not include the `.`).
     """
     for file_name in os.listdir(src_dir):
         file_path = os.path.join(src_dir, file_name)
         new_file_path = os.path.join(
             dst_dir,
             os.path.splitext(file_name)[0] + '.' + file_ext)
         converter = ffmpy3.FFmpeg(inputs={file_path: None},
                                   outputs={new_file_path: None})
         converter.run()