python - 使用 derolf/transcoder 进行动态转码

标签 python html ffmpeg video.js transcoding

https://github.com/derolf/transcoder

我需要在我的项目中本地转码和本地播放,没有其他外部连接到服务器。
它是 ffmpeg 进行动态转码的一个很好的来源。

就我而言,我必须将其转码为 mp4,因为它可以执行得更快。
但是我遇到了以下问题,我需要一些帮助来解决它。

----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 34089)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 593, in process_request_thread
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__
    self.finish()
  File "/usr/lib/python2.7/SocketServer.py", line 710, in finish
    self.wfile.close()
  File "/usr/lib/python2.7/socket.py", line 279, in close
    self.flush()
  File "/usr/lib/python2.7/socket.py", line 303, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe

这是我的代码:
服务器.py
    from flask import Flask, request, Response, abort, send_file, jsonify
import os, subprocess, re
import config

app = Flask(__name__)

@app.route('/media/<path:path>.js')
def media_content_js(path):
    d= os.path.abspath( os.path.join( config.media_folder, path ) )
    print d
    if not os.path.isfile( d ): abort(404)
    cmdline= list()
    cmdline.append( config.ffmpeg )
    cmdline.append( "-i" )
    cmdline.append( d );
    print cmdline
    duration= -1
    FNULL = open(os.devnull, 'w')
    proc= subprocess.Popen( cmdline, stderr=subprocess.PIPE, stdout=FNULL )
    try:
        for line in iter(proc.stderr.readline,''):
            line= line.rstrip()
            #Duration: 00:00:45.13, start: 0.000000, bitrate: 302 kb/s
            m = re.search('Duration: (..):(..):(..)\...', line)
            if m is not None: duration= int(m.group(1)) * 3600 + int(m.group(2)) * 60 + int(m.group(3)) + 1
    finally:
        proc.kill()

    return jsonify(duration=duration)

@app.route('/media/<path:path>.mp4')
def media_content_ogv(path):
    d= os.path.abspath( os.path.join( config.media_folder, path ) )
    print d
    if not os.path.isfile( d ): abort(404)
    start= request.args.get("start") or 0
    print start
    def generate():
        cmdline= list()
        cmdline.append( config.ffmpeg )
        cmdline.append( "-i" )
        cmdline.append( d );
        cmdline.append( "-ss" )
        cmdline.append( str(start) );
        cmdline.extend( config.ffmpeg_args )
        print cmdline
        FNULL = open(os.devnull, 'w')
        proc= subprocess.Popen( cmdline, stdout=subprocess.PIPE, stderr=FNULL )
        try:
            f= proc.stdout
            byte = f.read(512)
            while byte:
                yield byte
                byte = f.read(512)
        finally:
            proc.kill()

    return Response(response=generate(),status=200,mimetype='video/mp4',headers={'Access-Control-Allow-Origin': '*', "Content-Type":"video/mp4","Content-Disposition":"inline","Content-Transfer-Enconding":"binary"})

@app.route('/', defaults={"path":"index.html"})
@app.route('/<path:path>')
def static_content(path):
    d= os.path.abspath( os.path.join( config.static_folder, path ) )
    if not os.path.isfile( d ): abort(404)
    return send_file( d )

app.run( host="0.0.0.0",port=config.port, threaded=True, debug=True )

配置文件
media_folder=   "media"
static_folder=  "static"
port=       8123
ffmpeg=     "/usr/bin/ffmpeg"

ffmpeg_args=    [ "-f", "avi" ,"-acodec", "libfdk_aac", "-b:a", "128k", "-vcodec", "libx264", "-b:v", "1200k" , "-flags" , "+aic+mv4", "pipe:1"]

索引.html
<!DOCTYPE html>
<html>
<head>
    <link href="http:////vjs.zencdn.net/4.5/video-js.css" rel="stylesheet">
    <script src="http://vjs.zencdn.net/4.5/video.js"></script>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
    <video id="video" class="video-js vjs-default-skin" controls preload="auto" width="640" height="264">
    </video>
    <script>
        var video= videojs('video');
        video.src("media/testavi.avi.mp4");

        // hack duration
        video.duration= function() { return video.theDuration; };
        video.start= 0;
        video.oldCurrentTime= video.currentTime;
        video.currentTime= function(time) 
        { 
            if( time == undefined )
            {
                return video.oldCurrentTime() + video.start;
            }
            console.log(time)
            video.start= time;
            video.oldCurrentTime(0);
            video.src("media/testavi.avi.mp4?start=" + time);
            video.play();
            return this;
        };

        $.getJSON( "media/testavi.avi.js", function( data ) 
        {
            video.theDuration= data.duration;
        });
    </script>
</body>

最佳答案

我也遇到过一些问题,解决方案是使用 shell 调用 ffmpeg。为什么?因为 FFmpeg 没有输入参数,所以它有参数。

我使用以下代码在 python 中转码:

import subprocess

ffmpeg_pipe="ffmpeg -i fileinput -vcodec libx264 out.mp4"

pid = subprocess.Popen(ffmpeg_pipe, shell=True).pid

关于python - 使用 derolf/transcoder 进行动态转码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32439242/

相关文章:

python - 使用 Python 将视频转换为单独的帧而不使用 ffmpeg?

Python argparse 多个元变量名称

python - 是否有类似 wbo 的 Python SAT 求解器?

python - 如何使用 Python for osx 或 macos 获取用户登录/注销时间

html - 最大限度。文本行数;这种方法可靠吗?

android - Cordova 应用程序图片和布局在某些设备中拉伸(stretch),特别是 Samsung galaxy S4

python - 固定代码以制作三角形

html - 嵌套 div 和类的 css

ios - iOS 中的 CGImage 渲染

batch-file - FFMPEG - 我正在尝试使用 ffmpeg 选择文件夹中的所有 .mp4 文件,并以文件名作为图像名称对其进行截图