2 * FFplay : Simple Media Player based on the ffmpeg libraries
3 * Copyright (c) 2003 Fabrice Bellard
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 #define HAVE_AV_CONFIG_H
25 #include <SDL_thread.h>
28 #undef main /* We don't want SDL to override our main() */
41 DosGetInfoBlocks(&tib, &pib);
43 // Change flag from VIO to PM:
44 if (pib->pib_ultype==2) pib->pib_ultype = 3;
50 #define MAX_VIDEOQ_SIZE (5 * 256 * 1024)
51 #define MAX_AUDIOQ_SIZE (5 * 16 * 1024)
52 #define MAX_SUBTITLEQ_SIZE (5 * 16 * 1024)
54 /* SDL audio buffer size, in samples. Should be small to have precise
55 A/V sync as SDL does not have hardware buffer fullness info. */
56 #define SDL_AUDIO_BUFFER_SIZE 1024
58 /* no AV sync correction is done if below the AV sync threshold */
59 #define AV_SYNC_THRESHOLD 0.01
60 /* no AV correction is done if too big error */
61 #define AV_NOSYNC_THRESHOLD 10.0
63 /* maximum audio speed change to get correct sync */
64 #define SAMPLE_CORRECTION_PERCENT_MAX 10
66 /* we use about AUDIO_DIFF_AVG_NB A-V differences to make the average */
67 #define AUDIO_DIFF_AVG_NB 20
69 /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
70 #define SAMPLE_ARRAY_SIZE (2*65536)
72 typedef struct PacketQueue {
73 AVPacketList *first_pkt, *last_pkt;
81 #define VIDEO_PICTURE_QUEUE_SIZE 1
82 #define SUBPICTURE_QUEUE_SIZE 4
84 typedef struct VideoPicture {
85 double pts; ///<presentation time stamp for this picture
87 int width, height; /* source height & width */
91 typedef struct SubPicture {
92 double pts; /* presentation time stamp for this picture */
97 AV_SYNC_AUDIO_MASTER, /* default choice */
99 AV_SYNC_EXTERNAL_CLOCK, /* synchronize to an external clock */
102 typedef struct VideoState {
103 SDL_Thread *parse_tid;
104 SDL_Thread *video_tid;
105 AVInputFormat *iformat;
114 int dtg_active_format;
119 double external_clock; /* external clock base */
120 int64_t external_clock_time;
123 double audio_diff_cum; /* used for AV difference average computation */
124 double audio_diff_avg_coef;
125 double audio_diff_threshold;
126 int audio_diff_avg_count;
129 int audio_hw_buf_size;
130 /* samples output by the codec. we reserve more space for avsync
132 uint8_t audio_buf[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2];
133 unsigned int audio_buf_size; /* in bytes */
134 int audio_buf_index; /* in bytes */
136 uint8_t *audio_pkt_data;
139 int show_audio; /* if true, display audio samples */
140 int16_t sample_array[SAMPLE_ARRAY_SIZE];
141 int sample_array_index;
144 SDL_Thread *subtitle_tid;
146 int subtitle_stream_changed;
147 AVStream *subtitle_st;
148 PacketQueue subtitleq;
149 SubPicture subpq[SUBPICTURE_QUEUE_SIZE];
150 int subpq_size, subpq_rindex, subpq_windex;
151 SDL_mutex *subpq_mutex;
152 SDL_cond *subpq_cond;
155 double frame_last_pts;
156 double frame_last_delay;
157 double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame
161 double video_current_pts; ///<current displayed pts (different from video_clock if frame fifos are used)
162 int64_t video_current_pts_time; ///<time (av_gettime) at which we updated video_current_pts - used to have running video pts
163 VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
164 int pictq_size, pictq_rindex, pictq_windex;
165 SDL_mutex *pictq_mutex;
166 SDL_cond *pictq_cond;
168 SDL_mutex *video_decoder_mutex;
169 SDL_mutex *audio_decoder_mutex;
170 SDL_mutex *subtitle_decoder_mutex;
172 // QETimer *video_timer;
174 int width, height, xleft, ytop;
177 void show_help(void);
178 static int audio_write_get_buf_size(VideoState *is);
180 /* options specified by the user */
181 static AVInputFormat *file_iformat;
182 static AVImageFormat *image_format;
183 static const char *input_filename;
184 static int fs_screen_width;
185 static int fs_screen_height;
186 static int screen_width = 640;
187 static int screen_height = 480;
188 static int audio_disable;
189 static int video_disable;
190 static int display_disable;
191 static int show_status;
192 static int av_sync_type = AV_SYNC_AUDIO_MASTER;
193 static int64_t start_time = AV_NOPTS_VALUE;
194 static int debug = 0;
195 static int debug_mv = 0;
197 static int thread_count = 1;
198 static int workaround_bugs = 1;
200 static int genpts = 0;
201 static int lowres = 0;
202 static int idct = FF_IDCT_AUTO;
203 static enum AVDiscard skip_frame= AVDISCARD_DEFAULT;
204 static enum AVDiscard skip_idct= AVDISCARD_DEFAULT;
205 static enum AVDiscard skip_loop_filter= AVDISCARD_DEFAULT;
206 static int error_resilience = FF_ER_CAREFUL;
207 static int error_concealment = 3;
209 /* current context */
210 static int is_full_screen;
211 static VideoState *cur_stream;
212 static int64_t audio_callback_time;
214 #define FF_ALLOC_EVENT (SDL_USEREVENT)
215 #define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
216 #define FF_QUIT_EVENT (SDL_USEREVENT + 2)
220 /* packet queue handling */
221 static void packet_queue_init(PacketQueue *q)
223 memset(q, 0, sizeof(PacketQueue));
224 q->mutex = SDL_CreateMutex();
225 q->cond = SDL_CreateCond();
228 static void packet_queue_flush(PacketQueue *q)
230 AVPacketList *pkt, *pkt1;
232 SDL_LockMutex(q->mutex);
233 for(pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
235 av_free_packet(&pkt->pkt);
242 SDL_UnlockMutex(q->mutex);
245 static void packet_queue_end(PacketQueue *q)
247 packet_queue_flush(q);
248 SDL_DestroyMutex(q->mutex);
249 SDL_DestroyCond(q->cond);
252 static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
256 /* duplicate the packet */
257 if (av_dup_packet(pkt) < 0)
260 pkt1 = av_malloc(sizeof(AVPacketList));
267 SDL_LockMutex(q->mutex);
273 q->last_pkt->next = pkt1;
276 q->size += pkt1->pkt.size;
277 /* XXX: should duplicate packet data in DV case */
278 SDL_CondSignal(q->cond);
280 SDL_UnlockMutex(q->mutex);
284 static void packet_queue_abort(PacketQueue *q)
286 SDL_LockMutex(q->mutex);
288 q->abort_request = 1;
290 SDL_CondSignal(q->cond);
292 SDL_UnlockMutex(q->mutex);
295 /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
296 static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
301 SDL_LockMutex(q->mutex);
304 if (q->abort_request) {
311 q->first_pkt = pkt1->next;
315 q->size -= pkt1->pkt.size;
324 SDL_CondWait(q->cond, q->mutex);
327 SDL_UnlockMutex(q->mutex);
331 static inline void fill_rectangle(SDL_Surface *screen,
332 int x, int y, int w, int h, int color)
339 SDL_FillRect(screen, &rect, color);
343 /* draw only the border of a rectangle */
344 void fill_border(VideoState *s, int x, int y, int w, int h, int color)
348 /* fill the background */
352 w2 = s->width - (x + w);
358 h2 = s->height - (y + h);
361 fill_rectangle(screen,
365 fill_rectangle(screen,
366 s->xleft + s->width - w2, s->ytop,
369 fill_rectangle(screen,
370 s->xleft + w1, s->ytop,
371 s->width - w1 - w2, h1,
373 fill_rectangle(screen,
374 s->xleft + w1, s->ytop + s->height - h2,
375 s->width - w1 - w2, h2,
383 #define ONE_HALF (1 << (SCALEBITS - 1))
384 #define FIX(x) ((int) ((x) * (1<<SCALEBITS) + 0.5))
386 #define RGB_TO_Y_CCIR(r, g, b) \
387 ((FIX(0.29900*219.0/255.0) * (r) + FIX(0.58700*219.0/255.0) * (g) + \
388 FIX(0.11400*219.0/255.0) * (b) + (ONE_HALF + (16 << SCALEBITS))) >> SCALEBITS)
390 #define RGB_TO_U_CCIR(r1, g1, b1, shift)\
391 (((- FIX(0.16874*224.0/255.0) * r1 - FIX(0.33126*224.0/255.0) * g1 + \
392 FIX(0.50000*224.0/255.0) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
394 #define RGB_TO_V_CCIR(r1, g1, b1, shift)\
395 (((FIX(0.50000*224.0/255.0) * r1 - FIX(0.41869*224.0/255.0) * g1 - \
396 FIX(0.08131*224.0/255.0) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
398 #define ALPHA_BLEND(a, oldp, newp, s)\
399 ((((oldp << s) * (255 - (a))) + (newp * (a))) / (255 << s))
401 #define RGBA_IN(r, g, b, a, s)\
403 unsigned int v = ((const uint32_t *)(s))[0];\
404 a = (v >> 24) & 0xff;\
405 r = (v >> 16) & 0xff;\
406 g = (v >> 8) & 0xff;\
410 #define YUVA_IN(y, u, v, a, s, pal)\
412 unsigned int val = ((const uint32_t *)(pal))[*(const uint8_t*)s];\
413 a = (val >> 24) & 0xff;\
414 y = (val >> 16) & 0xff;\
415 u = (val >> 8) & 0xff;\
419 #define YUVA_OUT(d, y, u, v, a)\
421 ((uint32_t *)(d))[0] = (a << 24) | (y << 16) | (u << 8) | v;\
427 static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect)
429 int wrap, wrap3, width2, skip2;
430 int y, u, v, a, u1, v1, a1, w, h;
431 uint8_t *lum, *cb, *cr;
435 lum = dst->data[0] + rect->y * dst->linesize[0];
436 cb = dst->data[1] + (rect->y >> 1) * dst->linesize[1];
437 cr = dst->data[2] + (rect->y >> 1) * dst->linesize[2];
439 width2 = (rect->w + 1) >> 1;
440 skip2 = rect->x >> 1;
441 wrap = dst->linesize[0];
442 wrap3 = rect->linesize;
444 pal = rect->rgba_palette; /* Now in YCrCb! */
452 YUVA_IN(y, u, v, a, p, pal);
453 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
454 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
455 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
461 for(w = rect->w - (rect->x & 1); w >= 2; w -= 2) {
462 YUVA_IN(y, u, v, a, p, pal);
466 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
468 YUVA_IN(y, u, v, a, p + BPP, pal);
472 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
473 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
474 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
481 YUVA_IN(y, u, v, a, p, pal);
482 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
483 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
484 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
486 p += wrap3 + (wrap3 - rect->w * BPP);
487 lum += wrap + (wrap - rect->w - rect->x);
488 cb += dst->linesize[1] - width2 - skip2;
489 cr += dst->linesize[2] - width2 - skip2;
491 for(h = rect->h - (rect->y & 1); h >= 2; h -= 2) {
497 YUVA_IN(y, u, v, a, p, pal);
501 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
504 YUVA_IN(y, u, v, a, p, pal);
508 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
509 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
510 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
516 for(w = rect->w - (rect->x & 1); w >= 2; w -= 2) {
517 YUVA_IN(y, u, v, a, p, pal);
521 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
523 YUVA_IN(y, u, v, a, p, pal);
527 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
531 YUVA_IN(y, u, v, a, p, pal);
535 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
537 YUVA_IN(y, u, v, a, p, pal);
541 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
543 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 2);
544 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 2);
548 p += -wrap3 + 2 * BPP;
552 YUVA_IN(y, u, v, a, p, pal);
556 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
559 YUVA_IN(y, u, v, a, p, pal);
563 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
564 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
565 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
571 p += wrap3 + (wrap3 - rect->w * BPP);
572 lum += wrap + (wrap - rect->w - rect->x);
573 cb += dst->linesize[1] - width2 - skip2;
574 cr += dst->linesize[2] - width2 - skip2;
576 /* handle odd height */
583 YUVA_IN(y, u, v, a, p, pal);
584 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
585 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
586 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
592 for(w = rect->w - (rect->x & 1); w >= 2; w -= 2) {
593 YUVA_IN(y, u, v, a, p, pal);
597 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
599 YUVA_IN(y, u, v, a, p + BPP, pal);
603 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
604 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u, 1);
605 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v, 1);
612 YUVA_IN(y, u, v, a, p, pal);
613 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
614 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
615 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
620 static void free_subpicture(SubPicture *sp)
624 for (i = 0; i < sp->sub.num_rects; i++)
626 av_free(sp->sub.rects[i].bitmap);
627 av_free(sp->sub.rects[i].rgba_palette);
630 av_free(sp->sub.rects);
632 memset(&sp->sub, 0, sizeof(AVSubtitle));
635 static void video_image_display(VideoState *is)
641 int width, height, x, y;
645 vp = &is->pictq[is->pictq_rindex];
647 /* XXX: use variable in the frame */
648 if (is->video_st->codec->sample_aspect_ratio.num == 0)
651 aspect_ratio = av_q2d(is->video_st->codec->sample_aspect_ratio)
652 * is->video_st->codec->width / is->video_st->codec->height;;
653 if (aspect_ratio <= 0.0)
654 aspect_ratio = (float)is->video_st->codec->width /
655 (float)is->video_st->codec->height;
656 /* if an active format is indicated, then it overrides the
659 if (is->video_st->codec->dtg_active_format != is->dtg_active_format) {
660 is->dtg_active_format = is->video_st->codec->dtg_active_format;
661 printf("dtg_active_format=%d\n", is->dtg_active_format);
665 switch(is->video_st->codec->dtg_active_format) {
666 case FF_DTG_AFD_SAME:
671 aspect_ratio = 4.0 / 3.0;
673 case FF_DTG_AFD_16_9:
674 aspect_ratio = 16.0 / 9.0;
676 case FF_DTG_AFD_14_9:
677 aspect_ratio = 14.0 / 9.0;
679 case FF_DTG_AFD_4_3_SP_14_9:
680 aspect_ratio = 14.0 / 9.0;
682 case FF_DTG_AFD_16_9_SP_14_9:
683 aspect_ratio = 14.0 / 9.0;
685 case FF_DTG_AFD_SP_4_3:
686 aspect_ratio = 4.0 / 3.0;
693 if (is->subpq_size > 0)
695 sp = &is->subpq[is->subpq_rindex];
697 if (vp->pts >= sp->pts + ((float) sp->sub.start_display_time / 1000))
699 SDL_LockYUVOverlay (vp->bmp);
701 pict.data[0] = vp->bmp->pixels[0];
702 pict.data[1] = vp->bmp->pixels[2];
703 pict.data[2] = vp->bmp->pixels[1];
705 pict.linesize[0] = vp->bmp->pitches[0];
706 pict.linesize[1] = vp->bmp->pitches[2];
707 pict.linesize[2] = vp->bmp->pitches[1];
709 for (i = 0; i < sp->sub.num_rects; i++)
710 blend_subrect(&pict, &sp->sub.rects[i]);
712 SDL_UnlockYUVOverlay (vp->bmp);
718 /* XXX: we suppose the screen has a 1.0 pixel ratio */
720 width = ((int)rint(height * aspect_ratio)) & -3;
721 if (width > is->width) {
723 height = ((int)rint(width / aspect_ratio)) & -3;
725 x = (is->width - width) / 2;
726 y = (is->height - height) / 2;
727 if (!is->no_background) {
728 /* fill the background */
729 // fill_border(is, x, y, width, height, QERGB(0x00, 0x00, 0x00));
731 is->no_background = 0;
733 rect.x = is->xleft + x;
734 rect.y = is->xleft + y;
737 SDL_DisplayYUVOverlay(vp->bmp, &rect);
740 fill_rectangle(screen,
741 is->xleft, is->ytop, is->width, is->height,
742 QERGB(0x00, 0x00, 0x00));
747 static inline int compute_mod(int a, int b)
756 static void video_audio_display(VideoState *s)
758 int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
759 int ch, channels, h, h2, bgcolor, fgcolor;
762 /* compute display index : center on currently output samples */
763 channels = s->audio_st->codec->channels;
764 nb_display_channels = channels;
767 delay = audio_write_get_buf_size(s);
770 /* to be more precise, we take into account the time spent since
771 the last buffer computation */
772 if (audio_callback_time) {
773 time_diff = av_gettime() - audio_callback_time;
774 delay += (time_diff * s->audio_st->codec->sample_rate) / 1000000;
777 delay -= s->width / 2;
778 if (delay < s->width)
780 i_start = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
781 s->last_i_start = i_start;
783 i_start = s->last_i_start;
786 bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
787 fill_rectangle(screen,
788 s->xleft, s->ytop, s->width, s->height,
791 fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);
793 /* total height for one channel */
794 h = s->height / nb_display_channels;
795 /* graph height / 2 */
797 for(ch = 0;ch < nb_display_channels; ch++) {
799 y1 = s->ytop + ch * h + (h / 2); /* position of center line */
800 for(x = 0; x < s->width; x++) {
801 y = (s->sample_array[i] * h2) >> 15;
808 fill_rectangle(screen,
809 s->xleft + x, ys, 1, y,
812 if (i >= SAMPLE_ARRAY_SIZE)
813 i -= SAMPLE_ARRAY_SIZE;
817 fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);
819 for(ch = 1;ch < nb_display_channels; ch++) {
820 y = s->ytop + ch * h;
821 fill_rectangle(screen,
822 s->xleft, y, s->width, 1,
825 SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
828 /* display the current picture, if any */
829 static void video_display(VideoState *is)
831 if (is->audio_st && is->show_audio)
832 video_audio_display(is);
833 else if (is->video_st)
834 video_image_display(is);
837 static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque)
840 event.type = FF_REFRESH_EVENT;
841 event.user.data1 = opaque;
842 SDL_PushEvent(&event);
843 return 0; /* 0 means stop timer */
846 /* schedule a video refresh in 'delay' ms */
847 static void schedule_refresh(VideoState *is, int delay)
849 SDL_AddTimer(delay, sdl_refresh_timer_cb, is);
852 /* get the current audio clock value */
853 static double get_audio_clock(VideoState *is)
856 int hw_buf_size, bytes_per_sec;
857 pts = is->audio_clock;
858 hw_buf_size = audio_write_get_buf_size(is);
861 bytes_per_sec = is->audio_st->codec->sample_rate *
862 2 * is->audio_st->codec->channels;
865 pts -= (double)hw_buf_size / bytes_per_sec;
869 /* get the current video clock value */
870 static double get_video_clock(VideoState *is)
876 delta = (av_gettime() - is->video_current_pts_time) / 1000000.0;
878 return is->video_current_pts + delta;
881 /* get the current external clock value */
882 static double get_external_clock(VideoState *is)
886 return is->external_clock + ((ti - is->external_clock_time) * 1e-6);
889 /* get the current master clock value */
890 static double get_master_clock(VideoState *is)
894 if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
896 val = get_video_clock(is);
898 val = get_audio_clock(is);
899 } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
901 val = get_audio_clock(is);
903 val = get_video_clock(is);
905 val = get_external_clock(is);
910 /* seek in the stream */
911 static void stream_seek(VideoState *is, int64_t pos, int rel)
915 is->seek_flags = rel < 0 ? AVSEEK_FLAG_BACKWARD : 0;
920 /* pause or resume the video */
921 static void stream_pause(VideoState *is)
923 is->paused = !is->paused;
925 is->video_current_pts = get_video_clock(is);
929 /* called to display each frame */
930 static void video_refresh_timer(void *opaque)
932 VideoState *is = opaque;
934 double actual_delay, delay, sync_threshold, ref_clock, diff;
936 SubPicture *sp, *sp2;
939 if (is->pictq_size == 0) {
940 /* if no picture, need to wait */
941 schedule_refresh(is, 1);
943 /* dequeue the picture */
944 vp = &is->pictq[is->pictq_rindex];
946 /* update current video pts */
947 is->video_current_pts = vp->pts;
948 is->video_current_pts_time = av_gettime();
950 /* compute nominal delay */
951 delay = vp->pts - is->frame_last_pts;
952 if (delay <= 0 || delay >= 1.0) {
953 /* if incorrect delay, use previous one */
954 delay = is->frame_last_delay;
956 is->frame_last_delay = delay;
957 is->frame_last_pts = vp->pts;
959 /* update delay to follow master synchronisation source */
960 if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) ||
961 is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
962 /* if video is slave, we try to correct big delays by
963 duplicating or deleting a frame */
964 ref_clock = get_master_clock(is);
965 diff = vp->pts - ref_clock;
967 /* skip or repeat frame. We take into account the
968 delay to compute the threshold. I still don't know
969 if it is the best guess */
970 sync_threshold = AV_SYNC_THRESHOLD;
971 if (delay > sync_threshold)
972 sync_threshold = delay;
973 if (fabs(diff) < AV_NOSYNC_THRESHOLD) {
974 if (diff <= -sync_threshold)
976 else if (diff >= sync_threshold)
981 is->frame_timer += delay;
982 /* compute the REAL delay (we need to do that to avoid
984 actual_delay = is->frame_timer - (av_gettime() / 1000000.0);
985 if (actual_delay < 0.010) {
986 /* XXX: should skip picture */
987 actual_delay = 0.010;
989 /* launch timer for next picture */
990 schedule_refresh(is, (int)(actual_delay * 1000 + 0.5));
992 #if defined(DEBUG_SYNC)
993 printf("video: delay=%0.3f actual_delay=%0.3f pts=%0.3f A-V=%f\n",
994 delay, actual_delay, vp->pts, -diff);
997 if(is->subtitle_st) {
998 if (is->subtitle_stream_changed) {
999 SDL_LockMutex(is->subpq_mutex);
1001 while (is->subpq_size) {
1002 free_subpicture(&is->subpq[is->subpq_rindex]);
1004 /* update queue size and signal for next picture */
1005 if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
1006 is->subpq_rindex = 0;
1010 is->subtitle_stream_changed = 0;
1012 SDL_CondSignal(is->subpq_cond);
1013 SDL_UnlockMutex(is->subpq_mutex);
1015 if (is->subpq_size > 0) {
1016 sp = &is->subpq[is->subpq_rindex];
1018 if (is->subpq_size > 1)
1019 sp2 = &is->subpq[(is->subpq_rindex + 1) % SUBPICTURE_QUEUE_SIZE];
1023 if ((is->video_current_pts > (sp->pts + ((float) sp->sub.end_display_time / 1000)))
1024 || (sp2 && is->video_current_pts > (sp2->pts + ((float) sp2->sub.start_display_time / 1000))))
1026 free_subpicture(sp);
1028 /* update queue size and signal for next picture */
1029 if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
1030 is->subpq_rindex = 0;
1032 SDL_LockMutex(is->subpq_mutex);
1034 SDL_CondSignal(is->subpq_cond);
1035 SDL_UnlockMutex(is->subpq_mutex);
1041 /* display picture */
1044 /* update queue size and signal for next picture */
1045 if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
1046 is->pictq_rindex = 0;
1048 SDL_LockMutex(is->pictq_mutex);
1050 SDL_CondSignal(is->pictq_cond);
1051 SDL_UnlockMutex(is->pictq_mutex);
1053 } else if (is->audio_st) {
1054 /* draw the next audio frame */
1056 schedule_refresh(is, 40);
1058 /* if only audio stream, then display the audio bars (better
1059 than nothing, just to test the implementation */
1061 /* display picture */
1064 schedule_refresh(is, 100);
1067 static int64_t last_time;
1069 int aqsize, vqsize, sqsize;
1072 cur_time = av_gettime();
1073 if (!last_time || (cur_time - last_time) >= 500 * 1000) {
1078 aqsize = is->audioq.size;
1080 vqsize = is->videoq.size;
1081 if (is->subtitle_st)
1082 sqsize = is->subtitleq.size;
1084 if (is->audio_st && is->video_st)
1085 av_diff = get_audio_clock(is) - get_video_clock(is);
1086 printf("%7.2f A-V:%7.3f aq=%5dKB vq=%5dKB sq=%5dB \r",
1087 get_master_clock(is), av_diff, aqsize / 1024, vqsize / 1024, sqsize);
1089 last_time = cur_time;
1094 /* allocate a picture (needs to do that in main thread to avoid
1095 potential locking problems */
1096 static void alloc_picture(void *opaque)
1098 VideoState *is = opaque;
1101 vp = &is->pictq[is->pictq_windex];
1104 SDL_FreeYUVOverlay(vp->bmp);
1107 /* XXX: use generic function */
1108 /* XXX: disable overlay if no hardware acceleration or if RGB format */
1109 switch(is->video_st->codec->pix_fmt) {
1110 case PIX_FMT_YUV420P:
1111 case PIX_FMT_YUV422P:
1112 case PIX_FMT_YUV444P:
1113 case PIX_FMT_YUV422:
1114 case PIX_FMT_YUV410P:
1115 case PIX_FMT_YUV411P:
1123 vp->bmp = SDL_CreateYUVOverlay(is->video_st->codec->width,
1124 is->video_st->codec->height,
1127 vp->width = is->video_st->codec->width;
1128 vp->height = is->video_st->codec->height;
1130 SDL_LockMutex(is->pictq_mutex);
1132 SDL_CondSignal(is->pictq_cond);
1133 SDL_UnlockMutex(is->pictq_mutex);
1138 * @param pts the dts of the pkt / pts of the frame and guessed if not known
1140 static int queue_picture(VideoState *is, AVFrame *src_frame, double pts)
1146 /* wait until we have space to put a new picture */
1147 SDL_LockMutex(is->pictq_mutex);
1148 while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE &&
1149 !is->videoq.abort_request) {
1150 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1152 SDL_UnlockMutex(is->pictq_mutex);
1154 if (is->videoq.abort_request)
1157 vp = &is->pictq[is->pictq_windex];
1159 /* alloc or resize hardware picture buffer */
1161 vp->width != is->video_st->codec->width ||
1162 vp->height != is->video_st->codec->height) {
1167 /* the allocation must be done in the main thread to avoid
1169 event.type = FF_ALLOC_EVENT;
1170 event.user.data1 = is;
1171 SDL_PushEvent(&event);
1173 /* wait until the picture is allocated */
1174 SDL_LockMutex(is->pictq_mutex);
1175 while (!vp->allocated && !is->videoq.abort_request) {
1176 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1178 SDL_UnlockMutex(is->pictq_mutex);
1180 if (is->videoq.abort_request)
1184 /* if the frame is not skipped, then display it */
1186 /* get a pointer on the bitmap */
1187 SDL_LockYUVOverlay (vp->bmp);
1189 dst_pix_fmt = PIX_FMT_YUV420P;
1190 pict.data[0] = vp->bmp->pixels[0];
1191 pict.data[1] = vp->bmp->pixels[2];
1192 pict.data[2] = vp->bmp->pixels[1];
1194 pict.linesize[0] = vp->bmp->pitches[0];
1195 pict.linesize[1] = vp->bmp->pitches[2];
1196 pict.linesize[2] = vp->bmp->pitches[1];
1197 img_convert(&pict, dst_pix_fmt,
1198 (AVPicture *)src_frame, is->video_st->codec->pix_fmt,
1199 is->video_st->codec->width, is->video_st->codec->height);
1200 /* update the bitmap content */
1201 SDL_UnlockYUVOverlay(vp->bmp);
1205 /* now we can update the picture count */
1206 if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
1207 is->pictq_windex = 0;
1208 SDL_LockMutex(is->pictq_mutex);
1210 SDL_UnlockMutex(is->pictq_mutex);
1216 * compute the exact PTS for the picture if it is omitted in the stream
1217 * @param pts1 the dts of the pkt / pts of the frame
1219 static int output_picture2(VideoState *is, AVFrame *src_frame, double pts1)
1221 double frame_delay, pts;
1226 /* update video clock with pts, if present */
1227 is->video_clock = pts;
1229 pts = is->video_clock;
1231 /* update video clock for next frame */
1232 frame_delay = av_q2d(is->video_st->codec->time_base);
1233 /* for MPEG2, the frame can be repeated, so we update the
1234 clock accordingly */
1235 frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
1236 is->video_clock += frame_delay;
1238 #if defined(DEBUG_SYNC) && 0
1241 if (src_frame->pict_type == FF_B_TYPE)
1243 else if (src_frame->pict_type == FF_I_TYPE)
1247 printf("frame_type=%c clock=%0.3f pts=%0.3f\n",
1251 return queue_picture(is, src_frame, pts);
1254 static int video_thread(void *arg)
1256 VideoState *is = arg;
1257 AVPacket pkt1, *pkt = &pkt1;
1258 int len1, got_picture;
1259 AVFrame *frame= avcodec_alloc_frame();
1263 while (is->paused && !is->videoq.abort_request) {
1266 if (packet_queue_get(&is->videoq, pkt, 1) < 0)
1268 /* NOTE: ipts is the PTS of the _first_ picture beginning in
1269 this packet, if any */
1271 if (pkt->dts != AV_NOPTS_VALUE)
1272 pts = av_q2d(is->video_st->time_base)*pkt->dts;
1274 SDL_LockMutex(is->video_decoder_mutex);
1275 len1 = avcodec_decode_video(is->video_st->codec,
1276 frame, &got_picture,
1277 pkt->data, pkt->size);
1278 SDL_UnlockMutex(is->video_decoder_mutex);
1282 if (output_picture2(is, frame, pts) < 0)
1285 av_free_packet(pkt);
1288 stream_pause(cur_stream);
1295 static int subtitle_thread(void *arg)
1297 VideoState *is = arg;
1299 AVPacket pkt1, *pkt = &pkt1;
1300 int len1, got_subtitle;
1303 int r, g, b, y, u, v, a;
1306 while (is->paused && !is->subtitleq.abort_request) {
1309 if (packet_queue_get(&is->subtitleq, pkt, 1) < 0)
1312 SDL_LockMutex(is->subpq_mutex);
1313 while (is->subpq_size >= SUBPICTURE_QUEUE_SIZE &&
1314 !is->subtitleq.abort_request) {
1315 SDL_CondWait(is->subpq_cond, is->subpq_mutex);
1317 SDL_UnlockMutex(is->subpq_mutex);
1319 if (is->subtitleq.abort_request)
1322 sp = &is->subpq[is->subpq_windex];
1324 /* NOTE: ipts is the PTS of the _first_ picture beginning in
1325 this packet, if any */
1327 if (pkt->pts != AV_NOPTS_VALUE)
1328 pts = av_q2d(is->subtitle_st->time_base)*pkt->pts;
1330 SDL_LockMutex(is->subtitle_decoder_mutex);
1331 len1 = avcodec_decode_subtitle(is->subtitle_st->codec,
1332 &sp->sub, &got_subtitle,
1333 pkt->data, pkt->size);
1334 SDL_UnlockMutex(is->subtitle_decoder_mutex);
1337 if (got_subtitle && sp->sub.format == 0) {
1340 for (i = 0; i < sp->sub.num_rects; i++)
1342 for (j = 0; j < sp->sub.rects[i].nb_colors; j++)
1344 RGBA_IN(r, g, b, a, sp->sub.rects[i].rgba_palette + j);
1345 y = RGB_TO_Y_CCIR(r, g, b);
1346 u = RGB_TO_U_CCIR(r, g, b, 0);
1347 v = RGB_TO_V_CCIR(r, g, b, 0);
1348 YUVA_OUT(sp->sub.rects[i].rgba_palette + j, y, u, v, a);
1352 /* now we can update the picture count */
1353 if (++is->subpq_windex == SUBPICTURE_QUEUE_SIZE)
1354 is->subpq_windex = 0;
1355 SDL_LockMutex(is->subpq_mutex);
1357 SDL_UnlockMutex(is->subpq_mutex);
1359 av_free_packet(pkt);
1362 // stream_pause(cur_stream);
1368 /* copy samples for viewing in editor window */
1369 static void update_sample_display(VideoState *is, short *samples, int samples_size)
1371 int size, len, channels;
1373 channels = is->audio_st->codec->channels;
1375 size = samples_size / sizeof(short);
1377 len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
1380 memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
1382 is->sample_array_index += len;
1383 if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
1384 is->sample_array_index = 0;
1389 /* return the new audio buffer size (samples can be added or deleted
1390 to get better sync if video or external master clock) */
1391 static int synchronize_audio(VideoState *is, short *samples,
1392 int samples_size1, double pts)
1394 int n, samples_size;
1397 n = 2 * is->audio_st->codec->channels;
1398 samples_size = samples_size1;
1400 /* if not master, then we try to remove or add samples to correct the clock */
1401 if (((is->av_sync_type == AV_SYNC_VIDEO_MASTER && is->video_st) ||
1402 is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
1403 double diff, avg_diff;
1404 int wanted_size, min_size, max_size, nb_samples;
1406 ref_clock = get_master_clock(is);
1407 diff = get_audio_clock(is) - ref_clock;
1409 if (diff < AV_NOSYNC_THRESHOLD) {
1410 is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
1411 if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
1412 /* not enough measures to have a correct estimate */
1413 is->audio_diff_avg_count++;
1415 /* estimate the A-V difference */
1416 avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
1418 if (fabs(avg_diff) >= is->audio_diff_threshold) {
1419 wanted_size = samples_size + ((int)(diff * is->audio_st->codec->sample_rate) * n);
1420 nb_samples = samples_size / n;
1422 min_size = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
1423 max_size = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
1424 if (wanted_size < min_size)
1425 wanted_size = min_size;
1426 else if (wanted_size > max_size)
1427 wanted_size = max_size;
1429 /* add or remove samples to correction the synchro */
1430 if (wanted_size < samples_size) {
1431 /* remove samples */
1432 samples_size = wanted_size;
1433 } else if (wanted_size > samples_size) {
1434 uint8_t *samples_end, *q;
1438 nb = (samples_size - wanted_size);
1439 samples_end = (uint8_t *)samples + samples_size - n;
1440 q = samples_end + n;
1442 memcpy(q, samples_end, n);
1446 samples_size = wanted_size;
1450 printf("diff=%f adiff=%f sample_diff=%d apts=%0.3f vpts=%0.3f %f\n",
1451 diff, avg_diff, samples_size - samples_size1,
1452 is->audio_clock, is->video_clock, is->audio_diff_threshold);
1456 /* too big difference : may be initial PTS errors, so
1458 is->audio_diff_avg_count = 0;
1459 is->audio_diff_cum = 0;
1463 return samples_size;
1466 /* decode one audio frame and returns its uncompressed size */
1467 static int audio_decode_frame(VideoState *is, uint8_t *audio_buf, double *pts_ptr)
1469 AVPacket *pkt = &is->audio_pkt;
1470 int n, len1, data_size;
1474 /* NOTE: the audio packet can contain several frames */
1475 while (is->audio_pkt_size > 0) {
1476 SDL_LockMutex(is->audio_decoder_mutex);
1477 len1 = avcodec_decode_audio(is->audio_st->codec,
1478 (int16_t *)audio_buf, &data_size,
1479 is->audio_pkt_data, is->audio_pkt_size);
1480 SDL_UnlockMutex(is->audio_decoder_mutex);
1482 /* if error, we skip the frame */
1483 is->audio_pkt_size = 0;
1487 is->audio_pkt_data += len1;
1488 is->audio_pkt_size -= len1;
1491 /* if no pts, then compute it */
1492 pts = is->audio_clock;
1494 n = 2 * is->audio_st->codec->channels;
1495 is->audio_clock += (double)data_size /
1496 (double)(n * is->audio_st->codec->sample_rate);
1497 #if defined(DEBUG_SYNC)
1499 static double last_clock;
1500 printf("audio: delay=%0.3f clock=%0.3f pts=%0.3f\n",
1501 is->audio_clock - last_clock,
1502 is->audio_clock, pts);
1503 last_clock = is->audio_clock;
1509 /* free the current packet */
1511 av_free_packet(pkt);
1513 if (is->paused || is->audioq.abort_request) {
1517 /* read next packet */
1518 if (packet_queue_get(&is->audioq, pkt, 1) < 0)
1520 is->audio_pkt_data = pkt->data;
1521 is->audio_pkt_size = pkt->size;
1523 /* if update the audio clock with the pts */
1524 if (pkt->pts != AV_NOPTS_VALUE) {
1525 is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts;
1530 /* get the current audio output buffer size, in samples. With SDL, we
1531 cannot have a precise information */
1532 static int audio_write_get_buf_size(VideoState *is)
1534 return is->audio_hw_buf_size - is->audio_buf_index;
1538 /* prepare a new audio buffer */
1539 void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
1541 VideoState *is = opaque;
1542 int audio_size, len1;
1545 audio_callback_time = av_gettime();
1548 if (is->audio_buf_index >= is->audio_buf_size) {
1549 audio_size = audio_decode_frame(is, is->audio_buf, &pts);
1550 if (audio_size < 0) {
1551 /* if error, just output silence */
1552 is->audio_buf_size = 1024;
1553 memset(is->audio_buf, 0, is->audio_buf_size);
1556 update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
1557 audio_size = synchronize_audio(is, (int16_t *)is->audio_buf, audio_size,
1559 is->audio_buf_size = audio_size;
1561 is->audio_buf_index = 0;
1563 len1 = is->audio_buf_size - is->audio_buf_index;
1566 memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
1569 is->audio_buf_index += len1;
1574 /* open a given stream. Return 0 if OK */
1575 static int stream_component_open(VideoState *is, int stream_index)
1577 AVFormatContext *ic = is->ic;
1578 AVCodecContext *enc;
1580 SDL_AudioSpec wanted_spec, spec;
1582 if (stream_index < 0 || stream_index >= ic->nb_streams)
1584 enc = ic->streams[stream_index]->codec;
1586 /* prepare audio output */
1587 if (enc->codec_type == CODEC_TYPE_AUDIO) {
1588 wanted_spec.freq = enc->sample_rate;
1589 wanted_spec.format = AUDIO_S16SYS;
1590 /* hack for AC3. XXX: suppress that */
1591 if (enc->channels > 2)
1593 wanted_spec.channels = enc->channels;
1594 wanted_spec.silence = 0;
1595 wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
1596 wanted_spec.callback = sdl_audio_callback;
1597 wanted_spec.userdata = is;
1598 if (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
1599 fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
1602 is->audio_hw_buf_size = spec.size;
1605 codec = avcodec_find_decoder(enc->codec_id);
1606 enc->debug_mv = debug_mv;
1609 av_log_set_level(AV_LOG_DEBUG);
1610 enc->workaround_bugs = workaround_bugs;
1611 enc->lowres = lowres;
1612 if(lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
1613 enc->idct_algo= idct;
1614 if(fast) enc->flags2 |= CODEC_FLAG2_FAST;
1615 enc->skip_frame= skip_frame;
1616 enc->skip_idct= skip_idct;
1617 enc->skip_loop_filter= skip_loop_filter;
1618 enc->error_resilience= error_resilience;
1619 enc->error_concealment= error_concealment;
1621 avcodec_open(enc, codec) < 0)
1623 #if defined(HAVE_THREADS)
1625 avcodec_thread_init(enc, thread_count);
1627 enc->thread_count= thread_count;
1628 switch(enc->codec_type) {
1629 case CODEC_TYPE_AUDIO:
1630 is->audio_stream = stream_index;
1631 is->audio_st = ic->streams[stream_index];
1632 is->audio_buf_size = 0;
1633 is->audio_buf_index = 0;
1635 /* init averaging filter */
1636 is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
1637 is->audio_diff_avg_count = 0;
1638 /* since we do not have a precise anough audio fifo fullness,
1639 we correct audio sync only if larger than this threshold */
1640 is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / enc->sample_rate;
1642 memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
1643 packet_queue_init(&is->audioq);
1646 case CODEC_TYPE_VIDEO:
1647 is->video_stream = stream_index;
1648 is->video_st = ic->streams[stream_index];
1650 is->frame_last_delay = 40e-3;
1651 is->frame_timer = (double)av_gettime() / 1000000.0;
1652 is->video_current_pts_time = av_gettime();
1654 packet_queue_init(&is->videoq);
1655 is->video_tid = SDL_CreateThread(video_thread, is);
1657 case CODEC_TYPE_SUBTITLE:
1658 is->subtitle_stream = stream_index;
1659 is->subtitle_st = ic->streams[stream_index];
1660 packet_queue_init(&is->subtitleq);
1662 is->subtitle_tid = SDL_CreateThread(subtitle_thread, is);
1670 static void stream_component_close(VideoState *is, int stream_index)
1672 AVFormatContext *ic = is->ic;
1673 AVCodecContext *enc;
1675 if (stream_index < 0 || stream_index >= ic->nb_streams)
1677 enc = ic->streams[stream_index]->codec;
1679 switch(enc->codec_type) {
1680 case CODEC_TYPE_AUDIO:
1681 packet_queue_abort(&is->audioq);
1685 packet_queue_end(&is->audioq);
1687 case CODEC_TYPE_VIDEO:
1688 packet_queue_abort(&is->videoq);
1690 /* note: we also signal this mutex to make sure we deblock the
1691 video thread in all cases */
1692 SDL_LockMutex(is->pictq_mutex);
1693 SDL_CondSignal(is->pictq_cond);
1694 SDL_UnlockMutex(is->pictq_mutex);
1696 SDL_WaitThread(is->video_tid, NULL);
1698 packet_queue_end(&is->videoq);
1700 case CODEC_TYPE_SUBTITLE:
1701 packet_queue_abort(&is->subtitleq);
1703 /* note: we also signal this mutex to make sure we deblock the
1704 video thread in all cases */
1705 SDL_LockMutex(is->subpq_mutex);
1706 is->subtitle_stream_changed = 1;
1708 SDL_CondSignal(is->subpq_cond);
1709 SDL_UnlockMutex(is->subpq_mutex);
1711 SDL_WaitThread(is->subtitle_tid, NULL);
1713 packet_queue_end(&is->subtitleq);
1720 switch(enc->codec_type) {
1721 case CODEC_TYPE_AUDIO:
1722 is->audio_st = NULL;
1723 is->audio_stream = -1;
1725 case CODEC_TYPE_VIDEO:
1726 is->video_st = NULL;
1727 is->video_stream = -1;
1729 case CODEC_TYPE_SUBTITLE:
1730 is->subtitle_st = NULL;
1731 is->subtitle_stream = -1;
1738 static void dump_stream_info(const AVFormatContext *s)
1741 fprintf(stderr, "Track: %d\n", s->track);
1742 if (s->title[0] != '\0')
1743 fprintf(stderr, "Title: %s\n", s->title);
1744 if (s->author[0] != '\0')
1745 fprintf(stderr, "Author: %s\n", s->author);
1746 if (s->album[0] != '\0')
1747 fprintf(stderr, "Album: %s\n", s->album);
1749 fprintf(stderr, "Year: %d\n", s->year);
1750 if (s->genre[0] != '\0')
1751 fprintf(stderr, "Genre: %s\n", s->genre);
1754 /* since we have only one decoding thread, we can use a global
1755 variable instead of a thread local variable */
1756 static VideoState *global_video_state;
1758 static int decode_interrupt_cb(void)
1760 return (global_video_state && global_video_state->abort_request);
1763 /* this thread gets the stream from the disk or the network */
1764 static int decode_thread(void *arg)
1766 VideoState *is = arg;
1767 AVFormatContext *ic;
1768 int err, i, ret, video_index, audio_index, use_play;
1769 AVPacket pkt1, *pkt = &pkt1;
1770 AVFormatParameters params, *ap = ¶ms;
1774 is->video_stream = -1;
1775 is->audio_stream = -1;
1776 is->subtitle_stream = -1;
1778 global_video_state = is;
1779 url_set_interrupt_cb(decode_interrupt_cb);
1781 memset(ap, 0, sizeof(*ap));
1782 ap->image_format = image_format;
1783 ap->initial_pause = 1; /* we force a pause when starting an RTSP
1786 err = av_open_input_file(&ic, is->filename, is->iformat, 0, ap);
1788 print_error(is->filename, err);
1793 #ifdef CONFIG_NETWORK
1794 use_play = (ic->iformat == &rtsp_demux);
1800 ic->flags |= AVFMT_FLAG_GENPTS;
1803 err = av_find_stream_info(ic);
1805 fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
1809 ic->pb.eof_reached= 0; //FIXME hack, ffplay maybe shouldnt use url_feof() to test for the end
1812 /* if seeking requested, we execute it */
1813 if (start_time != AV_NOPTS_VALUE) {
1816 timestamp = start_time;
1817 /* add the stream start time */
1818 if (ic->start_time != AV_NOPTS_VALUE)
1819 timestamp += ic->start_time;
1820 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
1822 fprintf(stderr, "%s: could not seek to position %0.3f\n",
1823 is->filename, (double)timestamp / AV_TIME_BASE);
1827 /* now we can begin to play (RTSP stream only) */
1831 err = av_find_stream_info(ic);
1833 fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
1839 for(i = 0; i < ic->nb_streams; i++) {
1840 AVCodecContext *enc = ic->streams[i]->codec;
1841 switch(enc->codec_type) {
1842 case CODEC_TYPE_AUDIO:
1843 if (audio_index < 0 && !audio_disable)
1846 case CODEC_TYPE_VIDEO:
1847 if (video_index < 0 && !video_disable)
1855 dump_format(ic, 0, is->filename, 0);
1856 dump_stream_info(ic);
1859 /* open the streams */
1860 if (audio_index >= 0) {
1861 stream_component_open(is, audio_index);
1864 if (video_index >= 0) {
1865 stream_component_open(is, video_index);
1867 if (!display_disable)
1871 if (is->video_stream < 0 && is->audio_stream < 0) {
1872 fprintf(stderr, "%s: could not open codecs\n", is->filename);
1878 if (is->abort_request)
1880 #ifdef CONFIG_NETWORK
1881 if (is->paused != is->last_paused) {
1882 is->last_paused = is->paused;
1888 if (is->paused && ic->iformat == &rtsp_demux) {
1889 /* wait 10 ms to avoid trying to get another packet */
1896 /* XXX: must lock decoder threads */
1897 SDL_LockMutex(is->video_decoder_mutex);
1898 SDL_LockMutex(is->audio_decoder_mutex);
1899 SDL_LockMutex(is->subtitle_decoder_mutex);
1900 ret = av_seek_frame(is->ic, -1, is->seek_pos, is->seek_flags);
1902 fprintf(stderr, "%s: error while seeking\n", is->ic->filename);
1904 if (is->audio_stream >= 0) {
1905 packet_queue_flush(&is->audioq);
1907 if (is->subtitle_stream >= 0) {
1908 packet_queue_flush(&is->subtitleq);
1910 if (is->video_stream >= 0) {
1911 packet_queue_flush(&is->videoq);
1912 avcodec_flush_buffers(ic->streams[video_index]->codec);
1915 SDL_UnlockMutex(is->subtitle_decoder_mutex);
1916 SDL_UnlockMutex(is->audio_decoder_mutex);
1917 SDL_UnlockMutex(is->video_decoder_mutex);
1921 /* if the queue are full, no need to read more */
1922 if (is->audioq.size > MAX_AUDIOQ_SIZE ||
1923 is->videoq.size > MAX_VIDEOQ_SIZE ||
1924 is->subtitleq.size > MAX_SUBTITLEQ_SIZE ||
1925 url_feof(&ic->pb)) {
1930 ret = av_read_frame(ic, pkt);
1932 if (url_ferror(&ic->pb) == 0) {
1933 SDL_Delay(100); /* wait for user event */
1938 if (pkt->stream_index == is->audio_stream) {
1939 packet_queue_put(&is->audioq, pkt);
1940 } else if (pkt->stream_index == is->video_stream) {
1941 packet_queue_put(&is->videoq, pkt);
1942 } else if (pkt->stream_index == is->subtitle_stream) {
1943 packet_queue_put(&is->subtitleq, pkt);
1945 av_free_packet(pkt);
1948 /* wait until the end */
1949 while (!is->abort_request) {
1955 /* disable interrupting */
1956 global_video_state = NULL;
1958 /* close each stream */
1959 if (is->audio_stream >= 0)
1960 stream_component_close(is, is->audio_stream);
1961 if (is->video_stream >= 0)
1962 stream_component_close(is, is->video_stream);
1963 if (is->subtitle_stream >= 0)
1964 stream_component_close(is, is->subtitle_stream);
1966 av_close_input_file(is->ic);
1967 is->ic = NULL; /* safety */
1969 url_set_interrupt_cb(NULL);
1974 event.type = FF_QUIT_EVENT;
1975 event.user.data1 = is;
1976 SDL_PushEvent(&event);
1981 static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
1985 is = av_mallocz(sizeof(VideoState));
1988 pstrcpy(is->filename, sizeof(is->filename), filename);
1989 is->iformat = iformat;
1991 is->width = screen->w;
1992 is->height = screen->h;
1997 /* start video display */
1998 is->pictq_mutex = SDL_CreateMutex();
1999 is->pictq_cond = SDL_CreateCond();
2001 is->subpq_mutex = SDL_CreateMutex();
2002 is->subpq_cond = SDL_CreateCond();
2004 is->subtitle_decoder_mutex = SDL_CreateMutex();
2005 is->audio_decoder_mutex = SDL_CreateMutex();
2006 is->video_decoder_mutex = SDL_CreateMutex();
2008 /* add the refresh timer to draw the picture */
2009 schedule_refresh(is, 40);
2011 is->av_sync_type = av_sync_type;
2012 is->parse_tid = SDL_CreateThread(decode_thread, is);
2013 if (!is->parse_tid) {
2020 static void stream_close(VideoState *is)
2024 /* XXX: use a special url_shutdown call to abort parse cleanly */
2025 is->abort_request = 1;
2026 SDL_WaitThread(is->parse_tid, NULL);
2028 /* free all pictures */
2029 for(i=0;i<VIDEO_PICTURE_QUEUE_SIZE; i++) {
2032 SDL_FreeYUVOverlay(vp->bmp);
2036 SDL_DestroyMutex(is->pictq_mutex);
2037 SDL_DestroyCond(is->pictq_cond);
2038 SDL_DestroyMutex(is->subpq_mutex);
2039 SDL_DestroyCond(is->subpq_cond);
2040 SDL_DestroyMutex(is->subtitle_decoder_mutex);
2041 SDL_DestroyMutex(is->audio_decoder_mutex);
2042 SDL_DestroyMutex(is->video_decoder_mutex);
2045 static void stream_cycle_channel(VideoState *is, int codec_type)
2047 AVFormatContext *ic = is->ic;
2048 int start_index, stream_index;
2051 if (codec_type == CODEC_TYPE_VIDEO)
2052 start_index = is->video_stream;
2053 else if (codec_type == CODEC_TYPE_AUDIO)
2054 start_index = is->audio_stream;
2056 start_index = is->subtitle_stream;
2057 if (start_index < (codec_type == CODEC_TYPE_SUBTITLE ? -1 : 0))
2059 stream_index = start_index;
2061 if (++stream_index >= is->ic->nb_streams)
2063 if (codec_type == CODEC_TYPE_SUBTITLE)
2070 if (stream_index == start_index)
2072 st = ic->streams[stream_index];
2073 if (st->codec->codec_type == codec_type) {
2074 /* check that parameters are OK */
2075 switch(codec_type) {
2076 case CODEC_TYPE_AUDIO:
2077 if (st->codec->sample_rate != 0 &&
2078 st->codec->channels != 0)
2081 case CODEC_TYPE_VIDEO:
2082 case CODEC_TYPE_SUBTITLE:
2090 stream_component_close(is, start_index);
2091 stream_component_open(is, stream_index);
2095 static void toggle_full_screen(void)
2098 is_full_screen = !is_full_screen;
2099 if (!fs_screen_width) {
2100 /* use default SDL method */
2101 SDL_WM_ToggleFullScreen(screen);
2103 /* use the recorded resolution */
2104 flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;
2105 if (is_full_screen) {
2106 w = fs_screen_width;
2107 h = fs_screen_height;
2108 flags |= SDL_FULLSCREEN;
2112 flags |= SDL_RESIZABLE;
2114 screen = SDL_SetVideoMode(w, h, 0, flags);
2115 cur_stream->width = w;
2116 cur_stream->height = h;
2120 static void toggle_pause(void)
2123 stream_pause(cur_stream);
2127 static void step_to_next_frame(void)
2130 if (cur_stream->paused)
2131 cur_stream->paused=0;
2132 cur_stream->video_current_pts = get_video_clock(cur_stream);
2137 static void do_exit(void)
2140 stream_close(cur_stream);
2149 static void toggle_audio_display(void)
2152 cur_stream->show_audio = !cur_stream->show_audio;
2156 /* handle an event sent by the GUI */
2157 static void event_loop(void)
2160 double incr, pos, frac;
2163 SDL_WaitEvent(&event);
2164 switch(event.type) {
2166 switch(event.key.keysym.sym) {
2172 toggle_full_screen();
2178 case SDLK_s: //S: Step to next frame
2179 step_to_next_frame();
2183 stream_cycle_channel(cur_stream, CODEC_TYPE_AUDIO);
2187 stream_cycle_channel(cur_stream, CODEC_TYPE_VIDEO);
2191 stream_cycle_channel(cur_stream, CODEC_TYPE_SUBTITLE);
2194 toggle_audio_display();
2209 pos = get_master_clock(cur_stream);
2211 stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), incr);
2218 case SDL_MOUSEBUTTONDOWN:
2221 int tns, thh, tmm, tss;
2222 tns = cur_stream->ic->duration/1000000LL;
2224 tmm = (tns%3600)/60;
2226 frac = (double)event.button.x/(double)cur_stream->width;
2231 fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n", frac*100,
2232 hh, mm, ss, thh, tmm, tss);
2233 stream_seek(cur_stream, (int64_t)(cur_stream->ic->start_time+frac*cur_stream->ic->duration), 0);
2236 case SDL_VIDEORESIZE:
2238 screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
2239 SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
2240 cur_stream->width = event.resize.w;
2241 cur_stream->height = event.resize.h;
2248 case FF_ALLOC_EVENT:
2249 alloc_picture(event.user.data1);
2251 case FF_REFRESH_EVENT:
2252 video_refresh_timer(event.user.data1);
2260 void opt_width(const char *arg)
2262 screen_width = atoi(arg);
2265 void opt_height(const char *arg)
2267 screen_height = atoi(arg);
2270 static void opt_format(const char *arg)
2272 file_iformat = av_find_input_format(arg);
2273 if (!file_iformat) {
2274 fprintf(stderr, "Unknown input format: %s\n", arg);
2279 static void opt_image_format(const char *arg)
2283 for(f = first_image_format; f != NULL; f = f->next) {
2284 if (!strcmp(arg, f->name))
2288 fprintf(stderr, "Unknown image format: '%s'\n", arg);
2294 #ifdef CONFIG_NETWORK
2295 void opt_rtp_tcp(void)
2297 /* only tcp protocol */
2298 rtsp_default_protocols = (1 << RTSP_PROTOCOL_RTP_TCP);
2302 void opt_sync(const char *arg)
2304 if (!strcmp(arg, "audio"))
2305 av_sync_type = AV_SYNC_AUDIO_MASTER;
2306 else if (!strcmp(arg, "video"))
2307 av_sync_type = AV_SYNC_VIDEO_MASTER;
2308 else if (!strcmp(arg, "ext"))
2309 av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
2314 void opt_seek(const char *arg)
2316 start_time = parse_date(arg, 1);
2319 static void opt_debug(const char *arg)
2324 static void opt_vismv(const char *arg)
2326 debug_mv = atoi(arg);
2329 static void opt_thread_count(const char *arg)
2331 thread_count= atoi(arg);
2332 #if !defined(HAVE_THREADS)
2333 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2337 const OptionDef options[] = {
2338 { "h", 0, {(void*)show_help}, "show help" },
2339 { "x", HAS_ARG, {(void*)opt_width}, "force displayed width", "width" },
2340 { "y", HAS_ARG, {(void*)opt_height}, "force displayed height", "height" },
2341 { "fs", OPT_BOOL, {(void*)&is_full_screen}, "force full screen" },
2342 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2343 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2344 { "ss", HAS_ARG, {(void*)&opt_seek}, "seek to a given position in seconds", "pos" },
2345 { "nodisp", OPT_BOOL, {(void*)&display_disable}, "disable graphical display" },
2346 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2347 { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2348 { "stats", OPT_BOOL | OPT_EXPERT, {(void*)&show_status}, "show status", "" },
2349 { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2350 { "bug", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&workaround_bugs}, "workaround bugs", "" },
2351 { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
2352 { "fast", OPT_BOOL | OPT_EXPERT, {(void*)&fast}, "non spec compliant optimizations", "" },
2353 { "genpts", OPT_BOOL | OPT_EXPERT, {(void*)&genpts}, "generate pts", "" },
2354 { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&lowres}, "", "" },
2355 { "skiploop", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&skip_loop_filter}, "", "" },
2356 { "skipframe", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&skip_frame}, "", "" },
2357 { "skipidct", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&skip_idct}, "", "" },
2358 { "idct", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&idct}, "set idct algo", "algo" },
2359 { "er", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&error_resilience}, "set error detection threshold (0-4)", "threshold" },
2360 { "ec", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&error_concealment}, "set error concealment options", "bit_mask" },
2361 #ifdef CONFIG_NETWORK
2362 { "rtp_tcp", OPT_EXPERT, {(void*)&opt_rtp_tcp}, "force RTP/TCP protocol usage", "" },
2364 { "sync", HAS_ARG | OPT_EXPERT, {(void*)opt_sync}, "set audio-video sync. type (type=audio/video/ext)", "type" },
2365 { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
2369 void show_help(void)
2371 printf("ffplay version " FFMPEG_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
2372 "usage: ffplay [options] input_file\n"
2373 "Simple media player\n");
2375 show_help_options(options, "Main options:\n",
2377 show_help_options(options, "\nAdvanced options:\n",
2378 OPT_EXPERT, OPT_EXPERT);
2379 printf("\nWhile playing:\n"
2381 "f toggle full screen\n"
2383 "a cycle audio channel\n"
2384 "v cycle video channel\n"
2385 "t cycle subtitle channel\n"
2386 "w show audio waves\n"
2387 "left/right seek backward/forward 10 seconds\n"
2388 "down/up seek backward/forward 1 minute\n"
2389 "mouse click seek to percentage in file corresponding to fraction of width\n"
2394 void parse_arg_file(const char *filename)
2396 if (!strcmp(filename, "-"))
2398 input_filename = filename;
2401 /* Called from the main */
2402 int main(int argc, char **argv)
2406 /* register all codecs, demux and protocols */
2410 MorphToPM(); // Morph the VIO application to a PM one to be able to use Win* functions
2412 // Make stdout and stderr unbuffered
2413 setbuf( stdout, NULL );
2414 setbuf( stderr, NULL );
2417 parse_options(argc, argv, options);
2419 if (!input_filename)
2422 if (display_disable) {
2425 flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
2426 #if !defined(CONFIG_WIN32) && !defined(CONFIG_DARWIN)
2427 flags |= SDL_INIT_EVENTTHREAD; /* Not supported on win32 or darwin */
2429 if (SDL_Init (flags)) {
2430 fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
2434 if (!display_disable) {
2435 #ifdef HAVE_SDL_VIDEO_SIZE
2436 const SDL_VideoInfo *vi = SDL_GetVideoInfo();
2437 fs_screen_width = vi->current_w;
2438 fs_screen_height = vi->current_h;
2440 flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;
2441 if (is_full_screen && fs_screen_width) {
2442 w = fs_screen_width;
2443 h = fs_screen_height;
2444 flags |= SDL_FULLSCREEN;
2448 flags |= SDL_RESIZABLE;
2450 #ifndef CONFIG_DARWIN
2451 screen = SDL_SetVideoMode(w, h, 0, flags);
2453 /* setting bits_per_pixel = 0 or 32 causes blank video on OS X */
2454 screen = SDL_SetVideoMode(w, h, 24, flags);
2457 fprintf(stderr, "SDL: could not set video mode - exiting\n");
2460 SDL_WM_SetCaption("FFplay", "FFplay");
2463 SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
2464 SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
2465 SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
2466 SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
2468 cur_stream = stream_open(input_filename, file_iformat);