通过ffmpegwrapper切割MPEG-TS文件?

时间:2016-01-16 04:34:46

标签: ios objective-c c ffmpeg

我在设备上有MPEG-TS文件。我想在设备上的文件开始时缩短相当准确的时间。

FFmpegWrapper为基础,我希望能够实现这一目标。

但是,我在ffmpeg的C API上有点迷失。我从哪里开始?

我尝试在启动PTS之前丢弃所有数据包,但这打破了视频流。

    packet->pts = av_rescale_q(packet->pts, inputStream.stream->time_base, outputStream.stream->time_base);
    packet->dts = av_rescale_q(packet->dts, inputStream.stream->time_base, outputStream.stream->time_base);

    if(startPts == 0){
        startPts = packet->pts;
    }

    if(packet->pts < cutTimeStartPts + startPts){
        av_free_packet(packet);
        continue;
    }

如何在不破坏视频流的情况下切断部分输入文件的开头?当背靠背播放时,我想要2个剪切片段无缝地一起运行。

ffmpeg -i time.ts -c:v libx264 -c:a copy -ss $CUT_POINT -map 0 -y after.ts
ffmpeg -i time.ts -c:v libx264 -c:a copy -to $CUT_POINT -map 0 -y before.ts

似乎是我需要的。我认为需要重新编码,因此视频可以从任意点开始,而不是现有的关键帧。如果有更有效的解决方案,那就太棒了。如果没有,这就足够了。

编辑:这是我的尝试。我正在拼凑从here复制的各种不完全理解的作品。我离开&#34;切割&#34;现在尝试获得音频+视频编码而不会分层复杂。我在avcodec_encode_video2(...)

上获得了EXC_BAD_ACCESS
- (void)convertInputPath:(NSString *)inputPath outputPath:(NSString *)outputPath
                 options:(NSDictionary *)options progressBlock:(FFmpegWrapperProgressBlock)progressBlock
         completionBlock:(FFmpegWrapperCompletionBlock)completionBlock {
    dispatch_async(conversionQueue, ^{
        FFInputFile *inputFile = nil;
        FFOutputFile *outputFile = nil;
        NSError *error = nil;

        inputFile = [[FFInputFile alloc] initWithPath:inputPath options:options];
        outputFile = [[FFOutputFile alloc] initWithPath:outputPath options:options];

        [self setupDirectStreamCopyFromInputFile:inputFile outputFile:outputFile];
        if (![outputFile openFileForWritingWithError:&error]) {
            [self finishWithSuccess:NO error:error completionBlock:completionBlock];
            return;
        }
        if (![outputFile writeHeaderWithError:&error]) {
            [self finishWithSuccess:NO error:error completionBlock:completionBlock];
            return;
        }

        AVRational default_timebase;
        default_timebase.num = 1;
        default_timebase.den = AV_TIME_BASE;
        FFStream *outputVideoStream = outputFile.streams[0];
        FFStream *inputVideoStream = inputFile.streams[0];

        AVFrame *frame;
        AVPacket inPacket, outPacket;

        frame = avcodec_alloc_frame();
        av_init_packet(&inPacket);

        while (av_read_frame(inputFile.formatContext, &inPacket) >= 0) {
            if (inPacket.stream_index == 0) {
                int frameFinished;
                avcodec_decode_video2(inputVideoStream.stream->codec, frame, &frameFinished, &inPacket);
//                if (frameFinished && frame->pkt_pts >= starttime_int64 && frame->pkt_pts <= endtime_int64) {
                if (frameFinished){
                    av_init_packet(&outPacket);
                    int output;
                    avcodec_encode_video2(outputVideoStream.stream->codec, &outPacket, frame, &output);
                    if (output) {
                        if (av_write_frame(outputFile.formatContext, &outPacket) != 0) {
                            fprintf(stderr, "convert(): error while writing video frame\n");
                            [self finishWithSuccess:NO error:nil completionBlock:completionBlock];
                        }
                    }
                    av_free_packet(&outPacket);
                }
                if (frame->pkt_pts > endtime_int64) {
                    break;
                }
            }
        }
        av_free_packet(&inPacket);

        if (![outputFile writeTrailerWithError:&error]) {
            [self finishWithSuccess:NO error:error completionBlock:completionBlock];
            return;
        }

        [self finishWithSuccess:YES error:nil completionBlock:completionBlock];
    });
}

2 个答案:

答案 0 :(得分:18)

FFmpeg(在本例中为libavformat / codec)API非常接近地映射ffmpeg.exe命令行参数。要打开文件,请使用avformat_open_input_file()。最后两个参数可以为NULL。这将为您填写AVFormatContext。现在,您开始在循环中使用av_read_frame()读取帧。 pkt.stream_index将告诉您每个数据包所属的流,并且avformatcontext-&gt; streams [pkt.stream_index]是随附的流信息,它告诉您它使用的编解码器,它的视频/音频等等。使用avformat_close()关闭。

对于多路复用,请使用反向,有关详细信息,请参阅muxing。基本上它是输入文件中每个现有流的allocateavio_open2add streams(基本上是context-&gt; streams []),avformat_write_header(),{{ 3}}在一个循环中,av_interleaved_write_frame()关闭(和av_write_trailer()最终分配的上下文)。

使用libavcodec完成视频流的编码/解码。对于从复用器获取的每个AVPacket,请使用free。使用avcodec_decode_video2()进行输出AVFrame的编码。请注意,两者都会引入延迟,因此对每个函数的前几次调用不会返回任何数据,您需要通过使用NULL输入数据调用每个函数来刷新缓存数据,以获取尾部数据包/帧。 av_interleave_write_frame将正确交错数据包,因此视频/音频流不会同步(如:相同时间戳的视频数据包在ts文件中的音频数据包之后出现MB)。

如果您需要更详细的avcodec_decode_video2,avcodec_encode_video2,av_read_frame或av_interleaved_write_frame示例,只需Google&#34; $ function example&#34;并且您将看到完整示例,说明如何正确使用它们。对于x264编码,在调用avcodec_open2进行编码质量设置时,AVCodecContext中为avcodec_encode_video2()。在C API中,您可以使用set some default parameters来执行此操作,例如:

AVDictionary opts = *NULL;
av_dict_set(&opts, "preset", "veryslow", 0);
// use either crf or b, not both! See the link above on H264 encoding options
av_dict_set_int(&opts, "b", 1000, 0);
av_dict_set_int(&opts, "crf", 10, 0);

[编辑]哦,我忘记了一个部分,即时间戳。每个AVPacket和AVFrame在其结构中都有一个pts变量,您可以使用它来决定是否在输出流中包含数据包/帧。因此,对于音频,您可以使用解复步骤中的AVDictionary作为分隔符,对于视频,您可以使用解码步骤中的AVPacket.pts作为分隔符。他们各自的文件告诉你他们是什么单位。

[edit2]我发现你在没有实际代码的情况下仍然遇到了一些问题,所以这里是一个真正的(工作)代码转换器,可以对视频进行重新编码并重新复用音频。它可能有大量的错误,泄漏和缺乏正确的错误报告,它也没有处理时间戳(我把它留给你作为练习),但它做了你要求的基本事情:

#include <stdio.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>

static AVFormatContext *inctx, *outctx;
#define MAX_STREAMS 16
static AVCodecContext *inavctx[MAX_STREAMS];
static AVCodecContext *outavctx[MAX_STREAMS];

static int openInputFile(const char *file) {
    int res;

    inctx = NULL;
    res = avformat_open_input(& inctx, file, NULL, NULL);
    if (res != 0)
        return res;
    res = avformat_find_stream_info(inctx, NULL);
    if (res < 0)
        return res;

    return 0;
}

static void closeInputFile(void) {
    int n;

    for (n = 0; n < inctx->nb_streams; n++)
        if (inavctx[n]) {
            avcodec_close(inavctx[n]);
            avcodec_free_context(&inavctx[n]);
        }

    avformat_close_input(&inctx);
}

static int openOutputFile(const char *file) {
    int res, n;

    outctx = avformat_alloc_context();
    outctx->oformat = av_guess_format(NULL, file, NULL);
    if ((res = avio_open2(&outctx->pb, file, AVIO_FLAG_WRITE, NULL, NULL)) < 0)
        return res;

    for (n = 0; n < inctx->nb_streams; n++) {
        AVStream *inst = inctx->streams[n];
        AVCodecContext *inc = inst->codec;

        if (inc->codec_type == AVMEDIA_TYPE_VIDEO) {
            // video decoder
            inavctx[n] = avcodec_alloc_context3(inc->codec);
            avcodec_copy_context(inavctx[n], inc);
            if ((res = avcodec_open2(inavctx[n], avcodec_find_decoder(inc->codec_id), NULL)) < 0)
                return res;

            // video encoder
            AVCodec *encoder = avcodec_find_encoder_by_name("libx264");
            AVStream *outst = avformat_new_stream(outctx, encoder);
            outst->codec->width = inavctx[n]->width;
            outst->codec->height = inavctx[n]->height;
            outst->codec->pix_fmt = inavctx[n]->pix_fmt;
            AVDictionary *dict = NULL;
            av_dict_set(&dict, "preset", "veryslow", 0);
            av_dict_set_int(&dict, "crf", 10, 0);
            outavctx[n] = avcodec_alloc_context3(encoder);
            avcodec_copy_context(outavctx[n], outst->codec);
            if ((res = avcodec_open2(outavctx[n], encoder, &dict)) < 0)
                return res;
        } else if (inc->codec_type == AVMEDIA_TYPE_AUDIO) {
            avformat_new_stream(outctx, inc->codec);
            inavctx[n] = outavctx[n] = NULL;
        } else {
            fprintf(stderr, "Don’t know what to do with stream %d\n", n);
            return -1;
        }
    }

    if ((res = avformat_write_header(outctx, NULL)) < 0)
        return res;

    return 0;
}

static void closeOutputFile(void) {
    int n;

    av_write_trailer(outctx);
    for (n = 0; n < outctx->nb_streams; n++)
        if (outctx->streams[n]->codec)
            avcodec_close(outctx->streams[n]->codec);
    avformat_free_context(outctx);
}

static int encodeFrame(int stream_index, AVFrame *frame, int *gotOutput) {
    AVPacket outPacket;
    int res;

    av_init_packet(&outPacket);
    if ((res = avcodec_encode_video2(outavctx[stream_index], &outPacket, frame, gotOutput)) < 0) {
        fprintf(stderr, "Failed to encode frame\n");
        return res;
    }
    if (*gotOutput) {
        outPacket.stream_index = stream_index;
        if ((res = av_interleaved_write_frame(outctx, &outPacket)) < 0) {
            fprintf(stderr, "Failed to write packet\n");
            return res;
        }
    }
    av_free_packet(&outPacket);

    return 0;
}

static int decodePacket(int stream_index, AVPacket *pkt, AVFrame *frame, int *frameFinished) {
    int res;

    if ((res = avcodec_decode_video2(inavctx[stream_index], frame,
                                     frameFinished, pkt)) < 0) {
        fprintf(stderr, "Failed to decode frame\n");
        return res;
    }
    if (*frameFinished){
        int hasOutput;

        frame->pts = frame->pkt_pts;
        return encodeFrame(stream_index, frame, &hasOutput);
    } else {
        return 0;
    }
}

int main(int argc, char *argv[]) {
    char *input = argv[1];
    char *output = argv[2];
    int res, n;

    printf("Converting %s to %s\n", input, output);
    av_register_all();
    if ((res = openInputFile(input)) < 0) {
        fprintf(stderr, "Failed to open input file %s\n", input);
        return res;
    }
    if ((res = openOutputFile(output)) < 0) {
        fprintf(stderr, "Failed to open output file %s\n", input);
        return res;
    }

    AVFrame *frame = av_frame_alloc();
    AVPacket inPacket;

    av_init_packet(&inPacket);
    while (av_read_frame(inctx, &inPacket) >= 0) {
        if (inavctx[inPacket.stream_index] != NULL) {
            int frameFinished;
            if ((res = decodePacket(inPacket.stream_index, &inPacket, frame, &frameFinished)) < 0) {
                return res;
            }
        } else {
            if ((res = av_interleaved_write_frame(outctx, &inPacket)) < 0) {
                fprintf(stderr, "Failed to write packet\n");
                return res;
            }
        }
    }

    for (n = 0; n < inctx->nb_streams; n++) {
        if (inavctx[n]) {
            // flush decoder
            int frameFinished;
            do {
                inPacket.data = NULL;
                inPacket.size = 0;
                if ((res = decodePacket(n, &inPacket, frame, &frameFinished)) < 0)
                    return res;
            } while (frameFinished);

            // flush encoder
            int gotOutput;
            do {
                if ((res = encodeFrame(n, NULL, &gotOutput)) < 0)
                    return res;
            } while (gotOutput);
        }
    }
    av_free_packet(&inPacket);

    closeInputFile();
    closeOutputFile();

    return 0;
}

答案 1 :(得分:-3)

查看this问题的已接受答案。

简而言之,您可以使用:

ffmpeg -i time.ts -c:v libx264 -c:a copy -ss $CUT_POINT -map 0 -y after.ts
ffmpeg -i time.ts -c:v libx264 -c:a copy -to $CUT_POINT -map 0 -y before.ts

仅供参考,该问题的接受答案是:

如何在保留所有音轨的同时使用ffmpeg拆分和加入文件?

正如您所发现的,根据stream specification documentation,比特流副本只会选择一个(音频)曲目:

  

默认情况下,ffmpeg仅包含输入文件中存在的每种类型的一个流(视频,音频,字幕),并将它们添加到每个输出文件中。它根据以下标准选择每个中的“最佳”:对于视频,它是具有最高分辨率的流,对于音频,它是具有最多通道的流,对于字幕,它是第一个字幕流。在几个相同类型的流速率相等的情况下,选择具有最低索引的流。

选择所有音轨:

ffmpeg -i InputFile.ts-c copy -ss 00:12:34.567 -t 00:34:56.789 -map 0:v -map 0:a FirstFile.ts

选择第三个​​音轨:

ffmpeg -i InputFile.ts -c copy -ss 00:12:34.567 -t 00:34:56.789 -map 0:v -map 0:a:2 FirstFile.ts

您可以在ffmpeg文档的advanced options部分中详细了解并查看其他流选择示例。

如上所述,我还会将原始命令中的-vcodec copy -acodec copy合并到-c copy中,以实现表达的紧凑性。

分割:

所以,将这些与你想要在两个文件中实现的内容结合起来进行拆分以便以后重新加入:

ffmpeg -i InputOne.ts -ss 00:02:00.0 -c copy -map 0:v -map 0:a OutputOne.ts
ffmpeg -i InputTwo.ts -c copy -t 00:03:05.0 -map 0:v -map 0:a OutputTwo.ts

会给你:

  • OutputOne.ts ,这是第一个输入文件的前两分钟之后的所有内容
  • OutputTwo.ts ,这是第一个第二个输入文件的3分5秒

加入:

ffmpeg支持连接文件而无需重新编码described extensively in its concatenation documentation

创建要加入的文件列表(例如join.txt):

file '/path/to/files/OutputOne.ts'
file '/path/to/files/OutputTwo.ts'

然后您的ffmpeg命令可以使用concat demuxer

 ffmpeg -f concat -i join.txt -c copy FinalOutput.ts

由于您使用的是mpeg传输流(.ts),因此您 也可以使用concat 协议:< / p>

ffmpeg -i "concat:OutputOne.ts|OutputTwo.ts" -c copy -bsf:a aac_adtstoasc output.mp4

根据上面链接的concat页面上的示例。我会把它留给你来试验。