FFmpeg常用命令大全,并简单封装

本文详细介绍FFmpeg的使用方法,包括视频转换、网络推送、视频拼接等操作,并提供了多个实用案例,如视频格式转换、图像处理及音频处理等。

1、ffmpeg使用语法
命令格式:
ffmpeg -i [输入文件名] [参数选项] -f [格式] [输出文件]
ffmpeg [[options][`-i’ input_file]]… {[options] output_file}…
1、参数选项:
(1) -an: 去掉音频
(2) -acodec: 音频选项, 一般后面加copy表示拷贝
(3) -vcodec:视频选项,一般后面加copy表示拷贝
2、格式:
(1) h264: 表示输出的是h264的视频裸流
(2) mp4: 表示输出的是mp4的视频
(3)mpegts: 表示ts视频流
如果没有输入文件,那么视音频捕捉(只在Linux下有效,因为Linux下把音视频设备当作文件句柄来处理)就会起作用。作为通用的规则,选项一般用于下一个特定的文件。如果你给 –b 64选项,改选会设置下一个视频速率。对于原始输入文件,格式选项可能是需要的。缺省情况下,ffmpeg试图尽可能的无损转换,采用与输入同样的音频视频参数来输出。(by ternence.hsu)

2、视频转换
H264视频转ts视频流

ffmpeg -i test.h264 -vcodec copy -f mpegts test.ts

H264视频转mp4

ffmpeg -i test.h264 -vcodec copy -f mp4 test.mp4

ts视频转mp4

ffmpeg -i test.ts -acodec copy -vcodec copy -f mp4 test.mp4
mp4视频转flv
ffmpeg -i test.mp4 -acodec copy -vcodec copy -f flv test.flv

转换文件为3GP格式

ffmpeg -y -i test.mpeg -bitexact -vcodec h263 -b 128 -r 15 -s 176x144 -acodec aac -ac 2 -ar 22500 -ab 24 -f 3gp test.3gp

转换文件为3GP格式 v2

ffmpeg -y -i test.wmv -ac 1 -acodec libamr_nb -ar 8000 -ab 12200 -s 176x144 -b 128 -r 15 test.3gp

使用 ffmpeg 编码得到高质量的视频

ffmpeg.exe -i “D:\Video\Fearless\Fearless.avi” -target film-dvd -s 720x352 -padtop 64 -padbottom 64 -maxrate 7350000 -b 3700000 -sc_threshold 1000000000 -trellis -cgop -g 12 -bf 2 -qblur 0.3 -qcomp 0.7 -me full -dc 10 -mbd 2 -aspect 16:9 -pass 2 -passlogfile “D:\Video\ffmpegencode” -an -f mpeg2video “D:\Fearless.m2v”

转换指定格式文件到FLV格式

ffmpeg.exe -i test.mp3 -ab 56 -ar 22050 -b 500 -r 15 -s 320x240 f:\test.flv
ffmpeg.exe -i test.wmv -ab 56 -ar 22050 -b 500 -r 15 -s 320x240 f:\test.flv

转码解密的VOB

ffmpeg -i snatch_1.vob -f avi -vcodec mpeg4 -b 800 -g 300 -bf 2 -acodec mp3 -ab 128 snatch.avi

(上面的命令行将vob的文件转化成avi文件,mpeg4的视频和mp3的音频。注意命令中使用了B帧,所以mpeg4流是divx5兼容的。GOP大小是300意味着29.97帧频下每10秒就有INTRA帧。该映射在音频语言的DVD转码时候尤其有用,同时编码到几种格式并且在输入流和输出流之间建立映射)

转换文件为3GP格式

ffmpeg -i test.avi -y -b 20 -s sqcif -r 10 -acodec amr_wb -ab 23.85 -ac 1 -ar 16000 test.3gp

(如果要转换为3GP格式,则ffmpeg在编译时必须加上–enable-amr_nb –enable-amr_wb,详细内容可参考:转换视频为3GPP格式)

转换文件为MP4格式(支持iPhone/iTouch)

ffmpeg -y -i input.wmv -f mp4 -async 1-s 480x320 -acodec libfaac -vcodec libxvid -qscale 7 -dts_delta_threshold 1 output.mp4
ffmpeg -y -i source_video.avi input -acodec libfaac -ab 128000 -vcodec mpeg4 -b 1200000 -mbd 2 -flags +4mv+trell -aic 2 -cmp 2 -subcmp 2 -s 320x180 -title X final_video.mp4

将一段音频与一段视频混合

ffmpeg -i son.wav -i video_origine.avi video_finale.mpg

将一段视频转换为DVD格式

ffmpeg -i source_video.avi -target pal-dvd -ps 2000000000 -aspect 16:9 finale_video.mpeg

(target pal-dvd : Output format ps 2000000000 maximum size for the output file, in bits (here, 2 Gb) aspect 16:9 : Widescreen)

转换一段视频为DivX格式

ffmpeg -i video_origine.avi -s 320x240 -vcodec msmpeg4v2 video_finale.avi

Turn X images to a video sequence

ffmpeg -f image2 -i image%d.jpg video.mpg

(This command will transform all the images from the current directory (named image1.jpg, image2.jpg, etc…) to a video file named video.mpg.)

Turn a video to X images

ffmpeg -i video.mpg image%d.jpg

(This command will generate the files named image1.jpg, image2.jpg, … ;The following image formats are also availables : PGM, PPM, PAM, PGMYUV, JPEG, GIF, PNG, TIFF, SGI.)

使用ffmpeg录像屏幕(仅限Linux平台)

ffmpeg -vcodec mpeg4 -b 1000 -r 10 -g 300 -vd x11:0,0 -s 1024x768 ~/test.avi

(-vd x11:0,0 指录制所使用的偏移为 x=0 和 y=0,-s 1024×768 指录制视频的大小为 1024×768。录制的视频文件为 test.avi,将保存到用户主目录中;如果你只想录制一个应用程序窗口或者桌面上的一个固定区域,那么可以指定偏移位置和区域大小。使用xwininfo -frame命令可以完成查找上述参数。)

重新调整视频尺寸大小(仅限Linux平台)

ffmpeg -vcodec mpeg4 -b 1000 -r 10 -g 300 -i ~/test.avi -s 800×600 ~/test-800-600.avi

把摄像头的实时视频录制下来,存储为文件(仅限Linux平台)

ffmpeg -f video4linux -s 320*240 -r 10 -i /dev/video0 test.asf

使用ffmpeg压制H.264视频

ffmpeg -threads 4 -i INPUT -r 29.97 -vcodec libx264 -s 480x272 -flags +loop -cmp chroma -deblockalpha 0 -deblockbeta 0 -crf 24 -bt 256k -refs 1 -coder 0 -me umh -me_range 16 -subq 5 -partitions parti4x4+parti8x8+partp8x8 -g 250 -keyint_min 25 -level 30 -qmin 10 -qmax 51 -trellis 2 -sc_threshold 40 -i_qfactor 0.71 -acodec libfaac -ab 128k -ar 48000 -ac 2 OUTPUT

(使用该指令可以压缩出比较清晰,而且文件转小的H.264视频文件)

3、网络推送
udp视频流的推送
ffmpeg -re -i 1.ts -c copy -f mpegts udp://192.168.0.106:1234

4、视频拼接
裸码流的拼接,先拼接裸码流,再做容器的封装
ffmpeg -i “concat:test1.h264|test2.h264” -vcodec copy -f h264 out12.h264

5、图像相关
截取一张352x240尺寸大小的,格式为jpg的图片

ffmpeg -i test.asf -y -f image2 -t 0.001 -s 352x240 a.jpg

把视频的前30帧转换成一个Animated Gif

ffmpeg -i test.asf -vframes 30 -y -f gif a.gif

截取指定时间的缩微图,-ss后跟的时间单位为秒

ffmpeg -i test.avi -y -f image2 -ss 8 -t 0.001 -s 350x240 test.jpg

6、音频处理

转换wav到mp2格式

ffmpeg -i /tmp/a.wav -ab 64 /tmp/a.mp2 -ab 128 /tmp/b.mp2 -map 0:0 -map 0:0

(上面的命令行转换一个64Kbits 的a.wav到128kbits的a.mp2 ‘-map file:index’在输出流的顺序上定义了哪一路输入流是用于每一个输出流的。)

7、切割ts分片
ffmpeg -i input.mp4 -c:v libx264 -c:a aac -strict -2 -f hls -hls_list_size 6 -hls_time 5 output1.m3u8

FFmpeg命令的简单封装类

TransformationCommands.java

package com.example.extjeremyli.ffmpegdemo.utils;

import android.util.Pair;

public interface TransformationCommands {
    String[] getDefaultScaleVideoCmd(final String from, final String to, Pair<Integer, Integer> config);
    String[] getDefaultWatermarkImageCmd(final String from, final String watermarkPath, final String to);
    String[] getDefaultScaledImageCmd(final String from, final String to, Pair<Integer, Integer> config);
    String[] getDefaultVideoThumbCmd(final String from, final String to);
    String[] getDefaultRotateCmd(final String from, final String to);
}

FFmpegCommands.java

package com.example.extjeremyli.ffmpegdemo.utils;

import android.util.Pair;

public class FFmpegCommands implements TransformationCommands {

    /**
     * Applying watermark in the center of the video:
     *      ffmpeg -i E:\test2.mp4 -i E:\watermark_large.png -filter_complex
     *      "overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2" -codec:a copy E:\output.flv
     *
     * Applying watermark in the left bottom of the image:
     *      ffmpeg -i E:\test_img.jpg -i E:\watermark_large.png -filter_complex "overlay=10:main_h-overlay_h-10"
     *      -codec:a copy E:\output.png
     *
     * Resize video:
     *      ffmpeg -y -i E:\test3.mp4 -s 640*480 -r 15 -aspect 3:4 -ab 12288
     *      -vcodec mpeg4 -b 2097152 E:\debug_video.mp4
     * */

    private final String SCALE_TEMPLATE = "scale=%s:%s";

    @Override
    public String[] getDefaultScaleVideoCmd(String from, String to, Pair<Integer, Integer> config) {
        final String scaleFilter = String.format(SCALE_TEMPLATE, config.first, config.second); // apply width and height

        FFmpegCommandBuilder commandBuilder = new FFmpegCommandBuilder();
        commandBuilder.allowOverwrightFilesWithoutAsking();
        commandBuilder.setInputFile(from);
        commandBuilder.setFilter(scaleFilter);
        commandBuilder.setFrameRate("15");
        commandBuilder.setAB("12288"); // clarify the property
        commandBuilder.setVCodec("mpeg4");
        commandBuilder.setTransformationSpeed("fast");
        commandBuilder.setAudioCodec("copy");
        commandBuilder.setB("2097152");
        commandBuilder.setDestination(to);

        return commandBuilder.build();
    }

    @Override
    public String[] getDefaultWatermarkImageCmd(String from, String watermarkPath, String to) {

        FFmpegCommandBuilder commandBuilder = new FFmpegCommandBuilder();
        commandBuilder.allowOverwrightFilesWithoutAsking();
        commandBuilder.setInputFile(from);
        commandBuilder.setSecondInputFile(watermarkPath);
        commandBuilder.setComplexFilter("overlay=10:main_h-overlay_h-10");
        commandBuilder.setCodecAudio("copy");
        commandBuilder.setDestination(to);

        return commandBuilder.build();
    }

    @Override
    public String[] getDefaultScaledImageCmd(String from, String to, Pair<Integer, Integer> config) {
        final String scaleFilter = String.format(SCALE_TEMPLATE, config.first, config.second); // apply width and height

        FFmpegCommandBuilder commandBuilder = new FFmpegCommandBuilder();
        commandBuilder.allowOverwrightFilesWithoutAsking();
        commandBuilder.setInputFile(from);
        commandBuilder.setFilter(scaleFilter);
        commandBuilder.setDestination(to);

        return commandBuilder.build();
    }

    @Override
    public String[] getDefaultVideoThumbCmd(String from, String to) {
        FFmpegCommandBuilder commandBuilder = new FFmpegCommandBuilder();
        commandBuilder.allowOverwrightFilesWithoutAsking();
        commandBuilder.setInputFile(from);
        commandBuilder.setStartTruncatePosition("00:00:01"); // since 1st second of the video
        commandBuilder.setVframes("1");
        commandBuilder.setDestination(to);

        return commandBuilder.build();
    }

    @Override
    public String[] getDefaultRotateCmd(String from, String to) {
        FFmpegCommandBuilder commandBuilder = new FFmpegCommandBuilder();
        commandBuilder.setInputFile(from);
        commandBuilder.setCopy("copy");
        commandBuilder.setMetadata("-metadata:s:v:0");
        commandBuilder.setRotate(90);
        commandBuilder.setDestination(to);
        return commandBuilder.build();
    }


}

FFmpegCommandBuilder.java

package com.example.extjeremyli.ffmpegdemo.utils;

import android.util.Log;

import java.util.ArrayList;

/*package*/ class FFmpegCommandBuilder {

    /**
     * -y       overwrite output files without asking
     * -i       input filename
     * -s       set frame size
     * -r       set frame rate
     * -vcodec  set the vcodec
     * -b
     * -ab
     * -ac      Set the number of audio channels
     * -ar      Set the audio sampling frequency
     * -ss      Set the start position since video will be truncated {@see https://ffmpeg.org/ffmpeg.html}
     * -vf      applying filter
     * -aspect  set vignette aspect.
     * -preset  encoding (enum value, ultrafast is the fastest way)
     * -transpose= <value> rotation params 1 = 90Clockwise
     * */

    /** ffmpeg -i input.mp4 -c copy -metadata:s:v:0 rotate=90 output.mp4
     * transpose args:
     * 0 = 90CounterCLockwise and Vertical Flip (default)
     * 1 = 90Clockwise
     * 2 = 90CounterClockwise
     * 3 = 90Clockwise and Vertical Flip
     * */

    // maximum compression
    //ffmpeg -y -i /storage/emulated/0/main.mp4 -s 480x320 -r 20 -c:v libx264 -preset ultrafast -c:a copy -me_method zero -tune fastdecode -tune zerolatency -strict -2 -b:v 1000k -pix_fmt yuv420p /storage/emulated/0/output.mp4
    private ArrayList<String> commandList = new ArrayList<>();
    private String copy;
    private String metadata;
    private int rotate;


    public String[] build() {
        StringBuilder builder = new StringBuilder();
        for (String cmd : commandList) {
            builder.append(cmd).append(" ");

        }
        Log.d("JIANG", "!!!FFMPEG!!! " + builder.toString());
        String[] commandArray = new String[commandList.size()];
        commandList.toArray(commandArray);
        return commandArray;
    }

    public void allowOverwrightFilesWithoutAsking() {
//        this.allowOverwrightFilesWithoutAsking = true;
        commandList.add(Params.OVERWRIGHT_OUTPUT_WITHOUT_ASKING);
    }

    public void setInputFile(final String input) {
        commandList.add(Params.INPUT_FILE_NAME);
        commandList.add(input);
    }

    public void setSecondInputFile(final String input) {
        commandList.add(Params.INPUT_FILE_NAME);
        commandList.add(input);
    }

    public void setStrict() {
//        this.allowStrict = true;
        commandList.add(Params.STRICT);
    }

    public void setFrameSize(final String frameSize) {
        commandList.add(Params.FRAME_SIZE);
        commandList.add(frameSize);
    }

    public void setFrameRate(final String frameRate) {
        commandList.add(Params.FRAME_RATE);
        commandList.add(frameRate);
    }

    public void setVCodec(final String codec) {
        commandList.add(Params.VIDEO_CODEC);
        commandList.add(codec);
    }

    public void setB(final String b) {
        commandList.add(Params.B);
        commandList.add(b);
    }

    public void setAB(final String value) {
        commandList.add(Params.AB);
        commandList.add(value);
    }

    public void setAudioChannels(final String audioChannels) {
        commandList.add(Params.NUMBER_OF_AUDIO_CHANNELS);
        commandList.add(audioChannels);
    }

    public void setSampleFrequency(final String sampleFrequency) {
        commandList.add(Params.AUDIO_SAMPLING_FREQUENCY);
        commandList.add(sampleFrequency);
    }

    /**
     * Must be called as the last command
     * */
    public void setDestination(final String destination) {
        commandList.add(destination);
    }

    public void setScaleVideo(final String scaleValue) {
        commandList.add(Params.SCALE);
        commandList.add(scaleValue);
    }

    public void setStartTruncatePosition(final String position) {
        commandList.add(Params.SS);
        commandList.add(position);
    }

    public void setCodec(final String codec) {
        commandList.add(Params.CODEC);
        commandList.add(codec);
    }

    public void setCodecAudio(final String value) {
        commandList.add(Params.CODEC_AUDIO);
        commandList.add(value);
    }

    public void setDuration(final String duration) {
        commandList.add(Params.DURATION);
        commandList.add(duration);
    }

    public void setFilter(final String filter) {
        commandList.add(Params.FILTER);
        commandList.add(filter);
    }

    public void setVignetteAspect(final String aspect) {
        commandList.add(Params.VIGNETTE_ASPECT);
        commandList.add(aspect);
    }

    public void showFormats(final String value) {
        commandList.add(Params.SAMPLE_FORMAT);
        commandList.add(value);
    }

    public void setComplexFilter(String complexFilter) {
        commandList.add(Params.COMPLEX_FILTER);
        commandList.add(complexFilter);
    }

    public void setTransformationSpeed(final String value) {
        commandList.add(Params.SPEED);
        commandList.add(value);
    }

    public void setVframes(final String value) {
        commandList.add(Params.VFRAMES);
        commandList.add(value);
    }

    public void setAudioCodec(final String value) {
        commandList.add(Params.AUDIO_CODEC);
        commandList.add(value);
    }

    public void setRotation(final int angle) {
        switch (angle) {
            case 90:
                setFilter(Params.ROTATION);
                break;
        }
    }

    public void setCopy(String copy) {
        commandList.add(Params.COPY);
        commandList.add(copy);
    }

    public void setMetadata(String metadata) {
        commandList.add(metadata);
    }

    public void setRotate(int rotate) {
        commandList.add("rotate=" + rotate);
    }

    /**
     * The intent of this class is to provide human-readable parameters of video
     * transformation library.
     * */
    private static class Params {
        private static final String OVERWRIGHT_OUTPUT_WITHOUT_ASKING = "-y";
        private static final String INPUT_FILE_NAME = "-i";
        private static final String STRICT = "-strict";
        private static final String FRAME_SIZE = "-s"; // scale
        private static final String FRAME_RATE = "-r";
        private static final String VIDEO_CODEC = "-vcodec";
        private static final String AUDIO_CODEC = "-acodec";
        private static final String B = "-b"; // TODO clarify what is it
        private static final String AB = "-ab"; // TODO clarify what is it
        private static final String NUMBER_OF_AUDIO_CHANNELS = "-ac";
        private static final String AUDIO_SAMPLING_FREQUENCY = "-ar";
        private static final String SCALE = "scale=";
        private static final String DISPLAY_ASPECT_RATIO = "setdar";
        private static final String SAMPLE_ASPECT_RATIO = "setsar";
        private static final String SS = "-ss";
        private static final String CODEC = "-codec";
        private static final String CODEC_AUDIO = "-codec:a";
        private static final String DURATION = "-t";
        private static final String FILTER = "-vf";
        private static final String VIGNETTE_ASPECT = "-aspect";
        private static final String SAMPLE_FORMAT = "-sample_fmt";
        private static final String COMPLEX_FILTER = "-filter_complex";
        private static final String SPEED = "-preset";
        private static final String VFRAMES = "-vframes";
        private static final String ROTATION = "\"transpose=1\"";
        private static final String COPY = "-c";
    }
}
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值