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