Advertisement
Guest User

Untitled

a guest
Apr 21st, 2016
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. void decodeVideoToFrames(const char *filePath){
  2.   AVCodec         *codec;
  3.   AVCodecContext  *codecCtx= NULL;
  4.   AVFormatContext *formatCtx = NULL;
  5.   AVFrame         *frame;
  6.   int             videoStreamIdx;
  7.   AVPacket        pkt;
  8.   int             frameFinished;
  9.    
  10.   avcodec_register_all();
  11.   av_register_all();
  12.  
  13.   formatCtx = avformat_alloc_context();
  14.  
  15.   avformat_open_input(&formatCtx, filePath, 0, NULL);
  16.  
  17.   avformat_find_stream_info(formatCtx, NULL);
  18.  
  19.   //for debugging, remove later
  20.   //av_dump_format(formatCtx, 0, filePath, 0);
  21.  
  22.   int i = 0;
  23.   videoStreamIdx = -1;
  24.   //the for loop exit condition is wrong, not sure what the right one is yet.
  25.   for(i = 0; -1 == videoStreamIdx; i++){
  26.     if(AVMEDIA_TYPE_VIDEO == formatCtx->streams[i]->codec->codec_type){
  27.       videoStreamIdx = i;
  28.       break;
  29.     }
  30.   }
  31.  
  32.   codecCtx = formatCtx->streams[videoStreamIdx]->codec;
  33.  
  34.   codec = avcodec_find_decoder(codecCtx->codec_id);
  35.  
  36.   avcodec_open2(codecCtx, codec, NULL);
  37.  
  38.   frame = av_frame_alloc();
  39.  
  40.   i = 0;
  41.   while(av_read_frame(formatCtx, &pkt) >= 0){
  42.     if(pkt.stream_index == videoStreamIdx){
  43.       i++;
  44.       avcodec_decode_video2(codecCtx, frame, &frameFinished, &pkt);
  45.       if(frameFinished){
  46.        
  47.         struct SwsContext* convertCtx;
  48.         //This can be improved significantly
  49.         convertCtx = sws_getContext(codecCtx->width, codecCtx->height, codecCtx->pix_fmt,
  50.                                 32,  18,  AV_PIX_FMT_RGB24, 0, 0, 0, 0);
  51.      
  52.         size_t allocSize = av_image_get_buffer_size(codecCtx->pix_fmt, codecCtx->width, codecCtx->height, 3);
  53.         uint8_t *outData = (uint8_t*) malloc(allocSize);
  54.         memset(outData, 0, allocSize);
  55.        
  56.         int outLinesize = 18;
  57.        
  58.         sws_scale(convertCtx, frame->data, frame->linesize, 0, 144, &outData, &outLinesize);
  59.  
  60.         sws_freeContext(convertCtx);
  61.    
  62.         FramesIn.push(outData);
  63.       }
  64.     }
  65.    
  66.     av_packet_unref(&pkt);
  67.   }
  68.  
  69.   av_free(frame);
  70.  
  71.   avcodec_close(codecCtx);
  72.   avformat_close_input(&formatCtx);
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement