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