项目代码: https://blog.csdn.net/al4fun/article/details/104293868
下面代码展示了如何将mp4文件转换为flv文件。
因为mp4和flv都只是封装格式,底层音视频编码可以保持不变,因此这里的做法是直接从源文件中读取音视频流并写入目标文件,封装格式的转换由AVFormatContext完成。
整体流程与提取音视频流类似,同样要进行时间基的转换。
java层调用:
File srcFile = copyFile();
if (srcFile != null) {
File dstFile = new File(getCacheDir().getAbsolutePath(), "sintel.flv");
if (dstFile.exists()) {
dstFile.delete();
}
remux("file:" + srcFile.getAbsolutePath(), "file:" + dstFile.getAbsolutePath());
}
native层实现:
//env: Android JNI, C++11, FFmpeg4.0.
static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt, const char *tag);
extern "C"
JNIEXPORT int JNICALL
Java_com_example_helloffmpeg_MainActivity_remux(JNIEnv *env, jobject thiz, jstring file_path,
jstring dst_file_path) {
const char *in_filename = env->GetStringUTFChars(file_path, nullptr);
const char *out_filename = env->GetStringUTFChars(dst_file_path, nullptr);
__android_log_write(ANDROID_LOG_ERROR, TAG, in_filename);
__android_log_write(ANDROID_LOG_ERROR, TAG, out_filename);
AVOutputFormat *ofmt = nullptr;
AVFormatContext *ifmt_ctx = nullptr, *ofmt_ctx = nullptr;
AVPacket pkt;
int ret, i;
int stream_index = 0;
int *stream_mapping = nullptr;
int stream_mapping_size = 0;
//ifmt_ctx
if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "Could not open input file '%s'", in_filename);
goto end;
}
if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "Failed to retrieve input stream information");
goto end;
}
av_dump_format(ifmt_ctx, 0, in_filename, 0);
//ofmt_ctx、ofmt
//获得ofmt_ctx和ofmt的另一种方法,参考extractAudio函数
avformat_alloc_output_context2(&ofmt_ctx, nullptr, nullptr, out_filename);
if (!ofmt_ctx) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "Could not create output context\n");
ret = AVERROR_UNKNOWN;
goto end;
}
ofmt = ofmt_ctx->oformat;
stream_mapping_size = ifmt_ctx->nb_streams;
stream_mapping = (int *) av_mallocz_array(stream_mapping_size, sizeof(*stream_mapping));
if (!stream_mapping) {
ret = AVERROR(ENOMEM);
goto end;
}
//遍历每一路流
for (i = 0; i < ifmt_ctx->nb_streams; i++) {
AVStream *out_stream;
AVStream *in_stream = ifmt_ctx->streams[i];
AVCodecParameters *in_codecpar = in_stream->codecpar;
//输出文件中只保留了音频流、视频流和字幕流
if (in_codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
in_codecpar->codec_type != AVMEDIA_TYPE_VIDEO &&
in_codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) {
stream_mapping[i] = -1;
continue;
}
//角标是此路流在输入文件中的索引
//值是此路流在输出文件中的索引
stream_mapping[i] = stream_index++;
out_stream = avformat_new_stream(ofmt_ctx, nullptr);
if (!out_stream) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "Failed allocating output stream\n");
ret = AVERROR_UNKNOWN;
goto end;
}
//拷贝流的codec参数
ret = avcodec_parameters_copy(out_stream->codecpar, in_codecpar);
if (ret < 0) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "Failed to copy codec parameters\n");
goto end;
}
out_stream->codecpar->codec_tag = 0;
}
av_dump_format(ofmt_ctx, 0, out_filename, 1);
if (!(ofmt->flags & AVFMT_NOFILE)) {
//创建并初始化AVIOContext
ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
if (ret < 0) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "Could not open output file '%s'",
out_filename);
goto end;
}
}
//写媒体文件头信息
ret = avformat_write_header(ofmt_ctx, nullptr);
if (ret < 0) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "Error occurred when opening output file\n");
goto end;
}
while (1) {
AVStream *in_stream, *out_stream;
//读取packet
ret = av_read_frame(ifmt_ctx, &pkt);
if (ret < 0) break;
in_stream = ifmt_ctx->streams[pkt.stream_index];
//无效的流 或 不是我们想要的流
if (pkt.stream_index >= stream_mapping_size ||
stream_mapping[pkt.stream_index] < 0) {
av_packet_unref(&pkt);
continue;
}
pkt.stream_index = stream_mapping[pkt.stream_index];
out_stream = ofmt_ctx->streams[pkt.stream_index];
log_packet(ifmt_ctx, &pkt, "in");
//输入流和输出流的时间基可能不同,因此要根据时间基的不同对时间戳pts进行转换
pkt.pts = av_rescale_q(pkt.pts, in_stream->time_base, out_stream->time_base);
pkt.dts = av_rescale_q(pkt.dts, in_stream->time_base, out_stream->time_base);
//根据时间基转换duration
pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
pkt.pos = -1;
log_packet(ofmt_ctx, &pkt, "out");
//写入packet数据
ret = av_interleaved_write_frame(ofmt_ctx, &pkt);
if (ret < 0) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "Error muxing packet\n");
break;
}
av_packet_unref(&pkt);
}
//写媒体文件尾信息
av_write_trailer(ofmt_ctx);
end:
env->ReleaseStringUTFChars(file_path, in_filename);
env->ReleaseStringUTFChars(dst_file_path, out_filename);
if (ifmt_ctx) avformat_close_input(&ifmt_ctx);
if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE)) avio_closep(&ofmt_ctx->pb);
if (ofmt_ctx) avformat_free_context(ofmt_ctx);
if (stream_mapping) av_freep(&stream_mapping);
if (ret < 0 && ret != AVERROR_EOF) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "Error occurred: %s\n", av_err2str(ret));
return 1;
}
return 0;
}
static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt, const char *tag) {
AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
printf("%s: pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n",
tag,
av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, time_base),
av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, time_base),
av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, time_base),
pkt->stream_index);
}