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