static TF_Buffer *read_graph(const char *model_filename) { TF_Buffer *graph_buf; unsigned char *graph_data = NULL; AVIOContext *model_file_context; long size, bytes_read; if (avio_open(&model_file_context, model_filename, AVIO_FLAG_READ) < 0){ return NULL; } size = avio_size(model_file_context); graph_data = av_malloc(size); if (!graph_data){ avio_closep(&model_file_context); return NULL; } bytes_read = avio_read(model_file_context, graph_data, size); avio_closep(&model_file_context); if (bytes_read != size){ av_freep(&graph_data); return NULL; } graph_buf = TF_NewBuffer(); graph_buf->data = (void *)graph_data; graph_buf->length = size; graph_buf->data_deallocator = free_buffer; return graph_buf; }
static void close_slaves(AVFormatContext *avf) { TeeContext *tee = avf->priv_data; AVFormatContext *avf2; unsigned i, j; for (i = 0; i < tee->nb_slaves; i++) { avf2 = tee->slaves[i].avf; for (j = 0; j < avf2->nb_streams; j++) { AVBitStreamFilterContext *bsf_next, *bsf = tee->slaves[i].bsfs[j]; while (bsf) { bsf_next = bsf->next; av_bitstream_filter_close(bsf); bsf = bsf_next; } } av_freep(&tee->slaves[i].stream_map); av_freep(&tee->slaves[i].bsfs); avio_closep(&avf2->pb); avformat_free_context(avf2); tee->slaves[i].avf = NULL; } }
static void finalize (GObject *object) { GeglProperties *o = GEGL_PROPERTIES (object); if (o->user_data) { Priv *p = (Priv*)o->user_data; flush_audio (o); flush_video (o); av_write_trailer (p->oc); if (p->video_st) close_video (p, p->oc, p->video_st); if (p->audio_st) close_audio (p, p->oc, p->audio_st); avio_closep (&p->oc->pb); avformat_free_context (p->oc); g_free (o->user_data); o->user_data = NULL; } G_OBJECT_CLASS (g_type_class_peek_parent (G_OBJECT_GET_CLASS (object)))->finalize (object); }
FFMPEGWriter::~FFMPEGWriter() { // writte missing data if(m_input_samples) encode(); close(); av_write_trailer(m_formatCtx); if(m_frame) av_frame_free(&m_frame); if(m_packet) { #ifdef FFMPEG_OLD_CODE delete m_packet; #else av_packet_free(&m_packet); #endif } #ifdef FFMPEG_OLD_CODE avcodec_close(m_codecCtx); #else if(m_codecCtx) avcodec_free_context(&m_codecCtx); #endif avio_closep(&m_formatCtx->pb); avformat_free_context(m_formatCtx); }
AVFormatWriter::~AVFormatWriter() { QMutexLocker locker(avcodeclock); if (m_ctx) { (void)av_write_trailer(m_ctx); avio_closep(&m_ctx->pb); for(unsigned int i = 0; i < m_ctx->nb_streams; i++) { av_freep(&m_ctx->streams[i]); } av_freep(&m_ctx); } if (m_audioInBuf) av_freep(&m_audioInBuf); if (m_audioInPBuf) av_freep(&m_audioInPBuf); if (m_audPicture) av_frame_free(&m_audPicture); Cleanup(); av_frame_free(&m_picture); }
static int sap_write_close(AVFormatContext *s) { struct SAPState *sap = s->priv_data; int i; for (i = 0; i < s->nb_streams; i++) { AVFormatContext *rtpctx = s->streams[i]->priv_data; if (!rtpctx) continue; av_write_trailer(rtpctx); avio_closep(&rtpctx->pb); avformat_free_context(rtpctx); s->streams[i]->priv_data = NULL; } if (sap->last_time && sap->ann && sap->ann_fd) { sap->ann[0] |= 4; /* Session deletion*/ ffurl_write(sap->ann_fd, sap->ann, sap->ann_size); } av_freep(&sap->ann); if (sap->ann_fd) ffurl_close(sap->ann_fd); ff_network_close(); return 0; }
static av_cold void uninit(AVFilterContext *ctx) { MetadataContext *s = ctx->priv; if (s->avio_context) { avio_closep(&s->avio_context); } }
static void close_encoder(EncoderContext *ec) { flush_frames(ec); av_write_trailer(ec->oc); close_stream(ec->oc, &(ec->video_st)); avio_closep(&(ec->oc->pb)); }
void AVFormatWriter::Cleanup(void) { if (m_ctx && m_ctx->pb) { avio_closep(&m_ctx->pb); } delete m_avfRingBuffer; m_avfRingBuffer = NULL; delete m_ringBuffer; m_ringBuffer = NULL; }
static void cleanup_save(struct GrooveFile *file) { struct GrooveFilePrivate *f = (struct GrooveFilePrivate *) file; av_free_packet(&f->audio_pkt); if (f->tempfile_exists) { remove(f->oc->filename); f->tempfile_exists = 0; } if (f->oc) { avio_closep(&f->oc->pb); avformat_free_context(f->oc); f->oc = NULL; } }
//////////////////////////////////////////////////////////////// // ビデオキャプチャ停止 // // 引数: なし // 返値: なし //////////////////////////////////////////////////////////////// void AVI6::StopAVI( void ) { #ifndef NOAVI if(oc){ cCritical::Lock(); isAVI = false; av_write_trailer(oc); CloseStream(oc, &video_st); CloseStream(oc, &audio_st); avio_closep(&oc->pb); avformat_free_context(oc); oc = NULL; cCritical::UnLock(); } #endif }
static void release() { if(inputFile.fmt_ctx != NULL) { avformat_close_input(&inputFile.fmt_ctx); } if(outputFile.fmt_ctx != NULL) { if(!(outputFile.fmt_ctx->oformat->flags & AVFMT_NOFILE)) { avio_closep(&outputFile.fmt_ctx->pb); } avformat_free_context(outputFile.fmt_ctx); } }
GifWriter::~GifWriter() { finish(); if (mStreamPtr->codec) { avcodec_close(mStreamPtr->codec); } if (mFmtCtxPtr && !(mFmtCtxPtr->oformat->flags & AVFMT_NOFILE)) { avio_closep(&mFmtCtxPtr->pb); } if (mFmtCtxPtr) { avformat_free_context(mFmtCtxPtr); } }
void AVIDump::CloseVideoFile() { av_frame_free(&s_src_frame); av_frame_free(&s_scaled_frame); avcodec_free_context(&s_codec_context); if (s_format_context) { avio_closep(&s_format_context->pb); } avformat_free_context(s_format_context); s_format_context = nullptr; if (s_sws_context) { sws_freeContext(s_sws_context); s_sws_context = nullptr; } }
void VideoEncoder::endCapture() { if(mpOutputContext) { // Flush the codex avcodec_send_frame(mpCodecContext, nullptr); flush(mpCodecContext, mpOutputContext, mpOutputStream, mFilename); av_write_trailer(mpOutputContext); avio_closep(&mpOutputContext->pb); avcodec_free_context(&mpCodecContext); av_frame_free(&mpFrame); sws_freeContext(mpSwsContext); avformat_free_context(mpOutputContext); mpOutputContext = nullptr; mpOutputStream = nullptr; } safe_delete(mpFlippedImage) }
static int tee_write_trailer(AVFormatContext *avf) { TeeContext *tee = avf->priv_data; AVFormatContext *avf2; int ret_all = 0, ret; unsigned i; for (i = 0; i < tee->nb_slaves; i++) { avf2 = tee->slaves[i].avf; if ((ret = av_write_trailer(avf2)) < 0) if (!ret_all) ret_all = ret; if (!(avf2->oformat->flags & AVFMT_NOFILE)) { if ((ret = avio_closep(&avf2->pb)) < 0) if (!ret_all) ret_all = ret; } } close_slaves(avf); return ret_all; }
// 内部函数实现 static int split_media_file(char *dst, char *src, __int64 start, __int64 end, PFN_SPC spc) { AVFormatContext *ifmt_ctx = NULL; AVFormatContext *ofmt_ctx = NULL; AVStream *istream = NULL; AVStream *ostream = NULL; AVRational tbms = { 1, 1000 }; AVRational tbvs = { 1, 1 }; int64_t startpts = -1; int64_t duration = -1; int64_t total = -1; int64_t current = -1; int streamidx= 0; int ret = -1; av_register_all(); avformat_network_init(); if ((ret = avformat_open_input(&ifmt_ctx, src, 0, 0)) < 0) { printf("could not open input file '%s' !", src); goto done; } if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) { printf("failed to retrieve input stream information ! \n"); goto done; } avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, dst); if (!ofmt_ctx) { printf("could not create output context !\n"); goto done; } for (unsigned i=0; i<ifmt_ctx->nb_streams; i++) { istream = ifmt_ctx->streams[i]; if (istream->codec->codec_type == AVMEDIA_TYPE_VIDEO) { streamidx = i; tbvs = ifmt_ctx->streams[i]->time_base; } ostream = avformat_new_stream(ofmt_ctx, istream->codec->codec); if (!ostream) { printf("failed allocating output stream !\n"); goto done; } ret = avcodec_copy_context(ostream->codec, istream->codec); if (ret < 0) { printf("failed to copy context from input to output stream codec context !\n"); goto done; } ostream->codec->codec_tag = 0; if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) { ostream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } } if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) { ret = avio_open(&ofmt_ctx->pb, dst, AVIO_FLAG_WRITE); if (ret < 0) { printf("could not open output file '%s' !", dst); goto done; } } // calulate pts if (start >= 0) { startpts = ifmt_ctx->start_time * 1000 / AV_TIME_BASE; duration = ifmt_ctx->duration * 1000 / AV_TIME_BASE; total = duration - start; if (total < 0) total = 1; current = 0; start += startpts; end += startpts; start = av_rescale_q_rnd(start, tbms, tbvs, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); end = av_rescale_q_rnd(end , tbms, tbvs, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); // seek to start position av_seek_frame(ifmt_ctx, streamidx, start, AVSEEK_FLAG_BACKWARD); } else { startpts = ifmt_ctx->start_time * 1000 / AV_TIME_BASE; duration = end; total = end; current = 0; start = startpts; end += startpts; start = av_rescale_q_rnd(start, tbms, tbvs, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); end = av_rescale_q_rnd(end , tbms, tbvs, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); } // write header ret = avformat_write_header(ofmt_ctx, NULL); if (ret < 0) { printf("error occurred when writing output file header !\n"); goto done; } while (!g_exit_remux) { AVPacket pkt; ret = av_read_frame(ifmt_ctx, &pkt); if (ret < 0) { // fprintf(stderr, "failed to read frame !\n"); break; } // get start pts if (pkt.stream_index == streamidx) { if (pkt.pts > end) { g_exit_remux = 1; goto next; } if (spc) { current = av_rescale_q_rnd(pkt.pts - start, tbvs, tbms, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); if (current < 0 ) current = 0; if (current > total) current = total; spc(current, total); } } istream = ifmt_ctx->streams[pkt.stream_index]; ostream = ofmt_ctx->streams[pkt.stream_index]; pkt.pts = av_rescale_q_rnd(pkt.pts, istream->time_base, ostream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); pkt.dts = av_rescale_q_rnd(pkt.dts, istream->time_base, ostream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); pkt.duration = av_rescale_q(pkt.duration, istream->time_base, ostream->time_base); pkt.pos = -1; ret = av_interleaved_write_frame(ofmt_ctx, &pkt); if (ret < 0) { printf("error muxing packet !\n"); g_exit_remux = 1; goto next; } next: av_packet_unref(&pkt); } // write trailer av_write_trailer(ofmt_ctx); done: // close input avformat_close_input(&ifmt_ctx); // close output if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) { avio_closep(&ofmt_ctx->pb); } avformat_free_context(ofmt_ctx); avformat_network_deinit(); // done printf("\n"); spc(total, total); printf("\ndone.\n"); return ret; }
int main_dummy(int argc, char **argv) #endif { AVOutputFormat *ofmt = NULL; AVFormatContext *inVideoFmtCtx = NULL, *inAudioFmtCtx = NULL, *outFmtCtx = NULL; AVPacket pkt; const char *inVideo_filename, *inAudio_filename, *out_filename; int ret, i; if (argc < 3) { printf("usage: %s input output\n" "API example program to remux a media file with libavformat and libavcodec.\n" "The output format is guessed according to the file extension.\n" "\n", argv[0]); return 1; } inVideo_filename = argv[1]; inAudio_filename = argv[2]; out_filename = argv[3]; av_register_all(); /* =============== OPEN STREAMS ================*/ if ((ret = open_input_file2(argv[1], &inVideoFmtCtx)) < 0) goto end; if ((ret = open_input_file2(argv[2], &inAudioFmtCtx)) < 0) goto end; /* ========== ALLOCATE OUTPUT CONTEXT ==========*/ avformat_alloc_output_context2(&outFmtCtx, NULL, NULL, out_filename); if (!outFmtCtx) { fprintf(stderr, "Could not create output context\n"); ret = AVERROR_UNKNOWN; goto end; } ofmt = outFmtCtx->oformat; /* =============== SETUP VIDEO CODEC ================*/ for (i = 0; i < inVideoFmtCtx->nb_streams; i++) { AVStream *in_stream = inVideoFmtCtx->streams[i]; AVStream *out_stream = avformat_new_stream(outFmtCtx, in_stream->codec->codec); if (!out_stream) { fprintf(stderr, "Failed allocating output stream\n"); ret = AVERROR_UNKNOWN; goto end; } ret = avcodec_copy_context(out_stream->codec, in_stream->codec); if (ret < 0) { fprintf(stderr, "Failed to copy context from input to output stream codec context\n"); goto end; } out_stream->codec->codec_tag = 0; if (outFmtCtx->oformat->flags & AVFMT_GLOBALHEADER) out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } /* =============== SETUP AUDIO CODEC ================*/ for (i = 0; i < inAudioFmtCtx->nb_streams; i++) { setup_mp3_audio_codec(outFmtCtx); } av_dump_format(outFmtCtx, 0, out_filename, 1); if (!(ofmt->flags & AVFMT_NOFILE)) { ret = avio_open(&outFmtCtx->pb, out_filename, AVIO_FLAG_WRITE); if (ret < 0) { fprintf(stderr, "Could not open output file '%s'", out_filename); goto end; } } ret = avformat_write_header(outFmtCtx, NULL); if (ret < 0) { fprintf(stderr, "Error occurred when opening output file\n"); goto end; } /* =============== SETUP FILTERS ================*/ init_filters(inAudioFmtCtx, outFmtCtx); AVStream *in_stream, *out_stream; AVFrame* frame; while (1) { /* =============== VIDEO STREAM ================*/ ret = av_read_frame(inVideoFmtCtx, &pkt); if (ret < 0) break; in_stream = inVideoFmtCtx->streams[pkt.stream_index]; out_stream = outFmtCtx->streams[pkt.stream_index]; log_packet(inVideoFmtCtx, &pkt, "in"); /* copy packet */ pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)); pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)); pkt.duration = (int)av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base); pkt.pos = -1; log_packet(outFmtCtx, &pkt, "out"); ret = av_interleaved_write_frame(outFmtCtx, &pkt); if (ret < 0) { fprintf(stderr, "Error muxing packet\n"); break; } av_free_packet(&pkt); /* =============== AUDIO STREAM ================*/ #if 0 ret = av_read_frame(inAudioFmtCtx, &pkt); if (ret < 0) break; in_stream = inAudioFmtCtx->streams[pkt.stream_index]; pkt.stream_index++; out_stream = outFmtCtx->streams[pkt.stream_index]; log_packet(inAudioFmtCtx, &pkt, "in"); /* copy packet */ pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)); pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)); pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base); pkt.pos = -1; log_packet(outFmtCtx, &pkt, "out"); ret = av_interleaved_write_frame(outFmtCtx, &pkt); if (ret < 0) { fprintf(stderr, "Error muxing packet\n"); break; } av_free_packet(&pkt); #else if ((ret = av_read_frame(inAudioFmtCtx, &pkt)) < 0) break; int streamIndex = pkt.stream_index; int gotFrame; if (_filterCtx[streamIndex].FilterGraph) { av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n"); frame = av_frame_alloc(); if (!frame) { ret = AVERROR(ENOMEM); break; } av_packet_rescale_ts(&pkt, inAudioFmtCtx->streams[streamIndex]->time_base, inAudioFmtCtx->streams[streamIndex]->codec->time_base); ret = avcodec_decode_audio4(inAudioFmtCtx->streams[streamIndex]->codec, frame, &gotFrame, &pkt); if (ret < 0) { av_frame_free(&frame); av_log(NULL, AV_LOG_ERROR, "Decoding failed\n"); break; } if (gotFrame) { frame->pts = av_frame_get_best_effort_timestamp(frame); ret = filter_encode_write_frame(frame, inAudioFmtCtx, outFmtCtx, streamIndex); av_frame_free(&frame); if (ret < 0) goto end; } else { av_frame_free(&frame); } } else { /* remux this frame without reencoding */ av_packet_rescale_ts(&pkt, inAudioFmtCtx->streams[streamIndex]->time_base, outFmtCtx->streams[streamIndex+1]->time_base); ret = av_interleaved_write_frame(outFmtCtx, &pkt); if (ret < 0) goto end; } av_free_packet(&pkt); #endif // 0 } av_write_trailer(outFmtCtx); end: av_free_packet(&pkt); av_frame_free(&frame); for (i = 0; i < inAudioFmtCtx->nb_streams; i++) { avcodec_close(inAudioFmtCtx->streams[i]->codec); if (outFmtCtx && outFmtCtx->nb_streams > i && outFmtCtx->streams[i] && outFmtCtx->streams[i]->codec) avcodec_close(outFmtCtx->streams[i]->codec); if (_filterCtx && _filterCtx[i].FilterGraph) avfilter_graph_free(&_filterCtx[i].FilterGraph); } av_free(_filterCtx); avformat_close_input(&inVideoFmtCtx); avformat_close_input(&inAudioFmtCtx); /* close output */ if (outFmtCtx && !(ofmt->flags & AVFMT_NOFILE)) avio_closep(&outFmtCtx->pb); avformat_free_context(outFmtCtx); if (ret < 0 && ret != AVERROR_EOF) { //fprintf(stderr, "Error occurred: %s\n", av_err2str(ret)); return 1; } return 0; }
int main(int argc, char **argv) { AVOutputFormat *ofmt = NULL; AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL; AVPacket pkt; int ret, i; av_register_all(); if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) { fprintf(stderr, "Could not open input file '%s'", in_filename); goto end; } if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) { fprintf(stderr, "Failed to retrieve input stream information"); goto end; } av_dump_format(ifmt_ctx, 0, in_filename, 0); avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename); if (!ofmt_ctx) { fprintf(stderr, "Could not create output context\n"); ret = AVERROR_UNKNOWN; goto end; } ofmt = ofmt_ctx->oformat; for (i = 0; i < ifmt_ctx->nb_streams; i++) { AVStream *in_stream = ifmt_ctx->streams[i]; AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec); if (!out_stream) { fprintf(stderr, "Failed allocating output stream\n"); ret = AVERROR_UNKNOWN; goto end; } ret = avcodec_copy_context(out_stream->codec, in_stream->codec); if (ret < 0) { fprintf(stderr, "Failed to copy context from input to output stream codec context\n"); goto end; } out_stream->codec->codec_tag = 0; if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } av_dump_format(ofmt_ctx, 0, out_filename, 1); if (!(ofmt->flags & AVFMT_NOFILE)) { ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE); if (ret < 0) { fprintf(stderr, "Could not open output file '%s'", out_filename); goto end; } } ret = avformat_write_header(ofmt_ctx, NULL); if (ret < 0) { fprintf(stderr, "Error occurred when opening output file\n"); goto end; } int frame = 0; while (1) { AVStream *in_stream, *out_stream; ret = av_read_frame(ifmt_ctx, &pkt); if (ret < 0) break; in_stream = ifmt_ctx->streams[pkt.stream_index]; out_stream = ofmt_ctx->streams[pkt.stream_index]; //log_packet(ifmt_ctx, &pkt, "in"); /* copy packet */ pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)); pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)); pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base); pkt.pos = -1; //log_packet(ofmt_ctx, &pkt, "out"); ret = av_interleaved_write_frame(ofmt_ctx, &pkt); if (ret < 0) { fprintf(stderr, "Error muxing packet\n"); break; } av_free_packet(&pkt); frame++; } printf("프레임의 수 : %d\n", frame); av_write_trailer(ofmt_ctx); end: avformat_close_input(&ifmt_ctx); /* close output */ if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE)) avio_closep(&ofmt_ctx->pb); avformat_free_context(ofmt_ctx); if (ret < 0 && ret != AVERROR_EOF) { char buf[256]; av_strerror(ret, buf, sizeof(buf)); fprintf(stderr, "Error occurred: %s\n", buf); return 1; } return 0; }
int main(int argc, char **argv) { int ret; AVPacket packet = { .data = NULL, .size = 0 }; AVFrame *frame = NULL; enum AVMediaType type; unsigned int stream_index; unsigned int i; int got_frame; int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *); if (argc != 3) { av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file> <output file>\n", argv[0]); return 1; } av_register_all(); avfilter_register_all(); if ((ret = open_input_file(argv[1])) < 0) goto end; if ((ret = open_output_file(argv[2])) < 0) goto end; if ((ret = init_filters()) < 0) goto end; /* read all packets */ while (1) { if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0) break; stream_index = packet.stream_index; type = ifmt_ctx->streams[packet.stream_index]->codec->codec_type; av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n", stream_index); if (filter_ctx[stream_index].filter_graph) { av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n"); frame = av_frame_alloc(); if (!frame) { ret = AVERROR(ENOMEM); break; } av_packet_rescale_ts(&packet, ifmt_ctx->streams[stream_index]->time_base, ifmt_ctx->streams[stream_index]->codec->time_base); dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 : avcodec_decode_audio4; ret = dec_func(ifmt_ctx->streams[stream_index]->codec, frame, &got_frame, &packet); if (ret < 0) { av_frame_free(&frame); av_log(NULL, AV_LOG_ERROR, "Decoding failed\n"); break; } if (got_frame) { frame->pts = av_frame_get_best_effort_timestamp(frame); ret = filter_encode_write_frame(frame, stream_index); av_frame_free(&frame); if (ret < 0) goto end; } else { av_frame_free(&frame); } } else { /* remux this frame without reencoding */ av_packet_rescale_ts(&packet, ifmt_ctx->streams[stream_index]->time_base, ofmt_ctx->streams[stream_index]->time_base); ret = av_interleaved_write_frame(ofmt_ctx, &packet); if (ret < 0) goto end; } av_packet_unref(&packet); } /* flush filters and encoders */ for (i = 0; i < ifmt_ctx->nb_streams; i++) { /* flush filter */ if (!filter_ctx[i].filter_graph) continue; ret = filter_encode_write_frame(NULL, i); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Flushing filter failed\n"); goto end; } /* flush encoder */ ret = flush_encoder(i); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n"); goto end; } } av_write_trailer(ofmt_ctx); end: av_packet_unref(&packet); av_frame_free(&frame); for (i = 0; i < ifmt_ctx->nb_streams; i++) { avcodec_close(ifmt_ctx->streams[i]->codec); if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && ofmt_ctx->streams[i]->codec) avcodec_close(ofmt_ctx->streams[i]->codec); if (filter_ctx && filter_ctx[i].filter_graph) avfilter_graph_free(&filter_ctx[i].filter_graph); } av_free(filter_ctx); avformat_close_input(&ifmt_ctx); if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) avio_closep(&ofmt_ctx->pb); avformat_free_context(ofmt_ctx); if (ret < 0) av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret)); return ret ? 1 : 0; }
int ff_rtp_chain_mux_open(AVFormatContext **out, AVFormatContext *s, AVStream *st, URLContext *handle, int packet_size, int idx) { AVFormatContext *rtpctx = NULL; int ret; AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL); uint8_t *rtpflags; AVDictionary *opts = NULL; if (!rtp_format) { ret = AVERROR(ENOSYS); goto fail; } /* Allocate an AVFormatContext for each output stream */ rtpctx = avformat_alloc_context(); if (!rtpctx) { ret = AVERROR(ENOMEM); goto fail; } rtpctx->oformat = rtp_format; if (!avformat_new_stream(rtpctx, NULL)) { ret = AVERROR(ENOMEM); goto fail; } /* Pass the interrupt callback on */ rtpctx->interrupt_callback = s->interrupt_callback; /* Copy the max delay setting; the rtp muxer reads this. */ rtpctx->max_delay = s->max_delay; /* Copy other stream parameters. */ rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio; rtpctx->flags |= s->flags & AVFMT_FLAG_BITEXACT; /* Get the payload type from the codec */ if (st->id < RTP_PT_PRIVATE) rtpctx->streams[0]->id = ff_rtp_get_payload_type(s, st->codecpar, idx); else rtpctx->streams[0]->id = st->id; if (av_opt_get(s, "rtpflags", AV_OPT_SEARCH_CHILDREN, &rtpflags) >= 0) av_dict_set(&opts, "rtpflags", rtpflags, AV_DICT_DONT_STRDUP_VAL); /* Set the synchronized start time. */ rtpctx->start_time_realtime = s->start_time_realtime; avcodec_parameters_copy(rtpctx->streams[0]->codecpar, st->codecpar); rtpctx->streams[0]->time_base = st->time_base; if (handle) { ret = ffio_fdopen(&rtpctx->pb, handle); if (ret < 0) ffurl_close(handle); } else ret = ffio_open_dyn_packet_buf(&rtpctx->pb, packet_size); if (!ret) ret = avformat_write_header(rtpctx, &opts); av_dict_free(&opts); if (ret) { if (handle && rtpctx->pb) { avio_closep(&rtpctx->pb); } else if (rtpctx->pb) { ffio_free_dyn_buf(&rtpctx->pb); } avformat_free_context(rtpctx); return ret; } *out = rtpctx; return 0; fail: avformat_free_context(rtpctx); if (handle) ffurl_close(handle); return ret; }
static int write_packet(AVFormatContext *s, AVPacket *pkt) { VideoMuxData *img = s->priv_data; AVIOContext *pb[4]; char filename[1024]; AVCodecContext *codec = s->streams[pkt->stream_index]->codec; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(codec->pix_fmt); int i; int nb_renames = 0; if (!img->is_pipe) { if (img->update) { av_strlcpy(filename, img->path, sizeof(filename)); } else if (img->use_strftime) { time_t now0; struct tm *tm, tmpbuf; time(&now0); tm = localtime_r(&now0, &tmpbuf); if (!strftime(filename, sizeof(filename), img->path, tm)) { av_log(s, AV_LOG_ERROR, "Could not get frame filename with strftime\n"); return AVERROR(EINVAL); } } else if (av_get_frame_filename(filename, sizeof(filename), img->path, img->img_number) < 0 && img->img_number > 1) { av_log(s, AV_LOG_ERROR, "Could not get frame filename number %d from pattern '%s' (either set updatefirst or use a pattern like %%03d within the filename pattern)\n", img->img_number, img->path); return AVERROR(EINVAL); } for (i = 0; i < 4; i++) { snprintf(img->tmp[i], sizeof(img->tmp[i]), "%s.tmp", filename); av_strlcpy(img->target[i], filename, sizeof(img->target[i])); if (avio_open2(&pb[i], img->use_rename ? img->tmp[i] : filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL) < 0) { av_log(s, AV_LOG_ERROR, "Could not open file : %s\n", img->use_rename ? img->tmp[i] : filename); return AVERROR(EIO); } if (!img->split_planes || i+1 >= desc->nb_components) break; filename[strlen(filename) - 1] = "UVAx"[i]; } if (img->use_rename) nb_renames = i + 1; } else { pb[0] = s->pb; } if (img->split_planes) { int ysize = codec->width * codec->height; int usize = AV_CEIL_RSHIFT(codec->width, desc->log2_chroma_w) * AV_CEIL_RSHIFT(codec->height, desc->log2_chroma_h); if (desc->comp[0].depth >= 9) { ysize *= 2; usize *= 2; } avio_write(pb[0], pkt->data , ysize); avio_write(pb[1], pkt->data + ysize , usize); avio_write(pb[2], pkt->data + ysize + usize, usize); avio_closep(&pb[1]); avio_closep(&pb[2]); if (desc->nb_components > 3) { avio_write(pb[3], pkt->data + ysize + 2*usize, ysize); avio_closep(&pb[3]); } } else if (img->muxer) { int ret; AVStream *st; AVPacket pkt2 = {0}; AVFormatContext *fmt = NULL; av_assert0(!img->split_planes); ret = avformat_alloc_output_context2(&fmt, NULL, img->muxer, s->filename); if (ret < 0) return ret; st = avformat_new_stream(fmt, NULL); if (!st) { avformat_free_context(fmt); return AVERROR(ENOMEM); } st->id = pkt->stream_index; fmt->pb = pb[0]; if ((ret = av_copy_packet(&pkt2, pkt)) < 0 || (ret = av_dup_packet(&pkt2)) < 0 || (ret = avcodec_copy_context(st->codec, s->streams[0]->codec)) < 0 || (ret = avformat_write_header(fmt, NULL)) < 0 || (ret = av_interleaved_write_frame(fmt, &pkt2)) < 0 || (ret = av_write_trailer(fmt)) < 0) { av_packet_unref(&pkt2); avformat_free_context(fmt); return ret; } av_packet_unref(&pkt2); avformat_free_context(fmt); } else { avio_write(pb[0], pkt->data, pkt->size); } avio_flush(pb[0]); if (!img->is_pipe) { avio_closep(&pb[0]); for (i = 0; i < nb_renames; i++) { ff_rename(img->tmp[i], img->target[i], s); } } img->img_number++; return 0; }
int main(int argc, char **argv) { AVOutputFormat *ofmt = NULL; AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL; AVPacket pkt; const char *in_filename, *out_filename; int ret, i; if (argc < 3) { printf("usage: %s input output\n" "API example program to remux a media file with libavformat and libavcodec.\n" "The output format is guessed according to the file extension.\n" "\n", argv[0]); return 1; } in_filename = argv[1]; out_filename = argv[2]; av_register_all(); if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) { fprintf(stderr, "Could not open input file '%s'", in_filename); goto end; } if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) { fprintf(stderr, "Failed to retrieve input stream information"); goto end; } av_dump_format(ifmt_ctx, 0, in_filename, 0); avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename); if (!ofmt_ctx) { fprintf(stderr, "Could not create output context\n"); ret = AVERROR_UNKNOWN; goto end; } ofmt = ofmt_ctx->oformat; for (i = 0; i < ifmt_ctx->nb_streams; i++) { AVStream *in_stream = ifmt_ctx->streams[i]; AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec); if (!out_stream) { fprintf(stderr, "Failed allocating output stream\n"); ret = AVERROR_UNKNOWN; goto end; } ret = avcodec_copy_context(out_stream->codec, in_stream->codec); if (ret < 0) { fprintf(stderr, "Failed to copy context from input to output stream codec context\n"); goto end; } out_stream->codec->codec_tag = 0; if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } av_dump_format(ofmt_ctx, 0, out_filename, 1); if (!(ofmt->flags & AVFMT_NOFILE)) { ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE); if (ret < 0) { fprintf(stderr, "Could not open output file '%s'", out_filename); goto end; } } ret = avformat_write_header(ofmt_ctx, NULL); if (ret < 0) { fprintf(stderr, "Error occurred when opening output file\n"); goto end; } while (1) { AVStream *in_stream, *out_stream; ret = av_read_frame(ifmt_ctx, &pkt); if (ret < 0) break; in_stream = ifmt_ctx->streams[pkt.stream_index]; out_stream = ofmt_ctx->streams[pkt.stream_index]; log_packet(ifmt_ctx, &pkt, "in"); /* copy packet */ pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base); pkt.pos = -1; log_packet(ofmt_ctx, &pkt, "out"); ret = av_interleaved_write_frame(ofmt_ctx, &pkt); if (ret < 0) { fprintf(stderr, "Error muxing packet\n"); break; } av_free_packet(&pkt); } av_write_trailer(ofmt_ctx); end: avformat_close_input(&ifmt_ctx); /* close output */ if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE)) avio_closep(&ofmt_ctx->pb); avformat_free_context(ofmt_ctx); if (ret < 0 && ret != AVERROR_EOF) { fprintf(stderr, "Error occurred: %s\n", av_err2str(ret)); return 1; } return 0; }
/** Convert an audio file to an AAC file in an MP4 container. */ int compress(int argc, char **argv) { AVFormatContext *input_format_context = NULL, *output_format_context = NULL; AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL; SwrContext *resample_context = NULL; AVAudioFifo *fifo = NULL; int ret = AVERROR_EXIT; if (argc < 3) { fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]); exit(1); } const char *input_filename = argv[1]; const char *output_filename = argv[2]; /** Register all codecs and formats so that they can be used. */ av_register_all(); /** Open the input file for reading. */ if (open_input_file(input_filename, &input_format_context, &input_codec_context)) goto cleanup; /** Open the output file for writing. */ if (open_output_file(output_filename, input_codec_context, &output_format_context, &output_codec_context)) goto cleanup; /** Initialize the resampler to be able to convert audio sample formats. */ if (init_resampler(input_codec_context, output_codec_context, &resample_context)) goto cleanup; /** Initialize the FIFO buffer to store audio samples to be encoded. */ if (init_fifo(&fifo, output_codec_context)) goto cleanup; /** Write the header of the output file container. */ if (write_output_file_header(output_format_context)) goto cleanup; /** * Loop as long as we have input samples to read or output samples * to write; abort as soon as we have neither. */ while (1) { /** Use the encoder's desired frame size for processing. */ const int output_frame_size = output_codec_context->frame_size; int finished = 0; /** * Make sure that there is one frame worth of samples in the FIFO * buffer so that the encoder can do its work. * Since the decoder's and the encoder's frame size may differ, we * need to FIFO buffer to store as many frames worth of input samples * that they make up at least one frame worth of output samples. */ while (av_audio_fifo_size(fifo) < output_frame_size) { /** * Decode one frame worth of audio samples, convert it to the * output sample format and put it into the FIFO buffer. */ if (read_decode_convert_and_store(fifo, input_format_context, input_codec_context, output_codec_context, resample_context, &finished)) goto cleanup; /** * If we are at the end of the input file, we continue * encoding the remaining audio samples to the output file. */ if (finished) break; } /** * If we have enough samples for the encoder, we encode them. * At the end of the file, we pass the remaining samples to * the encoder. */ while (av_audio_fifo_size(fifo) >= output_frame_size || (finished && av_audio_fifo_size(fifo) > 0)) /** * Take one frame worth of audio samples from the FIFO buffer, * encode it and write it to the output file. */ if (load_encode_and_write(fifo, output_format_context, output_codec_context)) goto cleanup; /** * If we are at the end of the input file and have encoded * all remaining samples, we can exit this loop and finish. */ if (finished) { int data_written; /** Flush the encoder as it may have delayed frames. */ do { if (encode_audio_frame(NULL, output_format_context, output_codec_context, &data_written)) goto cleanup; } while (data_written); break; } } /** Write the trailer of the output file container. */ if (write_output_file_trailer(output_format_context)) goto cleanup; ret = 0; cleanup: if (fifo) av_audio_fifo_free(fifo); swr_free(&resample_context); if (output_codec_context) avcodec_close(output_codec_context); if (output_format_context) { avio_closep(&output_format_context->pb); avformat_free_context(output_format_context); } if (input_codec_context) avcodec_close(input_codec_context); if (input_format_context) avformat_close_input(&input_format_context); return ret; }
/** * Open an output file and the required encoder. * Also set some basic encoder parameters. * Some of these parameters are based on the input file's parameters. */ static int open_output_file(const char *filename, AVCodecContext *input_codec_context, AVFormatContext **output_format_context, AVCodecContext **output_codec_context) { AVIOContext *output_io_context = NULL; AVStream *stream = NULL; AVCodec *output_codec = NULL; int error; /** Open the output file to write to it. */ if ((error = avio_open(&output_io_context, filename, AVIO_FLAG_WRITE)) < 0) { fprintf(stderr, "Could not open output file '%s' (error '%s')\n", filename, get_error_text(error)); return error; } /** Create a new format context for the output container format. */ if (!(*output_format_context = avformat_alloc_context())) { fprintf(stderr, "Could not allocate output format context\n"); return AVERROR(ENOMEM); } /** Associate the output file (pointer) with the container format context. */ (*output_format_context)->pb = output_io_context; /** Guess the desired container format based on the file extension. */ if (!((*output_format_context)->oformat = av_guess_format(NULL, filename, NULL))) { fprintf(stderr, "Could not find output file format\n"); goto cleanup; } av_strlcpy((*output_format_context)->filename, filename, sizeof((*output_format_context)->filename)); /** Find the encoder to be used by its name. */ if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) { fprintf(stderr, "Could not find an AAC encoder.\n"); goto cleanup; } /** Create a new audio stream in the output file container. */ if (!(stream = avformat_new_stream(*output_format_context, output_codec))) { fprintf(stderr, "Could not create new stream\n"); error = AVERROR(ENOMEM); goto cleanup; } /** Save the encoder context for easier access later. */ *output_codec_context = stream->codec; /** * Set the basic encoder parameters. * The input file's sample rate is used to avoid a sample rate conversion. */ (*output_codec_context)->channels = 1; (*output_codec_context)->channel_layout = av_get_default_channel_layout(1); (*output_codec_context)->sample_rate = input_codec_context->sample_rate; (*output_codec_context)->sample_fmt = output_codec->sample_fmts[0]; (*output_codec_context)->bit_rate = output_bit_rate; /** Set the sample rate for the container. */ stream->time_base.den = input_codec_context->sample_rate; stream->time_base.num = 1; /** * Some container formats (like MP4) require global headers to be present * Mark the encoder so that it behaves accordingly. */ if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER) (*output_codec_context)->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; /** Open the encoder for the audio stream to use it later. */ if ((error = avcodec_open2(*output_codec_context, output_codec, NULL)) < 0) { fprintf(stderr, "Could not open output codec (error '%s')\n", get_error_text(error)); goto cleanup; } return 0; cleanup: avio_closep(&(*output_format_context)->pb); avformat_free_context(*output_format_context); *output_format_context = NULL; return error < 0 ? error : AVERROR_EXIT; }
/* * Class: com_jpou_meditor_ffmpeg_trans * Method: startTrans * Signature: (Ljava/lang/String;Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_com_jpou_ffmpeg_Transcoding_startTrans (JNIEnv *env, jobject clazz, jstring input, jstring output) { int ret; AVPacket packet = { .data = NULL, .size = 0 }; AVFrame *frame = NULL; enum AVMediaType type; unsigned int stream_index; unsigned int i; int got_frame; int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *); char *input_str, *output_str; input_str = (*env)->GetStringUTFChars(env, input, 0); output_str = (*env)->GetStringUTFChars(env, output, 0); LOGI("input_str ~ : %s -------------------", input_str); LOGI("output_str ~ : %s -------------------", output_str); if ((input == NULL) || (output == NULL)) { LOGI("input_str or output_str is null"); return (jboolean)0; } av_register_all(); avfilter_register_all(); if ((ret = open_input_file(input_str)) < 0) { LOGI("open_input_file error"); goto end; } if ((ret = open_output_file(output_str)) < 0) { LOGI("open_output_file error"); goto end; } LOGI("init_filters ----------------"); if ((ret = init_filters()) < 0) { LOGI("init_filters error"); goto end; } /* read all packets */ LOGI("start av_read_frame ----------------"); while (1) { if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0) break; stream_index = packet.stream_index; type = ifmt_ctx->streams[packet.stream_index]->codec->codec_type; LOGI("Demuxer gave frame of stream_index %u\n", stream_index); if (filter_ctx[stream_index].filter_graph) { av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n"); frame = av_frame_alloc(); if (!frame) { ret = AVERROR(ENOMEM); break; } av_packet_rescale_ts(&packet, ifmt_ctx->streams[stream_index]->time_base, ifmt_ctx->streams[stream_index]->codec->time_base); dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 : avcodec_decode_audio4; ret = dec_func(ifmt_ctx->streams[stream_index]->codec, frame, &got_frame, &packet); if (ret < 0) { av_frame_free(&frame); LOGI("Decoding failed\n"); break; } if (got_frame) { frame->pts = av_frame_get_best_effort_timestamp(frame); ret = filter_encode_write_frame(frame, stream_index); av_frame_free(&frame); if (ret < 0) goto end; } else { av_frame_free(&frame); } } else { /* remux this frame without reencoding */ av_packet_rescale_ts(&packet, ifmt_ctx->streams[stream_index]->time_base, ofmt_ctx->streams[stream_index]->time_base); ret = av_interleaved_write_frame(ofmt_ctx, &packet); if (ret < 0) goto end; } av_free_packet(&packet); } /* flush filters and encoders */ for (i = 0; i < ifmt_ctx->nb_streams; i++) { /* flush filter */ if (!filter_ctx[i].filter_graph) continue; ret = filter_encode_write_frame(NULL, i); if (ret < 0) { LOGI("Flushing filter failed\n"); goto end; } /* flush encoder */ ret = flush_encoder(i); if (ret < 0) { LOGI("Flushing encoder failed\n"); goto end; } } av_write_trailer(ofmt_ctx); return (jboolean)1; end: av_free_packet(&packet); av_frame_free(&frame); for (i = 0; i < ifmt_ctx->nb_streams; i++) { avcodec_close(ifmt_ctx->streams[i]->codec); if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && ofmt_ctx->streams[i]->codec) avcodec_close(ofmt_ctx->streams[i]->codec); if (filter_ctx && filter_ctx[i].filter_graph) avfilter_graph_free(&filter_ctx[i].filter_graph); } av_free(filter_ctx); avformat_close_input(&ifmt_ctx); if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) avio_closep(&ofmt_ctx->pb); avformat_free_context(ofmt_ctx); /** if (ret < 0) av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret)); */ return (jboolean)0; } #ifdef __cplusplus }
/** * Open an output file and the required encoder. * Also set some basic encoder parameters. * Some of these parameters are based on the input file's parameters. * @param filename File to be opened * @param input_codec_context Codec context of input file * @param[out] output_format_context Format context of output file * @param[out] output_codec_context Codec context of output file * @return Error code (0 if successful) */ int Transcode::open_output_file(const char *filename, AVCodecContext *input_codec_context, AVFormatContext **output_format_context, AVCodecContext **output_codec_context) { AVCodecContext *avctx = NULL; AVIOContext *output_io_context = NULL; AVStream *stream = NULL; AVCodec *output_codec = NULL; int error; /* Open the output file to write to it. */ if ((error = avio_open(&output_io_context, filename, AVIO_FLAG_WRITE)) < 0) { fprintf(stderr, "Could not open output file '%s' (error '%s')\n", filename, av_cplus_err2str(error)); return error; } /* Create a new format context for the output container format. */ if (!(*output_format_context = avformat_alloc_context())) { fprintf(stderr, "Could not allocate output format context\n"); return AVERROR(ENOMEM); } /* Associate the output file (pointer) with the container format context. */ (*output_format_context)->pb = output_io_context; /* Guess the desired container format based on the file extension. */ if (!((*output_format_context)->oformat = av_guess_format(NULL, filename, NULL))) { fprintf(stderr, "Could not find output file format\n"); goto cleanup; } av_strlcpy((*output_format_context)->filename, filename, sizeof((*output_format_context)->filename)); /* Find the encoder to be used by its name. */ //if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) { if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_VORBIS))) { fprintf(stderr, "Could not find an OGG encoder.\n"); goto cleanup; } /* Create a new audio stream in the output file container. */ if (!(stream = avformat_new_stream(*output_format_context, NULL))) { fprintf(stderr, "Could not create new stream\n"); error = AVERROR(ENOMEM); goto cleanup; } avctx = avcodec_alloc_context3(output_codec); if (!avctx) { fprintf(stderr, "Could not allocate an encoding context\n"); error = AVERROR(ENOMEM); goto cleanup; } /* Set the basic encoder parameters. * The input file's sample rate is used to avoid a sample rate conversion. */ avctx->channels = this->audio_dst.channels; avctx->channel_layout = av_get_default_channel_layout(this->audio_dst.channels); avctx->sample_rate = input_codec_context->sample_rate; avctx->sample_fmt = output_codec->sample_fmts[0]; avctx->bit_rate = this->audio_dst.bitrate; /* Allow the use of the experimental AAC encoder. */ avctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL; /* Set the sample rate for the container. */ stream->time_base.den = input_codec_context->sample_rate; stream->time_base.num = 1; /* Some container formats (like MP4) require global headers to be present. * Mark the encoder so that it behaves accordingly. */ if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER) avctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; /* Open the encoder for the audio stream to use it later. */ if ((error = avcodec_open2(avctx, output_codec, NULL)) < 0) { fprintf(stderr, "Could not open output codec (error '%s')\n", av_cplus_err2str(error)); goto cleanup; } error = avcodec_parameters_from_context(stream->codecpar, avctx); if (error < 0) { fprintf(stderr, "Could not initialize stream parameters\n"); goto cleanup; } /* Save the encoder context for easier access later. */ *output_codec_context = avctx; return 0; cleanup: avcodec_free_context(&avctx); avio_closep(&(*output_format_context)->pb); avformat_free_context(*output_format_context); *output_format_context = NULL; return error < 0 ? error : AVERROR_EXIT; }
int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s filename\n", argv[0]); return 0; } f = fopen("002.avi", "wb"); if (signal(SIGINT, mysigint) == SIG_ERR) printf("Cannot handle SIGINT!\n"); //if (signal(SIGHUP, mysighup) == SIG_ERR) // printf("Cannot handle SIGHUP!\n"); //if (signal(SIGTERM, mysigterm) == SIG_ERR) // printf("Cannot handle SIGTERM!\n"); /* can SIGKILL be handled by our own function? */ //if (signal(SIGKILL, mysigkill) == SIG_ERR) // printf("Cannot handle SIGKILL!\n"); // Register all available file formats and codecs av_register_all(); int err; // Init SDL with video support err = SDL_Init(SDL_INIT_VIDEO); if (err < 0) { fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); return -1; } // Open video file const char* filename = argv[1]; AVFormatContext* format_context = NULL; err = avformat_open_input(&format_context, filename, NULL, NULL); if (err < 0) { fprintf(stderr, "ffmpeg: Unable to open input file\n"); return -1; } // Retrieve stream information err = avformat_find_stream_info(format_context, NULL); if (err < 0) { fprintf(stderr, "ffmpeg: Unable to find stream info\n"); return -1; } // Dump information about file onto standard error av_dump_format(format_context, 0, argv[1], 0); // Find the first video stream int video_stream; for (video_stream = 0; video_stream < format_context->nb_streams; ++video_stream) { if (format_context->streams[video_stream]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { break; } } if (video_stream == format_context->nb_streams) { fprintf(stderr, "ffmpeg: Unable to find video stream\n"); return -1; } AVCodecContext* codec_context = format_context->streams[video_stream]->codec; AVCodec* codec = avcodec_find_decoder(codec_context->codec_id); err = avcodec_open2(codec_context, codec, NULL); if (err < 0) { fprintf(stderr, "ffmpeg: Unable to open codec\n"); return -1; } SDL_Surface* screen = SDL_SetVideoMode(codec_context->width, codec_context->height, 0, 0); if (screen == NULL) { fprintf(stderr, "Couldn't set video mode\n"); return -1; } SDL_Overlay* bmp = SDL_CreateYUVOverlay(codec_context->width, codec_context->height, SDL_YV12_OVERLAY, screen); struct SwsContext* img_convert_context; img_convert_context = sws_getCachedContext(NULL, codec_context->width, codec_context->height, codec_context->pix_fmt, codec_context->width, codec_context->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL); if (img_convert_context == NULL) { fprintf(stderr, "Cannot initialize the conversion context\n"); return -1; } AVFrame* frame = avcodec_alloc_frame(); AVPacket packet; AVPacket packet_copy; // preparing output ... int i, ret; char * outputfile = "test.mpg"; AVFormatContext * oformat_context = NULL; AVOutputFormat *ofmt = NULL; avformat_alloc_output_context2(&oformat_context, NULL, NULL, outputfile); if (!oformat_context) { fprintf(stderr, "Could not create output context\n"); ret = AVERROR_UNKNOWN; return (-1); }; ofmt = oformat_context->oformat; for (i = 0; i < format_context->nb_streams; i++) { AVStream *in_stream = format_context->streams[i]; AVStream *out_stream = avformat_new_stream(oformat_context, in_stream->codec->codec); if (!out_stream) { fprintf(stderr, "Failed allocating output stream\n"); ret = AVERROR_UNKNOWN; return (-1); } ret = avcodec_copy_context(out_stream->codec, in_stream->codec); if (ret < 0) { fprintf(stderr, "Failed to copy context from input to output stream codec context\n"); return (-1); } out_stream->codec->codec_tag = 0; if (oformat_context->oformat->flags & AVFMT_GLOBALHEADER) out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } av_dump_format(oformat_context, 0, outputfile, 1); if (!(ofmt->flags & AVFMT_NOFILE)) { ret = avio_open(&oformat_context->pb, outputfile, AVIO_FLAG_WRITE); if (ret < 0) { fprintf(stderr, "Could not open output file '%s'", outputfile); return (-1); } } ret = avformat_write_header(oformat_context, NULL); if (ret < 0) { fprintf(stderr, "Error occurred when opening output file\n"); return (-1); }; AVStream *in_stream, *out_stream; while (av_read_frame(format_context, &packet) >= 0) { av_copy_packet(&packet_copy, &packet); // in_stream = format_context->streams[packet_copy.stream_index]; // out_stream = oformat_context->streams[packet_copy.stream_index]; // packet_copy.pts = av_rescale_q_rnd(packet_copy.pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); // packet_copy.dts = av_rescale_q_rnd(packet_copy.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); // packet_copy.duration = av_rescale_q(packet_copy.duration, in_stream->time_base, out_stream->time_base); // packet_copy.pos = -1; ret = av_interleaved_write_frame(oformat_context, &packet_copy); if (ret < 0) { fprintf(stderr, "Error muxing packet\n"); }; if (packet.stream_index == video_stream) { // Video stream packet int frame_finished; avcodec_decode_video2(codec_context, frame, &frame_finished, &packet); if (frame_finished) { SDL_LockYUVOverlay(bmp); // Convert frame to YV12 pixel format for display in SDL overlay AVPicture pict; pict.data[0] = bmp->pixels[0]; pict.data[1] = bmp->pixels[2]; // it's because YV12 pict.data[2] = bmp->pixels[1]; pict.linesize[0] = bmp->pitches[0]; pict.linesize[1] = bmp->pitches[2]; pict.linesize[2] = bmp->pitches[1]; sws_scale(img_convert_context, frame->data, frame->linesize, 0, codec_context->height, pict.data, pict.linesize); SDL_UnlockYUVOverlay(bmp); SDL_Rect rect; rect.x = 0; rect.y = 0; rect.w = codec_context->width; rect.h = codec_context->height; SDL_DisplayYUVOverlay(bmp, &rect); printf("%d\n", packet.size); fwrite(packet.data, 1, packet.size, f); } } // Free the packet that was allocated by av_read_frame av_free_packet(&packet); // Handling SDL events there SDL_Event event; if (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { break; } } } fclose(f); av_write_trailer(oformat_context); if (oformat_context && !(ofmt->flags & AVFMT_NOFILE)) avio_closep(&oformat_context->pb); avformat_free_context(oformat_context); sws_freeContext(img_convert_context); // Free the YUV frame av_free(frame); // Close the codec avcodec_close(codec_context); // Close the video file avformat_close_input(&format_context); // Quit SDL SDL_Quit(); return 0; }
int main(int argc, char **argv) { char *in_graph_desc, **out_dev_name; int nb_out_dev = 0, nb_streams = 0; AVFilterGraph *in_graph = NULL; Stream *streams = NULL, *st; AVFrame *frame = NULL; int i, j, run = 1, ret; //av_log_set_level(AV_LOG_DEBUG); if (argc < 3) { av_log(NULL, AV_LOG_ERROR, "Usage: %s filter_graph dev:out [dev2:out2...]\n\n" "Examples:\n" "%s movie=file.nut:s=v+a xv:- alsa:default\n" "%s movie=file.nut:s=v+a uncodedframecrc:pipe:0\n", argv[0], argv[0], argv[0]); exit(1); } in_graph_desc = argv[1]; out_dev_name = argv + 2; nb_out_dev = argc - 2; av_register_all(); avdevice_register_all(); avfilter_register_all(); /* Create input graph */ if (!(in_graph = avfilter_graph_alloc())) { ret = AVERROR(ENOMEM); av_log(NULL, AV_LOG_ERROR, "Unable to alloc graph graph: %s\n", av_err2str(ret)); goto fail; } ret = avfilter_graph_parse_ptr(in_graph, in_graph_desc, NULL, NULL, NULL); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Unable to parse graph: %s\n", av_err2str(ret)); goto fail; } nb_streams = 0; for (i = 0; i < in_graph->nb_filters; i++) { AVFilterContext *f = in_graph->filters[i]; for (j = 0; j < f->nb_inputs; j++) { if (!f->inputs[j]) { av_log(NULL, AV_LOG_ERROR, "Graph has unconnected inputs\n"); ret = AVERROR(EINVAL); goto fail; } } for (j = 0; j < f->nb_outputs; j++) if (!f->outputs[j]) nb_streams++; } if (!nb_streams) { av_log(NULL, AV_LOG_ERROR, "Graph has no output stream\n"); ret = AVERROR(EINVAL); goto fail; } if (nb_out_dev != 1 && nb_out_dev != nb_streams) { av_log(NULL, AV_LOG_ERROR, "Graph has %d output streams, %d devices given\n", nb_streams, nb_out_dev); ret = AVERROR(EINVAL); goto fail; } if (!(streams = av_calloc(nb_streams, sizeof(*streams)))) { ret = AVERROR(ENOMEM); av_log(NULL, AV_LOG_ERROR, "Could not allocate streams\n"); } st = streams; for (i = 0; i < in_graph->nb_filters; i++) { AVFilterContext *f = in_graph->filters[i]; for (j = 0; j < f->nb_outputs; j++) { if (!f->outputs[j]) { if ((ret = create_sink(st++, in_graph, f, j)) < 0) goto fail; } } } av_assert0(st - streams == nb_streams); if ((ret = avfilter_graph_config(in_graph, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Failed to configure graph\n"); goto fail; } /* Create output devices */ for (i = 0; i < nb_out_dev; i++) { char *fmt = NULL, *dev = out_dev_name[i]; st = &streams[i]; if ((dev = strchr(dev, ':'))) { *(dev++) = 0; fmt = out_dev_name[i]; } ret = avformat_alloc_output_context2(&st->mux, NULL, fmt, dev); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Failed to allocate output: %s\n", av_err2str(ret)); goto fail; } if (!(st->mux->oformat->flags & AVFMT_NOFILE)) { ret = avio_open2(&st->mux->pb, st->mux->filename, AVIO_FLAG_WRITE, NULL, NULL); if (ret < 0) { av_log(st->mux, AV_LOG_ERROR, "Failed to init output: %s\n", av_err2str(ret)); goto fail; } } } for (; i < nb_streams; i++) streams[i].mux = streams[0].mux; /* Create output device streams */ for (i = 0; i < nb_streams; i++) { st = &streams[i]; if (!(st->stream = avformat_new_stream(st->mux, NULL))) { ret = AVERROR(ENOMEM); av_log(NULL, AV_LOG_ERROR, "Failed to create output stream\n"); goto fail; } st->stream->codec->codec_type = st->link->type; st->stream->time_base = st->stream->codec->time_base = st->link->time_base; switch (st->link->type) { case AVMEDIA_TYPE_VIDEO: st->stream->codec->codec_id = AV_CODEC_ID_RAWVIDEO; st->stream->avg_frame_rate = st->stream-> r_frame_rate = av_buffersink_get_frame_rate(st->sink); st->stream->codec->width = st->link->w; st->stream->codec->height = st->link->h; st->stream->codec->sample_aspect_ratio = st->link->sample_aspect_ratio; st->stream->codec->pix_fmt = st->link->format; break; case AVMEDIA_TYPE_AUDIO: st->stream->codec->channel_layout = st->link->channel_layout; st->stream->codec->channels = avfilter_link_get_channels(st->link); st->stream->codec->sample_rate = st->link->sample_rate; st->stream->codec->sample_fmt = st->link->format; st->stream->codec->codec_id = av_get_pcm_codec(st->stream->codec->sample_fmt, -1); break; default: av_assert0(!"reached"); } } /* Init output devices */ for (i = 0; i < nb_out_dev; i++) { st = &streams[i]; if ((ret = avformat_write_header(st->mux, NULL)) < 0) { av_log(st->mux, AV_LOG_ERROR, "Failed to init output: %s\n", av_err2str(ret)); goto fail; } } /* Check output devices */ for (i = 0; i < nb_streams; i++) { st = &streams[i]; ret = av_write_uncoded_frame_query(st->mux, st->stream->index); if (ret < 0) { av_log(st->mux, AV_LOG_ERROR, "Uncoded frames not supported on stream #%d: %s\n", i, av_err2str(ret)); goto fail; } } while (run) { ret = avfilter_graph_request_oldest(in_graph); if (ret < 0) { if (ret == AVERROR_EOF) { run = 0; } else { av_log(NULL, AV_LOG_ERROR, "Error filtering: %s\n", av_err2str(ret)); break; } } for (i = 0; i < nb_streams; i++) { st = &streams[i]; while (1) { if (!frame && !(frame = av_frame_alloc())) { ret = AVERROR(ENOMEM); av_log(NULL, AV_LOG_ERROR, "Could not allocate frame\n"); goto fail; } ret = av_buffersink_get_frame_flags(st->sink, frame, AV_BUFFERSINK_FLAG_NO_REQUEST); if (ret < 0) { if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) av_log(NULL, AV_LOG_WARNING, "Error in sink: %s\n", av_err2str(ret)); break; } if (frame->pts != AV_NOPTS_VALUE) frame->pts = av_rescale_q(frame->pts, st->link ->time_base, st->stream->time_base); ret = av_interleaved_write_uncoded_frame(st->mux, st->stream->index, frame); frame = NULL; if (ret < 0) { av_log(st->stream->codec, AV_LOG_ERROR, "Error writing frame: %s\n", av_err2str(ret)); goto fail; } } } } ret = 0; for (i = 0; i < nb_out_dev; i++) { st = &streams[i]; av_write_trailer(st->mux); } fail: av_frame_free(&frame); avfilter_graph_free(&in_graph); if (streams) { for (i = 0; i < nb_out_dev; i++) { st = &streams[i]; if (st->mux) { if (st->mux->pb) avio_closep(&st->mux->pb); avformat_free_context(st->mux); } } } av_freep(&streams); return ret < 0; }
/** * * @param orig * @param dest * @return */ int Transcode::transcode(string orig, string dest, TID3Tags *tags) { AVFormatContext *input_format_context = NULL, *output_format_context = NULL; AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL; SwrContext *resample_context = NULL; AVAudioFifo *fifo = NULL; int ret = AVERROR_EXIT; this->pts = 0; if (orig.empty() || dest.empty()) { fprintf(stderr, "Files to process not especified\n"); return ret; } /* Register all codecs and formats so that they can be used. */ av_register_all(); /* Open the input file for reading. */ if (open_input_file(orig.c_str(), &input_format_context, &input_codec_context)) goto cleanup; /* Open the output file for writing. */ if (open_output_file(dest.c_str(), input_codec_context, &output_format_context, &output_codec_context)) goto cleanup; /**Copy the metadata if exist*/ copy_metadata(input_format_context, output_format_context, tags); /* Initialize the resampler to be able to convert audio sample formats. */ if (init_resampler(input_codec_context, output_codec_context, &resample_context)) goto cleanup; /* Initialize the FIFO buffer to store audio samples to be encoded. */ if (init_fifo(&fifo, output_codec_context)) goto cleanup; /* Write the header of the output file container. */ if (write_output_file_header(output_format_context)) goto cleanup; /* Loop as long as we have input samples to read or output samples * to write; abort as soon as we have neither. */ while (1) { /* Use the encoder's desired frame size for processing. */ const int output_frame_size = output_codec_context->frame_size; int finished = 0; /* Make sure that there is one frame worth of samples in the FIFO * buffer so that the encoder can do its work. * Since the decoder's and the encoder's frame size may differ, we * need to FIFO buffer to store as many frames worth of input samples * that they make up at least one frame worth of output samples. */ while (av_audio_fifo_size(fifo) < output_frame_size) { /* Decode one frame worth of audio samples, convert it to the * output sample format and put it into the FIFO buffer. */ if (read_decode_convert_and_store(fifo, input_format_context, input_codec_context, output_codec_context, resample_context, &finished)) goto cleanup; /* If we are at the end of the input file, we continue * encoding the remaining audio samples to the output file. */ if (finished) break; } /* If we have enough samples for the encoder, we encode them. * At the end of the file, we pass the remaining samples to * the encoder. */ while (av_audio_fifo_size(fifo) >= output_frame_size || (finished && av_audio_fifo_size(fifo) > 0)) /* Take one frame worth of audio samples from the FIFO buffer, * encode it and write it to the output file. */ if (load_encode_and_write(fifo, output_format_context, output_codec_context)) goto cleanup; /* If we are at the end of the input file and have encoded * all remaining samples, we can exit this loop and finish. */ if (finished) { int data_written; /* Flush the encoder as it may have delayed frames. */ do { if (encode_audio_frame(NULL, output_format_context, output_codec_context, &data_written)) goto cleanup; } while (data_written); break; } } /* Write the trailer of the output file container. */ if (write_output_file_trailer(output_format_context)) goto cleanup; ret = 0; cleanup: if (fifo) av_audio_fifo_free(fifo); swr_free(&resample_context); if (output_codec_context) avcodec_free_context(&output_codec_context); if (output_format_context) { avio_closep(&output_format_context->pb); avformat_free_context(output_format_context); } if (input_codec_context) avcodec_free_context(&input_codec_context); if (input_format_context) avformat_close_input(&input_format_context); return ret; }