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