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