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