通过ffmpegwrapper切割MPEG-TS文件?

Ste*_*all 17 c ffmpeg objective-c ios

我在设备上有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;
    }
Run Code Online (Sandbox Code Playgroud)

如何在不破坏视频流的情况下切断部分输入文件的开头?当背靠背播放时,我想要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
Run Code Online (Sandbox Code Playgroud)

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

编辑:这是我的尝试.我各个部分我不完全了解,从复制拼凑这里.我现在暂时离开"切割"部分,试图将音频+视频编码编写而不会分层复杂.我得到了EXC_BAD_ACCESSavcodec_encode_video2(...)

- (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];
    });
}
Run Code Online (Sandbox Code Playgroud)

Ron*_*tje 18

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

对于多路复用,请使用反向,有关详细信息,请参阅多路复用.基本上它是分配, avio_open2,为输入文件中的每个现有流添加流(基本上是context- > streams []),循环中的avformat_write_header(),av_interleaved_write_frame(),av_write_trailer()来关闭(并释放分配的上下文)结束).

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

如果您需要更详细的avcodec_decode_video2,avcodec_encode_video2,av_read_frame或av_interleaved_write_frame示例,只需Google"$ function example",您就会看到完整的示例,展示如何正确使用它们.对于x264编码,在调用avcodec_open2进行编码质量设置时,请在AVCodecContext中设置一些默认参数.在C API中,您可以使用AVDictionary执行此操作,例如:

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);
Run Code Online (Sandbox Code Playgroud)

[编辑]哦,我忘记了一个部分,即时间戳.每个AVPacket和AVFrame在其结构中都有一个pts变量,您可以使用它来决定是否在输出流中包含数据包/帧.因此,对于音频,您将使用解复步骤中的AVPacket.pts作为分隔符,对于视频,您将使用解码步骤中的AVFrame.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;
}
Run Code Online (Sandbox Code Playgroud)


Ash*_*uja -3

查看问题的已接受答案。

基本上简而言之,您可以使用:

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
Run Code Online (Sandbox Code Playgroud)

仅供参考,该问题的公认答案是:

如何在ffmpeg保留所有音轨的同时拆分和合并文件?

正如您所发现的,根据流规范文档,比特流副本将仅选择一个(音频)轨道:

默认情况下,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
Run Code Online (Sandbox Code Playgroud)

要选择第三个音轨:

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
Run Code Online (Sandbox Code Playgroud)

您可以在文档的高级选项部分阅读有关流选择的更多信息并查看其他示例ffmpeg

为了表达的紧凑性,我还将-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
Run Code Online (Sandbox Code Playgroud)

会给你:

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

加入:

ffmpeg支持文件串联而无需重新编码,这在其串联文档中有详细描述

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

file '/path/to/files/OutputOne.ts'
file '/path/to/files/OutputTwo.ts'
Run Code Online (Sandbox Code Playgroud)

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

 ffmpeg -f concat -i join.txt -c copy FinalOutput.ts
Run Code Online (Sandbox Code Playgroud)

由于您正在使用mpeg传输流 ( .ts),因此您也应该能够使用 concat协议:

ffmpeg -i "concat:OutputOne.ts|OutputTwo.ts" -c copy -bsf:a aac_adtstoasc output.mp4
Run Code Online (Sandbox Code Playgroud)

根据上面链接的 concat 页面上的示例。我将把它留给你去尝试。

  • 是的,那么我该如何通过 ffmpeg C api 来做到这一点呢?这对我来说没用。 (8认同)