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