Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 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.   frame = av_frame_alloc();
  15.  
  16.   avformat_open_input(&formatCtx, filePath, 0, NULL);
  17.  
  18.   avformat_find_stream_info(formatCtx, NULL);
  19.  
  20.   videoStreamIdx = -1;
  21.   //the for loop exit condition is wrong, not sure what the right one is yet.
  22.   for(int i = 0; -1 == videoStreamIdx; i++){
  23.     if(AVMEDIA_TYPE_VIDEO == formatCtx->streams[i]->codec->codec_type){
  24.       videoStreamIdx = i;
  25.       break;
  26.     }
  27.   }
  28.  
  29.   codecCtx = formatCtx->streams[videoStreamIdx]->codec;
  30.  
  31.   codec = avcodec_find_decoder(codecCtx->codec_id);
  32.  
  33.   avcodec_open2(codecCtx, codec, NULL);
  34.  
  35.   struct SwsContext* convertCtx;
  36.   //This can be improved significantly
  37.   convertCtx = sws_getContext(codecCtx->width, codecCtx->height, codecCtx->pix_fmt,
  38.                                 32,  18,  AV_PIX_FMT_RGB24, SWS_POINT, 0, 0, 0);
  39.  
  40.   while(av_read_frame(formatCtx, &pkt) >= 0){
  41.     if(pkt.stream_index == videoStreamIdx){
  42.       avcodec_decode_video2(codecCtx, frame, &frameFinished, &pkt);
  43.       if(frameFinished){
  44.      
  45.         size_t allocSize = av_image_get_buffer_size(AV_PIX_FMT_RGB24, 32, 18, 3);
  46.         uint8_t *data = (uint8_t*) malloc(allocSize);
  47.         int outLinesize = 32 * 3;
  48.        
  49.         sws_scale(convertCtx, frame->data, frame->linesize, 0, 144,
  50.             &data, &outLinesize);
  51.    
  52.         FramesIn.push(data);
  53.       }
  54.     }
  55.    
  56.     av_packet_unref(&pkt);
  57.   }
  58.  
  59.   sws_freeContext(convertCtx);
  60.   av_free(frame);
  61.   avcodec_close(codecCtx);
  62.   avformat_close_input(&formatCtx);
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement