patch for DV capturing by Dan Dennedy <dan at dennedy dot org>
[libav.git] / ffplay.c
CommitLineData
01310af2
FB
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 "common.h"
21#include "avformat.h"
22
23#include "cmdutils.h"
24
25#include <SDL.h>
26#include <SDL_thread.h>
27
31319a8c
FB
28#ifdef CONFIG_WIN32
29#undef main /* We don't want SDL to override our main() */
30#endif
31
01310af2
FB
32#if defined(__linux__)
33#define HAVE_X11
34#endif
35
36#ifdef HAVE_X11
37#include <X11/Xlib.h>
38#endif
39
40#define MAX_VIDEOQ_SIZE (5 * 256 * 1024)
41#define MAX_AUDIOQ_SIZE (5 * 16 * 1024)
42
43/* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
44#define SAMPLE_ARRAY_SIZE (2*65536)
45
46typedef struct PacketQueue {
47 AVPacketList *first_pkt, *last_pkt;
48 int nb_packets;
49 int size;
50 int abort_request;
51 SDL_mutex *mutex;
52 SDL_cond *cond;
53} PacketQueue;
54
55#define VIDEO_PICTURE_QUEUE_SIZE 1
56
57typedef struct VideoPicture {
58 int delay; /* delay before showing the next picture */
59 SDL_Overlay *bmp;
60 int width, height; /* source height & width */
61 int allocated;
62} VideoPicture;
63
64enum {
65 AV_SYNC_AUDIO_MASTER, /* default choice */
66 AV_SYNC_VIDEO_MASTER,
67 AV_SYNC_EXTERNAL_CLOCK, /* if external clock, then you must update external_clock yourself */
68};
69
70typedef struct VideoState {
71 SDL_Thread *parse_tid;
72 SDL_Thread *video_tid;
73 int no_background;
74 int abort_request;
75 int paused;
416e3508 76 int last_paused;
01310af2
FB
77 AVFormatContext *ic;
78 int dtg_active_format;
79
80 int audio_stream;
81
82 int av_sync_type;
83 double external_clock; /* external clock */
84
85 double audio_clock; /* current audio clock value */
86 AVStream *audio_st;
87 PacketQueue audioq;
88 int audio_hw_buf_size;
89 /* samples output by the codec. we reserve more space for avsync
90 compensation */
91 uint8_t audio_buf[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2];
92 int audio_buf_size; /* in bytes */
93 int audio_buf_index; /* in bytes */
94 AVPacket audio_pkt;
95 uint8_t *audio_pkt_data;
96 int audio_pkt_size;
97 int64_t audio_pkt_ipts;
98
99 int show_audio; /* if true, display audio samples */
100 int16_t sample_array[SAMPLE_ARRAY_SIZE];
101 int sample_array_index;
5e0257e3 102 int last_i_start;
01310af2
FB
103
104 double video_clock; /* current video clock value */
105 int video_stream;
106 AVStream *video_st;
107 PacketQueue videoq;
108
109 VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
110 int pictq_size, pictq_rindex, pictq_windex;
111 SDL_mutex *pictq_mutex;
112 SDL_cond *pictq_cond;
113
114 // QETimer *video_timer;
115 char filename[1024];
116 int width, height, xleft, ytop;
117} VideoState;
118
119void show_help(void);
120int audio_write_get_buf_size(VideoState *is);
121
122/* options specified by the user */
123static AVInputFormat *file_iformat;
124static const char *input_filename;
125static int fs_screen_width;
126static int fs_screen_height;
127static int screen_width = 640;
128static int screen_height = 480;
129static int audio_disable;
130static int video_disable;
131static int display_disable;
132static int show_status;
133
134/* current context */
135static int is_full_screen;
136static VideoState *cur_stream;
5e0257e3 137static int64_t audio_callback_time;
01310af2
FB
138
139#define FF_ALLOC_EVENT (SDL_USEREVENT)
140#define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
141
142SDL_Surface *screen;
143
144/* packet queue handling */
145static void packet_queue_init(PacketQueue *q)
146{
147 memset(q, 0, sizeof(PacketQueue));
148 q->mutex = SDL_CreateMutex();
149 q->cond = SDL_CreateCond();
150}
151
152static void packet_queue_end(PacketQueue *q)
153{
154 AVPacketList *pkt, *pkt1;
155
156 for(pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
157 pkt1 = pkt->next;
158 av_free_packet(&pkt->pkt);
159 }
160 SDL_DestroyMutex(q->mutex);
161 SDL_DestroyCond(q->cond);
162}
163
164static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
165{
166 AVPacketList *pkt1;
167
168 pkt1 = av_malloc(sizeof(AVPacketList));
169 if (!pkt1)
170 return -1;
171 pkt1->pkt = *pkt;
172 pkt1->next = NULL;
173
174 SDL_LockMutex(q->mutex);
175
176 if (!q->last_pkt)
177
178 q->first_pkt = pkt1;
179 else
180 q->last_pkt->next = pkt1;
181 q->last_pkt = pkt1;
182 q->nb_packets++;
183 q->size += pkt1->pkt.size;
184 /* XXX: should duplicate packet data in DV case */
185 SDL_CondSignal(q->cond);
186
187 SDL_UnlockMutex(q->mutex);
188 return 0;
189}
190
191static void packet_queue_abort(PacketQueue *q)
192{
193 SDL_LockMutex(q->mutex);
194
195 q->abort_request = 1;
196
197 SDL_CondSignal(q->cond);
198
199 SDL_UnlockMutex(q->mutex);
200}
201
202/* return < 0 if aborted, 0 if no packet and > 0 if packet. */
203static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
204{
205 AVPacketList *pkt1;
206 int ret;
207
208 SDL_LockMutex(q->mutex);
209
210 for(;;) {
211 if (q->abort_request) {
212 ret = -1;
213 break;
214 }
215
216 pkt1 = q->first_pkt;
217 if (pkt1) {
218 q->first_pkt = pkt1->next;
219 if (!q->first_pkt)
220 q->last_pkt = NULL;
221 q->nb_packets--;
222 q->size -= pkt1->pkt.size;
223 *pkt = pkt1->pkt;
224 av_free(pkt1);
225 ret = 1;
226 break;
227 } else if (!block) {
228 ret = 0;
229 break;
230 } else {
231 SDL_CondWait(q->cond, q->mutex);
232 }
233 }
234 SDL_UnlockMutex(q->mutex);
235 return ret;
236}
237
238static inline void fill_rectangle(SDL_Surface *screen,
239 int x, int y, int w, int h, int color)
240{
241 SDL_Rect rect;
242 rect.x = x;
243 rect.y = y;
244 rect.w = w;
245 rect.h = h;
246 SDL_FillRect(screen, &rect, color);
247}
248
249#if 0
250/* draw only the border of a rectangle */
251void fill_border(VideoState *s, int x, int y, int w, int h, int color)
252{
253 int w1, w2, h1, h2;
254
255 /* fill the background */
256 w1 = x;
257 if (w1 < 0)
258 w1 = 0;
259 w2 = s->width - (x + w);
260 if (w2 < 0)
261 w2 = 0;
262 h1 = y;
263 if (h1 < 0)
264 h1 = 0;
265 h2 = s->height - (y + h);
266 if (h2 < 0)
267 h2 = 0;
268 fill_rectangle(screen,
269 s->xleft, s->ytop,
270 w1, s->height,
271 color);
272 fill_rectangle(screen,
273 s->xleft + s->width - w2, s->ytop,
274 w2, s->height,
275 color);
276 fill_rectangle(screen,
277 s->xleft + w1, s->ytop,
278 s->width - w1 - w2, h1,
279 color);
280 fill_rectangle(screen,
281 s->xleft + w1, s->ytop + s->height - h2,
282 s->width - w1 - w2, h2,
283 color);
284}
285#endif
286
287static void video_image_display(VideoState *is)
288{
289 VideoPicture *vp;
290 float aspect_ratio;
291 int width, height, x, y;
292 SDL_Rect rect;
293
294 vp = &is->pictq[is->pictq_rindex];
295 if (vp->bmp) {
296 /* XXX: use variable in the frame */
297 aspect_ratio = is->video_st->codec.aspect_ratio;
298 if (aspect_ratio <= 0.0)
299 aspect_ratio = (float)is->video_st->codec.width /
300 (float)is->video_st->codec.height;
301 /* if an active format is indicated, then it overrides the
302 mpeg format */
303#if 0
304 if (is->video_st->codec.dtg_active_format != is->dtg_active_format) {
305 is->dtg_active_format = is->video_st->codec.dtg_active_format;
306 printf("dtg_active_format=%d\n", is->dtg_active_format);
307 }
308#endif
309#if 0
310 switch(is->video_st->codec.dtg_active_format) {
311 case FF_DTG_AFD_SAME:
312 default:
313 /* nothing to do */
314 break;
315 case FF_DTG_AFD_4_3:
316 aspect_ratio = 4.0 / 3.0;
317 break;
318 case FF_DTG_AFD_16_9:
319 aspect_ratio = 16.0 / 9.0;
320 break;
321 case FF_DTG_AFD_14_9:
322 aspect_ratio = 14.0 / 9.0;
323 break;
324 case FF_DTG_AFD_4_3_SP_14_9:
325 aspect_ratio = 14.0 / 9.0;
326 break;
327 case FF_DTG_AFD_16_9_SP_14_9:
328 aspect_ratio = 14.0 / 9.0;
329 break;
330 case FF_DTG_AFD_SP_4_3:
331 aspect_ratio = 4.0 / 3.0;
332 break;
333 }
334#endif
335
336 /* XXX: we suppose the screen has a 1.0 pixel ratio */
337 height = is->height;
338 width = ((int)rint(height * aspect_ratio)) & -3;
339 if (width > is->width) {
340 width = is->width;
341 height = ((int)rint(width / aspect_ratio)) & -3;
342 }
343 x = (is->width - width) / 2;
344 y = (is->height - height) / 2;
345 if (!is->no_background) {
346 /* fill the background */
347 // fill_border(is, x, y, width, height, QERGB(0x00, 0x00, 0x00));
348 } else {
349 is->no_background = 0;
350 }
351 rect.x = is->xleft + x;
352 rect.y = is->xleft + y;
353 rect.w = width;
354 rect.h = height;
355 SDL_DisplayYUVOverlay(vp->bmp, &rect);
356 } else {
357#if 0
358 fill_rectangle(screen,
359 is->xleft, is->ytop, is->width, is->height,
360 QERGB(0x00, 0x00, 0x00));
361#endif
362 }
363}
364
365static inline int compute_mod(int a, int b)
366{
367 a = a % b;
368 if (a >= 0)
369 return a;
370 else
371 return a + b;
372}
373
374static void video_audio_display(VideoState *s)
375{
376 int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
377 int ch, channels, h, h2, bgcolor, fgcolor;
378 int16_t time_diff;
379
380 /* compute display index : center on currently output samples */
381 channels = s->audio_st->codec.channels;
382 nb_display_channels = channels;
5e0257e3
FB
383 if (!s->paused) {
384 n = 2 * channels;
385 delay = audio_write_get_buf_size(s);
386 delay /= n;
387
388 /* to be more precise, we take into account the time spent since
389 the last buffer computation */
390 if (audio_callback_time) {
391 time_diff = av_gettime() - audio_callback_time;
392 delay += (time_diff * s->audio_st->codec.sample_rate) / 1000000;
393 }
394
395 delay -= s->width / 2;
396 if (delay < s->width)
397 delay = s->width;
398 i_start = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
399 s->last_i_start = i_start;
400 } else {
401 i_start = s->last_i_start;
01310af2
FB
402 }
403
01310af2
FB
404 bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
405 fill_rectangle(screen,
406 s->xleft, s->ytop, s->width, s->height,
407 bgcolor);
408
409 fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);
410
411 /* total height for one channel */
412 h = s->height / nb_display_channels;
413 /* graph height / 2 */
414 h2 = (h * 9) / 20;
415 for(ch = 0;ch < nb_display_channels; ch++) {
416 i = i_start + ch;
417 y1 = s->ytop + ch * h + (h / 2); /* position of center line */
418 for(x = 0; x < s->width; x++) {
419 y = (s->sample_array[i] * h2) >> 15;
420 if (y < 0) {
421 y = -y;
422 ys = y1 - y;
423 } else {
424 ys = y1;
425 }
426 fill_rectangle(screen,
427 s->xleft + x, ys, 1, y,
428 fgcolor);
429 i += channels;
430 if (i >= SAMPLE_ARRAY_SIZE)
431 i -= SAMPLE_ARRAY_SIZE;
432 }
433 }
434
435 fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);
436
437 for(ch = 1;ch < nb_display_channels; ch++) {
438 y = s->ytop + ch * h;
439 fill_rectangle(screen,
440 s->xleft, y, s->width, 1,
441 fgcolor);
442 }
443 SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
444}
445
446/* display the current picture, if any */
447static void video_display(VideoState *is)
448{
449 if (is->audio_st && is->show_audio)
450 video_audio_display(is);
451 else if (is->video_st)
452 video_image_display(is);
453}
454
455static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque)
456{
457 SDL_Event event;
458 event.type = FF_REFRESH_EVENT;
459 event.user.data1 = opaque;
460 SDL_PushEvent(&event);
461 return 0; /* 0 means stop timer */
462}
463
464/* schedule a video refresh in 'delay' ms */
465static void schedule_refresh(VideoState *is, int delay)
466{
467 SDL_AddTimer(delay, sdl_refresh_timer_cb, is);
468}
469
470/* called to display each frame */
471static void video_refresh_timer(void *opaque)
472{
473 VideoState *is = opaque;
474 VideoPicture *vp;
475
476 if (is->video_st) {
477 if (is->pictq_size == 0) {
478 /* if no picture, need to wait */
479 schedule_refresh(is, 40);
480 } else {
481 vp = &is->pictq[is->pictq_rindex];
482
483 /* launch timer for next picture */
484 schedule_refresh(is, vp->delay);
485
486 /* display picture */
487 video_display(is);
488
489 /* update queue size and signal for next picture */
490 if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
491 is->pictq_rindex = 0;
492
493 SDL_LockMutex(is->pictq_mutex);
494 is->pictq_size--;
495 SDL_CondSignal(is->pictq_cond);
496 SDL_UnlockMutex(is->pictq_mutex);
497 }
498 } else if (is->audio_st) {
499 /* draw the next audio frame */
500
501 schedule_refresh(is, 40);
502
503 /* if only audio stream, then display the audio bars (better
504 than nothing, just to test the implementation */
505
506 /* display picture */
507 video_display(is);
508 } else {
509 schedule_refresh(is, 100);
510 }
511 if (show_status) {
512 static int64_t last_time;
513 int64_t cur_time;
514 int aqsize, vqsize;
515
516 cur_time = av_gettime();
517 if (!last_time || (cur_time - last_time) >= 500 * 1000) {
518 aqsize = 0;
519 vqsize = 0;
520 if (is->audio_st)
521 aqsize = is->audioq.size;
522 if (is->video_st)
523 vqsize = is->videoq.size;
524 printf("A:%7.2f V:%7.2f aq=%5dKB vq=%5dKB \r",
525 is->audio_clock, is->video_clock, aqsize / 1024, vqsize / 1024);
526 fflush(stdout);
527 last_time = cur_time;
528 }
529 }
530}
531
532/* allocate a picture (needs to do that in main thread to avoid
533 potential locking problems */
534static void alloc_picture(void *opaque)
535{
536 VideoState *is = opaque;
537 VideoPicture *vp;
538 int is_yuv;
539
540 vp = &is->pictq[is->pictq_windex];
541
542 if (vp->bmp)
543 SDL_FreeYUVOverlay(vp->bmp);
544
545 /* XXX: use generic function */
546 switch(is->video_st->codec.pix_fmt) {
547 case PIX_FMT_YUV420P:
548 case PIX_FMT_YUV422P:
549 case PIX_FMT_YUV444P:
550 case PIX_FMT_YUV422:
551 case PIX_FMT_YUV410P:
552 case PIX_FMT_YUV411P:
553 is_yuv = 1;
554 break;
555 default:
556 is_yuv = 0;
557 break;
558 }
559
560 if (is_yuv) {
561 vp->bmp = SDL_CreateYUVOverlay(is->video_st->codec.width,
562 is->video_st->codec.height,
563 SDL_YV12_OVERLAY,
564 screen);
565 } else {
566#if 0
567 vp->bmp = bmp_alloc(screen,
568 is->video_st->codec.width,
569 is->video_st->codec.height,
570 screen->bitmap_format,
571 0);
572#endif
573 vp->bmp = NULL;
574 }
575 vp->width = is->video_st->codec.width;
576 vp->height = is->video_st->codec.height;
577
578 SDL_LockMutex(is->pictq_mutex);
579 vp->allocated = 1;
580 SDL_CondSignal(is->pictq_cond);
581 SDL_UnlockMutex(is->pictq_mutex);
582}
583
584#define VIDEO_CORRECTION_THRESHOLD 0.2
585
586static int output_picture(VideoState *is, AVPicture *src_pict, double pts)
587{
588 VideoPicture *vp;
589 int dst_pix_fmt;
590 AVPicture pict;
591 double delay, ref_clock, diff;
592
593 /* wait until we have space to put a new picture */
594 SDL_LockMutex(is->pictq_mutex);
595 while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE &&
596 !is->videoq.abort_request) {
597 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
598 }
599 SDL_UnlockMutex(is->pictq_mutex);
600
601 if (is->videoq.abort_request)
602 return -1;
603
604 vp = &is->pictq[is->pictq_windex];
605
606 /* alloc or resize hardware picture buffer */
607 if (!vp->bmp ||
608 vp->width != is->video_st->codec.width ||
609 vp->height != is->video_st->codec.height) {
610 SDL_Event event;
611
612 vp->allocated = 0;
613
614 /* the allocation must be done in the main thread to avoid
615 locking problems */
616 event.type = FF_ALLOC_EVENT;
617 event.user.data1 = is;
618 SDL_PushEvent(&event);
619
620 /* wait until the picture is allocated */
621 SDL_LockMutex(is->pictq_mutex);
622 while (!vp->allocated && !is->videoq.abort_request) {
623 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
624 }
625 SDL_UnlockMutex(is->pictq_mutex);
626
627 if (is->videoq.abort_request)
628 return -1;
629 }
630
631 if (vp->bmp) {
632 /* get a pointer on the bitmap */
633 SDL_LockYUVOverlay (vp->bmp);
634
635 dst_pix_fmt = PIX_FMT_YUV420P;
636 pict.data[0] = vp->bmp->pixels[0];
637 pict.data[1] = vp->bmp->pixels[2];
638 pict.data[2] = vp->bmp->pixels[1];
639
640 pict.linesize[0] = vp->bmp->pitches[0];
641 pict.linesize[1] = vp->bmp->pitches[2];
642 pict.linesize[2] = vp->bmp->pitches[1];
643
644 img_convert(&pict, dst_pix_fmt,
645 src_pict, is->video_st->codec.pix_fmt,
646 is->video_st->codec.width, is->video_st->codec.height);
647 /* update the bitmap content */
648 SDL_UnlockYUVOverlay(vp->bmp);
649
650 /* compute delay for the next frame and take into account the
651 pts if needed to make a correction. Since we do not support
652 correct MPEG B frame PTS, we put a high threshold */
653
654 if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
655 ref_clock = is->video_clock;
656 } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
657 /* cannot use audio master if no audio, so fall back to no sync */
658 if (!is->audio_st)
659 ref_clock = is->video_clock;
660 else
661 ref_clock = is->audio_clock;
662 } else {
663 ref_clock = is->external_clock;
664 }
665 diff = is->video_clock - ref_clock;
666 delay = (double)is->video_st->codec.frame_rate_base /
667 (double)is->video_st->codec.frame_rate;
668 if (fabs(diff) > VIDEO_CORRECTION_THRESHOLD) {
669 /* if too big difference, then we adjust */
670 delay += diff;
671 /* compute the difference */
672 if (delay < 0.01)
673 delay = 0.01;
674 else if (delay > 1.0)
675 delay = 1.0;
676 }
677 vp->delay = (int)(delay * 1000 + 0.5);
678
679 /* now we can update the picture count */
680 if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
681 is->pictq_windex = 0;
682 SDL_LockMutex(is->pictq_mutex);
683 is->pictq_size++;
684 SDL_UnlockMutex(is->pictq_mutex);
685 }
686
687 /* update video clock */
688 if (pts != 0) {
689 is->video_clock = pts;
690 } else {
691 is->video_clock += (double)is->video_st->codec.frame_rate_base /
692 (double)is->video_st->codec.frame_rate;
693 }
694 return 0;
695}
696
697static int video_thread(void *arg)
698{
699 VideoState *is = arg;
700 AVPacket pkt1, *pkt = &pkt1;
701 unsigned char *ptr;
702 int len, len1, got_picture, i;
703 AVFrame frame;
704 AVPicture pict;
705 int64_t ipts;
706 double pts;
707
708 for(;;) {
709 while (is->paused && !is->videoq.abort_request) {
710 SDL_Delay(10);
711 }
712 if (packet_queue_get(&is->videoq, pkt, 1) < 0)
713 break;
714 ipts = pkt->pts;
715 ptr = pkt->data;
716 if (is->video_st->codec.codec_id == CODEC_ID_RAWVIDEO) {
717 avpicture_fill(&pict, ptr,
718 is->video_st->codec.pix_fmt,
719 is->video_st->codec.width,
720 is->video_st->codec.height);
721 pts = 0;
722 if (ipts != AV_NOPTS_VALUE)
723 pts = (double)ipts * is->ic->pts_num / is->ic->pts_den;
724 if (output_picture(is, &pict, pts) < 0)
725 goto the_end;
726 } else {
727 len = pkt->size;
728 while (len > 0) {
729 len1 = avcodec_decode_video(&is->video_st->codec,
730 &frame, &got_picture, ptr, len);
731 if (len1 < 0)
732 break;
733 if (got_picture) {
734 for(i=0;i<4;i++) {
735 pict.data[i] = frame.data[i];
736 pict.linesize[i] = frame.linesize[i];
737 }
738 pts = 0;
739 if (ipts != AV_NOPTS_VALUE)
740 pts = (double)ipts * is->ic->pts_num / is->ic->pts_den;
741 ipts = AV_NOPTS_VALUE;
742 if (output_picture(is, &pict, pts) < 0)
743 goto the_end;
744 }
745 ptr += len1;
746 len -= len1;
747 }
748 }
749 av_free_packet(pkt);
750 }
751 the_end:
752 return 0;
753}
754
755/* copy samples for viewing in editor window */
756static void update_sample_display(VideoState *is, short *samples, int samples_size)
757{
758 int size, len, channels;
759
760 channels = is->audio_st->codec.channels;
761
762 size = samples_size / sizeof(short);
763 while (size > 0) {
764 len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
765 if (len > size)
766 len = size;
767 memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
768 samples += len;
769 is->sample_array_index += len;
770 if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
771 is->sample_array_index = 0;
772 size -= len;
773 }
774}
775
776/* maximum audio speed change to get correct sync */
777#define SAMPLE_CORRECTION_PERCENT_MAX 2
778
779/* return the new audio buffer size (samples can be added or deleted
780 to get better sync if video or external master clock) */
781static int synchronize_audio(VideoState *is, short *samples,
782 int samples_size, double pts)
783{
784 int n, delay;
785 double ref_clock;
786
787 n = 2 * is->audio_st->codec.channels;
788
789 if (is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)
790 ref_clock = is->external_clock;
791 else if (is->av_sync_type == AV_SYNC_VIDEO_MASTER && is->video_st)
792 ref_clock = is->video_clock;
793 else
794 ref_clock = is->audio_clock;
795
796 /* if not master, then we try to remove or add samples to correct the clock */
797
798 if (((is->av_sync_type == AV_SYNC_VIDEO_MASTER && is->video_st) ||
799 is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK) && pts != 0) {
800 double diff;
801 int wanted_size, min_size, max_size, nb_samples;
802 delay = audio_write_get_buf_size(is);
803 diff = pts - (double)delay / (double)(n * is->audio_st->codec.sample_rate) - ref_clock;
804 wanted_size = (int)(diff * is->audio_st->codec.sample_rate) * n;
805 nb_samples = samples_size / n;
806
807 min_size = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
808 max_size = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
809 if (wanted_size < min_size)
810 wanted_size = min_size;
811 else if (wanted_size > max_size)
812 wanted_size = max_size;
813
814 /* do the correct */
815 /* XXX: do it better with sample interpolation */
816 if (wanted_size < samples_size) {
817 /* remove samples */
818 samples_size = wanted_size;
819 } else if (wanted_size > samples_size) {
820 uint8_t *samples_end, *q;
821 int nb;
822
823 /* add samples */
824 nb = (samples_size - wanted_size);
825 samples_end = (uint8_t *)samples + samples_size - n;
826 q = samples_end + n;
827 while (nb > 0) {
828 memcpy(q, samples_end, n);
829 q += n;
830 nb -= n;
831 }
832 samples_size = wanted_size;
833 }
834 }
835
836 /* update audio clock */
837 if (is->av_sync_type == AV_SYNC_AUDIO_MASTER && pts != 0) {
838 /* a pts is given: we update the audio clock precisely */
839 delay = audio_write_get_buf_size(is);
840 is->audio_clock = pts - (double)delay / (double)(n * is->audio_st->codec.sample_rate);
841 } else {
842 is->audio_clock += (double)samples_size / (double)(n * is->audio_st->codec.sample_rate);
843 }
844 return samples_size;
845}
846
847/* decode one audio frame and returns its uncompressed size */
848static int audio_decode_frame(VideoState *is, uint8_t *audio_buf, double *pts_ptr)
849{
850 AVPacket *pkt = &is->audio_pkt;
851 int len1, data_size;
852 double pts;
853
854 for(;;) {
855 if (is->paused || is->audioq.abort_request) {
856 return -1;
857 }
858 while (is->audio_pkt_size > 0) {
859 len1 = avcodec_decode_audio(&is->audio_st->codec,
860 (int16_t *)audio_buf, &data_size,
861 is->audio_pkt_data, is->audio_pkt_size);
862 if (len1 < 0)
863 break;
864 is->audio_pkt_data += len1;
865 is->audio_pkt_size -= len1;
866 if (data_size > 0) {
867 pts = 0;
868 if (is->audio_pkt_ipts != AV_NOPTS_VALUE)
869 pts = (double)is->audio_pkt_ipts * is->ic->pts_num / is->ic->pts_den;
870 *pts_ptr = pts;
871 is->audio_pkt_ipts = AV_NOPTS_VALUE;
872 /* we got samples : we can exit now */
873 return data_size;
874 }
875 }
876
877 /* free previous packet if any */
878 if (pkt->destruct)
879 av_free_packet(pkt);
880
881 /* read next packet */
882 if (packet_queue_get(&is->audioq, pkt, 1) < 0)
883 return -1;
884 is->audio_pkt_data = pkt->data;
885 is->audio_pkt_size = pkt->size;
886 is->audio_pkt_ipts = pkt->pts;
887 }
888}
889
890int audio_write_get_buf_size(VideoState *is)
891{
892 int delay;
893 delay = is->audio_hw_buf_size;
894#if 0
895 /* just a test to check if the estimated delay is OK */
896 {
897 int val;
898 if (ioctl(sdl_audio_fd, SNDCTL_DSP_GETODELAY, &val) < 0)
899 perror("SNDCTL_DSP_GETODELAY");
900 printf("real_delay=%d delay=%d\n", val, delay);
901 }
902#endif
903 return delay;
904}
905
906
907/* prepare a new audio buffer */
908void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
909{
910 VideoState *is = opaque;
911 int audio_size, len1;
912 double pts;
913
914 audio_callback_time = av_gettime();
915
916 while (len > 0) {
917 if (is->audio_buf_index >= is->audio_buf_size) {
918 audio_size = audio_decode_frame(is, is->audio_buf, &pts);
919 if (audio_size < 0) {
920 /* if error, just output silence */
921 is->audio_buf_size = 1024;
922 memset(is->audio_buf, 0, is->audio_buf_size);
923 } else {
924 if (is->show_audio)
925 update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
926 audio_size = synchronize_audio(is, (int16_t *)is->audio_buf, audio_size,
927 pts);
928 is->audio_buf_size = audio_size;
929 }
930 is->audio_buf_index = 0;
931 }
932 len1 = is->audio_buf_size - is->audio_buf_index;
933 if (len1 > len)
934 len1 = len;
935 memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
936 len -= len1;
937 stream += len1;
938 is->audio_buf_index += len1;
939 }
940}
941
942
943/* open a given stream. Return 0 if OK */
944static int stream_component_open(VideoState *is, int stream_index)
945{
946 AVFormatContext *ic = is->ic;
947 AVCodecContext *enc;
948 AVCodec *codec;
949 SDL_AudioSpec wanted_spec, spec;
950
951 if (stream_index < 0 || stream_index >= ic->nb_streams)
952 return -1;
953 enc = &ic->streams[stream_index]->codec;
954
955
956 /* prepare audio output */
957 if (enc->codec_type == CODEC_TYPE_AUDIO) {
958 wanted_spec.freq = enc->sample_rate;
959 wanted_spec.format = AUDIO_S16SYS;
960 wanted_spec.channels = enc->channels;
961 wanted_spec.silence = 0;
962 wanted_spec.samples = 8192;
963 wanted_spec.callback = sdl_audio_callback;
964 wanted_spec.userdata = is;
965 if (SDL_OpenAudio(&wanted_spec, &spec) < 0)
966 return -1;
967 is->audio_hw_buf_size = spec.size;
968 }
969
970 codec = avcodec_find_decoder(enc->codec_id);
971 if (!codec ||
972 avcodec_open(enc, codec) < 0)
973 return -1;
974 switch(enc->codec_type) {
975 case CODEC_TYPE_AUDIO:
976 is->audio_stream = stream_index;
977 is->audio_st = ic->streams[stream_index];
978 is->audio_buf_size = 0;
979 is->audio_buf_index = 0;
980 is->audio_pkt_size = 0;
981 memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
982 packet_queue_init(&is->audioq);
983 SDL_PauseAudio(0);
984 break;
985 case CODEC_TYPE_VIDEO:
986 is->video_stream = stream_index;
987 is->video_st = ic->streams[stream_index];
988
989 packet_queue_init(&is->videoq);
990 is->video_tid = SDL_CreateThread(video_thread, is);
991 break;
992 default:
993 break;
994 }
995 return 0;
996}
997
998static void stream_component_close(VideoState *is, int stream_index)
999{
1000 AVFormatContext *ic = is->ic;
1001 AVCodecContext *enc;
1002
1003 enc = &ic->streams[stream_index]->codec;
1004
1005 switch(enc->codec_type) {
1006 case CODEC_TYPE_AUDIO:
1007 packet_queue_abort(&is->audioq);
1008
1009 SDL_CloseAudio();
1010
1011 packet_queue_end(&is->audioq);
1012 break;
1013 case CODEC_TYPE_VIDEO:
1014 packet_queue_abort(&is->videoq);
1015
1016 /* note: we also signal this mutex to make sure we deblock the
1017 video thread in all cases */
1018 SDL_LockMutex(is->pictq_mutex);
1019 SDL_CondSignal(is->pictq_cond);
1020 SDL_UnlockMutex(is->pictq_mutex);
1021
1022 SDL_WaitThread(is->video_tid, NULL);
1023
1024 packet_queue_end(&is->videoq);
1025 break;
1026 default:
1027 break;
1028 }
1029
1030 avcodec_close(enc);
1031 switch(enc->codec_type) {
1032 case CODEC_TYPE_AUDIO:
1033 is->audio_st = NULL;
1034 is->audio_stream = -1;
1035 break;
1036 case CODEC_TYPE_VIDEO:
1037 is->video_st = NULL;
1038 is->video_stream = -1;
1039 break;
1040 default:
1041 break;
1042 }
1043}
1044
416e3508
FB
1045/* since we have only one decoding thread, we can use a global
1046 variable instead of a thread local variable */
1047static VideoState *global_video_state;
1048
1049static int decode_interrupt_cb(void)
1050{
1051 return (global_video_state && global_video_state->abort_request);
1052}
01310af2
FB
1053
1054/* this thread gets the stream from the disk or the network */
1055static int decode_thread(void *arg)
1056{
1057 VideoState *is = arg;
1058 AVFormatContext *ic;
1059 int err, i, ret, video_index, audio_index;
1060 AVPacket pkt1, *pkt = &pkt1;
1061
1062 video_index = -1;
1063 audio_index = -1;
1064 is->video_stream = -1;
1065 is->audio_stream = -1;
1066
416e3508
FB
1067 global_video_state = is;
1068 url_set_interrupt_cb(decode_interrupt_cb);
1069
01310af2
FB
1070 err = av_open_input_file(&ic, is->filename, NULL, 0, NULL);
1071 if (err < 0)
1072 return 0;
1073 is->ic = ic;
1074 err = av_find_stream_info(ic);
1075 if (err < 0)
1076 goto fail;
1077
1078 for(i = 0; i < ic->nb_streams; i++) {
1079 AVCodecContext *enc = &ic->streams[i]->codec;
1080 switch(enc->codec_type) {
1081 case CODEC_TYPE_AUDIO:
1082 if (audio_index < 0 && !audio_disable)
1083 audio_index = i;
1084 break;
1085 case CODEC_TYPE_VIDEO:
1086 if (video_index < 0 && !video_disable)
1087 video_index = i;
1088 break;
1089 default:
1090 break;
1091 }
1092 }
1093 if (show_status) {
1094 dump_format(ic, 0, is->filename, 0);
1095 }
1096
1097 /* open the streams */
1098 if (audio_index >= 0) {
1099 stream_component_open(is, audio_index);
1100 }
1101
1102 if (video_index >= 0) {
1103 stream_component_open(is, video_index);
1104 } else {
1105 if (!display_disable)
1106 is->show_audio = 1;
1107 }
1108
1109 if (is->video_stream < 0 && is->audio_stream < 0) {
1110 goto fail;
1111 }
1112
1113 for(;;) {
1114 if (is->abort_request)
1115 break;
416e3508
FB
1116 if (is->paused != is->last_paused) {
1117 is->last_paused = is->paused;
1118 if (ic->iformat == &rtsp_demux) {
1119 if (is->paused)
1120 rtsp_pause(ic);
1121 else
1122 rtsp_resume(ic);
1123 }
1124 }
1125 if (is->paused && ic->iformat == &rtsp_demux) {
1126 /* wait 10 ms to avoid trying to get another packet */
1127 /* XXX: horrible */
1128 SDL_Delay(10);
1129 continue;
1130 }
1131
01310af2
FB
1132 /* if the queue are full, no need to read more */
1133 if (is->audioq.size > MAX_AUDIOQ_SIZE ||
1134 is->videoq.size > MAX_VIDEOQ_SIZE) {
1135 /* wait 10 ms */
1136 SDL_Delay(10);
1137 continue;
1138 }
1139 ret = av_read_packet(ic, pkt);
1140 if (ret < 0) {
1141 break;
1142 }
1143 if (pkt->stream_index == is->audio_stream) {
1144 packet_queue_put(&is->audioq, pkt);
1145 } else if (pkt->stream_index == is->video_stream) {
1146 packet_queue_put(&is->videoq, pkt);
1147 } else {
1148 av_free_packet(pkt);
1149 }
1150 }
1151 /* wait until the end */
1152 while (!is->abort_request) {
1153 SDL_Delay(100);
1154 }
1155
1156 fail:
416e3508
FB
1157 /* disable interrupting */
1158 global_video_state = NULL;
1159
01310af2
FB
1160 /* close each stream */
1161 if (is->audio_stream >= 0)
1162 stream_component_close(is, is->audio_stream);
1163 if (is->video_stream >= 0)
1164 stream_component_close(is, is->video_stream);
1165
1166 av_close_input_file(is->ic);
1167 is->ic = NULL; /* safety */
416e3508
FB
1168 url_set_interrupt_cb(NULL);
1169
01310af2
FB
1170 return 0;
1171}
1172
1173/* pause or resume the video */
1174static void stream_pause(VideoState *is)
1175{
1176 is->paused = !is->paused;
1177}
1178
1179static VideoState *stream_open(const char *filename)
1180{
1181 VideoState *is;
1182
1183 is = av_mallocz(sizeof(VideoState));
1184 if (!is)
1185 return NULL;
1186 pstrcpy(is->filename, sizeof(is->filename), filename);
1187 if (screen) {
1188 is->width = screen->w;
1189 is->height = screen->h;
1190 }
1191 is->ytop = 0;
1192 is->xleft = 0;
1193
1194 /* start video display */
1195 is->pictq_mutex = SDL_CreateMutex();
1196 is->pictq_cond = SDL_CreateCond();
1197
1198 /* add the refresh timer to draw the picture */
1199 schedule_refresh(is, 40);
1200
1201 is->av_sync_type = AV_SYNC_AUDIO_MASTER;
1202
1203 is->parse_tid = SDL_CreateThread(decode_thread, is);
1204 if (!is->parse_tid) {
1205 av_free(is);
1206 return NULL;
1207 }
1208 return is;
1209}
1210
1211static void stream_close(VideoState *is)
1212{
1213 VideoPicture *vp;
1214 int i;
1215 /* XXX: use a special url_shutdown call to abort parse cleanly */
1216 is->abort_request = 1;
1217 SDL_WaitThread(is->parse_tid, NULL);
1218
1219 /* free all pictures */
1220 for(i=0;i<VIDEO_PICTURE_QUEUE_SIZE; i++) {
1221 vp = &is->pictq[i];
1222 if (vp->bmp) {
1223 SDL_FreeYUVOverlay(vp->bmp);
1224 vp->bmp = NULL;
1225 }
1226 }
1227 SDL_DestroyMutex(is->pictq_mutex);
1228 SDL_DestroyCond(is->pictq_cond);
1229}
1230
1231void toggle_full_screen(void)
1232{
1233 int w, h, flags;
1234 is_full_screen = !is_full_screen;
1235 if (!fs_screen_width) {
1236 /* use default SDL method */
1237 SDL_WM_ToggleFullScreen(screen);
1238 } else {
1239 /* use the recorded resolution */
1240 flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;
1241 if (is_full_screen) {
1242 w = fs_screen_width;
1243 h = fs_screen_height;
1244 flags |= SDL_FULLSCREEN;
1245 } else {
1246 w = screen_width;
1247 h = screen_height;
1248 flags |= SDL_RESIZABLE;
1249 }
1250 screen = SDL_SetVideoMode(w, h, 0, flags);
1251 cur_stream->width = w;
1252 cur_stream->height = h;
1253 }
1254}
1255
1256void toggle_pause(void)
1257{
1258 if (cur_stream)
1259 stream_pause(cur_stream);
1260}
1261
1262void do_exit(void)
1263{
1264 if (cur_stream) {
1265 stream_close(cur_stream);
1266 cur_stream = NULL;
1267 }
1268 if (show_status)
1269 printf("\n");
1270 SDL_Quit();
1271 exit(0);
1272}
1273
1274void toggle_audio_display(void)
1275{
1276 if (cur_stream) {
1277 cur_stream->show_audio = !cur_stream->show_audio;
1278 }
1279}
1280
1281/* handle an event sent by the GUI */
1282void event_loop(void)
1283{
1284 SDL_Event event;
1285
1286 for(;;) {
1287 SDL_WaitEvent(&event);
1288 switch(event.type) {
1289 case SDL_KEYDOWN:
1290 switch(event.key.keysym.sym) {
1291 case SDLK_ESCAPE:
1292 case SDLK_q:
1293 do_exit();
1294 break;
1295 case SDLK_f:
1296 toggle_full_screen();
1297 break;
1298 case SDLK_p:
1299 case SDLK_SPACE:
1300 toggle_pause();
1301 break;
1302 case SDLK_a:
1303 toggle_audio_display();
1304 break;
1305 default:
1306 break;
1307 }
1308 break;
1309 case SDL_VIDEORESIZE:
1310 if (cur_stream) {
1311 screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
1312 SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
1313 cur_stream->width = event.resize.w;
1314 cur_stream->height = event.resize.h;
1315 }
1316 break;
1317 case SDL_QUIT:
1318 do_exit();
1319 break;
1320 case FF_ALLOC_EVENT:
1321 alloc_picture(event.user.data1);
1322 break;
1323 case FF_REFRESH_EVENT:
1324 video_refresh_timer(event.user.data1);
1325 break;
1326 default:
1327 break;
1328 }
1329 }
1330}
1331
1332void opt_width(const char *arg)
1333{
1334 screen_width = atoi(arg);
1335}
1336
1337void opt_height(const char *arg)
1338{
1339 screen_height = atoi(arg);
1340}
1341
1342static void opt_format(const char *arg)
1343{
1344 file_iformat = av_find_input_format(arg);
1345 if (!file_iformat) {
1346 fprintf(stderr, "Unknown input format: %s\n", arg);
1347 exit(1);
1348 }
1349}
1350
416e3508
FB
1351void opt_rtp_tcp(void)
1352{
1353 /* only tcp protocol */
1354 rtsp_default_protocols = (1 << RTSP_PROTOCOL_RTP_TCP);
1355}
1356
01310af2
FB
1357const OptionDef options[] = {
1358 { "h", 0, {(void*)show_help}, "show help" },
1359 { "x", HAS_ARG, {(void*)opt_width}, "force displayed width", "width" },
1360 { "y", HAS_ARG, {(void*)opt_height}, "force displayed height", "height" },
1361 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
1362 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
1363 { "nodisp", OPT_BOOL, {(void*)&display_disable}, "disable graphical display" },
1364 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
1365 { "stats", OPT_BOOL | OPT_EXPERT, {(void*)&show_status}, "show status", "" },
416e3508 1366 { "rtp_tcp", OPT_EXPERT, {(void*)&opt_rtp_tcp}, "force RTP/TCP protocol usage", "" },
01310af2
FB
1367 { NULL, },
1368};
1369
1370void show_help(void)
1371{
1372 printf("usage: ffplay [options] input_file\n"
1373 "Simple media player\n");
1374 printf("\n");
1375 show_help_options(options);
1376 printf("\nWhile playing:\n"
1377 "q, ESC quit\n"
1378 "f toggle full screen\n"
1379 "p, SPC pause\n"
1380 "a show audio waves\n"
1381 );
1382 exit(1);
1383}
1384
1385void parse_arg_file(const char *filename)
1386{
1387 input_filename = filename;
1388}
1389
1390/* Called from the main */
1391int main(int argc, char **argv)
1392{
1393 int flags;
1394
1395 /* register all codecs, demux and protocols */
1396 av_register_all();
1397
1398 parse_options(argc, argv, options);
1399
1400 if (!input_filename)
1401 show_help();
1402
1403 if (display_disable) {
1404 video_disable = 1;
1405 }
31319a8c
FB
1406 flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
1407#ifndef CONFIG_WIN32
1408 flags |= SDL_INIT_EVENTTHREAD; /* Not supported on win32 */
1409#endif
01310af2
FB
1410 if (SDL_Init (flags)) {
1411 fprintf(stderr, "Could not initialize SDL - exiting\n");
1412 exit(1);
1413 }
1414
1415 if (!display_disable) {
1416 screen = SDL_SetVideoMode(screen_width, screen_height, 0,
1417 SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
1418 if (!screen) {
1419 fprintf(stderr, "SDL: could not set video mode - exiting\n");
1420 exit(1);
1421 }
1422 SDL_WM_SetCaption("FFplay", "FFplay");
1423#ifdef HAVE_X11
1424 /* save the screen resolution... SDL should allow full screen
1425 by resizing the window */
1426 {
1427 Display *dpy;
1428 dpy = XOpenDisplay(NULL);
1429 if (dpy) {
1430 fs_screen_width = DisplayWidth(dpy, DefaultScreen(dpy));
1431 fs_screen_height = DisplayHeight(dpy, DefaultScreen(dpy));
1432 XCloseDisplay(dpy);
1433 }
1434 }
1435#endif
1436 }
1437
1438 SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
1439 SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
1440 SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
1441 SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
1442
1443 cur_stream = stream_open(input_filename);
1444
1445 event_loop();
1446
1447 /* never returns */
1448
1449 return 0;
1450}