Skip to content

Instantly share code, notes, and snippets.

@lqt0223
Last active February 19, 2018 00:16
Show Gist options
  • Select an option

  • Save lqt0223/b47e9c520360ab62e5d21c2a51023488 to your computer and use it in GitHub Desktop.

Select an option

Save lqt0223/b47e9c520360ab62e5d21c2a51023488 to your computer and use it in GitHub Desktop.
21 Using FFMpeg - bootstrap code for decoding
// a very simplified FFMPEG decoding bootstrap code (without any error handling...)
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
int main(int argc, const char *argv[])
{
// register formats
av_register_all();
// init format context and open the file
AVFormatContext *pFormatContext = avformat_alloc_context();
avformat_open_input(&pFormatContext, argv[1], NULL, NULL);
// find the video stream from streams in a file, and init codec
AVCodec *pCodec = NULL;
int video_stream_index = av_find_best_stream(pFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, &pCodec, 0);
AVCodecParameters *pCodecParameters = pFormatContext->streams[video_stream_index]->codecpar;
// init codec context
AVCodecContext *pCodecContext = avcodec_alloc_context3(pCodec);
avcodec_parameters_to_context(pCodecContext, pCodecParameters);
avcodec_open2(pCodecContext, pCodec, NULL);
// alloc frame and packet
AVFrame *pFrame = av_frame_alloc();
AVPacket *pPacket = av_packet_alloc();
int response = 0;
int how_many_packets_to_process = 8;
// call read frame in a loop
while (av_read_frame(pFormatContext, pPacket) >= 0 && how_many_packets_to_process > 0)
{
if (pPacket->stream_index == video_stream_index) {
// send packet
avcodec_send_packet(pCodecContext, pPacket);
how_many_packets_to_process--;
// attempting to receive frame
while(avcodec_receive_frame(pCodecContext, pFrame) >= 0) {
// do something with decoded frame here...
printf("%"PRId64, pFrame->pts);
printf("\n");
}
}
// clear up packet buffer for next frame
av_packet_unref(pPacket);
}
// free memory
avformat_close_input(&pFormatContext);
avformat_free_context(pFormatContext);
av_packet_free(&pPacket);
av_frame_free(&pFrame);
avcodec_free_context(&pCodecContext);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment