VideoHelp 操作模块

# -*- coding: utf-8 -*-
# !/usr/bin/env python
# Software: PyCharm
# __author__ == "YU HAIPENG"
# fileName: VideoHelp.py
# Month: 五月
# time: 2021/5/22 17:06
"""
https://ffmpeg.org/ffmpeg-filters.html 文档
https://blog.csdn.net/weixin_42081389/article/details/100543007
ffmpeg -y -i 待转换mp4文件路径 -vcodec copy -acodec copy -vbsf h264_mp4toannexb 目标ts文件
ffmpeg -i 待转换ts文件路径 -c copy -map 0 -f segment -segment_list 目标m3u8文件 -segment_time 单个切片时长 目标ts切片文件名称

通用选项
    -L license

    -h 帮助

    -fromats 显示可用的格式,编解码的,协议的。。。

    -f fmt 强迫采用格式fmt

    -I filename 输入文件

    -y 覆盖输出文件

    -t duration 设置纪录时间 hh:mm:ss[.xxx]格式的记录时间也支持

    -ss position 搜索到指定的时间 [-]hh:mm:ss[.xxx]的格式也支持

    -title string 设置标题

    -author string 设置作者

    -copyright string 设置版权

    -comment string 设置评论

    -target type 设置目标文件类型(vcd,svcd,dvd) 所有的格式选项(比特率,编解码以及缓冲区大小)自动设置 ,只需要输入如下的就可以了:
    ffmpeg -i myfile.avi -target vcd /tmp/vcd.mpg

    -hq 激活高质量设置

    -itsoffset offset 设置以秒为基准的时间偏移,该选项影响所有后面的输入文件。
        该偏移被加到输入文件的时戳,定义一个正偏移意味着相应的流被延迟了 offset秒。 [-]hh:mm:ss[.xxx]的格式也支持

视频选项
    -b bitrate 设置比特率,缺省200kb/s

    -r fps 设置帧频 缺省25

    -s size 设置帧大小 格式为WXH 缺省160X128.下面的简写也可以直接使用:
    Sqcif 128X96 qcif 176X144 cif 252X288 4cif 704X576

    -aspect aspect 设置横纵比 4:3 16:9 或 1.3333 1.7777

    -croptop size 设置顶部切除带大小 像素单位

    -cropbottom size –cropleft size –cropright size

    -padtop size 设置顶部补齐的大小 像素单位

    -padbottom size –padleft size –padright size –padcolor color 设置补齐条颜色(hex,6个16进制的数,红:绿:兰排列,比如 000000代表黑色)

    -vn 不做视频记录

    -bt tolerance 设置视频码率容忍度kbit/s

    -maxrate bitrate设置最大视频码率容忍度

    -minrate bitreate 设置最小视频码率容忍度

    -bufsize size 设置码率控制缓冲区大小

    -vcodec codec 强制使用codec编解码方式。 如果用copy表示原始编解码数据必须被拷贝。

    -sameq 使用同样视频质量作为源(VBR)

    -pass n 选择处理遍数(1或者2)。两遍编码非常有用。第一遍生成统计信息,第二遍生成精确的请求的码率

    -passlogfile file 选择两遍的纪录文件名为file

高级视频选项
    -g gop_size 设置图像组大小

    -intra 仅适用帧内编码

    -qscale q 使用固定的视频量化标度(VBR)

    -qmin q 最小视频量化标度(VBR)

    -qmax q 最大视频量化标度(VBR)

    -qdiff q 量化标度间最大偏差 (VBR)

    -qblur blur 视频量化标度柔化(VBR)

    -qcomp compression 视频量化标度压缩(VBR)

    -rc_init_cplx complexity 一遍编码的初始复杂度

    -b_qfactor factor 在p和b帧间的qp因子

    -i_qfactor factor 在p和i帧间的qp因子

    -b_qoffset offset 在p和b帧间的qp偏差

    -i_qoffset offset 在p和i帧间的qp偏差

    -rc_eq equation 设置码率控制方程 默认tex^qComp

    -rc_override override 特定间隔下的速率控制重载

    -me method 设置运动估计的方法 可用方法有 zero phods log x1 epzs(缺省) full

    -dct_algo algo 设置dct的算法 可用的有 0 FF_DCT_AUTO 缺省的DCT 1 FF_DCT_FASTINT 2 FF_DCT_INT 3 FF_DCT_MMX 4 FF_DCT_MLIB 5 FF_DCT_ALTIVEC

    -idct_algo algo 设置idct算法。可用的有 0 FF_IDCT_AUTO 缺省的IDCT 1 FF_IDCT_INT 2 FF_IDCT_SIMPLE 3 FF_IDCT_SIMPLEMMX 4 FF_IDCT_LIBMPEG2MMX 5 FF_IDCT_PS2 6 FF_IDCT_MLIB 7 FF_IDCT_ARM 8 FF_IDCT_ALTIVEC 9 FF_IDCT_SH4 10 FF_IDCT_SIMPLEARM

    -er n 设置错误残留为n 1 FF_ER_CAREFULL 缺省 2 FF_ER_COMPLIANT 3 FF_ER_AGGRESSIVE 4 FF_ER_VERY_AGGRESSIVE

    -ec bit_mask 设置错误掩蔽为bit_mask,该值为如下值的位掩码 1 FF_EC_GUESS_MVS (default=enabled) 2 FF_EC_DEBLOCK (default=enabled)

    -bf frames 使用frames B 帧,支持mpeg1,mpeg2,mpeg4

    -mbd mode 宏块决策 0 FF_MB_DECISION_SIMPLE 使用mb_cmp 1 FF_MB_DECISION_BITS 2 FF_MB_DECISION_RD

    -4mv 使用4个运动矢量 仅用于mpeg4

    -part 使用数据划分 仅用于mpeg4

    -bug param 绕过没有被自动监测到编码器的问题

    -strict strictness 跟标准的严格性

    -aic 使能高级帧内编码 h263+

    -umv 使能无限运动矢量 h263+

    -deinterlace 不采用交织方法

    -interlace 强迫交织法编码 仅对mpeg2和mpeg4有效。当你的输入是交织的并且你想要保持交织以最小图像损失的时候采用该选项。可选的方法是不交织,但是损失更大

    -psnr 计算压缩帧的psnr

    -vstats 输出视频编码统计到vstats_hhmmss.log

    -vhook module 插入视频处理模块 module 包括了模块名和参数,用空格分开

音频选项
    -ab bitrate 设置音频码率

    -ar freq 设置音频采样率

    -ac channels 设置通道 缺省为1

    -an 不使能音频纪录

    -acodec codec 使用codec编解码
音频/视频捕获选项
    -vd device 设置视频捕获设备。比如/dev/video0

    -vc channel 设置视频捕获通道 DV1394专用

    -tvstd standard 设置电视标准 NTSC PAL(SECAM)

    -dv1394 设置DV1394捕获

    -av device 设置音频设备 比如/dev/dsp

高级选项
    -map file:stream 设置输入流映射

    -debug 打印特定调试信息

    -benchmark 为基准测试加入时间

    -hex 倾倒每一个输入包

    -bitexact 仅使用位精确算法 用于编解码测试

    -ps size 设置包大小,以bits为单位

    -re 以本地帧频读数据,主要用于模拟捕获设备

    -loop 循环输入流。只工作于图像流,用于ffserver测试
# todo example
1、avi转MP4命令:
    ffmpeg -i .\\Video.avi -c copy -map 0 video.mp4
    或
    ffmpeg -i .\\Video.avi -c:v libx264 -crf 19 -preset slow -c:a aac -b:a 192k -ac 2  video.mp4

    //剪切视频
    ffmpeg -ss 0:1:30 -t 0:0:50 -i 1.avi -vcodec copy -acodec copy 3.mp4
    //-r 提取图像的频率,-ss 开始时间,-t 持续时间
MP4转ts
    ffmpeg -i .\video.mp4 output.ts
视频压缩
    1)ffmpeg -i 123_ffmpeg.mp4  (压缩的文件更大更清晰,一般情况下不用)

     2)ffmpeg.exe -i 123.MP4 -b:v 700k 1231_ffmpeg.mp4(压缩的更小,相对模糊一些)
"""
import os
from re import compile
import filetype
import platform
import subprocess
import requests
from requests.utils import requote_uri
import time
import shutil
from concurrent.futures import ThreadPoolExecutor, as_completed
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

reg = compile(r".*%0+\dd\.ts")
center_num = 40


def main_path(path: str):
    """
    路径总函数
    @param path:
    @return:
    """
    current_path = os.getcwd()
    if path.startswith('..'):
        path = _wne_path(_parse(path, current_path))
    elif path.startswith('.'):
        path = _wne_path(path[1:], current_path)
    elif path:
        path = _wne_path(path)
    else:
        raise ValueError('文件路径错误')
    return path


def _parse(path: str, current_path):
    """
    解析 .. 路径
    :param path:
    :param current_path:
    :return:
    """
    new_path_args = list(filter(lambda x: x != '', _get_path_params(path)))
    row = 0
    while row < len(new_path_args):
        if new_path_args[row] == '..':
            current_path = os.path.dirname(current_path)
            new_path_args.remove(new_path_args[row])
            row -= 1
        else:
            break
        row += 1
    return os.path.join(current_path, *new_path_args)


def _wne_path(new_path: str, current_path=None):
    new_path_args = _get_path_params(new_path)
    if current_path:
        path = os.path.join(current_path, *new_path_args)
    else:
        sys_str = get_sys()
        if sys_str == "Windows":
            if new_path_args[0].find(':') != -1:
                new_path_args[0] += os.sep
            path = os.path.join(*new_path_args)
        elif sys_str == ["Linux", "Mac", "Darwin"]:
            if new_path_args[0] == '':
                new_path_args[0] = os.sep
            path = os.path.join(*new_path_args)
        else:
            path = new_path
    return path


def get_sys():
    """
    平台
    @return:
    """
    sys_str = platform.system()
    return sys_str


def get_home():
    """
    家目录
    @return:
    """
    return os.path.expanduser("~")


def _get_path_params(path):
    """
    路径参数
    @param path:
    @return:
    """
    return path.split('/') if path.find('/') != -1 else path.split('\\')


def guss_file_type(file_path):
    """
    file_path
    @param file_path:
    @return:
    """
    kind = filetype.guess_extension(file_path)
    return kind


def m3u8_to_mp4_slice_download(m3u8_urls: list, sep=100, **kwargs):
    """
    分片下载
    @param m3u8_urls:  urls 数组 过大时可用分片下载  传入的 m3u8_urls必须排好序 果ts文件名 或 ts 文件路径
    @param sep:
    @param kwargs: M3u8ToMp4 参数
    @return:
    """
    n = 1
    mp4_path_name = kwargs.pop("mp4_path_name", None) or "temp"
    if mp4_path_name.endswith(".mp4"):
        mp4_path_name = os.path.splitext(mp4_path_name)[0]
    m3u_pt, save_mp4_pt = (None, None)
    for start in range(0, len(m3u8_urls), sep):
        new_list = m3u8_urls[start:start + sep]
        m3u_pt, save_mp4_pt = M3u8ToM
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值