我是靠谱客的博主 勤恳春天,这篇文章主要介绍ffmpeg tutorial3,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
## An ffmpeg and SDL Tutorial Page 1 2 3 4 5 6 7 End Prev Home Next &nbsp_place_holder; Text version ## Tutorial 03: Playing Sound Code: tutorial03.c ### Audio So now we want to play sound. SDL also gives us methods for outputting sound. The `SDL_OpenAudio()` function is used to open the audio device itself. It takes as arguments an `SDL_AudioSpec` 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 waveform. 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 `SDL_AudioSpec` struct, we call `SDL_OpenAudio()`, 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==AVMEDIA_TYPE_VIDEO && videoStream < 0) { videoStream=i; } if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_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 `AVCodecContext` from the stream, just like we did with the video stream: AVCodecContext *aCodecCtxOrig; AVCodecContext *aCodecCtx; aCodecCtxOrig=pFormatCtx->streams[audioStream]->codec; If you remember from the previous tutorials, we still need to open the audio codec itself. This is straightforward: AVCodec *aCodec; aCodec = avcodec_find_decoder(aCodecCtx->codec_id); if(!aCodec) { fprintf(stderr, "Unsupported codec!n"); return -1; } // Copy context aCodecCtx = avcodec_alloc_context3(aCodec); if(avcodec_copy_context(aCodecCtx, aCodecCtxOrig) != 0) { fprintf(stderr, "Couldn't copy codec context"); return -1; // Error copying codec context } /* set up SDL Audio here */ avcodec_open2(aCodecCtx, aCodec, NULL); Contained within the 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(SDL_OpenAudio(&wanted;_spec, &spec;) < 0) { fprintf(stderr, "SDL_OpenAudio: %sn", 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 `avcodec_decode_audio2` 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 `SDL_OpenAudio`. ### 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: `AVPacketList`, which is just a linked list for packets. Here's our queue structure: typedef struct PacketQueue { AVPacketList *first_pkt, *last_pkt; int nb_packets; int size; SDL_mutex *mutex; SDL_cond *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 mutex and a condtion variable 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 = SDL_CreateMutex(); q->cond = SDL_CreateCond(); } Then we will make a function to put stuff in our queue: int packet_queue_put(PacketQueue *q, AVPacket *pkt) { AVPacketList *pkt1; if(av_dup_packet(pkt) < 0) { return -1; } pkt1 = av_malloc(sizeof(AVPacketList)); if (!pkt1) return -1; pkt1->pkt = *pkt; pkt1->next = NULL; SDL_LockMutex(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; SDL_CondSignal(q->cond); SDL_UnlockMutex(q->mutex); return 0; } `SDL_LockMutex()` locks the mutex in the queue so we can add something to it, and then `SDL_CondSignal()` 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 `SDL_CondWait()` 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, AVPacket *pkt, int block) { AVPacketList *pkt1; int ret; SDL_LockMutex(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; av_free(pkt1); ret = 1; break; } else if (!block) { ret = 0; break; } else { SDL_CondWait(q->cond, q->mutex); } } SDL_UnlockMutex(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 SDL_CondWait()` function. Basically, all CondWait does is wait for a signal from `SDL_CondSignal()` (or `SDL_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. SDL_PollEvent(&event;); switch(event.type) { case SDL_QUIT: quit = 1; 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() { ... avcodec_open2(aCodecCtx, aCodec, NULL); packet_queue_init(&audioq;); SDL_PauseAudio(0); `SDL_PauseAudio()` 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(av_read_frame(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 { av_free_packet(&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) { AVCodecContext *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(AVCodecContext *aCodecCtx, uint8_t *audio_buf, int buf_size) { static AVPacket pkt; static uint8_t *audio_pkt_data = NULL; static int audio_pkt_size = 0; static AVFrame frame; int len1, data_size = 0; for(;;) { while(audio_pkt_size > 0) { int got_frame = 0; len1 = avcodec_decode_audio4(aCodecCtx, &frame;, &got;_frame, &pkt;); if(len1 < 0) { /* if error, skip frame */ audio_pkt_size = 0; break; } audio_pkt_data += len1; audio_pkt_size -= len1; data_size = 0; if(got_frame) { data_size = av_samples_get_buffer_size(NULL, aCodecCtx->channels, frame.nb_samples, aCodecCtx->sample_fmt, 1); assert(data_size <= buf_size); memcpy(audio_buf, frame.data[0], data_size); } 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) av_free_packet(&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 `avcodec_decode_audio4()`, which acts a lot like its sister function, `avcodec_decode_video()`, 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. Once we have the frame, we simply copy it to our audio buffer, making sure the data_size is smaller than our audio buffer. 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. 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 -lswscale -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! _**>>** Spawning Threads_ * * * Function Reference Data Reference email: dranger at gmail dot com Back to dranger.com This work is licensed under the Creative Commons Attribution-Share Alike 2.5 License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/2.5/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA. Code examples are based off of FFplay, Copyright (c) 2003 Fabrice Bellard, and a tutorial by Martin Bohme. // tutorial03.c // A pedagogical video player that will stream through every video frame as fast as it can // and play audio (out of sync). // // Code based on FFplay, Copyright (c) 2003 Fabrice Bellard, // and a tutorial by Martin Bohme (boehme@inb.uni-luebeckREMOVETHIS.de) // Tested on Gentoo, CVS version 5/01/07 compiled with GCC 4.1.1 // With updates from https://github.com/chelyaev/ffmpeg-tutorial // Updates tested on: // LAVC 54.59.100, LAVF 54.29.104, LSWS 2.1.101, SDL 1.2.15 // on GCC 4.7.2 in Debian February 2015 // // Use // // gcc -o tutorial03 tutorial03.c -lavformat -lavcodec -lswscale -lz -lm `sdl-config --cflags --libs` // to build (assuming libavformat and libavcodec are correctly installed, // and assuming you have sdl-config. Please refer to SDL docs for your installation.) // // Run using // tutorial03 myvideofile.mpg // // to play the stream on your screen. #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> #include <SDL.h> #include <SDL_thread.h> #ifdef __MINGW32__ #undef main /* Prevents SDL from overriding main() */ #endif #include <stdio.h> #include <assert.h> // compatibility with newer API #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1) #define av_frame_alloc avcodec_alloc_frame #define av_frame_free avcodec_free_frame #endif #define SDL_AUDIO_BUFFER_SIZE 1024 #define MAX_AUDIO_FRAME_SIZE 192000 typedef struct PacketQueue {   AVPacketList *first_pkt, *last_pkt;   int nb_packets;   int size;   SDL_mutex *mutex;   SDL_cond *cond; } PacketQueue; PacketQueue audioq; int quit = 0; void packet_queue_init(PacketQueue *q) {   memset(q, 0, sizeof(PacketQueue));   q->mutex = SDL_CreateMutex();   q->cond = SDL_CreateCond(); } int packet_queue_put(PacketQueue *q, AVPacket *pkt) {   AVPacketList *pkt1;   if(av_dup_packet(pkt) < 0) {     return -1;   }   pkt1 = av_malloc(sizeof(AVPacketList));   if (!pkt1)     return -1;   pkt1->pkt = *pkt;   pkt1->next = NULL;       SDL_LockMutex(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;   SDL_CondSignal(q->cond);     SDL_UnlockMutex(q->mutex);   return 0; } static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block) {   AVPacketList *pkt1;   int ret;     SDL_LockMutex(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;       av_free(pkt1);       ret = 1;       break;     } else if (!block) {       ret = 0;       break;     } else {       SDL_CondWait(q->cond, q->mutex);     }   }   SDL_UnlockMutex(q->mutex);   return ret; } int audio_decode_frame(AVCodecContext *aCodecCtx, uint8_t *audio_buf, int buf_size) {   static AVPacket pkt;   static uint8_t *audio_pkt_data = NULL;   static int audio_pkt_size = 0;   static AVFrame frame;   int len1, data_size = 0;   for(;;) {     while(audio_pkt_size > 0) {       int got_frame = 0;       len1 = avcodec_decode_audio4(aCodecCtx, &frame, &got_frame, &pkt);       if(len1 < 0) {     /* if error, skip frame */     audio_pkt_size = 0;     break;       }       audio_pkt_data += len1;       audio_pkt_size -= len1;       data_size = 0;       if(got_frame) {     data_size = av_samples_get_buffer_size(NULL,                            aCodecCtx->channels,                            frame.nb_samples,                            aCodecCtx->sample_fmt,                            1);     assert(data_size <= buf_size);     memcpy(audio_buf, frame.data[0], data_size);       }       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)       av_free_packet(&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;   } } void audio_callback(void *userdata, Uint8 *stream, int len) {   AVCodecContext *aCodecCtx = (AVCodecContext *)userdata;   int len1, audio_size;   static uint8_t audio_buf[(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; // arbitrary?     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;   } } int main(int argc, char *argv[]) {   AVFormatContext *pFormatCtx = NULL;   int             i, videoStream, audioStream;   AVCodecContext  *pCodecCtxOrig = NULL;   AVCodecContext  *pCodecCtx = NULL;   AVCodec         *pCodec = NULL;   AVFrame         *pFrame = NULL;   AVPacket        packet;   int             frameFinished;   struct SwsContext *sws_ctx = NULL;     AVCodecContext  *aCodecCtxOrig = NULL;   AVCodecContext  *aCodecCtx = NULL;   AVCodec         *aCodec = NULL;   SDL_Overlay     *bmp;   SDL_Surface     *screen;   SDL_Rect        rect;   SDL_Event       event;   SDL_AudioSpec   wanted_spec, spec;   if(argc < 2) {     fprintf(stderr, "Usage: test <file>n");     exit(1);   }   // Register all formats and codecs   av_register_all();     if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {     fprintf(stderr, "Could not initialize SDL - %sn", SDL_GetError());     exit(1);   }   // Open video file   if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL)!=0)     return -1; // Couldn't open file     // Retrieve stream information   if(avformat_find_stream_info(pFormatCtx, NULL)<0)     return -1; // Couldn't find stream information     // Dump information about file onto standard error   av_dump_format(pFormatCtx, 0, argv[1], 0);        // Find the first video stream   videoStream=-1;   audioStream=-1;   for(i=0; i<pFormatCtx->nb_streams; i++) {     if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO &&        videoStream < 0) {       videoStream=i;     }     if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO &&        audioStream < 0) {       audioStream=i;     }   }   if(videoStream==-1)     return -1; // Didn't find a video stream   if(audioStream==-1)     return -1;       aCodecCtxOrig=pFormatCtx->streams[audioStream]->codec;   aCodec = avcodec_find_decoder(aCodecCtxOrig->codec_id);   if(!aCodec) {     fprintf(stderr, "Unsupported codec!n");     return -1;   }   // Copy context   aCodecCtx = avcodec_alloc_context3(aCodec);   if(avcodec_copy_context(aCodecCtx, aCodecCtxOrig) != 0) {     fprintf(stderr, "Couldn't copy codec context");     return -1; // Error copying codec context   }   // Set audio settings from codec info   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(SDL_OpenAudio(&wanted_spec, &spec) < 0) {     fprintf(stderr, "SDL_OpenAudio: %sn", SDL_GetError());     return -1;   }   avcodec_open2(aCodecCtx, aCodec, NULL);   // audio_st = pFormatCtx->streams[index]   packet_queue_init(&audioq);   SDL_PauseAudio(0);   // Get a pointer to the codec context for the video stream   pCodecCtxOrig=pFormatCtx->streams[videoStream]->codec;     // Find the decoder for the video stream   pCodec=avcodec_find_decoder(pCodecCtxOrig->codec_id);   if(pCodec==NULL) {     fprintf(stderr, "Unsupported codec!n");     return -1; // Codec not found   }   // Copy context   pCodecCtx = avcodec_alloc_context3(pCodec);   if(avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0) {     fprintf(stderr, "Couldn't copy codec context");     return -1; // Error copying codec context   }   // Open codec   if(avcodec_open2(pCodecCtx, pCodec, NULL)<0)     return -1; // Could not open codec     // Allocate video frame   pFrame=av_frame_alloc();   // Make a screen to put our video #ifndef __DARWIN__         screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 0, 0); #else         screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 24, 0); #endif   if(!screen) {     fprintf(stderr, "SDL: could not set video mode - exitingn");     exit(1);   }     // Allocate a place to put our YUV image on that screen   bmp = SDL_CreateYUVOverlay(pCodecCtx->width,                  pCodecCtx->height,                  SDL_YV12_OVERLAY,                  screen);   // initialize SWS context for software scaling   sws_ctx = sws_getContext(pCodecCtx->width,                pCodecCtx->height,                pCodecCtx->pix_fmt,                pCodecCtx->width,                pCodecCtx->height,                PIX_FMT_YUV420P,                SWS_BILINEAR,                NULL,                NULL,                NULL                );   // Read frames and save first five frames to disk   i=0;   while(av_read_frame(pFormatCtx, &packet)>=0) {     // Is this a packet from the video stream?     if(packet.stream_index==videoStream) {       // Decode video frame       avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);              // Did we get a video frame?       if(frameFinished) {     SDL_LockYUVOverlay(bmp);     AVPicture pict;     pict.data[0] = bmp->pixels[0];     pict.data[1] = bmp->pixels[2];     pict.data[2] = bmp->pixels[1];     pict.linesize[0] = bmp->pitches[0];     pict.linesize[1] = bmp->pitches[2];     pict.linesize[2] = bmp->pitches[1];     // Convert the image into YUV format that SDL uses         sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data,           pFrame->linesize, 0, pCodecCtx->height,           pict.data, pict.linesize);          SDL_UnlockYUVOverlay(bmp);          rect.x = 0;     rect.y = 0;     rect.w = pCodecCtx->width;     rect.h = pCodecCtx->height;     SDL_DisplayYUVOverlay(bmp, &rect);     av_free_packet(&packet);       }     } else if(packet.stream_index==audioStream) {       packet_queue_put(&audioq, &packet);     } else {       av_free_packet(&packet);     }     // Free the packet that was allocated by av_read_frame     SDL_PollEvent(&event);     switch(event.type) {     case SDL_QUIT:       quit = 1;       SDL_Quit();       exit(0);       break;     default:       break;     }   }   // Free the YUV frame   av_frame_free(&pFrame);     // Close the codecs   avcodec_close(pCodecCtxOrig);   avcodec_close(pCodecCtx);   avcodec_close(aCodecCtxOrig);   avcodec_close(aCodecCtx);     // Close the video file   avformat_close_input(&pFormatCtx);     return 0; }  

最后

以上就是勤恳春天最近收集整理的关于ffmpeg tutorial3的全部内容,更多相关ffmpeg内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部