Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* FFmpeg Usage Example
- * Date : 28 July 2019
- */
- #include <stdio.h>
- #include <libavformat/avformat.h>
- #include <libavcodec/avcodec.h>
- #include <libavutil/avutil.h>
- #include <assert.h>
- int decode_packet(AVCodecContext*, AVPacket*, AVFrame*);
- int main(void) {
- AVFormatContext *pFormatContext = avformat_alloc_context();
- AVCodecParameters *pCodecParameters = NULL;
- if(avformat_open_input(&pFormatContext,"song.mp3",NULL,NULL)!=0) {
- fprintf(stderr,"Could not open file\n");
- return -1;
- }
- if(avformat_find_stream_info(pFormatContext,NULL)<0) {
- fprintf(stderr,"Could not find stream\n");
- return -1;
- }
- size_t stream_index = 0;
- for(;stream_index<pFormatContext->nb_streams;stream_index++) {
- if(pFormatContext->streams[stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
- pCodecParameters = pFormatContext->streams[stream_index]->codecpar;
- }
- break;
- }
- if(stream_index == -1) {
- fprintf(stderr,"could not retrive stream info from file\n");
- return -1;
- }
- AVStream *stream = pFormatContext->streams[stream_index];
- pCodecParameters = stream->codecpar;
- AVCodec *cdc = avcodec_find_decoder(pCodecParameters->codec_id);
- AVCodecContext *cdc_ctx = avcodec_alloc_context3(cdc);
- assert(pCodecParameters);
- if(avcodec_parameters_to_context(cdc_ctx,pCodecParameters) < 0) {
- fprintf(stderr,"Can't copy params to codec context\n");
- return -1;
- }
- if(avcodec_open2(cdc_ctx,cdc,NULL) < 0) {
- fprintf(stderr,"Failed to open decoder for stream\n");
- return -1;
- }
- AVFrame *frame = av_frame_alloc();
- if(!frame) {
- fprintf(stderr,"could not allocate memory for frame\n");
- return -1;
- }
- AVPacket *packet = av_packet_alloc();
- // av_init_packet(&packet);
- if(!packet) {
- fprintf(stderr,"could not allocate memory for packet");
- return -1;
- }
- packet->data=NULL;
- packet->size=0;
- // lets read the packets
- while(av_read_frame(pFormatContext,packet) >= 0) {
- if(packet->stream_index==stream_index) {
- int response = 0 ;
- response = decode_packet(cdc_ctx,packet,frame);
- if(response < 0)
- continue;
- }
- av_packet_unref(packet);
- }
- return 0;
- }
- int decode_packet(AVCodecContext *cdc_ctx , AVPacket *pkt, AVFrame *frm) {
- int response = avcodec_send_packet(cdc_ctx,pkt); if(response < 0)
- return response; while(response >= 0) {
- response = avcodec_receive_frame(cdc_ctx,frm);
- if(response == AVERROR(EAGAIN) || response == AVERROR_EOF)
- return -1;
- else if(response < 0)
- return response;
- }
- return 0;
- }
- ~
Add Comment
Please, Sign In to add comment