Advertisement
Guest User

libav

a guest
Nov 4th, 2014
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. void video_parser::process_data(own_data *cd, const char *video_type) { // own_data has a std::vector<unsigned char> data
  2.     AVCodec *codec;
  3.     AVCodecContext *codec_context = NULL;
  4.     AVPacket packet;
  5.     AVFrame *frame;
  6.    
  7.     av_init_packet(&packet);
  8.  
  9.     if (strcmp(video_type, "mpeg1") == 0) {
  10.         codec = avcodec_find_decoder(CODEC_ID_MPEG1VIDEO);
  11.     }
  12.     if (strcmp(video_type, "mp4") == 0) {
  13.         codec = avcodec_find_decoder(CODEC_ID_MPEG4);
  14.     }
  15.  
  16.     if (!codec) {
  17.         std::cerr << "codec not found\n";
  18.         exit(1);
  19.     }
  20.  
  21.     codec_context = avcodec_alloc_context3(codec);
  22.     if (!codec_context) {
  23.         std::cerr << "could not allocate video codec context\n";
  24.         exit(1);
  25.     }
  26.  
  27.     frame = avcodec_alloc_frame();
  28.  
  29.     if (codec->capabilities & CODEC_CAP_TRUNCATED) {
  30.         codec_context->flags |= CODEC_FLAG_TRUNCATED;
  31.     }
  32.  
  33.     if (avcodec_open2(codec_context, codec, NULL) < 0) {
  34.         std::cerr << "could not open codec\n";
  35.         exit(1);
  36.     }
  37.  
  38.     frame = avcodec_alloc_frame();
  39.     if (!frame) {
  40.         std::cerr << "could not allocate frame\n";
  41.         exit(1);
  42.     }
  43.    
  44.     int frame_count = 0;
  45.     int got_frame;
  46.     bool wrote_frame_to_disk = false;
  47.  
  48.     if (cd->get_buff_size() <= 0) {
  49.         std::cerr << "no data available\n";
  50.         exit(1);
  51.     }
  52.     //
  53.     packet.size = cd->get_buff_size();
  54.     packet.data = &cd->data[0];
  55.  
  56.     std::cout <<"packet.size: " << packet.size << std::endl;
  57.     codec_context->width = 640;
  58.     codec_context->height = 480;
  59.  
  60.     while (packet.size > 0) {
  61.         int len = avcodec_decode_video2(codec_context, frame, &got_frame, &packet);
  62.         std::cout <<"len: " << len << std::endl;
  63.         if (len < 0) {
  64.             std::cerr << "error while decoding frame " << frame_count << "\n";
  65.             exit(1);
  66.         }
  67.         if (got_frame) {
  68.             // do stuff
  69.             frame_count++;
  70.         }
  71.         if (packet.data) {
  72.             packet.size -= len;
  73.             packet.data += len;
  74.         }
  75.     }
  76.  
  77.     std::cout << "found " << frame_count << " frames \n";
  78.  
  79.     packet.data = NULL;
  80.     packet.size = 0;
  81.     avcodec_close(codec_context);
  82.     av_free(codec_context);
  83.     avcodec_free_frame(&frame);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement