10l pts vs. dts
[libav.git] / ffplay.c
1 /*
2 * FFplay : Simple Media Player based on the ffmpeg libraries
3 * Copyright (c) 2003 Fabrice Bellard
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 #define HAVE_AV_CONFIG_H
20 #include "avformat.h"
21
22 #include "cmdutils.h"
23
24 #include <SDL.h>
25 #include <SDL_thread.h>
26
27 #ifdef CONFIG_WIN32
28 #undef main /* We don't want SDL to override our main() */
29 #endif
30
31 #if defined(__linux__)
32 #define HAVE_X11
33 #endif
34
35 #ifdef HAVE_X11
36 #include <X11/Xlib.h>
37 #endif
38
39 //#define DEBUG_SYNC
40
41 #define MAX_VIDEOQ_SIZE (5 * 256 * 1024)
42 #define MAX_AUDIOQ_SIZE (5 * 16 * 1024)
43
44 /* SDL audio buffer size, in samples. Should be small to have precise
45 A/V sync as SDL does not have hardware buffer fullness info. */
46 #define SDL_AUDIO_BUFFER_SIZE 1024
47
48 /* no AV sync correction is done if below the AV sync threshold */
49 #define AV_SYNC_THRESHOLD 0.01
50 /* no AV correction is done if too big error */
51 #define AV_NOSYNC_THRESHOLD 10.0
52
53 /* maximum audio speed change to get correct sync */
54 #define SAMPLE_CORRECTION_PERCENT_MAX 10
55
56 /* we use about AUDIO_DIFF_AVG_NB A-V differences to make the average */
57 #define AUDIO_DIFF_AVG_NB 20
58
59 /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
60 #define SAMPLE_ARRAY_SIZE (2*65536)
61
62 typedef struct PacketQueue {
63 AVPacketList *first_pkt, *last_pkt;
64 int nb_packets;
65 int size;
66 int abort_request;
67 SDL_mutex *mutex;
68 SDL_cond *cond;
69 } PacketQueue;
70
71 #define VIDEO_PICTURE_QUEUE_SIZE 1
72
73 typedef struct VideoPicture {
74 double pts; /* presentation time stamp for this picture */
75 SDL_Overlay *bmp;
76 int width, height; /* source height & width */
77 int allocated;
78 } VideoPicture;
79
80 enum {
81 AV_SYNC_AUDIO_MASTER, /* default choice */
82 AV_SYNC_VIDEO_MASTER,
83 AV_SYNC_EXTERNAL_CLOCK, /* synchronize to an external clock */
84 };
85
86 typedef struct VideoState {
87 SDL_Thread *parse_tid;
88 SDL_Thread *video_tid;
89 AVInputFormat *iformat;
90 int no_background;
91 int abort_request;
92 int paused;
93 int last_paused;
94 int seek_req;
95 int64_t seek_pos;
96 AVFormatContext *ic;
97 int dtg_active_format;
98
99 int audio_stream;
100
101 int av_sync_type;
102 double external_clock; /* external clock base */
103 int64_t external_clock_time;
104
105 double audio_clock;
106 double audio_diff_cum; /* used for AV difference average computation */
107 double audio_diff_avg_coef;
108 double audio_diff_threshold;
109 int audio_diff_avg_count;
110 AVStream *audio_st;
111 PacketQueue audioq;
112 int audio_hw_buf_size;
113 /* samples output by the codec. we reserve more space for avsync
114 compensation */
115 uint8_t audio_buf[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2];
116 unsigned int audio_buf_size; /* in bytes */
117 int audio_buf_index; /* in bytes */
118 AVPacket audio_pkt;
119 uint8_t *audio_pkt_data;
120 int audio_pkt_size;
121
122 int show_audio; /* if true, display audio samples */
123 int16_t sample_array[SAMPLE_ARRAY_SIZE];
124 int sample_array_index;
125 int last_i_start;
126
127 double frame_timer;
128 double frame_last_pts;
129 double frame_last_delay;
130 double video_clock;
131 int video_stream;
132 AVStream *video_st;
133 PacketQueue videoq;
134 double video_last_P_pts; /* pts of the last P picture (needed if B
135 frames are present) */
136 double video_current_pts; /* current displayed pts (different from
137 video_clock if frame fifos are used) */
138 int64_t video_current_pts_time; /* time at which we updated
139 video_current_pts - used to
140 have running video pts */
141 VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
142 int pictq_size, pictq_rindex, pictq_windex;
143 SDL_mutex *pictq_mutex;
144 SDL_cond *pictq_cond;
145
146 // QETimer *video_timer;
147 char filename[1024];
148 int width, height, xleft, ytop;
149 } VideoState;
150
151 void show_help(void);
152 static int audio_write_get_buf_size(VideoState *is);
153
154 /* options specified by the user */
155 static AVInputFormat *file_iformat;
156 static AVImageFormat *image_format;
157 static const char *input_filename;
158 static int fs_screen_width;
159 static int fs_screen_height;
160 static int screen_width = 640;
161 static int screen_height = 480;
162 static int audio_disable;
163 static int video_disable;
164 static int display_disable;
165 static int show_status;
166 static int av_sync_type = AV_SYNC_AUDIO_MASTER;
167 static int64_t start_time = AV_NOPTS_VALUE;
168 static int debug = 0;
169 static int debug_mv = 0;
170 static int step = 0;
171 static int thread_count = 1;
172 static int workaround_bugs = 1;
173 static int fast = 0;
174 static int lowres = 0;
175 static int idct = FF_IDCT_AUTO;
176
177 /* current context */
178 static int is_full_screen;
179 static VideoState *cur_stream;
180 static int64_t audio_callback_time;
181
182 #define FF_ALLOC_EVENT (SDL_USEREVENT)
183 #define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
184 #define FF_QUIT_EVENT (SDL_USEREVENT + 2)
185
186 SDL_Surface *screen;
187
188 /* packet queue handling */
189 static void packet_queue_init(PacketQueue *q)
190 {
191 memset(q, 0, sizeof(PacketQueue));
192 q->mutex = SDL_CreateMutex();
193 q->cond = SDL_CreateCond();
194 }
195
196 static void packet_queue_flush(PacketQueue *q)
197 {
198 AVPacketList *pkt, *pkt1;
199
200 for(pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
201 pkt1 = pkt->next;
202 av_free_packet(&pkt->pkt);
203 av_freep(&pkt);
204 }
205 q->last_pkt = NULL;
206 q->first_pkt = NULL;
207 q->nb_packets = 0;
208 q->size = 0;
209 }
210
211 static void packet_queue_end(PacketQueue *q)
212 {
213 packet_queue_flush(q);
214 SDL_DestroyMutex(q->mutex);
215 SDL_DestroyCond(q->cond);
216 }
217
218 static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
219 {
220 AVPacketList *pkt1;
221
222 /* duplicate the packet */
223 if (av_dup_packet(pkt) < 0)
224 return -1;
225
226 pkt1 = av_malloc(sizeof(AVPacketList));
227 if (!pkt1)
228 return -1;
229 pkt1->pkt = *pkt;
230 pkt1->next = NULL;
231
232
233 SDL_LockMutex(q->mutex);
234
235 if (!q->last_pkt)
236
237 q->first_pkt = pkt1;
238 else
239 q->last_pkt->next = pkt1;
240 q->last_pkt = pkt1;
241 q->nb_packets++;
242 q->size += pkt1->pkt.size;
243 /* XXX: should duplicate packet data in DV case */
244 SDL_CondSignal(q->cond);
245
246 SDL_UnlockMutex(q->mutex);
247 return 0;
248 }
249
250 static void packet_queue_abort(PacketQueue *q)
251 {
252 SDL_LockMutex(q->mutex);
253
254 q->abort_request = 1;
255
256 SDL_CondSignal(q->cond);
257
258 SDL_UnlockMutex(q->mutex);
259 }
260
261 /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
262 static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
263 {
264 AVPacketList *pkt1;
265 int ret;
266
267 SDL_LockMutex(q->mutex);
268
269 for(;;) {
270 if (q->abort_request) {
271 ret = -1;
272 break;
273 }
274
275 pkt1 = q->first_pkt;
276 if (pkt1) {
277 q->first_pkt = pkt1->next;
278 if (!q->first_pkt)
279 q->last_pkt = NULL;
280 q->nb_packets--;
281 q->size -= pkt1->pkt.size;
282 *pkt = pkt1->pkt;
283 av_free(pkt1);
284 ret = 1;
285 break;
286 } else if (!block) {
287 ret = 0;
288 break;
289 } else {
290 SDL_CondWait(q->cond, q->mutex);
291 }
292 }
293 SDL_UnlockMutex(q->mutex);
294 return ret;
295 }
296
297 static inline void fill_rectangle(SDL_Surface *screen,
298 int x, int y, int w, int h, int color)
299 {
300 SDL_Rect rect;
301 rect.x = x;
302 rect.y = y;
303 rect.w = w;
304 rect.h = h;
305 SDL_FillRect(screen, &rect, color);
306 }
307
308 #if 0
309 /* draw only the border of a rectangle */
310 void fill_border(VideoState *s, int x, int y, int w, int h, int color)
311 {
312 int w1, w2, h1, h2;
313
314 /* fill the background */
315 w1 = x;
316 if (w1 < 0)
317 w1 = 0;
318 w2 = s->width - (x + w);
319 if (w2 < 0)
320 w2 = 0;
321 h1 = y;
322 if (h1 < 0)
323 h1 = 0;
324 h2 = s->height - (y + h);
325 if (h2 < 0)
326 h2 = 0;
327 fill_rectangle(screen,
328 s->xleft, s->ytop,
329 w1, s->height,
330 color);
331 fill_rectangle(screen,
332 s->xleft + s->width - w2, s->ytop,
333 w2, s->height,
334 color);
335 fill_rectangle(screen,
336 s->xleft + w1, s->ytop,
337 s->width - w1 - w2, h1,
338 color);
339 fill_rectangle(screen,
340 s->xleft + w1, s->ytop + s->height - h2,
341 s->width - w1 - w2, h2,
342 color);
343 }
344 #endif
345
346 static void video_image_display(VideoState *is)
347 {
348 VideoPicture *vp;
349 float aspect_ratio;
350 int width, height, x, y;
351 SDL_Rect rect;
352
353 vp = &is->pictq[is->pictq_rindex];
354 if (vp->bmp) {
355 /* XXX: use variable in the frame */
356 if (is->video_st->codec.sample_aspect_ratio.num == 0)
357 aspect_ratio = 0;
358 else
359 aspect_ratio = av_q2d(is->video_st->codec.sample_aspect_ratio)
360 * is->video_st->codec.width / is->video_st->codec.height;;
361 if (aspect_ratio <= 0.0)
362 aspect_ratio = (float)is->video_st->codec.width /
363 (float)is->video_st->codec.height;
364 /* if an active format is indicated, then it overrides the
365 mpeg format */
366 #if 0
367 if (is->video_st->codec.dtg_active_format != is->dtg_active_format) {
368 is->dtg_active_format = is->video_st->codec.dtg_active_format;
369 printf("dtg_active_format=%d\n", is->dtg_active_format);
370 }
371 #endif
372 #if 0
373 switch(is->video_st->codec.dtg_active_format) {
374 case FF_DTG_AFD_SAME:
375 default:
376 /* nothing to do */
377 break;
378 case FF_DTG_AFD_4_3:
379 aspect_ratio = 4.0 / 3.0;
380 break;
381 case FF_DTG_AFD_16_9:
382 aspect_ratio = 16.0 / 9.0;
383 break;
384 case FF_DTG_AFD_14_9:
385 aspect_ratio = 14.0 / 9.0;
386 break;
387 case FF_DTG_AFD_4_3_SP_14_9:
388 aspect_ratio = 14.0 / 9.0;
389 break;
390 case FF_DTG_AFD_16_9_SP_14_9:
391 aspect_ratio = 14.0 / 9.0;
392 break;
393 case FF_DTG_AFD_SP_4_3:
394 aspect_ratio = 4.0 / 3.0;
395 break;
396 }
397 #endif
398
399 /* XXX: we suppose the screen has a 1.0 pixel ratio */
400 height = is->height;
401 width = ((int)rint(height * aspect_ratio)) & -3;
402 if (width > is->width) {
403 width = is->width;
404 height = ((int)rint(width / aspect_ratio)) & -3;
405 }
406 x = (is->width - width) / 2;
407 y = (is->height - height) / 2;
408 if (!is->no_background) {
409 /* fill the background */
410 // fill_border(is, x, y, width, height, QERGB(0x00, 0x00, 0x00));
411 } else {
412 is->no_background = 0;
413 }
414 rect.x = is->xleft + x;
415 rect.y = is->xleft + y;
416 rect.w = width;
417 rect.h = height;
418 SDL_DisplayYUVOverlay(vp->bmp, &rect);
419 } else {
420 #if 0
421 fill_rectangle(screen,
422 is->xleft, is->ytop, is->width, is->height,
423 QERGB(0x00, 0x00, 0x00));
424 #endif
425 }
426 }
427
428 static inline int compute_mod(int a, int b)
429 {
430 a = a % b;
431 if (a >= 0)
432 return a;
433 else
434 return a + b;
435 }
436
437 static void video_audio_display(VideoState *s)
438 {
439 int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
440 int ch, channels, h, h2, bgcolor, fgcolor;
441 int16_t time_diff;
442
443 /* compute display index : center on currently output samples */
444 channels = s->audio_st->codec.channels;
445 nb_display_channels = channels;
446 if (!s->paused) {
447 n = 2 * channels;
448 delay = audio_write_get_buf_size(s);
449 delay /= n;
450
451 /* to be more precise, we take into account the time spent since
452 the last buffer computation */
453 if (audio_callback_time) {
454 time_diff = av_gettime() - audio_callback_time;
455 delay += (time_diff * s->audio_st->codec.sample_rate) / 1000000;
456 }
457
458 delay -= s->width / 2;
459 if (delay < s->width)
460 delay = s->width;
461 i_start = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
462 s->last_i_start = i_start;
463 } else {
464 i_start = s->last_i_start;
465 }
466
467 bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
468 fill_rectangle(screen,
469 s->xleft, s->ytop, s->width, s->height,
470 bgcolor);
471
472 fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);
473
474 /* total height for one channel */
475 h = s->height / nb_display_channels;
476 /* graph height / 2 */
477 h2 = (h * 9) / 20;
478 for(ch = 0;ch < nb_display_channels; ch++) {
479 i = i_start + ch;
480 y1 = s->ytop + ch * h + (h / 2); /* position of center line */
481 for(x = 0; x < s->width; x++) {
482 y = (s->sample_array[i] * h2) >> 15;
483 if (y < 0) {
484 y = -y;
485 ys = y1 - y;
486 } else {
487 ys = y1;
488 }
489 fill_rectangle(screen,
490 s->xleft + x, ys, 1, y,
491 fgcolor);
492 i += channels;
493 if (i >= SAMPLE_ARRAY_SIZE)
494 i -= SAMPLE_ARRAY_SIZE;
495 }
496 }
497
498 fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);
499
500 for(ch = 1;ch < nb_display_channels; ch++) {
501 y = s->ytop + ch * h;
502 fill_rectangle(screen,
503 s->xleft, y, s->width, 1,
504 fgcolor);
505 }
506 SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
507 }
508
509 /* display the current picture, if any */
510 static void video_display(VideoState *is)
511 {
512 if (is->audio_st && is->show_audio)
513 video_audio_display(is);
514 else if (is->video_st)
515 video_image_display(is);
516 }
517
518 static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque)
519 {
520 SDL_Event event;
521 event.type = FF_REFRESH_EVENT;
522 event.user.data1 = opaque;
523 SDL_PushEvent(&event);
524 return 0; /* 0 means stop timer */
525 }
526
527 /* schedule a video refresh in 'delay' ms */
528 static void schedule_refresh(VideoState *is, int delay)
529 {
530 SDL_AddTimer(delay, sdl_refresh_timer_cb, is);
531 }
532
533 /* get the current audio clock value */
534 static double get_audio_clock(VideoState *is)
535 {
536 double pts;
537 int hw_buf_size, bytes_per_sec;
538 pts = is->audio_clock;
539 hw_buf_size = audio_write_get_buf_size(is);
540 bytes_per_sec = 0;
541 if (is->audio_st) {
542 bytes_per_sec = is->audio_st->codec.sample_rate *
543 2 * is->audio_st->codec.channels;
544 }
545 if (bytes_per_sec)
546 pts -= (double)hw_buf_size / bytes_per_sec;
547 return pts;
548 }
549
550 /* get the current video clock value */
551 static double get_video_clock(VideoState *is)
552 {
553 double delta;
554 if (is->paused) {
555 delta = 0;
556 } else {
557 delta = (av_gettime() - is->video_current_pts_time) / 1000000.0;
558 }
559 return is->video_current_pts + delta;
560 }
561
562 /* get the current external clock value */
563 static double get_external_clock(VideoState *is)
564 {
565 int64_t ti;
566 ti = av_gettime();
567 return is->external_clock + ((ti - is->external_clock_time) * 1e-6);
568 }
569
570 /* get the current master clock value */
571 static double get_master_clock(VideoState *is)
572 {
573 double val;
574
575 if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
576 if (is->video_st)
577 val = get_video_clock(is);
578 else
579 val = get_audio_clock(is);
580 } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
581 if (is->audio_st)
582 val = get_audio_clock(is);
583 else
584 val = get_video_clock(is);
585 } else {
586 val = get_external_clock(is);
587 }
588 return val;
589 }
590
591 /* seek in the stream */
592 static void stream_seek(VideoState *is, int64_t pos)
593 {
594 is->seek_pos = pos;
595 is->seek_req = 1;
596 }
597
598 /* pause or resume the video */
599 static void stream_pause(VideoState *is)
600 {
601 is->paused = !is->paused;
602 if (is->paused) {
603 is->video_current_pts = get_video_clock(is);
604 }
605 }
606
607 /* called to display each frame */
608 static void video_refresh_timer(void *opaque)
609 {
610 VideoState *is = opaque;
611 VideoPicture *vp;
612 double actual_delay, delay, sync_threshold, ref_clock, diff;
613
614
615 if (is->video_st) {
616 if (is->pictq_size == 0) {
617 /* if no picture, need to wait */
618 schedule_refresh(is, 1);
619 } else {
620 /* dequeue the picture */
621 vp = &is->pictq[is->pictq_rindex];
622
623 /* update current video pts */
624 is->video_current_pts = vp->pts;
625 is->video_current_pts_time = av_gettime();
626
627 /* compute nominal delay */
628 delay = vp->pts - is->frame_last_pts;
629 if (delay <= 0 || delay >= 1.0) {
630 /* if incorrect delay, use previous one */
631 delay = is->frame_last_delay;
632 }
633 is->frame_last_delay = delay;
634 is->frame_last_pts = vp->pts;
635
636 /* update delay to follow master synchronisation source */
637 if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) ||
638 is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
639 /* if video is slave, we try to correct big delays by
640 duplicating or deleting a frame */
641 ref_clock = get_master_clock(is);
642 diff = vp->pts - ref_clock;
643
644 /* skip or repeat frame. We take into account the
645 delay to compute the threshold. I still don't know
646 if it is the best guess */
647 sync_threshold = AV_SYNC_THRESHOLD;
648 if (delay > sync_threshold)
649 sync_threshold = delay;
650 if (fabs(diff) < AV_NOSYNC_THRESHOLD) {
651 if (diff <= -sync_threshold)
652 delay = 0;
653 else if (diff >= sync_threshold)
654 delay = 2 * delay;
655 }
656 }
657
658 is->frame_timer += delay;
659 /* compute the REAL delay (we need to do that to avoid
660 long term errors */
661 actual_delay = is->frame_timer - (av_gettime() / 1000000.0);
662 if (actual_delay < 0.010) {
663 /* XXX: should skip picture */
664 actual_delay = 0.010;
665 }
666 /* launch timer for next picture */
667 schedule_refresh(is, (int)(actual_delay * 1000 + 0.5));
668
669 #if defined(DEBUG_SYNC)
670 printf("video: delay=%0.3f actual_delay=%0.3f pts=%0.3f A-V=%f\n",
671 delay, actual_delay, vp->pts, -diff);
672 #endif
673
674 /* display picture */
675 video_display(is);
676
677 /* update queue size and signal for next picture */
678 if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
679 is->pictq_rindex = 0;
680
681 SDL_LockMutex(is->pictq_mutex);
682 is->pictq_size--;
683 SDL_CondSignal(is->pictq_cond);
684 SDL_UnlockMutex(is->pictq_mutex);
685 }
686 } else if (is->audio_st) {
687 /* draw the next audio frame */
688
689 schedule_refresh(is, 40);
690
691 /* if only audio stream, then display the audio bars (better
692 than nothing, just to test the implementation */
693
694 /* display picture */
695 video_display(is);
696 } else {
697 schedule_refresh(is, 100);
698 }
699 if (show_status) {
700 static int64_t last_time;
701 int64_t cur_time;
702 int aqsize, vqsize;
703 double av_diff;
704
705 cur_time = av_gettime();
706 if (!last_time || (cur_time - last_time) >= 500 * 1000) {
707 aqsize = 0;
708 vqsize = 0;
709 if (is->audio_st)
710 aqsize = is->audioq.size;
711 if (is->video_st)
712 vqsize = is->videoq.size;
713 av_diff = 0;
714 if (is->audio_st && is->video_st)
715 av_diff = get_audio_clock(is) - get_video_clock(is);
716 printf("%7.2f A-V:%7.3f aq=%5dKB vq=%5dKB \r",
717 get_master_clock(is), av_diff, aqsize / 1024, vqsize / 1024);
718 fflush(stdout);
719 last_time = cur_time;
720 }
721 }
722 }
723
724 /* allocate a picture (needs to do that in main thread to avoid
725 potential locking problems */
726 static void alloc_picture(void *opaque)
727 {
728 VideoState *is = opaque;
729 VideoPicture *vp;
730
731 vp = &is->pictq[is->pictq_windex];
732
733 if (vp->bmp)
734 SDL_FreeYUVOverlay(vp->bmp);
735
736 #if 0
737 /* XXX: use generic function */
738 /* XXX: disable overlay if no hardware acceleration or if RGB format */
739 switch(is->video_st->codec.pix_fmt) {
740 case PIX_FMT_YUV420P:
741 case PIX_FMT_YUV422P:
742 case PIX_FMT_YUV444P:
743 case PIX_FMT_YUV422:
744 case PIX_FMT_YUV410P:
745 case PIX_FMT_YUV411P:
746 is_yuv = 1;
747 break;
748 default:
749 is_yuv = 0;
750 break;
751 }
752 #endif
753 vp->bmp = SDL_CreateYUVOverlay(is->video_st->codec.width,
754 is->video_st->codec.height,
755 SDL_YV12_OVERLAY,
756 screen);
757 vp->width = is->video_st->codec.width;
758 vp->height = is->video_st->codec.height;
759
760 SDL_LockMutex(is->pictq_mutex);
761 vp->allocated = 1;
762 SDL_CondSignal(is->pictq_cond);
763 SDL_UnlockMutex(is->pictq_mutex);
764 }
765
766 static int queue_picture(VideoState *is, AVFrame *src_frame, double pts)
767 {
768 VideoPicture *vp;
769 int dst_pix_fmt;
770 AVPicture pict;
771
772 /* wait until we have space to put a new picture */
773 SDL_LockMutex(is->pictq_mutex);
774 while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE &&
775 !is->videoq.abort_request) {
776 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
777 }
778 SDL_UnlockMutex(is->pictq_mutex);
779
780 if (is->videoq.abort_request)
781 return -1;
782
783 vp = &is->pictq[is->pictq_windex];
784
785 /* alloc or resize hardware picture buffer */
786 if (!vp->bmp ||
787 vp->width != is->video_st->codec.width ||
788 vp->height != is->video_st->codec.height) {
789 SDL_Event event;
790
791 vp->allocated = 0;
792
793 /* the allocation must be done in the main thread to avoid
794 locking problems */
795 event.type = FF_ALLOC_EVENT;
796 event.user.data1 = is;
797 SDL_PushEvent(&event);
798
799 /* wait until the picture is allocated */
800 SDL_LockMutex(is->pictq_mutex);
801 while (!vp->allocated && !is->videoq.abort_request) {
802 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
803 }
804 SDL_UnlockMutex(is->pictq_mutex);
805
806 if (is->videoq.abort_request)
807 return -1;
808 }
809
810 /* if the frame is not skipped, then display it */
811 if (vp->bmp) {
812 /* get a pointer on the bitmap */
813 SDL_LockYUVOverlay (vp->bmp);
814
815 dst_pix_fmt = PIX_FMT_YUV420P;
816 pict.data[0] = vp->bmp->pixels[0];
817 pict.data[1] = vp->bmp->pixels[2];
818 pict.data[2] = vp->bmp->pixels[1];
819
820 pict.linesize[0] = vp->bmp->pitches[0];
821 pict.linesize[1] = vp->bmp->pitches[2];
822 pict.linesize[2] = vp->bmp->pitches[1];
823 img_convert(&pict, dst_pix_fmt,
824 (AVPicture *)src_frame, is->video_st->codec.pix_fmt,
825 is->video_st->codec.width, is->video_st->codec.height);
826 /* update the bitmap content */
827 SDL_UnlockYUVOverlay(vp->bmp);
828
829 vp->pts = pts;
830
831 /* now we can update the picture count */
832 if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
833 is->pictq_windex = 0;
834 SDL_LockMutex(is->pictq_mutex);
835 is->pictq_size++;
836 SDL_UnlockMutex(is->pictq_mutex);
837 }
838 return 0;
839 }
840
841 /* compute the exact PTS for the picture if it is omitted in the stream */
842 static int output_picture2(VideoState *is, AVFrame *src_frame, double pts1)
843 {
844 double frame_delay, pts;
845
846 pts = pts1;
847
848 if (pts != 0) {
849 /* update video clock with pts, if present */
850 is->video_clock = pts;
851 } else {
852 pts = is->video_clock;
853 }
854 /* update video clock for next frame */
855 frame_delay = (double)is->video_st->codec.frame_rate_base /
856 (double)is->video_st->codec.frame_rate;
857 /* for MPEG2, the frame can be repeated, so we update the
858 clock accordingly */
859 if (src_frame->repeat_pict) {
860 frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
861 }
862 is->video_clock += frame_delay;
863
864 #if defined(DEBUG_SYNC) && 0
865 {
866 int ftype;
867 if (src_frame->pict_type == FF_B_TYPE)
868 ftype = 'B';
869 else if (src_frame->pict_type == FF_I_TYPE)
870 ftype = 'I';
871 else
872 ftype = 'P';
873 printf("frame_type=%c clock=%0.3f pts=%0.3f\n",
874 ftype, pts, pts1);
875 }
876 #endif
877 return queue_picture(is, src_frame, pts);
878 }
879
880 static int video_thread(void *arg)
881 {
882 VideoState *is = arg;
883 AVPacket pkt1, *pkt = &pkt1;
884 int len1, got_picture;
885 AVFrame *frame= avcodec_alloc_frame();
886 double pts;
887
888 for(;;) {
889 while (is->paused && !is->videoq.abort_request) {
890 SDL_Delay(10);
891 }
892 if (packet_queue_get(&is->videoq, pkt, 1) < 0)
893 break;
894 /* NOTE: ipts is the PTS of the _first_ picture beginning in
895 this packet, if any */
896 pts = 0;
897 if (pkt->dts != AV_NOPTS_VALUE)
898 pts = (double)pkt->dts / AV_TIME_BASE;
899
900 if (is->video_st->codec.codec_id == CODEC_ID_RAWVIDEO) {
901 avpicture_fill((AVPicture *)frame, pkt->data,
902 is->video_st->codec.pix_fmt,
903 is->video_st->codec.width,
904 is->video_st->codec.height);
905 frame->pict_type = FF_I_TYPE;
906 if (output_picture2(is, frame, pts) < 0)
907 goto the_end;
908 } else {
909 len1 = avcodec_decode_video(&is->video_st->codec,
910 frame, &got_picture,
911 pkt->data, pkt->size);
912 // if (len1 < 0)
913 // break;
914 if (got_picture) {
915 if (output_picture2(is, frame, pts) < 0)
916 goto the_end;
917 }
918 }
919 av_free_packet(pkt);
920 if (step)
921 if (cur_stream)
922 stream_pause(cur_stream);
923 }
924 the_end:
925 av_free(frame);
926 return 0;
927 }
928
929 /* copy samples for viewing in editor window */
930 static void update_sample_display(VideoState *is, short *samples, int samples_size)
931 {
932 int size, len, channels;
933
934 channels = is->audio_st->codec.channels;
935
936 size = samples_size / sizeof(short);
937 while (size > 0) {
938 len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
939 if (len > size)
940 len = size;
941 memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
942 samples += len;
943 is->sample_array_index += len;
944 if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
945 is->sample_array_index = 0;
946 size -= len;
947 }
948 }
949
950 /* return the new audio buffer size (samples can be added or deleted
951 to get better sync if video or external master clock) */
952 static int synchronize_audio(VideoState *is, short *samples,
953 int samples_size1, double pts)
954 {
955 int n, samples_size;
956 double ref_clock;
957
958 n = 2 * is->audio_st->codec.channels;
959 samples_size = samples_size1;
960
961 /* if not master, then we try to remove or add samples to correct the clock */
962 if (((is->av_sync_type == AV_SYNC_VIDEO_MASTER && is->video_st) ||
963 is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
964 double diff, avg_diff;
965 int wanted_size, min_size, max_size, nb_samples;
966
967 ref_clock = get_master_clock(is);
968 diff = get_audio_clock(is) - ref_clock;
969
970 if (diff < AV_NOSYNC_THRESHOLD) {
971 is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
972 if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
973 /* not enough measures to have a correct estimate */
974 is->audio_diff_avg_count++;
975 } else {
976 /* estimate the A-V difference */
977 avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
978
979 if (fabs(avg_diff) >= is->audio_diff_threshold) {
980 wanted_size = samples_size + ((int)(diff * is->audio_st->codec.sample_rate) * n);
981 nb_samples = samples_size / n;
982
983 min_size = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
984 max_size = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
985 if (wanted_size < min_size)
986 wanted_size = min_size;
987 else if (wanted_size > max_size)
988 wanted_size = max_size;
989
990 /* add or remove samples to correction the synchro */
991 if (wanted_size < samples_size) {
992 /* remove samples */
993 samples_size = wanted_size;
994 } else if (wanted_size > samples_size) {
995 uint8_t *samples_end, *q;
996 int nb;
997
998 /* add samples */
999 nb = (samples_size - wanted_size);
1000 samples_end = (uint8_t *)samples + samples_size - n;
1001 q = samples_end + n;
1002 while (nb > 0) {
1003 memcpy(q, samples_end, n);
1004 q += n;
1005 nb -= n;
1006 }
1007 samples_size = wanted_size;
1008 }
1009 }
1010 #if 0
1011 printf("diff=%f adiff=%f sample_diff=%d apts=%0.3f vpts=%0.3f %f\n",
1012 diff, avg_diff, samples_size - samples_size1,
1013 is->audio_clock, is->video_clock, is->audio_diff_threshold);
1014 #endif
1015 }
1016 } else {
1017 /* too big difference : may be initial PTS errors, so
1018 reset A-V filter */
1019 is->audio_diff_avg_count = 0;
1020 is->audio_diff_cum = 0;
1021 }
1022 }
1023
1024 return samples_size;
1025 }
1026
1027 /* decode one audio frame and returns its uncompressed size */
1028 static int audio_decode_frame(VideoState *is, uint8_t *audio_buf, double *pts_ptr)
1029 {
1030 AVPacket *pkt = &is->audio_pkt;
1031 int n, len1, data_size;
1032 double pts;
1033
1034 for(;;) {
1035 /* NOTE: the audio packet can contain several frames */
1036 while (is->audio_pkt_size > 0) {
1037 len1 = avcodec_decode_audio(&is->audio_st->codec,
1038 (int16_t *)audio_buf, &data_size,
1039 is->audio_pkt_data, is->audio_pkt_size);
1040 if (len1 < 0) {
1041 /* if error, we skip the frame */
1042 is->audio_pkt_size = 0;
1043 break;
1044 }
1045
1046 is->audio_pkt_data += len1;
1047 is->audio_pkt_size -= len1;
1048 if (data_size <= 0)
1049 continue;
1050 /* if no pts, then compute it */
1051 pts = is->audio_clock;
1052 *pts_ptr = pts;
1053 n = 2 * is->audio_st->codec.channels;
1054 is->audio_clock += (double)data_size /
1055 (double)(n * is->audio_st->codec.sample_rate);
1056 #if defined(DEBUG_SYNC)
1057 {
1058 static double last_clock;
1059 printf("audio: delay=%0.3f clock=%0.3f pts=%0.3f\n",
1060 is->audio_clock - last_clock,
1061 is->audio_clock, pts);
1062 last_clock = is->audio_clock;
1063 }
1064 #endif
1065 return data_size;
1066 }
1067
1068 /* free the current packet */
1069 if (pkt->data)
1070 av_free_packet(pkt);
1071
1072 if (is->paused || is->audioq.abort_request) {
1073 return -1;
1074 }
1075
1076 /* read next packet */
1077 if (packet_queue_get(&is->audioq, pkt, 1) < 0)
1078 return -1;
1079 is->audio_pkt_data = pkt->data;
1080 is->audio_pkt_size = pkt->size;
1081
1082 /* if update the audio clock with the pts */
1083 if (pkt->pts != AV_NOPTS_VALUE) {
1084 is->audio_clock = (double)pkt->pts / AV_TIME_BASE;
1085 }
1086 }
1087 }
1088
1089 /* get the current audio output buffer size, in samples. With SDL, we
1090 cannot have a precise information */
1091 static int audio_write_get_buf_size(VideoState *is)
1092 {
1093 return is->audio_hw_buf_size - is->audio_buf_index;
1094 }
1095
1096
1097 /* prepare a new audio buffer */
1098 void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
1099 {
1100 VideoState *is = opaque;
1101 int audio_size, len1;
1102 double pts;
1103
1104 audio_callback_time = av_gettime();
1105
1106 while (len > 0) {
1107 if (is->audio_buf_index >= is->audio_buf_size) {
1108 audio_size = audio_decode_frame(is, is->audio_buf, &pts);
1109 if (audio_size < 0) {
1110 /* if error, just output silence */
1111 is->audio_buf_size = 1024;
1112 memset(is->audio_buf, 0, is->audio_buf_size);
1113 } else {
1114 if (is->show_audio)
1115 update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
1116 audio_size = synchronize_audio(is, (int16_t *)is->audio_buf, audio_size,
1117 pts);
1118 is->audio_buf_size = audio_size;
1119 }
1120 is->audio_buf_index = 0;
1121 }
1122 len1 = is->audio_buf_size - is->audio_buf_index;
1123 if (len1 > len)
1124 len1 = len;
1125 memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
1126 len -= len1;
1127 stream += len1;
1128 is->audio_buf_index += len1;
1129 }
1130 }
1131
1132
1133 /* open a given stream. Return 0 if OK */
1134 static int stream_component_open(VideoState *is, int stream_index)
1135 {
1136 AVFormatContext *ic = is->ic;
1137 AVCodecContext *enc;
1138 AVCodec *codec;
1139 SDL_AudioSpec wanted_spec, spec;
1140
1141 if (stream_index < 0 || stream_index >= ic->nb_streams)
1142 return -1;
1143 enc = &ic->streams[stream_index]->codec;
1144
1145 /* prepare audio output */
1146 if (enc->codec_type == CODEC_TYPE_AUDIO) {
1147 wanted_spec.freq = enc->sample_rate;
1148 wanted_spec.format = AUDIO_S16SYS;
1149 /* hack for AC3. XXX: suppress that */
1150 if (enc->channels > 2)
1151 enc->channels = 2;
1152 wanted_spec.channels = enc->channels;
1153 wanted_spec.silence = 0;
1154 wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
1155 wanted_spec.callback = sdl_audio_callback;
1156 wanted_spec.userdata = is;
1157 if (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
1158 fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
1159 return -1;
1160 }
1161 is->audio_hw_buf_size = spec.size;
1162 }
1163
1164 codec = avcodec_find_decoder(enc->codec_id);
1165 enc->debug_mv = debug_mv;
1166 enc->debug = debug;
1167 enc->workaround_bugs = workaround_bugs;
1168 enc->lowres = lowres;
1169 enc->idct_algo= idct;
1170 if(fast) enc->flags2 |= CODEC_FLAG2_FAST;
1171 if (!codec ||
1172 avcodec_open(enc, codec) < 0)
1173 return -1;
1174 #if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
1175 if(thread_count>1)
1176 avcodec_thread_init(enc, thread_count);
1177 #endif
1178 enc->thread_count= thread_count;
1179 switch(enc->codec_type) {
1180 case CODEC_TYPE_AUDIO:
1181 is->audio_stream = stream_index;
1182 is->audio_st = ic->streams[stream_index];
1183 is->audio_buf_size = 0;
1184 is->audio_buf_index = 0;
1185
1186 /* init averaging filter */
1187 is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
1188 is->audio_diff_avg_count = 0;
1189 /* since we do not have a precise anough audio fifo fullness,
1190 we correct audio sync only if larger than this threshold */
1191 is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / enc->sample_rate;
1192
1193 memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
1194 packet_queue_init(&is->audioq);
1195 SDL_PauseAudio(0);
1196 break;
1197 case CODEC_TYPE_VIDEO:
1198 is->video_stream = stream_index;
1199 is->video_st = ic->streams[stream_index];
1200
1201 is->frame_last_delay = 40e-3;
1202 is->frame_timer = (double)av_gettime() / 1000000.0;
1203 is->video_current_pts_time = av_gettime();
1204
1205 packet_queue_init(&is->videoq);
1206 is->video_tid = SDL_CreateThread(video_thread, is);
1207 break;
1208 default:
1209 break;
1210 }
1211 return 0;
1212 }
1213
1214 static void stream_component_close(VideoState *is, int stream_index)
1215 {
1216 AVFormatContext *ic = is->ic;
1217 AVCodecContext *enc;
1218
1219 enc = &ic->streams[stream_index]->codec;
1220
1221 switch(enc->codec_type) {
1222 case CODEC_TYPE_AUDIO:
1223 packet_queue_abort(&is->audioq);
1224
1225 SDL_CloseAudio();
1226
1227 packet_queue_end(&is->audioq);
1228 break;
1229 case CODEC_TYPE_VIDEO:
1230 packet_queue_abort(&is->videoq);
1231
1232 /* note: we also signal this mutex to make sure we deblock the
1233 video thread in all cases */
1234 SDL_LockMutex(is->pictq_mutex);
1235 SDL_CondSignal(is->pictq_cond);
1236 SDL_UnlockMutex(is->pictq_mutex);
1237
1238 SDL_WaitThread(is->video_tid, NULL);
1239
1240 packet_queue_end(&is->videoq);
1241 break;
1242 default:
1243 break;
1244 }
1245
1246 avcodec_close(enc);
1247 switch(enc->codec_type) {
1248 case CODEC_TYPE_AUDIO:
1249 is->audio_st = NULL;
1250 is->audio_stream = -1;
1251 break;
1252 case CODEC_TYPE_VIDEO:
1253 is->video_st = NULL;
1254 is->video_stream = -1;
1255 break;
1256 default:
1257 break;
1258 }
1259 }
1260
1261 void dump_stream_info(AVFormatContext *s)
1262 {
1263 if (s->track != 0)
1264 fprintf(stderr, "Track: %d\n", s->track);
1265 if (s->title[0] != '\0')
1266 fprintf(stderr, "Title: %s\n", s->title);
1267 if (s->author[0] != '\0')
1268 fprintf(stderr, "Author: %s\n", s->author);
1269 if (s->album[0] != '\0')
1270 fprintf(stderr, "Album: %s\n", s->album);
1271 if (s->year != 0)
1272 fprintf(stderr, "Year: %d\n", s->year);
1273 if (s->genre[0] != '\0')
1274 fprintf(stderr, "Genre: %s\n", s->genre);
1275 }
1276
1277 /* since we have only one decoding thread, we can use a global
1278 variable instead of a thread local variable */
1279 static VideoState *global_video_state;
1280
1281 static int decode_interrupt_cb(void)
1282 {
1283 return (global_video_state && global_video_state->abort_request);
1284 }
1285
1286 /* this thread gets the stream from the disk or the network */
1287 static int decode_thread(void *arg)
1288 {
1289 VideoState *is = arg;
1290 AVFormatContext *ic;
1291 int err, i, ret, video_index, audio_index, use_play;
1292 AVPacket pkt1, *pkt = &pkt1;
1293 AVFormatParameters params, *ap = &params;
1294
1295 video_index = -1;
1296 audio_index = -1;
1297 is->video_stream = -1;
1298 is->audio_stream = -1;
1299
1300 global_video_state = is;
1301 url_set_interrupt_cb(decode_interrupt_cb);
1302
1303 memset(ap, 0, sizeof(*ap));
1304 ap->image_format = image_format;
1305 ap->initial_pause = 1; /* we force a pause when starting an RTSP
1306 stream */
1307
1308 err = av_open_input_file(&ic, is->filename, is->iformat, 0, ap);
1309 if (err < 0) {
1310 print_error(is->filename, err);
1311 ret = -1;
1312 goto fail;
1313 }
1314 is->ic = ic;
1315 #ifdef CONFIG_NETWORK
1316 use_play = (ic->iformat == &rtsp_demux);
1317 #else
1318 use_play = 0;
1319 #endif
1320 if (!use_play) {
1321 err = av_find_stream_info(ic);
1322 if (err < 0) {
1323 fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
1324 ret = -1;
1325 goto fail;
1326 }
1327 }
1328
1329 /* if seeking requested, we execute it */
1330 if (start_time != AV_NOPTS_VALUE) {
1331 int64_t timestamp;
1332
1333 timestamp = start_time;
1334 /* add the stream start time */
1335 if (ic->start_time != AV_NOPTS_VALUE)
1336 timestamp += ic->start_time;
1337 ret = av_seek_frame(ic, -1, timestamp);
1338 if (ret < 0) {
1339 fprintf(stderr, "%s: could not seek to position %0.3f\n",
1340 is->filename, (double)timestamp / AV_TIME_BASE);
1341 }
1342 }
1343
1344 /* now we can begin to play (RTSP stream only) */
1345 av_read_play(ic);
1346
1347 if (use_play) {
1348 err = av_find_stream_info(ic);
1349 if (err < 0) {
1350 fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
1351 ret = -1;
1352 goto fail;
1353 }
1354 }
1355
1356 for(i = 0; i < ic->nb_streams; i++) {
1357 AVCodecContext *enc = &ic->streams[i]->codec;
1358 switch(enc->codec_type) {
1359 case CODEC_TYPE_AUDIO:
1360 if (audio_index < 0 && !audio_disable)
1361 audio_index = i;
1362 break;
1363 case CODEC_TYPE_VIDEO:
1364 if (video_index < 0 && !video_disable)
1365 video_index = i;
1366 break;
1367 default:
1368 break;
1369 }
1370 }
1371 if (show_status) {
1372 dump_format(ic, 0, is->filename, 0);
1373 dump_stream_info(ic);
1374 }
1375
1376 /* open the streams */
1377 if (audio_index >= 0) {
1378 stream_component_open(is, audio_index);
1379 }
1380
1381 if (video_index >= 0) {
1382 stream_component_open(is, video_index);
1383 } else {
1384 if (!display_disable)
1385 is->show_audio = 1;
1386 }
1387
1388 if (is->video_stream < 0 && is->audio_stream < 0) {
1389 fprintf(stderr, "%s: could not open codecs\n", is->filename);
1390 ret = -1;
1391 goto fail;
1392 }
1393
1394 for(;;) {
1395 if (is->abort_request)
1396 break;
1397 #ifdef CONFIG_NETWORK
1398 if (is->paused != is->last_paused) {
1399 is->last_paused = is->paused;
1400 if (is->paused)
1401 av_read_pause(ic);
1402 else
1403 av_read_play(ic);
1404 }
1405 if (is->paused && ic->iformat == &rtsp_demux) {
1406 /* wait 10 ms to avoid trying to get another packet */
1407 /* XXX: horrible */
1408 SDL_Delay(10);
1409 continue;
1410 }
1411 #endif
1412 if (is->seek_req) {
1413 /* XXX: must lock decoder threads */
1414 ret = av_seek_frame(is->ic, -1, is->seek_pos);
1415 if (ret < 0) {
1416 fprintf(stderr, "%s: error while seeking\n", is->ic->filename);
1417 }else{
1418 if (is->audio_stream >= 0) {
1419 packet_queue_flush(&is->audioq);
1420 }
1421 if (is->video_stream >= 0) {
1422 packet_queue_flush(&is->videoq);
1423 avcodec_flush_buffers(&ic->streams[video_index]->codec);
1424 }
1425 }
1426 is->seek_req = 0;
1427 }
1428
1429 /* if the queue are full, no need to read more */
1430 if (is->audioq.size > MAX_AUDIOQ_SIZE ||
1431 is->videoq.size > MAX_VIDEOQ_SIZE ||
1432 url_feof(&ic->pb)) {
1433 /* wait 10 ms */
1434 SDL_Delay(10);
1435 continue;
1436 }
1437 ret = av_read_frame(ic, pkt);
1438 if (ret < 0) {
1439 break;
1440 }
1441 if (pkt->stream_index == is->audio_stream) {
1442 packet_queue_put(&is->audioq, pkt);
1443 } else if (pkt->stream_index == is->video_stream) {
1444 packet_queue_put(&is->videoq, pkt);
1445 } else {
1446 av_free_packet(pkt);
1447 }
1448 }
1449 /* wait until the end */
1450 while (!is->abort_request) {
1451 SDL_Delay(100);
1452 }
1453
1454 ret = 0;
1455 fail:
1456 /* disable interrupting */
1457 global_video_state = NULL;
1458
1459 /* close each stream */
1460 if (is->audio_stream >= 0)
1461 stream_component_close(is, is->audio_stream);
1462 if (is->video_stream >= 0)
1463 stream_component_close(is, is->video_stream);
1464 if (is->ic) {
1465 av_close_input_file(is->ic);
1466 is->ic = NULL; /* safety */
1467 }
1468 url_set_interrupt_cb(NULL);
1469
1470 if (ret != 0) {
1471 SDL_Event event;
1472
1473 event.type = FF_QUIT_EVENT;
1474 event.user.data1 = is;
1475 SDL_PushEvent(&event);
1476 }
1477 return 0;
1478 }
1479
1480 static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
1481 {
1482 VideoState *is;
1483
1484 is = av_mallocz(sizeof(VideoState));
1485 if (!is)
1486 return NULL;
1487 pstrcpy(is->filename, sizeof(is->filename), filename);
1488 is->iformat = iformat;
1489 if (screen) {
1490 is->width = screen->w;
1491 is->height = screen->h;
1492 }
1493 is->ytop = 0;
1494 is->xleft = 0;
1495
1496 /* start video display */
1497 is->pictq_mutex = SDL_CreateMutex();
1498 is->pictq_cond = SDL_CreateCond();
1499
1500 /* add the refresh timer to draw the picture */
1501 schedule_refresh(is, 40);
1502
1503 is->av_sync_type = av_sync_type;
1504 is->parse_tid = SDL_CreateThread(decode_thread, is);
1505 if (!is->parse_tid) {
1506 av_free(is);
1507 return NULL;
1508 }
1509 return is;
1510 }
1511
1512 static void stream_close(VideoState *is)
1513 {
1514 VideoPicture *vp;
1515 int i;
1516 /* XXX: use a special url_shutdown call to abort parse cleanly */
1517 is->abort_request = 1;
1518 SDL_WaitThread(is->parse_tid, NULL);
1519
1520 /* free all pictures */
1521 for(i=0;i<VIDEO_PICTURE_QUEUE_SIZE; i++) {
1522 vp = &is->pictq[i];
1523 if (vp->bmp) {
1524 SDL_FreeYUVOverlay(vp->bmp);
1525 vp->bmp = NULL;
1526 }
1527 }
1528 SDL_DestroyMutex(is->pictq_mutex);
1529 SDL_DestroyCond(is->pictq_cond);
1530 }
1531
1532 void stream_cycle_channel(VideoState *is, int codec_type)
1533 {
1534 AVFormatContext *ic = is->ic;
1535 int start_index, stream_index;
1536 AVStream *st;
1537
1538 if (codec_type == CODEC_TYPE_VIDEO)
1539 start_index = is->video_stream;
1540 else
1541 start_index = is->audio_stream;
1542 if (start_index < 0)
1543 return;
1544 stream_index = start_index;
1545 for(;;) {
1546 if (++stream_index >= is->ic->nb_streams)
1547 stream_index = 0;
1548 if (stream_index == start_index)
1549 return;
1550 st = ic->streams[stream_index];
1551 if (st->codec.codec_type == codec_type) {
1552 /* check that parameters are OK */
1553 switch(codec_type) {
1554 case CODEC_TYPE_AUDIO:
1555 if (st->codec.sample_rate != 0 &&
1556 st->codec.channels != 0)
1557 goto the_end;
1558 break;
1559 case CODEC_TYPE_VIDEO:
1560 goto the_end;
1561 default:
1562 break;
1563 }
1564 }
1565 }
1566 the_end:
1567 stream_component_close(is, start_index);
1568 stream_component_open(is, stream_index);
1569 }
1570
1571
1572 void toggle_full_screen(void)
1573 {
1574 int w, h, flags;
1575 is_full_screen = !is_full_screen;
1576 if (!fs_screen_width) {
1577 /* use default SDL method */
1578 SDL_WM_ToggleFullScreen(screen);
1579 } else {
1580 /* use the recorded resolution */
1581 flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;
1582 if (is_full_screen) {
1583 w = fs_screen_width;
1584 h = fs_screen_height;
1585 flags |= SDL_FULLSCREEN;
1586 } else {
1587 w = screen_width;
1588 h = screen_height;
1589 flags |= SDL_RESIZABLE;
1590 }
1591 screen = SDL_SetVideoMode(w, h, 0, flags);
1592 cur_stream->width = w;
1593 cur_stream->height = h;
1594 }
1595 }
1596
1597 void toggle_pause(void)
1598 {
1599 if (cur_stream)
1600 stream_pause(cur_stream);
1601 step = 0;
1602 }
1603
1604 void step_to_next_frame(void)
1605 {
1606 if (cur_stream) {
1607 if (cur_stream->paused)
1608 cur_stream->paused=0;
1609 cur_stream->video_current_pts = get_video_clock(cur_stream);
1610 }
1611 step = 1;
1612 }
1613
1614 void do_exit(void)
1615 {
1616 if (cur_stream) {
1617 stream_close(cur_stream);
1618 cur_stream = NULL;
1619 }
1620 if (show_status)
1621 printf("\n");
1622 SDL_Quit();
1623 exit(0);
1624 }
1625
1626 void toggle_audio_display(void)
1627 {
1628 if (cur_stream) {
1629 cur_stream->show_audio = !cur_stream->show_audio;
1630 }
1631 }
1632
1633 /* handle an event sent by the GUI */
1634 void event_loop(void)
1635 {
1636 SDL_Event event;
1637 double incr, pos, frac;
1638
1639 for(;;) {
1640 SDL_WaitEvent(&event);
1641 switch(event.type) {
1642 case SDL_KEYDOWN:
1643 switch(event.key.keysym.sym) {
1644 case SDLK_ESCAPE:
1645 case SDLK_q:
1646 do_exit();
1647 break;
1648 case SDLK_f:
1649 toggle_full_screen();
1650 break;
1651 case SDLK_p:
1652 case SDLK_SPACE:
1653 toggle_pause();
1654 break;
1655 case SDLK_s: //S: Step to next frame
1656 step_to_next_frame();
1657 break;
1658 case SDLK_a:
1659 if (cur_stream)
1660 stream_cycle_channel(cur_stream, CODEC_TYPE_AUDIO);
1661 break;
1662 case SDLK_v:
1663 if (cur_stream)
1664 stream_cycle_channel(cur_stream, CODEC_TYPE_VIDEO);
1665 break;
1666 case SDLK_w:
1667 toggle_audio_display();
1668 break;
1669 case SDLK_LEFT:
1670 incr = -10.0;
1671 goto do_seek;
1672 case SDLK_RIGHT:
1673 incr = 10.0;
1674 goto do_seek;
1675 case SDLK_UP:
1676 incr = 60.0;
1677 goto do_seek;
1678 case SDLK_DOWN:
1679 incr = -60.0;
1680 do_seek:
1681 if (cur_stream) {
1682 pos = get_master_clock(cur_stream);
1683 pos += incr;
1684 stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE));
1685 }
1686 break;
1687 default:
1688 break;
1689 }
1690 break;
1691 case SDL_MOUSEBUTTONDOWN:
1692 if (cur_stream) {
1693 int ns, hh, mm, ss;
1694 int tns, thh, tmm, tss;
1695 tns = cur_stream->ic->duration/1000000LL;
1696 thh = tns/3600;
1697 tmm = (tns%3600)/60;
1698 tss = (tns%60);
1699 frac = (double)event.button.x/(double)cur_stream->width;
1700 ns = frac*tns;
1701 hh = ns/3600;
1702 mm = (ns%3600)/60;
1703 ss = (ns%60);
1704 fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n", frac*100,
1705 hh, mm, ss, thh, tmm, tss);
1706 stream_seek(cur_stream, (int64_t)(cur_stream->ic->start_time+frac*cur_stream->ic->duration));
1707 }
1708 break;
1709 case SDL_VIDEORESIZE:
1710 if (cur_stream) {
1711 screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
1712 SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
1713 cur_stream->width = event.resize.w;
1714 cur_stream->height = event.resize.h;
1715 }
1716 break;
1717 case SDL_QUIT:
1718 case FF_QUIT_EVENT:
1719 do_exit();
1720 break;
1721 case FF_ALLOC_EVENT:
1722 alloc_picture(event.user.data1);
1723 break;
1724 case FF_REFRESH_EVENT:
1725 video_refresh_timer(event.user.data1);
1726 break;
1727 default:
1728 break;
1729 }
1730 }
1731 }
1732
1733 void opt_width(const char *arg)
1734 {
1735 screen_width = atoi(arg);
1736 }
1737
1738 void opt_height(const char *arg)
1739 {
1740 screen_height = atoi(arg);
1741 }
1742
1743 static void opt_format(const char *arg)
1744 {
1745 file_iformat = av_find_input_format(arg);
1746 if (!file_iformat) {
1747 fprintf(stderr, "Unknown input format: %s\n", arg);
1748 exit(1);
1749 }
1750 }
1751
1752 static void opt_image_format(const char *arg)
1753 {
1754 AVImageFormat *f;
1755
1756 for(f = first_image_format; f != NULL; f = f->next) {
1757 if (!strcmp(arg, f->name))
1758 break;
1759 }
1760 if (!f) {
1761 fprintf(stderr, "Unknown image format: '%s'\n", arg);
1762 exit(1);
1763 }
1764 image_format = f;
1765 }
1766
1767 #ifdef CONFIG_NETWORK
1768 void opt_rtp_tcp(void)
1769 {
1770 /* only tcp protocol */
1771 rtsp_default_protocols = (1 << RTSP_PROTOCOL_RTP_TCP);
1772 }
1773 #endif
1774
1775 void opt_sync(const char *arg)
1776 {
1777 if (!strcmp(arg, "audio"))
1778 av_sync_type = AV_SYNC_AUDIO_MASTER;
1779 else if (!strcmp(arg, "video"))
1780 av_sync_type = AV_SYNC_VIDEO_MASTER;
1781 else if (!strcmp(arg, "ext"))
1782 av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
1783 else
1784 show_help();
1785 }
1786
1787 void opt_seek(const char *arg)
1788 {
1789 start_time = parse_date(arg, 1);
1790 }
1791
1792 static void opt_debug(const char *arg)
1793 {
1794 debug = atoi(arg);
1795 }
1796
1797 static void opt_vismv(const char *arg)
1798 {
1799 debug_mv = atoi(arg);
1800 }
1801
1802 static void opt_thread_count(const char *arg)
1803 {
1804 thread_count= atoi(arg);
1805 #if !defined(HAVE_PTHREADS) && !defined(HAVE_W32THREADS)
1806 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
1807 #endif
1808 }
1809
1810 const OptionDef options[] = {
1811 { "h", 0, {(void*)show_help}, "show help" },
1812 { "x", HAS_ARG, {(void*)opt_width}, "force displayed width", "width" },
1813 { "y", HAS_ARG, {(void*)opt_height}, "force displayed height", "height" },
1814 #if 0
1815 /* disabled as SDL/X11 does not support it correctly on application launch */
1816 { "fs", OPT_BOOL, {(void*)&is_full_screen}, "force full screen" },
1817 #endif
1818 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
1819 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
1820 { "ss", HAS_ARG, {(void*)&opt_seek}, "seek to a given position in seconds", "pos" },
1821 { "nodisp", OPT_BOOL, {(void*)&display_disable}, "disable graphical display" },
1822 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
1823 { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
1824 { "stats", OPT_BOOL | OPT_EXPERT, {(void*)&show_status}, "show status", "" },
1825 { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
1826 { "bug", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&workaround_bugs}, "workaround bugs", "" },
1827 { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
1828 { "fast", OPT_BOOL | OPT_EXPERT, {(void*)&fast}, "non spec compliant optimizations", "" },
1829 { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&lowres}, "", "" },
1830 { "idct", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&idct}, "set idct algo", "algo" },
1831 #ifdef CONFIG_NETWORK
1832 { "rtp_tcp", OPT_EXPERT, {(void*)&opt_rtp_tcp}, "force RTP/TCP protocol usage", "" },
1833 #endif
1834 { "sync", HAS_ARG | OPT_EXPERT, {(void*)opt_sync}, "set audio-video sync. type (type=audio/video/ext)", "type" },
1835 { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
1836 { NULL, },
1837 };
1838
1839 void show_help(void)
1840 {
1841 printf("ffplay version " FFMPEG_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
1842 "usage: ffplay [options] input_file\n"
1843 "Simple media player\n");
1844 printf("\n");
1845 show_help_options(options, "Main options:\n",
1846 OPT_EXPERT, 0);
1847 show_help_options(options, "\nAdvanced options:\n",
1848 OPT_EXPERT, OPT_EXPERT);
1849 printf("\nWhile playing:\n"
1850 "q, ESC quit\n"
1851 "f toggle full screen\n"
1852 "p, SPC pause\n"
1853 "a cycle audio channel\n"
1854 "v cycle video channel\n"
1855 "w show audio waves\n"
1856 "left/right seek backward/forward 10 seconds\n"
1857 "down/up seek backward/forward 1 minute\n"
1858 "mouse click seek to percentage in file corresponding to fraction of width\n"
1859 );
1860 exit(1);
1861 }
1862
1863 void parse_arg_file(const char *filename)
1864 {
1865 if (!strcmp(filename, "-"))
1866 filename = "pipe:";
1867 input_filename = filename;
1868 }
1869
1870 /* Called from the main */
1871 int main(int argc, char **argv)
1872 {
1873 int flags, w, h;
1874
1875 /* register all codecs, demux and protocols */
1876 av_register_all();
1877
1878 parse_options(argc, argv, options);
1879
1880 if (!input_filename)
1881 show_help();
1882
1883 if (display_disable) {
1884 video_disable = 1;
1885 }
1886 flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
1887 #ifndef CONFIG_WIN32
1888 flags |= SDL_INIT_EVENTTHREAD; /* Not supported on win32 */
1889 #endif
1890 if (SDL_Init (flags)) {
1891 fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
1892 exit(1);
1893 }
1894
1895 if (!display_disable) {
1896 #ifdef HAVE_X11
1897 /* save the screen resolution... SDL should allow full screen
1898 by resizing the window */
1899 {
1900 Display *dpy;
1901 dpy = XOpenDisplay(NULL);
1902 if (dpy) {
1903 fs_screen_width = DisplayWidth(dpy, DefaultScreen(dpy));
1904 fs_screen_height = DisplayHeight(dpy, DefaultScreen(dpy));
1905 XCloseDisplay(dpy);
1906 }
1907 }
1908 #endif
1909 flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;
1910 if (is_full_screen && fs_screen_width) {
1911 w = fs_screen_width;
1912 h = fs_screen_height;
1913 flags |= SDL_FULLSCREEN;
1914 } else {
1915 w = screen_width;
1916 h = screen_height;
1917 flags |= SDL_RESIZABLE;
1918 }
1919 screen = SDL_SetVideoMode(w, h, 0, flags);
1920 if (!screen) {
1921 fprintf(stderr, "SDL: could not set video mode - exiting\n");
1922 exit(1);
1923 }
1924 SDL_WM_SetCaption("FFplay", "FFplay");
1925 }
1926
1927 SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
1928 SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
1929 SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
1930 SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
1931
1932 cur_stream = stream_open(input_filename, file_iformat);
1933
1934 event_loop();
1935
1936 /* never returns */
1937
1938 return 0;
1939 }