Chinaunix首页 | 论坛 | 博客
  • 博客访问: 85497
  • 博文数量: 14
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 153
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-13 11:26
文章分类

全部博文(14)

文章存档

2015年(2)

2014年(7)

2013年(5)

我的朋友

分类: C/C++

2014-04-22 20:48:50


Tutorial 03: Playing Sound

Audio

So now we want to play sound. SDL also gives us methods for outputting sound. The () function is used to open the audio device itself. It takes as arguments an  struct, which contains all the information about the audio we are going to output.

Before we show how you set this up, let's explain first about how audio is handled by computers. Digital audio consists of a long stream of samples. Each sample represents a value of the audio . Sounds are recorded at a certain sample rate, which simply says how fast to play each sample, and is measured in number of samples per second. Example sample rates are 22,050 and 44,100 samples per second, which are the rates used for radio and CD respectively. In addition, most audio can have more than one channel for stereo or surround, so for example, if the sample is in stereo, the samples will come 2 at a time. When we get data from a movie file, we don't know how many samples we will get, but ffmpeg will not give us partial samples - that also means that it will not split a stereo sample up, either.

SDL's method for playing audio is this: you set up your audio options: the sample rate (called "freq" for frequency in the SDL struct), number of channels, and so forth, and we also set a callback function and userdata. When we begin playing audio, SDL will continually call this callback function and ask it to fill the audio buffer with a certain number of bytes. After we put this information in the  struct, we call(), which will open the audio device and give us back another AudioSpec struct. These are the specs we will actually be using — we are not guaranteed to get what we asked for!

Setting Up the Audio

Keep that all in your head for the moment, because we don't actually have any information yet about the audio streams yet! Let's go back to the place in our code where we found the video stream and find which stream is the audio stream.

// Find the first video stream
videoStream=-1;
audioStream=-1;
for(i=0; i < pFormatCtx->nb_streams; i++) {
  if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO
     &&
       videoStream < 0) {
    videoStream=i;
  }
  if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO &&
     audioStream < 0) {
    audioStream=i;
  }
}
if(videoStream==-1)
  return -1; // Didn't find a video stream
if(audioStream==-1)
  return -1;
From here we can get all the info we want from the  from the stream, just like we did with the video stream:
 *aCodecCtx;

aCodecCtx=pFormatCtx->streams[audioStream]->codec;


Contained within this codec context is all the information we need to set up our audio:

wanted_spec.freq = aCodecCtx->sample_rate;
wanted_spec.format = AUDIO_S16SYS;
wanted_spec.channels = aCodecCtx->channels;
wanted_spec.silence = 0;
wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
wanted_spec.callback = audio_callback;
wanted_spec.userdata = aCodecCtx;

if((&wanted_spec, &spec) < 0) {
  fprintf(stderr, ": %s\n", SDL_GetError());
  return -1;
}
Let's go through these:
  • freq: The sample rate, as explained earlier.
  • format: This tells SDL what format we will be giving it. The "S" in "S16SYS" stands for "signed", the 16 says that each sample is 16 bits long, and "SYS" means that the endian-order will depend on the system you are on. This is the format that  will give us the audio in.
  • channels: Number of audio channels.
  • silence: This is the value that indicated silence. Since the audio is signed, 0 is of course the usual value.
  • samples: This is the size of the audio buffer that we would like SDL to give us when it asks for more audio. A good value here is between 512 and 8192; ffplay uses 1024.
  • callback: Here's where we pass the actual callback function. We'll talk more about the callback function later.
  • userdata: SDL will give our callback a void pointer to any user data that we want our callback function to have. We want to let it know about our codec context; you'll see why.
Finally, we open the audio with .


If you remember from the previous tutorials, we still need to open the audio codec itself. This is straightforward:

AVCodec         *aCodec;

aCodec = (aCodecCtx->codec_id);
if(!aCodec) {
  fprintf(stderr, "Unsupported codec!\n");
  return -1;
} (aCodecCtx, aCodec);


Queues

There! Now we're ready to start pulling audio information from the stream. But what do we do with that information? We are going to be continuously getting packets from the movie file, but at the same time SDL is going to call the callback function! The solution is going to be to create some kind of global structure that we can stuff audio packets in so our audio_callback has something to get audio data from! So what we're going to do is to create a queue of packets. ffmpeg even comes with a structure to help us with this: , which is just a linked list for packets. Here's our queue structure:

typedef struct PacketQueue {  *first_pkt, *last_pkt;
  int nb_packets;
  int size;  *mutex;  *cond;
} PacketQueue;
First, we should point out that nb_packets is not the same as size — size refers to a byte size that we get from packet->size. You'll notice that we have a  and a  in there. This is because SDL is running the audio process as a separate thread. If we don't lock the queue properly, we could really mess up our data. We'll see how in the implementation of the queue. Every programmer should know how to make a queue, but we're including this so you can learn the SDL functions.


First we make a function to initialize the queue:

void packet_queue_init(PacketQueue *q) {
  memset(q, 0, sizeof(PacketQueue));
  q->mutex = ();
  q->cond = ();
}
Then we will make a function to put stuff in our queue:
int packet_queue_put(PacketQueue *q,  *pkt) {  *pkt1;
  if((pkt) < 0) {
    return -1;
  }
  pkt1 = (sizeof());
  if (!pkt1)
    return -1;
  pkt1->pkt = *pkt;
  pkt1->next = NULL; (q->mutex);
  
  if (!q->last_pkt)
    q->first_pkt = pkt1;
  else
    q->last_pkt->next = pkt1;
  q->last_pkt = pkt1;
  q->nb_packets++;
  q->size += pkt1->pkt.size; (q->cond); (q->mutex);
  return 0;
}
() locks the mutex in the queue so we can add something to it, and then () sends a signal to our get function (if it is waiting) through our condition variable to tell it that there is data and it can proceed, then unlocks the mutex to let it go.


Here's the corresponding get function. Notice how () makes the function block (i.e. pause until we get data) if we tell it to.

int quit = 0;

static int packet_queue_get(PacketQueue *q,  *pkt, int block) {  *pkt1;
  int ret; (q->mutex);
  
  for(;;) {
    
    if(quit) {
      ret = -1;
      break;
    }

    pkt1 = q->first_pkt;
    if (pkt1) {
      q->first_pkt = pkt1->next;
      if (!q->first_pkt)
	q->last_pkt = NULL;
      q->nb_packets--;
      q->size -= pkt1->pkt.size;
      *pkt = pkt1->pkt; (pkt1);
      ret = 1;
      break;
    } else if (!block) {
      ret = 0;
      break;
    } else { (q->cond, q->mutex);
    }
  } (q->mutex);
  return ret;
}
As you can see, we've wrapped the function in a forever loop so we will be sure to get some data if we want to block. We avoid looping forever by making use of SDL's () function. Basically, all CondWait does is wait for a signal from () (orSDL_CondBroadcast()) and then continue. However, it looks as though we've trapped it within our mutex — if we hold the lock, our put function can't put anything in the queue! However, what SDL_CondWait() also does for us is to unlock the mutex we give it and then attempt to lock it again once we get the signal.


In Case of Fire

You'll also notice that we have a global quit variable that we check to make sure that we haven't set the program a quit signal (SDL automatically handles TERM signals and the like). Otherwise, the thread will continue forever and we'll have to kill -9 the program. ffmpeg also has a function for providing a callback to check and see if we need to quit some blocking function: .

int decode_interrupt_cb(void) {
  return quit;
}
...
main() {
... (decode_interrupt_cb);  
...    
  SDL_PollEvent(&event);
  switch(event.type) {
  case SDL_QUIT:
    quit = 1;
...
This only applies for ffmpeg functions that block, of course, not SDL ones. We make sure to set the quit flag to 1.


Feeding Packets

The only thing left is to set up our queue:

PacketQueue audioq;
main() {
... (aCodecCtx, aCodec);

  packet_queue_init(&audioq); (0);
() finally starts the audio device. It plays silence if it doesn't get data; which it won't right away.


So, we've got our queue set up, now we're ready to start feeding it packets. We go to our packet-reading loop:

while((pFormatCtx, &packet)>=0) {
  // Is this a packet from the video stream?
  if(packet.stream_index==videoStream) {
    // Decode video frame
    ....
    }
  } else if(packet.stream_index==audioStream) {
    packet_queue_put(&audioq, &packet);
  } else { (&packet);
  }
Note that we don't free the packet after we put it in the queue. We'll free it later when we decode it.


Fetching Packets

Now let's finally make our audio_callback function to fetch the packets on the queue. The callback has to be of the form void callback(void *userdata, Uint8 *stream, int len), where userdata of course is the pointer we gave to SDL, stream is the buffer we will be writing audio data to, and len is the size of that buffer. Here's the code:

void audio_callback(void *userdata, Uint8 *stream, int len) {  *aCodecCtx = (AVCodecContext *)userdata;
  int len1, audio_size;

  static uint8_t audio_buf[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2];
  static unsigned int audio_buf_size = 0;
  static unsigned int audio_buf_index = 0;

  while(len > 0) {
    if(audio_buf_index >= audio_buf_size) {
      /* We have already sent all our data; get more */
      audio_size = audio_decode_frame(aCodecCtx, audio_buf,
                                      sizeof(audio_buf));
      if(audio_size < 0) {
	/* If error, output silence */
	audio_buf_size = 1024;
	memset(audio_buf, 0, audio_buf_size);
      } else {
	audio_buf_size = audio_size;
      }
      audio_buf_index = 0;
    }
    len1 = audio_buf_size - audio_buf_index;
    if(len1 > len)
      len1 = len;
    memcpy(stream, (uint8_t *)audio_buf + audio_buf_index, len1);
    len -= len1;
    stream += len1;
    audio_buf_index += len1;
  }
}
This is basically a simple loop that will pull in data from another function we will write, audio_decode_frame(), store the result in an intermediary buffer, attempt to write len bytes to stream, and get more data if we don't have enough yet, or save it for later if we have some left over. The size of audio_buf is 1.5 times the size of the largest audio frame that ffmpeg will give us, which gives us a nice cushion.


Finally Decoding the Audio

Let's get to the real meat of the decoder, audio_decode_frame:

int audio_decode_frame( *aCodecCtx, uint8_t *audio_buf,
                       int buf_size) {

  static  pkt;
  static uint8_t *audio_pkt_data = NULL;
  static int audio_pkt_size = 0;

  int len1, data_size;

  for(;;) {
    while(audio_pkt_size > 0) {
      data_size = buf_size;
      len1 = (aCodecCtx, (int16_t *)audio_buf, &data_size, 
				  audio_pkt_data, audio_pkt_size);
      if(len1 < 0) {
	/* if error, skip frame */
	audio_pkt_size = 0;
	break;
      }
      audio_pkt_data += len1;
      audio_pkt_size -= len1;
      if(data_size <= 0) {
	/* No data yet, get more frames */
	continue;
      }
      /* We have data, return it and come back for more later */
      return data_size;
    }
    if(pkt.data) (&pkt);

    if(quit) {
      return -1;
    }

    if(packet_queue_get(&audioq, &pkt, 1) < 0) {
      return -1;
    }
    audio_pkt_data = pkt.data;
    audio_pkt_size = pkt.size;
  }
}
This whole process actually starts towards the end of the function, where we call packet_queue_get(). We pick the packet up off the queue, and save its information. Then, once we have a packet to work with, we call (), which acts a lot like its sister function,(), except in this case, a packet might have more than one frame, so you may have to call it several times to get all the data out of the packet. Also, remember the cast to audio_buf, because SDL gives an 8 bit int buffer, and ffmpeg gives us data in a 16 bit int buffer. You should also notice the difference between len1 and data_size. len1 is how much of the packet we've used, and data_size is the amount of raw data returned.

* A note: Why 2? Because there used to be an avcodec_decode_audio, but it's now deprecated. The new function reads from the data_size variable to figure out how bigaudio_buf is.

When we've got some data, we immediately return to see if we still need to get more data from the queue, or if we are done. If we still had more of the packet to process, we save it for later. If we finish up a packet, we finally get to free that packet.

So that's it! We've got audio being carried from the main read loop to the queue, which is then read by the audio_callback function, which hands that data to SDL, which SDL beams to your sound card. Go ahead and compile:

gcc -o tutorial03 tutorial03.c -lavutil -lavformat -lavcodec -lz -lm \
`sdl-config --cflags --libs`
Hooray! The video is still going as fast as possible, but the audio is playing in time. Why is this? That's because the audio information has a sample rate — we're pumping out audio information as fast as we can, but the audio simply plays from that stream at its leisure according to the sample rate.


We're almost ready to start syncing video and audio ourselves, but first we need to do a little program reorganization. The method of queueing up audio and playing it using a separate thread worked very well: it made the code more managable and more modular. Before we start syncing the video to the audio, we need to make our code easier to deal with. Next time: Spawning Threads!


源代码如下(修改部分代码,加入一些注释)

点击(此处)折叠或打开

  1. // tutorial03.c
  2. // A pedagogical video player that will stream through every video frame as fast as it can
  3. // and play audio (out of sync).
  4. //
  5. // This tutorial was written by Stephen Dranger (dranger@gmail.com).
  6. //
  7. // Code based on FFplay, Copyright (c) 2003 Fabrice Bellard,
  8. // and a tutorial by Martin Bohme (boehme@inb.uni-luebeckREMOVETHIS.de)
  9. // Tested on Gentoo, CVS version 5/01/07 compiled with GCC 4.1.1
  10. //
  11. // Use the Makefile to build all examples.
  12. //
  13. // Run using
  14. // tutorial03 myvideofile.mpg
  15. //
  16. // to play the stream on your screen.
  17. //
  18. //
  19. //
  20. //gcc -o tutorial03 tutorial03.c -lavformat -lavcodec -lavutil -lswscale -lz -lm -L/opt/libffmpeg/host/lib/ -I/opt/libffmpeg/host/include/ \
  21. -ldl -lpthread -lSDL2 -I/opt/libsdl/include/ -L/opt/libsdl/lib/ -g
  22. //./tutorial03 testvideo.mov
  23. //./tutorial03 rtsp://root:admin@192.168.17.203/live.sdp

  24. #include <libavcodec/avcodec.h>
  25. #include <libavformat/avformat.h>
  26. #include <libswscale/swscale.h>

  27. #include <SDL2/SDL.h>
  28. #include <SDL2/SDL_thread.h>

  29. #ifdef __MINGW32__
  30. #undef main /* Prevents SDL from overriding main() */
  31. #endif

  32. #include <stdio.h>

  33. #define SDL_AUDIO_BUFFER_SIZE 1024
  34. #define MAX_AUDIO_FRAME_SIZE 192000

  35. #define PLAYAUDIO 1
  36. typedef struct PacketQueue {
  37.     AVPacketList *first_pkt, *last_pkt;
  38.     int nb_packets;
  39.     int size;
  40.     SDL_mutex *mutex;
  41.     SDL_cond *cond;
  42. } PacketQueue;

  43. PacketQueue audioq;
  44. int quit = 0;

  45. void packet_queue_init(PacketQueue *q)
  46. {
  47.     memset(q, 0, sizeof(PacketQueue));
  48.     q->mutex = SDL_CreateMutex();
  49.     q->cond = SDL_CreateCond();
  50. }

  51. int packet_queue_put(PacketQueue *q, AVPacket *pkt)
  52. {
  53.     AVPacketList *pkt1;
  54.     if(av_dup_packet(pkt) < 0) {
  55.         return -1;
  56.     }

  57.     pkt1 = av_malloc(sizeof(AVPacketList));
  58.     if (!pkt1)
  59.         return -1;
  60.     pkt1->pkt = *pkt;
  61.     pkt1->next = NULL;

  62.     SDL_LockMutex(q->mutex);

  63.     if (!q->last_pkt)
  64.         q->first_pkt = pkt1;
  65.     else
  66.         q->last_pkt->next = pkt1;
  67.     q->last_pkt = pkt1;
  68.     q->nb_packets++;
  69.     q->size += pkt1->pkt.size;
  70.     SDL_CondSignal(q->cond);

  71.     SDL_UnlockMutex(q->mutex);
  72.     return 0;
  73. }

  74. static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
  75. {
  76.     AVPacketList *pkt1;
  77.     int ret;

  78.     SDL_LockMutex(q->mutex);

  79.     for(;;) {
  80.         if(quit) {
  81.             ret = -1;
  82.             break;
  83.         }
  84.         pkt1 = q->first_pkt;
  85.         if (pkt1) {
  86.             q->first_pkt = pkt1->next;
  87.             if (!q->first_pkt)
  88.                 q->last_pkt = NULL;
  89.             q->nb_packets--;
  90.             q->size -= pkt1->pkt.size;
  91.             *pkt = pkt1->pkt;
  92.             av_free(pkt1);
  93.             ret = 1;
  94.             break;
  95.         } else if (!block) {
  96.             ret = 0;
  97.             break;
  98.         } else {
  99.               SDL_CondWait(q->cond, q->mutex);
  100.         }
  101.     }
  102.     
  103.     SDL_UnlockMutex(q->mutex);
  104.     return ret;
  105. }

  106. int audio_decode_frame(AVCodecContext *aCodecCtx, uint8_t *audio_buf, int buf_size)
  107. {
  108.     static AVPacket pkt;
  109.     static uint8_t *audio_pkt_data = NULL;
  110.     static int audio_pkt_size = 0;
  111.     static AVFrame frame;
  112.     int len1, data_size = 0;

  113.     for(;;) {
  114.         while(audio_pkt_size > 0) {
  115.             int got_frame = 0;
  116.             len1 = avcodec_decode_audio4(aCodecCtx, &frame, &got_frame, &pkt);
  117.             if(len1 < 0) {
  118.                 /* if error, skip frame */
  119.                 audio_pkt_size = 0;
  120.                 break;
  121.             }
  122.             audio_pkt_data += len1;
  123.             audio_pkt_size -= len1;
  124.             if (got_frame){
  125.                 data_size = av_samples_get_buffer_size(NULL, aCodecCtx->channels,frame.nb_samples,aCodecCtx->sample_fmt,1);
  126.                 memcpy(audio_buf, frame.data[0], data_size);
  127.             }
  128.             if(data_size <= 0) {
  129.              /* No data yet, get more frames */
  130.              continue;
  131.             }
  132.             /* We have data, return it and come back for more later */
  133.             return data_size;
  134.         }
  135.     
  136.         if(pkt.data)
  137.             av_free_packet(&pkt);

  138.         if(quit) {
  139.             return -1;
  140.         }

  141.         if(packet_queue_get(&audioq, &pkt, 1) < 0) {
  142.             return -1;
  143.         }
  144.         audio_pkt_data = pkt.data;
  145.         audio_pkt_size = pkt.size;
  146.     }
  147. }

  148. void audio_callback(void *userdata, Uint8 *stream, int len)
  149. {
  150.     AVCodecContext *aCodecCtx = (AVCodecContext *)userdata;
  151.     int len1, audio_size;
  152.     static uint8_t audio_buf[(MAX_AUDIO_FRAME_SIZE * 3) / 2];
  153.     static unsigned int audio_buf_size = 0;
  154.     static unsigned int audio_buf_index = 0;

  155.     while(len > 0) {
  156.         if(audio_buf_index >= audio_buf_size) {
  157.             /* We have already sent all our data; get more */
  158.             audio_size = audio_decode_frame(aCodecCtx, audio_buf, audio_buf_size);
  159.             if(audio_size < 0) {
  160.                 /* If error, output silence */
  161.                 audio_buf_size = 1024; // arbitrary?
  162.                 memset(audio_buf, 0, audio_buf_size);
  163.             } else {
  164.                 audio_buf_size = audio_size;
  165.             }
  166.             audio_buf_index = 0;
  167.         }
  168.         len1 = audio_buf_size - audio_buf_index;
  169.         if(len1 > len)
  170.             len1 = len;
  171.         memcpy(stream, (uint8_t *)audio_buf + audio_buf_index, len1);
  172.         len -= len1;
  173.         stream += len1;
  174.         audio_buf_index += len1;
  175.     }
  176. }

  177. int main(int argc, char *argv[])
  178. {
  179.     AVFormatContext *pFormatCtx = NULL;
  180.     int i, videoStream, audioStream;
  181.     AVCodecContext *pCodecCtx = NULL;
  182.     AVCodec *pCodec = NULL;
  183.     AVFrame *pFrame = NULL;
  184.     AVPacket packet;
  185.     int frameFinished;
  186.     //float aspect_ratio;

  187.     AVCodecContext *aCodecCtx = NULL;
  188.     AVCodec *aCodec = NULL;

  189.     SDL_Texture *bmp = NULL;
  190.     SDL_Window *screen = NULL;
  191.     SDL_Rect rect;
  192.     SDL_Event event;
  193.     SDL_AudioSpec wanted_spec, spec;

  194.     struct SwsContext *sws_ctx = NULL;
  195.     AVDictionary *videoOptionsDict = NULL;
  196.     AVDictionary *audioOptionsDict = NULL;

  197.     if(argc < 2) {
  198.         fprintf(stderr, "Usage: test \n");
  199.         exit(1);
  200.     }
  201.     // Register all formats and codecs
  202.     av_register_all();

  203.     if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
  204.         fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
  205.         exit(1);
  206.     }

  207.     // Open video file
  208.     if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL)!=0)
  209.         return -1; // Couldn't open file

  210.     // Retrieve stream information
  211.     if(avformat_find_stream_info(pFormatCtx, NULL)<0)
  212.         return -1; // Couldn't find stream information

  213.     // Dump information about file onto standard error
  214.     av_dump_format(pFormatCtx, 0, argv[1], 0);

  215.     // Find the first video stream
  216.     videoStream=-1;
  217.     audioStream=-1;
  218.     for(i=0; i<pFormatCtx->nb_streams; i++) {
  219.         if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO &&
  220.             videoStream < 0) {
  221.             videoStream=i;
  222.         }
  223.         if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO && audioStream < 0) {
  224.             audioStream=i;
  225.         }
  226.     }
  227.     if(videoStream==-1)
  228.         return -1; // Didn't find a video stream
  229. #if(PLAYAUDIO)
  230.     if(audioStream==-1)
  231.         return -1;
  232.     aCodecCtx=pFormatCtx->streams[audioStream]->codec;
  233.     // Set audio settings from codec info
  234.     wanted_spec.freq = aCodecCtx->sample_rate;
  235.     wanted_spec.format = AUDIO_S16SYS;
  236.     wanted_spec.channels = aCodecCtx->channels;
  237.     wanted_spec.silence = 0;
  238.     wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
  239.     wanted_spec.callback = audio_callback;
  240.     wanted_spec.userdata = aCodecCtx;
  241.     if(SDL_OpenAudio(&wanted_spec, &spec) < 0) {
  242.         fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
  243.         return -1;
  244.     }
  245.     aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
  246.     if(!aCodec) {
  247.         aCodec = avcodec_find_decoder(AV_CODEC_ID_H264);
  248.         fprintf(stderr, "Unsupported audio codec! (%d) %p\n", aCodecCtx->codec_id, aCodec);
  249.         
  250.         return -1;
  251.     }
  252.     avcodec_open2(aCodecCtx, aCodec, &audioOptionsDict);

  253.     // audio_st = pFormatCtx->streams[index]
  254.     packet_queue_init(&audioq);
  255.     SDL_PauseAudio(0);
  256. #endif
  257.     // Get a pointer to the codec context for the video stream
  258.     pCodecCtx=pFormatCtx->streams[videoStream]->codec;

  259.     // Find the decoder for the video stream
  260.     pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
  261.     if(pCodec==NULL) {
  262.         fprintf(stderr, "Unsupported video codec!\n");
  263.         return -1; // Codec not found
  264.     }
  265.     // Open codec
  266.     if(avcodec_open2(pCodecCtx, pCodec, &videoOptionsDict)<0)
  267.         return -1; // Could not open codec

  268.     // Allocate video frame
  269.     pFrame=av_frame_alloc();

  270.     pFrame=avcodec_alloc_frame();

  271.     AVFrame* pFrameYUV = avcodec_alloc_frame();
  272.     if( pFrameYUV == NULL )
  273.         return -1;
  274.   
  275.       screen = SDL_CreateWindow("Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, pCodecCtx->width, pCodecCtx->height, SDL_WINDOW_FULLSCREEN_DESKTOP);
  276.     SDL_Renderer *renderer = SDL_CreateRenderer(screen, -1, 0);
  277.     if(!screen) {
  278.         fprintf(stderr, "SDL: could not set video mode - exiting (%s)\n", SDL_GetError());
  279.         exit(1);
  280.     }

  281.     // Allocate a place to put our YUV image on that screen
  282.     bmp = SDL_CreateTexture(renderer,SDL_PIXELFORMAT_YV12,SDL_TEXTUREACCESS_STREAMING,pCodecCtx->width,pCodecCtx->height);
  283.     sws_ctx = sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,pCodecCtx->width,pCodecCtx->height,PIX_FMT_YUV420P,SWS_BILINEAR,NULL,NULL,NULL);
  284.     int numBytes = avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);
  285.     uint8_t* buffer = (uint8_t *)av_malloc(numBytes*sizeof(uint8_t));
  286.     avpicture_fill((AVPicture *)pFrameYUV, buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);

  287.     // Read frames and save first five frames to disk
  288.     i = 0;
  289.     rect.x = 0;
  290.     rect.y = 0;
  291.     rect.w = pCodecCtx->width;
  292.     rect.h = pCodecCtx->height;

  293.     while(av_read_frame(pFormatCtx, &packet)>=0) {
  294.         // Is this a packet from the video stream?
  295.         if(packet.stream_index==videoStream) {
  296.             // Decode video frame
  297.             avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
  298.       
  299.             // Did we get a video frame?
  300.             if(frameFinished) {
  301.                 sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);
  302.                 ////iPitch 计算yuv一行数据占的字节数
  303.                 SDL_UpdateTexture( bmp, &rect, pFrameYUV->data[0], pFrameYUV->linesize[0] );
  304.                 SDL_RenderClear( renderer );
  305.                 SDL_RenderCopy( renderer, bmp, &rect, &rect );
  306.                 SDL_RenderPresent( renderer );    
  307.                 av_free_packet(&packet);
  308.             }
  309.             SDL_Delay(40);    //delay 40ms, fps = 25
  310.         } else if(packet.stream_index==audioStream) {
  311. #if(PLAYAUDIO)
  312.             packet_queue_put(&audioq, &packet);
  313. #endif
  314.         } else {
  315.             av_free_packet(&packet);
  316.         }
  317.         
  318.         // Free the packet that was allocated by av_read_frame
  319.         SDL_PollEvent(&event);
  320.         switch(event.type) {
  321.             case SDL_QUIT:
  322.                 quit = 1;
  323.                 SDL_Quit();
  324.                 exit(0);
  325.                 break;
  326.             default:
  327.                 break;
  328.         }

  329.     }

  330.     // Free the YUV frame
  331.     av_free(pFrame);
  332.   
  333.     // Close the codec
  334.     avcodec_close(pCodecCtx);
  335.   
  336.     // Close the video file
  337.     avformat_close_input(&pFormatCtx);
  338.   
  339.     return 0;
  340. }


阅读(1119) | 评论(0) | 转发(0) |
0

上一篇:ffmpeg - tutorial02

下一篇:ffmpeg - tutorial04

给主人留下些什么吧!~~