Ejemplo n.º 1
0
    def get_size_ffmpeg(self, ffmpeg_path, fname):
        cmd = [ffmpeg_path, '-i', fname]
        # Windows and other OS buffer 4096 and ffmpeg can output more
        # than that.
        err_tmp = tempfile.TemporaryFile()
        ffmpeg = subprocess.Popen(cmd, stderr=err_tmp,
                                  stdout=subprocess.PIPE,
                                  stdin=subprocess.PIPE)

        # wait configured # of seconds: if ffmpeg is not back give up
        limit = config.getFFmpegWait()
        if limit:
            for i in xrange(limit * 20):
                time.sleep(.05)
                if not ffmpeg.poll() == None:
                    break

            if ffmpeg.poll() == None:
                kill(ffmpeg)
                return False, 'FFmpeg timed out'
        else:
            ffmpeg.wait()

        err_tmp.seek(0)
        output = err_tmp.read()
        err_tmp.close()

        x = ffmpeg_size.search(output)
        if x:
            width = int(x.group(1))
            height = int(x.group(2))
        else:
            return False, "Couldn't parse size"

        return True, (width, height)
Ejemplo n.º 2
0
    def get_size_ffmpeg(self, ffmpeg_path, fname):
        cmd = [ffmpeg_path, '-i', fname]
        # Windows and other OS buffer 4096 and ffmpeg can output more
        # than that.
        err_tmp = tempfile.TemporaryFile()
        ffmpeg = subprocess.Popen(cmd, stderr=err_tmp,
                                  stdout=subprocess.PIPE,
                                  stdin=subprocess.PIPE)

        # wait configured # of seconds: if ffmpeg is not back give up
        limit = config.getFFmpegWait()
        if limit:
            for i in xrange(limit * 20):
                time.sleep(.05)
                if not ffmpeg.poll() == None:
                    break

            if ffmpeg.poll() == None:
                kill(ffmpeg)
                return False, 'FFmpeg timed out'
        else:
            ffmpeg.wait()

        err_tmp.seek(0)
        output = err_tmp.read()
        err_tmp.close()

        x = ffmpeg_size.search(output)
        if x:
            width = int(x.group(1))
            height = int(x.group(2))
        else:
            return False, "Couldn't parse size"

        return True, (width, height)
Ejemplo n.º 3
0
    def send_file(self, handler, path, query):
        seek = int(query.get('Seek', [0])[0])
        duration = int(query.get('Duration', [0])[0])
        always = (handler.container.getboolean('force_ffmpeg')
                  and config.get_bin('ffmpeg'))
        fname = unicode(path, 'utf-8')

        ext = os.path.splitext(fname)[1].lower()
        needs_transcode = ext in TRANSCODE or seek or duration or always

        if not needs_transcode:
            fsize = os.path.getsize(fname)
            handler.send_response(200)
            handler.send_header('Content-Length', fsize)
        else:
            handler.send_response(206)
            handler.send_header('Transfer-Encoding', 'chunked')
        handler.send_header('Content-Type', 'audio/mpeg')
        handler.end_headers()

        if needs_transcode:
            if mswindows:
                fname = fname.encode('cp1252')

            cmd = [config.get_bin('ffmpeg'), '-i', fname, '-vn']
            if ext in ['.mp3', '.mp2']:
                cmd += ['-acodec', 'copy']
            else:
                cmd += ['-ab', '320k', '-ar', '44100']
            cmd += ['-f', 'mp3', '-']
            if seek:
                cmd[-1:] = ['-ss', '%.3f' % (seek / 1000.0), '-']
            if duration:
                cmd[-1:] = ['-t', '%.3f' % (duration / 1000.0), '-']

            ffmpeg = subprocess.Popen(cmd,
                                      bufsize=BLOCKSIZE,
                                      stdout=subprocess.PIPE)
            while True:
                try:
                    block = ffmpeg.stdout.read(BLOCKSIZE)
                    handler.wfile.write('%x\r\n' % len(block))
                    handler.wfile.write(block)
                    handler.wfile.write('\r\n')
                except Exception, msg:
                    handler.server.logger.info(msg)
                    kill(ffmpeg)
                    break

                if not block:
                    break
Ejemplo n.º 4
0
    def send_file(self, handler, path, query):
        seek = int(query.get('Seek', [0])[0])
        duration = int(query.get('Duration', [0])[0])
        always = (handler.container.getboolean('force_ffmpeg') and
                  config.get_bin('ffmpeg'))
        fname = unicode(path, 'utf-8')

        ext = os.path.splitext(fname)[1].lower()
        needs_transcode = ext in TRANSCODE or seek or duration or always

        if not needs_transcode:
            fsize = os.path.getsize(fname)
            handler.send_response(200)
            handler.send_header('Content-Length', fsize)
        else:
            handler.send_response(206)
            handler.send_header('Transfer-Encoding', 'chunked')
        handler.send_header('Content-Type', 'audio/mpeg')
        handler.end_headers()

        if needs_transcode:
            if mswindows:
                fname = fname.encode('iso8859-1')

            cmd = [config.get_bin('ffmpeg'), '-i', fname, '-vn']
            if ext in ['.mp3', '.mp2']:
                cmd += ['-acodec', 'copy']
            else:
                cmd += ['-ab', '320k', '-ar', '44100']
            cmd += ['-f', 'mp3', '-']
            if seek:
                cmd[-1:] = ['-ss', '%.3f' % (seek / 1000.0), '-']
            if duration:
                cmd[-1:] = ['-t', '%.3f' % (duration / 1000.0), '-']

            ffmpeg = subprocess.Popen(cmd, bufsize=BLOCKSIZE,
                                      stdout=subprocess.PIPE)
            while True:
                try:
                    block = ffmpeg.stdout.read(BLOCKSIZE)
                    handler.wfile.write('%x\r\n' % len(block))
                    handler.wfile.write(block)
                    handler.wfile.write('\r\n')
                except Exception, msg:
                    handler.server.logger.info(msg)
                    kill(ffmpeg)
                    break

                if not block:
                    break
Ejemplo n.º 5
0
    def send_file(self, handler, container, name):
        seek, duration = 0, 0

        try:
            path, query = handler.path.split('?')
        except ValueError:
            path = handler.path
        else:
            opts = cgi.parse_qs(query)
            if 'Seek' in opts:
                seek = int(opts['Seek'][0])
            if 'Duration' in opts:
                seek = int(opts['Duration'][0])

        fname = os.path.join(os.path.normpath(container['path']),
                             unquote(path)[len(name) + 2:])
        fname = unicode(fname, 'utf-8')

        needs_transcode = os.path.splitext(fname)[1].lower() in TRANSCODE \
                          or seek or duration

        handler.send_response(200)
        handler.send_header('Content-Type', 'audio/mpeg')
        if not needs_transcode:
            fsize = os.path.getsize(fname)
            handler.send_header('Content-Length', fsize)
        handler.send_header('Connection', 'close')
        handler.end_headers()

        if needs_transcode:
            if mswindows:
                fname = fname.encode('iso8859-1')
            cmd = [ffmpeg_path(), '-i', fname, '-acodec', 'libmp3lame', '-ab', 
                   '320k', '-ar', '44100', '-f', 'mp3', '-']
            if seek:
                cmd[-1:] = ['-ss', '%.3f' % (seek / 1000.0), '-']
            if duration:
                cmd[-1:] = ['-t', '%.3f' % (duration / 1000.0), '-']

            ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE)
            try:
                shutil.copyfileobj(ffmpeg.stdout, handler.wfile)
            except:
                kill(ffmpeg.pid)
        else:
            f = file(fname, 'rb')
            try:
                shutil.copyfileobj(f, handler.wfile)
            except:
                pass
Ejemplo n.º 6
0
    def send_file(self, handler, path, query):
        seek = int(query.get('Seek', [0])[0])
        duration = int(query.get('Duration', [0])[0])
        always = (handler.container.get('force_ffmpeg', 'False').lower()
                  == 'true' and config.get_bin('ffmpeg'))
        fname = unicode(path, 'utf-8')

        ext = os.path.splitext(fname)[1].lower()
        needs_transcode = ext in TRANSCODE or seek or duration or always

        handler.send_response(200)
        handler.send_header('Content-Type', 'audio/mpeg')
        if not needs_transcode:
            fsize = os.path.getsize(fname)
            handler.send_header('Content-Length', fsize)
        handler.send_header('Connection', 'close')
        handler.end_headers()

        if needs_transcode:
            if mswindows:
                fname = fname.encode('iso8859-1')

            cmd = [config.get_bin('ffmpeg'), '-i', fname]
            if ext in ['.mp3', '.mp2']:
                cmd += ['-acodec', 'copy']
            else:
                cmd += ['-ab', '320k', '-ar', '44100']
            cmd += ['-f', 'mp3', '-']
            if seek:
                cmd[-1:] = ['-ss', '%.3f' % (seek / 1000.0), '-']
            if duration:
                cmd[-1:] = ['-t', '%.3f' % (duration / 1000.0), '-']

            ffmpeg = subprocess.Popen(cmd,
                                      bufsize=(64 * 1024),
                                      stdout=subprocess.PIPE)
            try:
                shutil.copyfileobj(ffmpeg.stdout, handler.wfile)
            except:
                kill(ffmpeg)
        else:
            f = open(fname, 'rb')
            try:
                shutil.copyfileobj(f, handler.wfile)
            except:
                pass
            f.close()
Ejemplo n.º 7
0
    def send_file(self, handler, container, name):
        seek, duration = 0, 0

        try:
            path, query = handler.path.split("?")
        except ValueError:
            path = handler.path
        else:
            opts = cgi.parse_qs(query)
            if "Seek" in opts:
                seek = int(opts["Seek"][0])
            if "Duration" in opts:
                seek = int(opts["Duration"][0])

        fname = os.path.join(os.path.normpath(container["path"]), unquote(path)[len(name) + 2 :])
        fname = unicode(fname, "utf-8")

        needs_transcode = os.path.splitext(fname)[1].lower() in TRANSCODE or seek or duration

        handler.send_response(200)
        handler.send_header("Content-Type", "audio/mpeg")
        if not needs_transcode:
            fsize = os.path.getsize(fname)
            handler.send_header("Content-Length", fsize)
        handler.send_header("Connection", "close")
        handler.end_headers()

        if needs_transcode:
            if mswindows:
                fname = fname.encode("iso8859-1")
            cmd = [ffmpeg_path(), "-i", fname, "-acodec", "libmp3lame", "-ab", "320k", "-ar", "44100", "-f", "mp3", "-"]
            if seek:
                cmd[-1:] = ["-ss", "%.3f" % (seek / 1000.0), "-"]
            if duration:
                cmd[-1:] = ["-t", "%.3f" % (duration / 1000.0), "-"]

            ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE)
            try:
                shutil.copyfileobj(ffmpeg.stdout, handler.wfile)
            except:
                kill(ffmpeg.pid)
        else:
            f = file(fname, "rb")
            try:
                shutil.copyfileobj(f, handler.wfile)
            except:
                pass
Ejemplo n.º 8
0
    def send_file(self, handler, path, query):
        seek = int(query.get('Seek', [0])[0])
        duration = int(query.get('Duration', [0])[0])
        always = (handler.container.get('force_ffmpeg',
                  'False').lower() == 'true' and config.get_bin('ffmpeg'))
        fname = unicode(path, 'utf-8')

        ext = os.path.splitext(fname)[1].lower()
        needs_transcode = ext in TRANSCODE or seek or duration or always

        handler.send_response(200)
        handler.send_header('Content-Type', 'audio/mpeg')
        if not needs_transcode:
            fsize = os.path.getsize(fname)
            handler.send_header('Content-Length', fsize)
        handler.send_header('Connection', 'close')
        handler.end_headers()

        if needs_transcode:
            if mswindows:
                fname = fname.encode('iso8859-1')

            cmd = [config.get_bin('ffmpeg'), '-i', fname]
            if ext in ['.mp3', '.mp2']:
                cmd += ['-acodec', 'copy']
            else:
                cmd += ['-ab', '320k', '-ar', '44100']
            cmd += ['-f', 'mp3', '-']
            if seek:
                cmd[-1:] = ['-ss', '%.3f' % (seek / 1000.0), '-']
            if duration:
                cmd[-1:] = ['-t', '%.3f' % (duration / 1000.0), '-']

            ffmpeg = subprocess.Popen(cmd, bufsize=(64 * 1024),
                                      stdout=subprocess.PIPE)
            try:
                shutil.copyfileobj(ffmpeg.stdout, handler.wfile)
            except:
                kill(ffmpeg)
        else:
            f = open(fname, 'rb')
            try:
                shutil.copyfileobj(f, handler.wfile)
            except:
                pass
            f.close()
Ejemplo n.º 9
0
    def send_file(self, handler, path, query):
        logger.debug('send_file entered...')
        seek = int(query.get('Seek', [0])[0])
        duration = int(query.get('Duration', [0])[0])
        always = (handler.container.getboolean('force_ffmpeg') and
                  config.get_bin('ffmpeg'))
        fname = path

        ext = os.path.splitext(fname)[1].lower()
        needs_transcode = ext in TRANSCODE or seek or duration or always

        if not needs_transcode:
            fsize = os.path.getsize(fname)
            handler.send_response(200)
            handler.send_header('Content-Length', fsize)
        else:
            # use chunked transfer-encoding to send transcoded data as we get it
            # see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding
            handler.send_response(206)
            handler.send_header('Transfer-Encoding', 'chunked')
        handler.send_header('Content-Type', 'audio/mpeg')
        handler.end_headers()

        if needs_transcode:
            cmd = [config.get_bin('ffmpeg'), '-hide_banner', '-nostdin', '-i', fname, '-vn']
            if ext in ['.mp3', '.mp2']:
                cmd += ['-acodec', 'copy']
            else:
                cmd += ['-ab', '320k', '-ar', '44100']
            cmd += ['-f', 'mp3', '-']
            if seek:
                cmd[-1:] = ['-ss', '%.3f' % (seek / 1000.0), '-']
            if duration:
                cmd[-1:] = ['-t', '%.3f' % (duration / 1000.0), '-']

            logger.debug('start process: {}'.format(cmd))
            ffmpeg = subprocess.Popen(cmd, bufsize=BLOCKSIZE,
                                      stdout=subprocess.PIPE)
            while True:
                try:
                    block = ffmpeg.stdout.read(BLOCKSIZE)
                    handler.wfile.write(b'%x\r\n' % len(block))
                    handler.wfile.write(block)
                    handler.wfile.write(b'\r\n')
                except Exception as msg:
                    handler.server.logger.info(msg)
                    kill(ffmpeg)
                    break

                if not block:
                    break
        else:
            f = open(fname, 'rb')
            try:
                shutil.copyfileobj(f, handler.wfile)
            except:
                pass
            f.close()

        try:
            handler.wfile.flush()
        except Exception as msg:
            handler.server.logger.info(msg)
Ejemplo n.º 10
0
    def get_image_ffmpeg(self, path, width, height, pshape, rot, attrs):
        ffmpeg_path = config.get_bin('ffmpeg')
        if not ffmpeg_path:
            return False, 'FFmpeg not found'

        fname = unicode(path, 'utf-8')
        if sys.platform == 'win32':
            fname = fname.encode('iso8859-1')

        if attrs and 'size' in attrs:
            result = attrs['size']
        else:
            status, result = self.get_size_ffmpeg(ffmpeg_path, fname)
            if not status:
                return False, result
            if attrs:
                attrs['size'] = result

        if rot in (90, 270):
            oldh, oldw = result
        else:
            oldw, oldh = result

        width, height = self.new_size(oldw, oldh, width, height, pshape)

        if rot == 270:
            filters = 'transpose=1,'
        elif rot == 180:
            filters = 'hflip,vflip,'
        elif rot == 90:
            filters = 'transpose=2,'
        else:
            filters = ''

        filters += 'format=yuvj420p,'

        neww, newh = oldw, oldh
        while (neww / width >= 50) or (newh / height >= 50):
            neww /= 2
            newh /= 2
            filters += 'scale=%d:%d,' % (neww, newh)

        filters += 'scale=%d:%d' % (width, height)

        cmd = [ffmpeg_path, '-i', fname, '-vf', filters, '-f', 'mjpeg', '-']
        jpeg_tmp = tempfile.TemporaryFile()
        ffmpeg = subprocess.Popen(cmd, stdout=jpeg_tmp,
                                  stdin=subprocess.PIPE)

        # wait configured # of seconds: if ffmpeg is not back give up
        limit = config.getFFmpegWait()
        if limit:
            for i in xrange(limit * 20):
                time.sleep(.05)
                if not ffmpeg.poll() == None:
                    break

            if ffmpeg.poll() == None:
                kill(ffmpeg)
                return False, 'FFmpeg timed out'
        else:
            ffmpeg.wait()

        jpeg_tmp.seek(0)
        output = jpeg_tmp.read()
        jpeg_tmp.close()

        if 'JFIF' not in output[:10]:
            output = output[:2] + JFIF_TAG + output[2:]

        return True, output
Ejemplo n.º 11
0
    def get_image_ffmpeg(self, path, width, height, pshape, rot, attrs):
        ffmpeg_path = config.get_bin('ffmpeg')
        if not ffmpeg_path:
            return False, 'FFmpeg not found'

        fname = unicode(path, 'utf-8')
        if sys.platform == 'win32':
            fname = fname.encode('cp1252')

        if attrs and 'size' in attrs:
            result = attrs['size']
        else:
            status, result = self.get_size_ffmpeg(ffmpeg_path, fname)
            if not status:
                return False, result
            if attrs:
                attrs['size'] = result

        if rot in (90, 270):
            oldh, oldw = result
        else:
            oldw, oldh = result

        width, height = self.new_size(oldw, oldh, width, height, pshape)

        if rot == 270:
            filters = 'transpose=1,'
        elif rot == 180:
            filters = 'hflip,vflip,'
        elif rot == 90:
            filters = 'transpose=2,'
        else:
            filters = ''

        filters += 'format=yuvj420p,'

        neww, newh = oldw, oldh
        while (neww / width >= 50) or (newh / height >= 50):
            neww /= 2
            newh /= 2
            filters += 'scale=%d:%d,' % (neww, newh)

        filters += 'scale=%d:%d' % (width, height)

        cmd = [ffmpeg_path, '-i', fname, '-vf', filters, '-f', 'mjpeg', '-']
        jpeg_tmp = tempfile.TemporaryFile()
        ffmpeg = subprocess.Popen(cmd, stdout=jpeg_tmp,
                                  stdin=subprocess.PIPE)

        # wait configured # of seconds: if ffmpeg is not back give up
        limit = config.getFFmpegWait()
        if limit:
            for i in xrange(limit * 20):
                time.sleep(.05)
                if not ffmpeg.poll() == None:
                    break

            if ffmpeg.poll() == None:
                kill(ffmpeg)
                return False, 'FFmpeg timed out'
        else:
            ffmpeg.wait()

        jpeg_tmp.seek(0)
        output = jpeg_tmp.read()
        jpeg_tmp.close()

        if 'JFIF' not in output[:10]:
            output = output[:2] + JFIF_TAG + output[2:]

        return True, output