ffp->m_ofmt_ctx = NULL;
ffp->m_ofmt = NULL;
ffp->is_record = 0;
ffp->record_error = 0;
if (!file_name || !strlen(file_name)) {
av_log(NULL, AV_LOG_ERROR, "Nani: filename is invalid");
goto end;
}
if (!is || !is->ic || is->paused || is->abort_request) { // no context, or the context has stopped
av_log(NULL, AV_LOG_ERROR, "Nani: is,is->ic,is->paused is invalid");
goto end;
}
if (ffp->is_record) {
av_log(NULL, AV_LOG_ERROR, "Nani: recording has started");
goto end;
}
/* Initialize libavcodec, and register all codecs and formats. */
av_register_all();
// Initialize an AVFormatContext structure for output
avformat_alloc_output_context2(&ffp->m_ofmt_ctx, NULL, NULL, file_name);
// avformat_alloc_output_context2(&ffp->m_ofmt_ctx,av_guess_format("mp4", NULL, "video/mp4"), NULL, NULL);
if (!ffp->m_ofmt_ctx) {
av_log(NULL, AV_LOG_ERROR, "Nani: Could not create output context filename is %s\n", file_name);
goto end;
}
ffp->m_ofmt = ffp->m_ofmt_ctx->oformat;
av_log(NULL, AV_LOG_ERROR, "Nani: is->ic->nb_streams=%d\n", is->ic->nb_streams);
/* Add the audio and video streams using the default format codecs and initialize the codecs. */
for (int i = 0; i < is->ic->nb_streams; i++) {
// Create an output stream channel against the input stream
AVStream *in_stream = is->ic->streams[i];
AVStream *out_stream = avformat_new_stream(ffp->m_ofmt_ctx, in_stream->codec->codec);
if (!out_stream) {
av_log(NULL, AV_LOG_ERROR, "Nani: Failed allocating output stream\n");
goto end;
}
// Copy the input video/audio parameters to the AVCodecContext structure of the output video/audio
av_log(ffp, AV_LOG_DEBUG, "Nani: in_stream->codec;%p\n", in_stream->codec);
if (avcodec_copy_context(out_stream->codec, in_stream->codec) < 0) {
av_log(NULL, AV_LOG_ERROR, "Nani: Failed to copy context from input to output stream codec context\n");
goto end;
}
out_stream->codec->codec_tag = 0;
if (ffp->m_ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) {
out_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
}
av_log(NULL, AV_LOG_ERROR, "Nani: Output Information\n");
av_dump_format(ffp->m_ofmt_ctx, 0, file_name, 1);
//Open the output file
if (!(ffp->m_ofmt->flags & AVFMT_NOFILE)) {
if (avio_open(&ffp->m_ofmt_ctx->pb, file_name, AVIO_FLAG_WRITE) < 0) {
av_log(NULL, AV_LOG_ERROR, "Nani: Could not open output file '%s'", file_name);
goto end;
}
}
//write video file header
if (avformat_write_header(ffp->m_ofmt_ctx, NULL) < 0) {
av_log(NULL, AV_LOG_ERROR, "Nani: Error occurred when opening output file\n");
goto end;
}
ffp->is_record = 1;
ffp->record_error = 0;
pthread_mutex_init(&ffp->record_mutex, NULL);
return 0;