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