2 * Copyright (c) 2003 Fabrice Bellard
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * simple media player based on the FFmpeg libraries
31 #include "libavutil/avstring.h"
32 #include "libavutil/colorspace.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/imgutils.h"
36 #include "libavutil/dict.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/samplefmt.h"
39 #include "libavutil/avassert.h"
40 #include "libavutil/time.h"
41 #include "libavformat/avformat.h"
42 #include "libavdevice/avdevice.h"
43 #include "libswscale/swscale.h"
44 #include "libavutil/opt.h"
45 #include "libavcodec/avfft.h"
46 #include "libswresample/swresample.h"
49 # include "libavfilter/avcodec.h"
50 # include "libavfilter/avfilter.h"
51 # include "libavfilter/avfiltergraph.h"
52 # include "libavfilter/buffersink.h"
53 # include "libavfilter/buffersrc.h"
57 #include <SDL_thread.h>
63 const char program_name[] = "ffplay";
64 const int program_birth_year = 2003;
66 #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
69 /* SDL audio buffer size, in samples. Should be small to have precise
70 A/V sync as SDL does not have hardware buffer fullness info. */
71 #define SDL_AUDIO_BUFFER_SIZE 1024
73 /* no AV sync correction is done if below the AV sync threshold */
74 #define AV_SYNC_THRESHOLD 0.01
75 /* no AV correction is done if too big error */
76 #define AV_NOSYNC_THRESHOLD 10.0
78 /* maximum audio speed change to get correct sync */
79 #define SAMPLE_CORRECTION_PERCENT_MAX 10
81 /* external clock speed adjustment constants for realtime sources based on buffer fullness */
82 #define EXTERNAL_CLOCK_SPEED_MIN 0.900
83 #define EXTERNAL_CLOCK_SPEED_MAX 1.010
84 #define EXTERNAL_CLOCK_SPEED_STEP 0.001
86 /* we use about AUDIO_DIFF_AVG_NB A-V differences to make the average */
87 #define AUDIO_DIFF_AVG_NB 20
89 /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
90 /* TODO: We assume that a decoded and resampled frame fits into this buffer */
91 #define SAMPLE_ARRAY_SIZE (8 * 65536)
93 #define CURSOR_HIDE_DELAY 1000000
95 static int64_t sws_flags = SWS_BICUBIC;
97 typedef struct MyAVPacketList {
99 struct MyAVPacketList *next;
103 typedef struct PacketQueue {
104 MyAVPacketList *first_pkt, *last_pkt;
113 #define VIDEO_PICTURE_QUEUE_SIZE 4
114 #define SUBPICTURE_QUEUE_SIZE 4
116 typedef struct VideoPicture {
117 double pts; // presentation timestamp for this picture
118 int64_t pos; // byte position in file
120 int width, height; /* source height & width */
121 AVRational sample_aspect_ratio;
127 AVFilterBufferRef *picref;
131 typedef struct SubPicture {
132 double pts; /* presentation time stamp for this picture */
136 typedef struct AudioParams {
140 enum AVSampleFormat fmt;
144 AV_SYNC_AUDIO_MASTER, /* default choice */
145 AV_SYNC_VIDEO_MASTER,
146 AV_SYNC_EXTERNAL_CLOCK, /* synchronize to an external clock */
149 typedef struct VideoState {
150 SDL_Thread *read_tid;
151 SDL_Thread *video_tid;
152 SDL_Thread *refresh_tid;
153 AVInputFormat *iformat;
159 int queue_attachments_req;
164 int read_pause_return;
171 double external_clock; ///< external clock base
172 double external_clock_drift; ///< external clock base - time (av_gettime) at which we updated external_clock
173 int64_t external_clock_time; ///< last reference time
174 double external_clock_speed; ///< speed of the external clock
177 double audio_diff_cum; /* used for AV difference average computation */
178 double audio_diff_avg_coef;
179 double audio_diff_threshold;
180 int audio_diff_avg_count;
183 int audio_hw_buf_size;
184 DECLARE_ALIGNED(16,uint8_t,audio_buf2)[AVCODEC_MAX_AUDIO_FRAME_SIZE * 4];
185 uint8_t silence_buf[SDL_AUDIO_BUFFER_SIZE];
188 unsigned int audio_buf_size; /* in bytes */
189 int audio_buf_index; /* in bytes */
190 int audio_write_buf_size;
191 AVPacket audio_pkt_temp;
193 int audio_pkt_temp_serial;
194 struct AudioParams audio_src;
195 struct AudioParams audio_tgt;
196 struct SwrContext *swr_ctx;
197 double audio_current_pts;
198 double audio_current_pts_drift;
199 int frame_drops_early;
200 int frame_drops_late;
204 SHOW_MODE_NONE = -1, SHOW_MODE_VIDEO = 0, SHOW_MODE_WAVES, SHOW_MODE_RDFT, SHOW_MODE_NB
206 int16_t sample_array[SAMPLE_ARRAY_SIZE];
207 int sample_array_index;
211 FFTSample *rdft_data;
214 SDL_Thread *subtitle_tid;
216 int subtitle_stream_changed;
217 AVStream *subtitle_st;
218 PacketQueue subtitleq;
219 SubPicture subpq[SUBPICTURE_QUEUE_SIZE];
220 int subpq_size, subpq_rindex, subpq_windex;
221 SDL_mutex *subpq_mutex;
222 SDL_cond *subpq_cond;
225 double frame_last_pts;
226 double frame_last_duration;
227 double frame_last_dropped_pts;
228 double frame_last_returned_time;
229 double frame_last_filter_delay;
230 int64_t frame_last_dropped_pos;
231 double video_clock; // pts of last decoded frame / predicted pts of next decoded frame
235 double video_current_pts; // current displayed pts (different from video_clock if frame fifos are used)
236 double video_current_pts_drift; // video_current_pts - time (av_gettime) at which we updated video_current_pts - used to have running video pts
237 int64_t video_current_pos; // current displayed file pos
238 double max_frame_duration; // maximum duration of a frame - above this, we consider the jump a timestamp discontinuity
239 VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
240 int pictq_size, pictq_rindex, pictq_windex;
241 SDL_mutex *pictq_mutex;
242 SDL_cond *pictq_cond;
244 struct SwsContext *img_convert_ctx;
246 SDL_Rect last_display_rect;
249 int width, height, xleft, ytop;
253 AVFilterContext *in_video_filter; // the first filter in the video chain
254 AVFilterContext *out_video_filter; // the last filter in the video chain
256 FrameBuffer *buffer_pool;
260 int last_video_stream, last_audio_stream, last_subtitle_stream;
262 SDL_cond *continue_read_thread;
265 /* options specified by the user */
266 static AVInputFormat *file_iformat;
267 static const char *input_filename;
268 static const char *window_title;
269 static int fs_screen_width;
270 static int fs_screen_height;
271 static int screen_width = 0;
272 static int screen_height = 0;
273 static int audio_disable;
274 static int video_disable;
275 static int wanted_stream[AVMEDIA_TYPE_NB] = {
276 [AVMEDIA_TYPE_AUDIO] = -1,
277 [AVMEDIA_TYPE_VIDEO] = -1,
278 [AVMEDIA_TYPE_SUBTITLE] = -1,
280 static int seek_by_bytes = -1;
281 static int display_disable;
282 static int show_status = 1;
283 static int av_sync_type = AV_SYNC_AUDIO_MASTER;
284 static int64_t start_time = AV_NOPTS_VALUE;
285 static int64_t duration = AV_NOPTS_VALUE;
286 static int workaround_bugs = 1;
288 static int genpts = 0;
289 static int lowres = 0;
290 static int idct = FF_IDCT_AUTO;
291 static enum AVDiscard skip_frame = AVDISCARD_DEFAULT;
292 static enum AVDiscard skip_idct = AVDISCARD_DEFAULT;
293 static enum AVDiscard skip_loop_filter = AVDISCARD_DEFAULT;
294 static int error_concealment = 3;
295 static int decoder_reorder_pts = -1;
297 static int exit_on_keydown;
298 static int exit_on_mousedown;
300 static int framedrop = -1;
301 static int infinite_buffer = -1;
302 static enum ShowMode show_mode = SHOW_MODE_NONE;
303 static const char *audio_codec_name;
304 static const char *subtitle_codec_name;
305 static const char *video_codec_name;
306 static int rdftspeed = 20;
307 static int64_t cursor_last_shown;
308 static int cursor_hidden = 0;
310 static char *vfilters = NULL;
313 /* current context */
314 static int is_full_screen;
315 static int64_t audio_callback_time;
317 static AVPacket flush_pkt;
319 #define FF_ALLOC_EVENT (SDL_USEREVENT)
320 #define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
321 #define FF_QUIT_EVENT (SDL_USEREVENT + 2)
323 static SDL_Surface *screen;
325 static int packet_queue_put(PacketQueue *q, AVPacket *pkt);
327 static int packet_queue_put_private(PacketQueue *q, AVPacket *pkt)
329 MyAVPacketList *pkt1;
331 if (q->abort_request)
334 pkt1 = av_malloc(sizeof(MyAVPacketList));
339 if (pkt == &flush_pkt)
341 pkt1->serial = q->serial;
346 q->last_pkt->next = pkt1;
349 q->size += pkt1->pkt.size + sizeof(*pkt1);
350 /* XXX: should duplicate packet data in DV case */
351 SDL_CondSignal(q->cond);
355 static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
359 /* duplicate the packet */
360 if (pkt != &flush_pkt && av_dup_packet(pkt) < 0)
363 SDL_LockMutex(q->mutex);
364 ret = packet_queue_put_private(q, pkt);
365 SDL_UnlockMutex(q->mutex);
367 if (pkt != &flush_pkt && ret < 0)
373 /* packet queue handling */
374 static void packet_queue_init(PacketQueue *q)
376 memset(q, 0, sizeof(PacketQueue));
377 q->mutex = SDL_CreateMutex();
378 q->cond = SDL_CreateCond();
379 q->abort_request = 1;
382 static void packet_queue_flush(PacketQueue *q)
384 MyAVPacketList *pkt, *pkt1;
386 SDL_LockMutex(q->mutex);
387 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
389 av_free_packet(&pkt->pkt);
396 SDL_UnlockMutex(q->mutex);
399 static void packet_queue_destroy(PacketQueue *q)
401 packet_queue_flush(q);
402 SDL_DestroyMutex(q->mutex);
403 SDL_DestroyCond(q->cond);
406 static void packet_queue_abort(PacketQueue *q)
408 SDL_LockMutex(q->mutex);
410 q->abort_request = 1;
412 SDL_CondSignal(q->cond);
414 SDL_UnlockMutex(q->mutex);
417 static void packet_queue_start(PacketQueue *q)
419 SDL_LockMutex(q->mutex);
420 q->abort_request = 0;
421 packet_queue_put_private(q, &flush_pkt);
422 SDL_UnlockMutex(q->mutex);
425 /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
426 static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block, int *serial)
428 MyAVPacketList *pkt1;
431 SDL_LockMutex(q->mutex);
434 if (q->abort_request) {
441 q->first_pkt = pkt1->next;
445 q->size -= pkt1->pkt.size + sizeof(*pkt1);
448 *serial = pkt1->serial;
456 SDL_CondWait(q->cond, q->mutex);
459 SDL_UnlockMutex(q->mutex);
463 static inline void fill_rectangle(SDL_Surface *screen,
464 int x, int y, int w, int h, int color, int update)
471 SDL_FillRect(screen, &rect, color);
472 if (update && w > 0 && h > 0)
473 SDL_UpdateRect(screen, x, y, w, h);
476 /* draw only the border of a rectangle */
477 static void fill_border(int xleft, int ytop, int width, int height, int x, int y, int w, int h, int color, int update)
481 /* fill the background */
485 w2 = width - (x + w);
491 h2 = height - (y + h);
494 fill_rectangle(screen,
498 fill_rectangle(screen,
499 xleft + width - w2, ytop,
502 fill_rectangle(screen,
506 fill_rectangle(screen,
507 xleft + w1, ytop + height - h2,
512 #define ALPHA_BLEND(a, oldp, newp, s)\
513 ((((oldp << s) * (255 - (a))) + (newp * (a))) / (255 << s))
515 #define RGBA_IN(r, g, b, a, s)\
517 unsigned int v = ((const uint32_t *)(s))[0];\
518 a = (v >> 24) & 0xff;\
519 r = (v >> 16) & 0xff;\
520 g = (v >> 8) & 0xff;\
524 #define YUVA_IN(y, u, v, a, s, pal)\
526 unsigned int val = ((const uint32_t *)(pal))[*(const uint8_t*)(s)];\
527 a = (val >> 24) & 0xff;\
528 y = (val >> 16) & 0xff;\
529 u = (val >> 8) & 0xff;\
533 #define YUVA_OUT(d, y, u, v, a)\
535 ((uint32_t *)(d))[0] = (a << 24) | (y << 16) | (u << 8) | v;\
541 static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw, int imgh)
543 int wrap, wrap3, width2, skip2;
544 int y, u, v, a, u1, v1, a1, w, h;
545 uint8_t *lum, *cb, *cr;
548 int dstx, dsty, dstw, dsth;
550 dstw = av_clip(rect->w, 0, imgw);
551 dsth = av_clip(rect->h, 0, imgh);
552 dstx = av_clip(rect->x, 0, imgw - dstw);
553 dsty = av_clip(rect->y, 0, imgh - dsth);
554 lum = dst->data[0] + dsty * dst->linesize[0];
555 cb = dst->data[1] + (dsty >> 1) * dst->linesize[1];
556 cr = dst->data[2] + (dsty >> 1) * dst->linesize[2];
558 width2 = ((dstw + 1) >> 1) + (dstx & ~dstw & 1);
560 wrap = dst->linesize[0];
561 wrap3 = rect->pict.linesize[0];
562 p = rect->pict.data[0];
563 pal = (const uint32_t *)rect->pict.data[1]; /* Now in YCrCb! */
571 YUVA_IN(y, u, v, a, p, pal);
572 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
573 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
574 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
580 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
581 YUVA_IN(y, u, v, a, p, pal);
585 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
587 YUVA_IN(y, u, v, a, p + BPP, pal);
591 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
592 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
593 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
600 YUVA_IN(y, u, v, a, p, pal);
601 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
602 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
603 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
607 p += wrap3 - dstw * BPP;
608 lum += wrap - dstw - dstx;
609 cb += dst->linesize[1] - width2 - skip2;
610 cr += dst->linesize[2] - width2 - skip2;
612 for (h = dsth - (dsty & 1); h >= 2; h -= 2) {
618 YUVA_IN(y, u, v, a, p, pal);
622 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
625 YUVA_IN(y, u, v, a, p, pal);
629 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
630 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
631 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
637 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
638 YUVA_IN(y, u, v, a, p, pal);
642 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
644 YUVA_IN(y, u, v, a, p + BPP, pal);
648 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
652 YUVA_IN(y, u, v, a, p, pal);
656 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
658 YUVA_IN(y, u, v, a, p + BPP, pal);
662 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
664 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 2);
665 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 2);
669 p += -wrap3 + 2 * BPP;
673 YUVA_IN(y, u, v, a, p, pal);
677 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
680 YUVA_IN(y, u, v, a, p, pal);
684 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
685 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
686 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
692 p += wrap3 + (wrap3 - dstw * BPP);
693 lum += wrap + (wrap - dstw - dstx);
694 cb += dst->linesize[1] - width2 - skip2;
695 cr += dst->linesize[2] - width2 - skip2;
697 /* handle odd height */
704 YUVA_IN(y, u, v, a, p, pal);
705 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
706 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
707 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
713 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
714 YUVA_IN(y, u, v, a, p, pal);
718 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
720 YUVA_IN(y, u, v, a, p + BPP, pal);
724 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
725 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u, 1);
726 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v, 1);
733 YUVA_IN(y, u, v, a, p, pal);
734 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
735 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
736 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
741 static void free_subpicture(SubPicture *sp)
743 avsubtitle_free(&sp->sub);
746 static void calculate_display_rect(SDL_Rect *rect, int scr_xleft, int scr_ytop, int scr_width, int scr_height, VideoPicture *vp)
749 int width, height, x, y;
751 if (vp->sample_aspect_ratio.num == 0)
754 aspect_ratio = av_q2d(vp->sample_aspect_ratio);
756 if (aspect_ratio <= 0.0)
758 aspect_ratio *= (float)vp->width / (float)vp->height;
760 /* XXX: we suppose the screen has a 1.0 pixel ratio */
762 width = ((int)rint(height * aspect_ratio)) & ~1;
763 if (width > scr_width) {
765 height = ((int)rint(width / aspect_ratio)) & ~1;
767 x = (scr_width - width) / 2;
768 y = (scr_height - height) / 2;
769 rect->x = scr_xleft + x;
770 rect->y = scr_ytop + y;
771 rect->w = FFMAX(width, 1);
772 rect->h = FFMAX(height, 1);
775 static void video_image_display(VideoState *is)
783 vp = &is->pictq[is->pictq_rindex];
785 if (is->subtitle_st) {
786 if (is->subpq_size > 0) {
787 sp = &is->subpq[is->subpq_rindex];
789 if (vp->pts >= sp->pts + ((float) sp->sub.start_display_time / 1000)) {
790 SDL_LockYUVOverlay (vp->bmp);
792 pict.data[0] = vp->bmp->pixels[0];
793 pict.data[1] = vp->bmp->pixels[2];
794 pict.data[2] = vp->bmp->pixels[1];
796 pict.linesize[0] = vp->bmp->pitches[0];
797 pict.linesize[1] = vp->bmp->pitches[2];
798 pict.linesize[2] = vp->bmp->pitches[1];
800 for (i = 0; i < sp->sub.num_rects; i++)
801 blend_subrect(&pict, sp->sub.rects[i],
802 vp->bmp->w, vp->bmp->h);
804 SDL_UnlockYUVOverlay (vp->bmp);
809 calculate_display_rect(&rect, is->xleft, is->ytop, is->width, is->height, vp);
811 SDL_DisplayYUVOverlay(vp->bmp, &rect);
813 if (rect.x != is->last_display_rect.x || rect.y != is->last_display_rect.y || rect.w != is->last_display_rect.w || rect.h != is->last_display_rect.h || is->force_refresh) {
814 int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
815 fill_border(is->xleft, is->ytop, is->width, is->height, rect.x, rect.y, rect.w, rect.h, bgcolor, 1);
816 is->last_display_rect = rect;
821 static inline int compute_mod(int a, int b)
823 return a < 0 ? a%b + b : a%b;
826 static void video_audio_display(VideoState *s)
828 int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
829 int ch, channels, h, h2, bgcolor, fgcolor;
831 int rdft_bits, nb_freq;
833 for (rdft_bits = 1; (1 << rdft_bits) < 2 * s->height; rdft_bits++)
835 nb_freq = 1 << (rdft_bits - 1);
837 /* compute display index : center on currently output samples */
838 channels = s->audio_tgt.channels;
839 nb_display_channels = channels;
841 int data_used= s->show_mode == SHOW_MODE_WAVES ? s->width : (2*nb_freq);
843 delay = s->audio_write_buf_size;
846 /* to be more precise, we take into account the time spent since
847 the last buffer computation */
848 if (audio_callback_time) {
849 time_diff = av_gettime() - audio_callback_time;
850 delay -= (time_diff * s->audio_tgt.freq) / 1000000;
853 delay += 2 * data_used;
854 if (delay < data_used)
857 i_start= x = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
858 if (s->show_mode == SHOW_MODE_WAVES) {
860 for (i = 0; i < 1000; i += channels) {
861 int idx = (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;
862 int a = s->sample_array[idx];
863 int b = s->sample_array[(idx + 4 * channels) % SAMPLE_ARRAY_SIZE];
864 int c = s->sample_array[(idx + 5 * channels) % SAMPLE_ARRAY_SIZE];
865 int d = s->sample_array[(idx + 9 * channels) % SAMPLE_ARRAY_SIZE];
867 if (h < score && (b ^ c) < 0) {
874 s->last_i_start = i_start;
876 i_start = s->last_i_start;
879 bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
880 if (s->show_mode == SHOW_MODE_WAVES) {
881 fill_rectangle(screen,
882 s->xleft, s->ytop, s->width, s->height,
885 fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);
887 /* total height for one channel */
888 h = s->height / nb_display_channels;
889 /* graph height / 2 */
891 for (ch = 0; ch < nb_display_channels; ch++) {
893 y1 = s->ytop + ch * h + (h / 2); /* position of center line */
894 for (x = 0; x < s->width; x++) {
895 y = (s->sample_array[i] * h2) >> 15;
902 fill_rectangle(screen,
903 s->xleft + x, ys, 1, y,
906 if (i >= SAMPLE_ARRAY_SIZE)
907 i -= SAMPLE_ARRAY_SIZE;
911 fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);
913 for (ch = 1; ch < nb_display_channels; ch++) {
914 y = s->ytop + ch * h;
915 fill_rectangle(screen,
916 s->xleft, y, s->width, 1,
919 SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
921 nb_display_channels= FFMIN(nb_display_channels, 2);
922 if (rdft_bits != s->rdft_bits) {
923 av_rdft_end(s->rdft);
924 av_free(s->rdft_data);
925 s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
926 s->rdft_bits = rdft_bits;
927 s->rdft_data = av_malloc(4 * nb_freq * sizeof(*s->rdft_data));
931 for (ch = 0; ch < nb_display_channels; ch++) {
932 data[ch] = s->rdft_data + 2 * nb_freq * ch;
934 for (x = 0; x < 2 * nb_freq; x++) {
935 double w = (x-nb_freq) * (1.0 / nb_freq);
936 data[ch][x] = s->sample_array[i] * (1.0 - w * w);
938 if (i >= SAMPLE_ARRAY_SIZE)
939 i -= SAMPLE_ARRAY_SIZE;
941 av_rdft_calc(s->rdft, data[ch]);
943 // least efficient way to do this, we should of course directly access it but its more than fast enough
944 for (y = 0; y < s->height; y++) {
945 double w = 1 / sqrt(nb_freq);
946 int a = sqrt(w * sqrt(data[0][2 * y + 0] * data[0][2 * y + 0] + data[0][2 * y + 1] * data[0][2 * y + 1]));
947 int b = (nb_display_channels == 2 ) ? sqrt(w * sqrt(data[1][2 * y + 0] * data[1][2 * y + 0]
948 + data[1][2 * y + 1] * data[1][2 * y + 1])) : a;
951 fgcolor = SDL_MapRGB(screen->format, a, b, (a + b) / 2);
953 fill_rectangle(screen,
954 s->xpos, s->height-y, 1, 1,
958 SDL_UpdateRect(screen, s->xpos, s->ytop, 1, s->height);
961 if (s->xpos >= s->width)
966 static void stream_close(VideoState *is)
970 /* XXX: use a special url_shutdown call to abort parse cleanly */
971 is->abort_request = 1;
972 SDL_WaitThread(is->read_tid, NULL);
973 SDL_WaitThread(is->refresh_tid, NULL);
974 packet_queue_destroy(&is->videoq);
975 packet_queue_destroy(&is->audioq);
976 packet_queue_destroy(&is->subtitleq);
978 /* free all pictures */
979 for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++) {
982 avfilter_unref_bufferp(&vp->picref);
985 SDL_FreeYUVOverlay(vp->bmp);
989 SDL_DestroyMutex(is->pictq_mutex);
990 SDL_DestroyCond(is->pictq_cond);
991 SDL_DestroyMutex(is->subpq_mutex);
992 SDL_DestroyCond(is->subpq_cond);
993 SDL_DestroyCond(is->continue_read_thread);
995 if (is->img_convert_ctx)
996 sws_freeContext(is->img_convert_ctx);
1001 static void do_exit(VideoState *is)
1006 av_lockmgr_register(NULL);
1010 av_freep(&vfilters);
1012 avformat_network_deinit();
1016 av_log(NULL, AV_LOG_QUIET, "%s", "");
1020 static void sigterm_handler(int sig)
1025 static int video_open(VideoState *is, int force_set_video_mode)
1027 int flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;
1029 VideoPicture *vp = &is->pictq[is->pictq_rindex];
1032 if (is_full_screen) flags |= SDL_FULLSCREEN;
1033 else flags |= SDL_RESIZABLE;
1035 if (is_full_screen && fs_screen_width) {
1036 w = fs_screen_width;
1037 h = fs_screen_height;
1038 } else if (!is_full_screen && screen_width) {
1041 } else if (vp->width) {
1042 calculate_display_rect(&rect, 0, 0, INT_MAX, vp->height, vp);
1049 if (screen && is->width == screen->w && screen->w == w
1050 && is->height== screen->h && screen->h == h && !force_set_video_mode)
1052 screen = SDL_SetVideoMode(w, h, 0, flags);
1054 fprintf(stderr, "SDL: could not set video mode - exiting\n");
1058 window_title = input_filename;
1059 SDL_WM_SetCaption(window_title, window_title);
1061 is->width = screen->w;
1062 is->height = screen->h;
1067 /* display the current picture, if any */
1068 static void video_display(VideoState *is)
1072 if (is->audio_st && is->show_mode != SHOW_MODE_VIDEO)
1073 video_audio_display(is);
1074 else if (is->video_st)
1075 video_image_display(is);
1078 static int refresh_thread(void *opaque)
1080 VideoState *is= opaque;
1081 while (!is->abort_request) {
1083 event.type = FF_REFRESH_EVENT;
1084 event.user.data1 = opaque;
1085 if (!is->refresh && (!is->paused || is->force_refresh)) {
1087 SDL_PushEvent(&event);
1089 //FIXME ideally we should wait the correct time but SDLs event passing is so slow it would be silly
1090 av_usleep(is->audio_st && is->show_mode != SHOW_MODE_VIDEO ? rdftspeed*1000 : 5000);
1095 /* get the current audio clock value */
1096 static double get_audio_clock(VideoState *is)
1099 return is->audio_current_pts;
1101 return is->audio_current_pts_drift + av_gettime() / 1000000.0;
1105 /* get the current video clock value */
1106 static double get_video_clock(VideoState *is)
1109 return is->video_current_pts;
1111 return is->video_current_pts_drift + av_gettime() / 1000000.0;
1115 /* get the current external clock value */
1116 static double get_external_clock(VideoState *is)
1119 return is->external_clock;
1121 double time = av_gettime() / 1000000.0;
1122 return is->external_clock_drift + time - (time - is->external_clock_time / 1000000.0) * (1.0 - is->external_clock_speed);
1126 static int get_master_sync_type(VideoState *is) {
1127 if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
1129 return AV_SYNC_VIDEO_MASTER;
1131 return AV_SYNC_AUDIO_MASTER;
1132 } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
1134 return AV_SYNC_AUDIO_MASTER;
1136 return AV_SYNC_EXTERNAL_CLOCK;
1138 return AV_SYNC_EXTERNAL_CLOCK;
1142 /* get the current master clock value */
1143 static double get_master_clock(VideoState *is)
1147 switch (get_master_sync_type(is)) {
1148 case AV_SYNC_VIDEO_MASTER:
1149 val = get_video_clock(is);
1151 case AV_SYNC_AUDIO_MASTER:
1152 val = get_audio_clock(is);
1155 val = get_external_clock(is);
1161 static void update_external_clock_pts(VideoState *is, double pts)
1163 is->external_clock_time = av_gettime();
1164 is->external_clock = pts;
1165 is->external_clock_drift = pts - is->external_clock_time / 1000000.0;
1168 static void check_external_clock_sync(VideoState *is, double pts) {
1169 if (fabs(get_external_clock(is) - pts) > AV_NOSYNC_THRESHOLD) {
1170 update_external_clock_pts(is, pts);
1174 static void update_external_clock_speed(VideoState *is, double speed) {
1175 update_external_clock_pts(is, get_external_clock(is));
1176 is->external_clock_speed = speed;
1179 static void check_external_clock_speed(VideoState *is) {
1180 if (is->video_stream >= 0 && is->videoq.nb_packets <= MIN_FRAMES / 2 ||
1181 is->audio_stream >= 0 && is->audioq.nb_packets <= MIN_FRAMES / 2) {
1182 update_external_clock_speed(is, FFMAX(EXTERNAL_CLOCK_SPEED_MIN, is->external_clock_speed - EXTERNAL_CLOCK_SPEED_STEP));
1183 } else if ((is->video_stream < 0 || is->videoq.nb_packets > MIN_FRAMES * 2) &&
1184 (is->audio_stream < 0 || is->audioq.nb_packets > MIN_FRAMES * 2)) {
1185 update_external_clock_speed(is, FFMIN(EXTERNAL_CLOCK_SPEED_MAX, is->external_clock_speed + EXTERNAL_CLOCK_SPEED_STEP));
1187 double speed = is->external_clock_speed;
1189 update_external_clock_speed(is, speed + EXTERNAL_CLOCK_SPEED_STEP * (1.0 - speed) / fabs(1.0 - speed));
1193 /* seek in the stream */
1194 static void stream_seek(VideoState *is, int64_t pos, int64_t rel, int seek_by_bytes)
1196 if (!is->seek_req) {
1199 is->seek_flags &= ~AVSEEK_FLAG_BYTE;
1201 is->seek_flags |= AVSEEK_FLAG_BYTE;
1206 /* pause or resume the video */
1207 static void stream_toggle_pause(VideoState *is)
1210 is->frame_timer += av_gettime() / 1000000.0 + is->video_current_pts_drift - is->video_current_pts;
1211 if (is->read_pause_return != AVERROR(ENOSYS)) {
1212 is->video_current_pts = is->video_current_pts_drift + av_gettime() / 1000000.0;
1214 is->video_current_pts_drift = is->video_current_pts - av_gettime() / 1000000.0;
1216 update_external_clock_pts(is, get_external_clock(is));
1217 is->paused = !is->paused;
1220 static double compute_target_delay(double delay, VideoState *is)
1222 double sync_threshold, diff;
1224 /* update delay to follow master synchronisation source */
1225 if (get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER) {
1226 /* if video is slave, we try to correct big delays by
1227 duplicating or deleting a frame */
1228 diff = get_video_clock(is) - get_master_clock(is);
1230 /* skip or repeat frame. We take into account the
1231 delay to compute the threshold. I still don't know
1232 if it is the best guess */
1233 sync_threshold = FFMAX(AV_SYNC_THRESHOLD, delay);
1234 if (fabs(diff) < AV_NOSYNC_THRESHOLD) {
1235 if (diff <= -sync_threshold)
1237 else if (diff >= sync_threshold)
1242 av_dlog(NULL, "video: delay=%0.3f A-V=%f\n",
1248 static void pictq_next_picture(VideoState *is) {
1249 /* update queue size and signal for next picture */
1250 if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
1251 is->pictq_rindex = 0;
1253 SDL_LockMutex(is->pictq_mutex);
1255 SDL_CondSignal(is->pictq_cond);
1256 SDL_UnlockMutex(is->pictq_mutex);
1259 static void pictq_prev_picture(VideoState *is) {
1260 VideoPicture *prevvp;
1261 /* update queue size and signal for the previous picture */
1262 prevvp = &is->pictq[(is->pictq_rindex + VIDEO_PICTURE_QUEUE_SIZE - 1) % VIDEO_PICTURE_QUEUE_SIZE];
1263 if (prevvp->allocated && prevvp->serial == is->videoq.serial) {
1264 SDL_LockMutex(is->pictq_mutex);
1265 if (is->pictq_size < VIDEO_PICTURE_QUEUE_SIZE - 1) {
1266 if (--is->pictq_rindex == -1)
1267 is->pictq_rindex = VIDEO_PICTURE_QUEUE_SIZE - 1;
1270 SDL_CondSignal(is->pictq_cond);
1271 SDL_UnlockMutex(is->pictq_mutex);
1275 static void update_video_pts(VideoState *is, double pts, int64_t pos, int serial) {
1276 double time = av_gettime() / 1000000.0;
1277 /* update current video pts */
1278 is->video_current_pts = pts;
1279 is->video_current_pts_drift = is->video_current_pts - time;
1280 is->video_current_pos = pos;
1281 is->frame_last_pts = pts;
1282 if (is->videoq.serial == serial)
1283 check_external_clock_sync(is, is->video_current_pts);
1286 /* called to display each frame */
1287 static void video_refresh(void *opaque)
1289 VideoState *is = opaque;
1293 SubPicture *sp, *sp2;
1295 if (!is->paused && get_master_sync_type(is) == AV_SYNC_EXTERNAL_CLOCK && is->realtime)
1296 check_external_clock_speed(is);
1298 if (!display_disable && is->show_mode != SHOW_MODE_VIDEO && is->audio_st)
1302 if (is->force_refresh)
1303 pictq_prev_picture(is);
1305 if (is->pictq_size == 0) {
1306 SDL_LockMutex(is->pictq_mutex);
1307 if (is->frame_last_dropped_pts != AV_NOPTS_VALUE && is->frame_last_dropped_pts > is->frame_last_pts) {
1308 update_video_pts(is, is->frame_last_dropped_pts, is->frame_last_dropped_pos, 0);
1309 is->frame_last_dropped_pts = AV_NOPTS_VALUE;
1311 SDL_UnlockMutex(is->pictq_mutex);
1312 // nothing to do, no picture to display in the queue
1314 double last_duration, duration, delay;
1315 /* dequeue the picture */
1316 vp = &is->pictq[is->pictq_rindex];
1318 if (vp->serial != is->videoq.serial) {
1319 pictq_next_picture(is);
1326 /* compute nominal last_duration */
1327 last_duration = vp->pts - is->frame_last_pts;
1328 if (last_duration > 0 && last_duration < is->max_frame_duration) {
1329 /* if duration of the last frame was sane, update last_duration in video state */
1330 is->frame_last_duration = last_duration;
1332 delay = compute_target_delay(is->frame_last_duration, is);
1334 time= av_gettime()/1000000.0;
1335 if (time < is->frame_timer + delay)
1339 is->frame_timer += delay * FFMAX(1, floor((time-is->frame_timer) / delay));
1341 SDL_LockMutex(is->pictq_mutex);
1342 update_video_pts(is, vp->pts, vp->pos, vp->serial);
1343 SDL_UnlockMutex(is->pictq_mutex);
1345 if (is->pictq_size > 1) {
1346 VideoPicture *nextvp = &is->pictq[(is->pictq_rindex + 1) % VIDEO_PICTURE_QUEUE_SIZE];
1347 duration = nextvp->pts - vp->pts;
1348 if(!is->step && (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) && time > is->frame_timer + duration){
1349 is->frame_drops_late++;
1350 pictq_next_picture(is);
1355 if (is->subtitle_st) {
1356 if (is->subtitle_stream_changed) {
1357 SDL_LockMutex(is->subpq_mutex);
1359 while (is->subpq_size) {
1360 free_subpicture(&is->subpq[is->subpq_rindex]);
1362 /* update queue size and signal for next picture */
1363 if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
1364 is->subpq_rindex = 0;
1368 is->subtitle_stream_changed = 0;
1370 SDL_CondSignal(is->subpq_cond);
1371 SDL_UnlockMutex(is->subpq_mutex);
1373 if (is->subpq_size > 0) {
1374 sp = &is->subpq[is->subpq_rindex];
1376 if (is->subpq_size > 1)
1377 sp2 = &is->subpq[(is->subpq_rindex + 1) % SUBPICTURE_QUEUE_SIZE];
1381 if ((is->video_current_pts > (sp->pts + ((float) sp->sub.end_display_time / 1000)))
1382 || (sp2 && is->video_current_pts > (sp2->pts + ((float) sp2->sub.start_display_time / 1000))))
1384 free_subpicture(sp);
1386 /* update queue size and signal for next picture */
1387 if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
1388 is->subpq_rindex = 0;
1390 SDL_LockMutex(is->subpq_mutex);
1392 SDL_CondSignal(is->subpq_cond);
1393 SDL_UnlockMutex(is->subpq_mutex);
1400 /* display picture */
1401 if (!display_disable && is->show_mode == SHOW_MODE_VIDEO)
1404 pictq_next_picture(is);
1406 if (is->step && !is->paused)
1407 stream_toggle_pause(is);
1410 is->force_refresh = 0;
1412 static int64_t last_time;
1414 int aqsize, vqsize, sqsize;
1417 cur_time = av_gettime();
1418 if (!last_time || (cur_time - last_time) >= 30000) {
1423 aqsize = is->audioq.size;
1425 vqsize = is->videoq.size;
1426 if (is->subtitle_st)
1427 sqsize = is->subtitleq.size;
1429 if (is->audio_st && is->video_st)
1430 av_diff = get_audio_clock(is) - get_video_clock(is);
1431 printf("%7.2f A-V:%7.3f fd=%4d aq=%5dKB vq=%5dKB sq=%5dB f=%"PRId64"/%"PRId64" \r",
1432 get_master_clock(is),
1434 is->frame_drops_early + is->frame_drops_late,
1438 is->video_st ? is->video_st->codec->pts_correction_num_faulty_dts : 0,
1439 is->video_st ? is->video_st->codec->pts_correction_num_faulty_pts : 0);
1441 last_time = cur_time;
1446 /* allocate a picture (needs to do that in main thread to avoid
1447 potential locking problems */
1448 static void alloc_picture(VideoState *is)
1452 vp = &is->pictq[is->pictq_windex];
1455 SDL_FreeYUVOverlay(vp->bmp);
1458 avfilter_unref_bufferp(&vp->picref);
1463 vp->bmp = SDL_CreateYUVOverlay(vp->width, vp->height,
1466 if (!vp->bmp || vp->bmp->pitches[0] < vp->width) {
1467 /* SDL allocates a buffer smaller than requested if the video
1468 * overlay hardware is unable to support the requested size. */
1469 fprintf(stderr, "Error: the video system does not support an image\n"
1470 "size of %dx%d pixels. Try using -lowres or -vf \"scale=w:h\"\n"
1471 "to reduce the image size.\n", vp->width, vp->height );
1475 SDL_LockMutex(is->pictq_mutex);
1477 SDL_CondSignal(is->pictq_cond);
1478 SDL_UnlockMutex(is->pictq_mutex);
1481 static void duplicate_right_border_pixels(SDL_Overlay *bmp) {
1482 int i, width, height;
1484 for (i = 0; i < 3; i++) {
1491 if (bmp->pitches[i] > width) {
1492 maxp = bmp->pixels[i] + bmp->pitches[i] * height - 1;
1493 for (p = bmp->pixels[i] + width - 1; p < maxp; p += bmp->pitches[i])
1499 static int queue_picture(VideoState *is, AVFrame *src_frame, double pts1, int64_t pos, int serial)
1502 double frame_delay, pts = pts1;
1504 /* compute the exact PTS for the picture if it is omitted in the stream
1505 * pts1 is the dts of the pkt / pts of the frame */
1507 /* update video clock with pts, if present */
1508 is->video_clock = pts;
1510 pts = is->video_clock;
1512 /* update video clock for next frame */
1513 frame_delay = av_q2d(is->video_st->codec->time_base);
1514 /* for MPEG2, the frame can be repeated, so we update the
1515 clock accordingly */
1516 frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
1517 is->video_clock += frame_delay;
1519 #if defined(DEBUG_SYNC) && 0
1520 printf("frame_type=%c clock=%0.3f pts=%0.3f\n",
1521 av_get_picture_type_char(src_frame->pict_type), pts, pts1);
1524 /* wait until we have space to put a new picture */
1525 SDL_LockMutex(is->pictq_mutex);
1527 /* keep the last already displayed picture in the queue */
1528 while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE - 2 &&
1529 !is->videoq.abort_request) {
1530 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1532 SDL_UnlockMutex(is->pictq_mutex);
1534 if (is->videoq.abort_request)
1537 vp = &is->pictq[is->pictq_windex];
1540 vp->sample_aspect_ratio = ((AVFilterBufferRef *)src_frame->opaque)->video->sample_aspect_ratio;
1542 vp->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, src_frame);
1545 /* alloc or resize hardware picture buffer */
1546 if (!vp->bmp || vp->reallocate || !vp->allocated ||
1547 vp->width != src_frame->width ||
1548 vp->height != src_frame->height) {
1553 vp->width = src_frame->width;
1554 vp->height = src_frame->height;
1556 /* the allocation must be done in the main thread to avoid
1557 locking problems. */
1558 event.type = FF_ALLOC_EVENT;
1559 event.user.data1 = is;
1560 SDL_PushEvent(&event);
1562 /* wait until the picture is allocated */
1563 SDL_LockMutex(is->pictq_mutex);
1564 while (!vp->allocated && !is->videoq.abort_request) {
1565 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1567 /* if the queue is aborted, we have to pop the pending ALLOC event or wait for the allocation to complete */
1568 if (is->videoq.abort_request && SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_EVENTMASK(FF_ALLOC_EVENT)) != 1) {
1569 while (!vp->allocated) {
1570 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1573 SDL_UnlockMutex(is->pictq_mutex);
1575 if (is->videoq.abort_request)
1579 /* if the frame is not skipped, then display it */
1581 AVPicture pict = { { 0 } };
1583 avfilter_unref_bufferp(&vp->picref);
1584 vp->picref = src_frame->opaque;
1587 /* get a pointer on the bitmap */
1588 SDL_LockYUVOverlay (vp->bmp);
1590 pict.data[0] = vp->bmp->pixels[0];
1591 pict.data[1] = vp->bmp->pixels[2];
1592 pict.data[2] = vp->bmp->pixels[1];
1594 pict.linesize[0] = vp->bmp->pitches[0];
1595 pict.linesize[1] = vp->bmp->pitches[2];
1596 pict.linesize[2] = vp->bmp->pitches[1];
1599 // FIXME use direct rendering
1600 av_picture_copy(&pict, (AVPicture *)src_frame,
1601 src_frame->format, vp->width, vp->height);
1603 av_opt_get_int(sws_opts, "sws_flags", 0, &sws_flags);
1604 is->img_convert_ctx = sws_getCachedContext(is->img_convert_ctx,
1605 vp->width, vp->height, src_frame->format, vp->width, vp->height,
1606 AV_PIX_FMT_YUV420P, sws_flags, NULL, NULL, NULL);
1607 if (is->img_convert_ctx == NULL) {
1608 fprintf(stderr, "Cannot initialize the conversion context\n");
1611 sws_scale(is->img_convert_ctx, src_frame->data, src_frame->linesize,
1612 0, vp->height, pict.data, pict.linesize);
1614 /* workaround SDL PITCH_WORKAROUND */
1615 duplicate_right_border_pixels(vp->bmp);
1616 /* update the bitmap content */
1617 SDL_UnlockYUVOverlay(vp->bmp);
1621 vp->serial = serial;
1623 /* now we can update the picture count */
1624 if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
1625 is->pictq_windex = 0;
1626 SDL_LockMutex(is->pictq_mutex);
1628 SDL_UnlockMutex(is->pictq_mutex);
1633 static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacket *pkt, int *serial)
1637 if (packet_queue_get(&is->videoq, pkt, 1, serial) < 0)
1640 if (pkt->data == flush_pkt.data) {
1641 avcodec_flush_buffers(is->video_st->codec);
1643 SDL_LockMutex(is->pictq_mutex);
1644 // Make sure there are no long delay timers (ideally we should just flush the queue but that's harder)
1645 while (is->pictq_size && !is->videoq.abort_request) {
1646 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1648 is->video_current_pos = -1;
1649 is->frame_last_pts = AV_NOPTS_VALUE;
1650 is->frame_last_duration = 0;
1651 is->frame_timer = (double)av_gettime() / 1000000.0;
1652 is->frame_last_dropped_pts = AV_NOPTS_VALUE;
1653 SDL_UnlockMutex(is->pictq_mutex);
1658 if(avcodec_decode_video2(is->video_st->codec, frame, &got_picture, pkt) < 0)
1664 if (decoder_reorder_pts == -1) {
1665 *pts = av_frame_get_best_effort_timestamp(frame);
1666 } else if (decoder_reorder_pts) {
1667 *pts = frame->pkt_pts;
1669 *pts = frame->pkt_dts;
1672 if (*pts == AV_NOPTS_VALUE) {
1676 if (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) {
1677 SDL_LockMutex(is->pictq_mutex);
1678 if (is->frame_last_pts != AV_NOPTS_VALUE && *pts) {
1679 double clockdiff = get_video_clock(is) - get_master_clock(is);
1680 double dpts = av_q2d(is->video_st->time_base) * *pts;
1681 double ptsdiff = dpts - is->frame_last_pts;
1682 if (fabs(clockdiff) < AV_NOSYNC_THRESHOLD &&
1683 ptsdiff > 0 && ptsdiff < AV_NOSYNC_THRESHOLD &&
1684 clockdiff + ptsdiff - is->frame_last_filter_delay < 0) {
1685 is->frame_last_dropped_pos = pkt->pos;
1686 is->frame_last_dropped_pts = dpts;
1687 is->frame_drops_early++;
1691 SDL_UnlockMutex(is->pictq_mutex);
1700 static int configure_filtergraph(AVFilterGraph *graph, const char *filtergraph,
1701 AVFilterContext *source_ctx, AVFilterContext *sink_ctx)
1704 AVFilterInOut *outputs = NULL, *inputs = NULL;
1707 outputs = avfilter_inout_alloc();
1708 inputs = avfilter_inout_alloc();
1709 if (!outputs || !inputs) {
1710 ret = AVERROR(ENOMEM);
1714 outputs->name = av_strdup("in");
1715 outputs->filter_ctx = source_ctx;
1716 outputs->pad_idx = 0;
1717 outputs->next = NULL;
1719 inputs->name = av_strdup("out");
1720 inputs->filter_ctx = sink_ctx;
1721 inputs->pad_idx = 0;
1722 inputs->next = NULL;
1724 if ((ret = avfilter_graph_parse(graph, filtergraph, &inputs, &outputs, NULL)) < 0)
1727 if ((ret = avfilter_link(source_ctx, 0, sink_ctx, 0)) < 0)
1731 ret = avfilter_graph_config(graph, NULL);
1733 avfilter_inout_free(&outputs);
1734 avfilter_inout_free(&inputs);
1738 static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const char *vfilters, AVFrame *frame)
1740 static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };
1741 char sws_flags_str[128];
1742 char buffersrc_args[256];
1744 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
1745 AVFilterContext *filt_src = NULL, *filt_out = NULL, *filt_crop;
1746 AVCodecContext *codec = is->video_st->codec;
1748 if (!buffersink_params)
1749 return AVERROR(ENOMEM);
1751 av_opt_get_int(sws_opts, "sws_flags", 0, &sws_flags);
1752 snprintf(sws_flags_str, sizeof(sws_flags_str), "flags=%"PRId64, sws_flags);
1753 graph->scale_sws_opts = av_strdup(sws_flags_str);
1755 snprintf(buffersrc_args, sizeof(buffersrc_args),
1756 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
1757 frame->width, frame->height, frame->format,
1758 is->video_st->time_base.num, is->video_st->time_base.den,
1759 codec->sample_aspect_ratio.num, FFMAX(codec->sample_aspect_ratio.den, 1));
1761 if ((ret = avfilter_graph_create_filter(&filt_src,
1762 avfilter_get_by_name("buffer"),
1763 "ffplay_buffer", buffersrc_args, NULL,
1767 buffersink_params->pixel_fmts = pix_fmts;
1768 ret = avfilter_graph_create_filter(&filt_out,
1769 avfilter_get_by_name("ffbuffersink"),
1770 "ffplay_buffersink", NULL, buffersink_params, graph);
1774 /* SDL YUV code is not handling odd width/height for some driver
1775 * combinations, therefore we crop the picture to an even width/height. */
1776 if ((ret = avfilter_graph_create_filter(&filt_crop,
1777 avfilter_get_by_name("crop"),
1778 "ffplay_crop", "floor(in_w/2)*2:floor(in_h/2)*2", NULL, graph)) < 0)
1780 if ((ret = avfilter_link(filt_crop, 0, filt_out, 0)) < 0)
1783 if ((ret = configure_filtergraph(graph, vfilters, filt_src, filt_crop)) < 0)
1786 is->in_video_filter = filt_src;
1787 is->out_video_filter = filt_out;
1790 av_freep(&buffersink_params);
1794 #endif /* CONFIG_AVFILTER */
1796 static int video_thread(void *arg)
1798 AVPacket pkt = { 0 };
1799 VideoState *is = arg;
1800 AVFrame *frame = avcodec_alloc_frame();
1801 int64_t pts_int = AV_NOPTS_VALUE, pos = -1;
1807 AVCodecContext *codec = is->video_st->codec;
1808 AVFilterGraph *graph = avfilter_graph_alloc();
1809 AVFilterContext *filt_out = NULL, *filt_in = NULL;
1812 enum AVPixelFormat last_format = -2;
1813 int last_serial = -1;
1815 if (codec->codec->capabilities & CODEC_CAP_DR1) {
1817 codec->get_buffer = codec_get_buffer;
1818 codec->release_buffer = codec_release_buffer;
1819 codec->opaque = &is->buffer_pool;
1825 AVFilterBufferRef *picref;
1828 while (is->paused && !is->videoq.abort_request)
1831 avcodec_get_frame_defaults(frame);
1832 av_free_packet(&pkt);
1834 ret = get_video_frame(is, frame, &pts_int, &pkt, &serial);
1842 if ( last_w != frame->width
1843 || last_h != frame->height
1844 || last_format != frame->format
1845 || last_serial != serial) {
1846 av_log(NULL, AV_LOG_INFO, "Frame changed from size:%dx%d to size:%dx%d\n",
1847 last_w, last_h, frame->width, frame->height);
1848 avfilter_graph_free(&graph);
1849 graph = avfilter_graph_alloc();
1850 if ((ret = configure_video_filters(graph, is, vfilters, frame)) < 0) {
1852 event.type = FF_QUIT_EVENT;
1853 event.user.data1 = is;
1854 SDL_PushEvent(&event);
1855 av_free_packet(&pkt);
1858 filt_in = is->in_video_filter;
1859 filt_out = is->out_video_filter;
1860 last_w = frame->width;
1861 last_h = frame->height;
1862 last_format = frame->format;
1863 last_serial = serial;
1866 frame->pts = pts_int;
1867 frame->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, frame);
1868 if (is->use_dr1 && frame->opaque) {
1869 FrameBuffer *buf = frame->opaque;
1870 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
1871 frame->data, frame->linesize,
1872 AV_PERM_READ | AV_PERM_PRESERVE,
1873 frame->width, frame->height,
1876 avfilter_copy_frame_props(fb, frame);
1877 fb->buf->priv = buf;
1878 fb->buf->free = filter_release_buffer;
1881 av_buffersrc_add_ref(filt_in, fb, AV_BUFFERSRC_FLAG_NO_COPY);
1884 av_buffersrc_write_frame(filt_in, frame);
1886 av_free_packet(&pkt);
1889 is->frame_last_returned_time = av_gettime() / 1000000.0;
1891 ret = av_buffersink_get_buffer_ref(filt_out, &picref, 0);
1897 is->frame_last_filter_delay = av_gettime() / 1000000.0 - is->frame_last_returned_time;
1898 if (fabs(is->frame_last_filter_delay) > AV_NOSYNC_THRESHOLD / 10.0)
1899 is->frame_last_filter_delay = 0;
1901 avfilter_copy_buf_props(frame, picref);
1903 pts_int = picref->pts;
1904 tb = filt_out->inputs[0]->time_base;
1906 frame->opaque = picref;
1908 if (av_cmp_q(tb, is->video_st->time_base)) {
1909 av_unused int64_t pts1 = pts_int;
1910 pts_int = av_rescale_q(pts_int, tb, is->video_st->time_base);
1911 av_dlog(NULL, "video_thread(): "
1912 "tb:%d/%d pts:%"PRId64" -> tb:%d/%d pts:%"PRId64"\n",
1913 tb.num, tb.den, pts1,
1914 is->video_st->time_base.num, is->video_st->time_base.den, pts_int);
1916 pts = pts_int * av_q2d(is->video_st->time_base);
1917 ret = queue_picture(is, frame, pts, pos, serial);
1920 pts = pts_int * av_q2d(is->video_st->time_base);
1921 ret = queue_picture(is, frame, pts, pkt.pos, serial);
1928 avcodec_flush_buffers(is->video_st->codec);
1930 avfilter_graph_free(&graph);
1932 av_free_packet(&pkt);
1933 avcodec_free_frame(&frame);
1937 static int subtitle_thread(void *arg)
1939 VideoState *is = arg;
1941 AVPacket pkt1, *pkt = &pkt1;
1945 int r, g, b, y, u, v, a;
1948 while (is->paused && !is->subtitleq.abort_request) {
1951 if (packet_queue_get(&is->subtitleq, pkt, 1, NULL) < 0)
1954 if (pkt->data == flush_pkt.data) {
1955 avcodec_flush_buffers(is->subtitle_st->codec);
1958 SDL_LockMutex(is->subpq_mutex);
1959 while (is->subpq_size >= SUBPICTURE_QUEUE_SIZE &&
1960 !is->subtitleq.abort_request) {
1961 SDL_CondWait(is->subpq_cond, is->subpq_mutex);
1963 SDL_UnlockMutex(is->subpq_mutex);
1965 if (is->subtitleq.abort_request)
1968 sp = &is->subpq[is->subpq_windex];
1970 /* NOTE: ipts is the PTS of the _first_ picture beginning in
1971 this packet, if any */
1973 if (pkt->pts != AV_NOPTS_VALUE)
1974 pts = av_q2d(is->subtitle_st->time_base) * pkt->pts;
1976 avcodec_decode_subtitle2(is->subtitle_st->codec, &sp->sub,
1977 &got_subtitle, pkt);
1978 if (got_subtitle && sp->sub.format == 0) {
1979 if (sp->sub.pts != AV_NOPTS_VALUE)
1980 pts = sp->sub.pts / (double)AV_TIME_BASE;
1983 for (i = 0; i < sp->sub.num_rects; i++)
1985 for (j = 0; j < sp->sub.rects[i]->nb_colors; j++)
1987 RGBA_IN(r, g, b, a, (uint32_t*)sp->sub.rects[i]->pict.data[1] + j);
1988 y = RGB_TO_Y_CCIR(r, g, b);
1989 u = RGB_TO_U_CCIR(r, g, b, 0);
1990 v = RGB_TO_V_CCIR(r, g, b, 0);
1991 YUVA_OUT((uint32_t*)sp->sub.rects[i]->pict.data[1] + j, y, u, v, a);
1995 /* now we can update the picture count */
1996 if (++is->subpq_windex == SUBPICTURE_QUEUE_SIZE)
1997 is->subpq_windex = 0;
1998 SDL_LockMutex(is->subpq_mutex);
2000 SDL_UnlockMutex(is->subpq_mutex);
2002 av_free_packet(pkt);
2007 /* copy samples for viewing in editor window */
2008 static void update_sample_display(VideoState *is, short *samples, int samples_size)
2012 size = samples_size / sizeof(short);
2014 len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
2017 memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
2019 is->sample_array_index += len;
2020 if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
2021 is->sample_array_index = 0;
2026 /* return the wanted number of samples to get better sync if sync_type is video
2027 * or external master clock */
2028 static int synchronize_audio(VideoState *is, int nb_samples)
2030 int wanted_nb_samples = nb_samples;
2032 /* if not master, then we try to remove or add samples to correct the clock */
2033 if (get_master_sync_type(is) != AV_SYNC_AUDIO_MASTER) {
2034 double diff, avg_diff;
2035 int min_nb_samples, max_nb_samples;
2037 diff = get_audio_clock(is) - get_master_clock(is);
2039 if (fabs(diff) < AV_NOSYNC_THRESHOLD) {
2040 is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
2041 if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
2042 /* not enough measures to have a correct estimate */
2043 is->audio_diff_avg_count++;
2045 /* estimate the A-V difference */
2046 avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
2048 if (fabs(avg_diff) >= is->audio_diff_threshold) {
2049 wanted_nb_samples = nb_samples + (int)(diff * is->audio_src.freq);
2050 min_nb_samples = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100));
2051 max_nb_samples = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100));
2052 wanted_nb_samples = FFMIN(FFMAX(wanted_nb_samples, min_nb_samples), max_nb_samples);
2054 av_dlog(NULL, "diff=%f adiff=%f sample_diff=%d apts=%0.3f vpts=%0.3f %f\n",
2055 diff, avg_diff, wanted_nb_samples - nb_samples,
2056 is->audio_clock, is->video_clock, is->audio_diff_threshold);
2059 /* too big difference : may be initial PTS errors, so
2061 is->audio_diff_avg_count = 0;
2062 is->audio_diff_cum = 0;
2066 return wanted_nb_samples;
2069 /* decode one audio frame and returns its uncompressed size */
2070 static int audio_decode_frame(VideoState *is, double *pts_ptr)
2072 AVPacket *pkt_temp = &is->audio_pkt_temp;
2073 AVPacket *pkt = &is->audio_pkt;
2074 AVCodecContext *dec = is->audio_st->codec;
2075 int len1, len2, data_size, resampled_data_size;
2076 int64_t dec_channel_layout;
2080 int flush_complete = 0;
2081 int wanted_nb_samples;
2084 /* NOTE: the audio packet can contain several frames */
2085 while (pkt_temp->size > 0 || (!pkt_temp->data && new_packet)) {
2087 if (!(is->frame = avcodec_alloc_frame()))
2088 return AVERROR(ENOMEM);
2090 avcodec_get_frame_defaults(is->frame);
2098 len1 = avcodec_decode_audio4(dec, is->frame, &got_frame, pkt_temp);
2100 /* if error, we skip the frame */
2105 pkt_temp->data += len1;
2106 pkt_temp->size -= len1;
2109 /* stop sending empty packets if the decoder is finished */
2110 if (!pkt_temp->data && dec->codec->capabilities & CODEC_CAP_DELAY)
2114 data_size = av_samples_get_buffer_size(NULL, is->frame->channels,
2115 is->frame->nb_samples,
2116 is->frame->format, 1);
2118 dec_channel_layout =
2119 (is->frame->channel_layout && is->frame->channels == av_get_channel_layout_nb_channels(is->frame->channel_layout)) ?
2120 is->frame->channel_layout : av_get_default_channel_layout(is->frame->channels);
2121 wanted_nb_samples = synchronize_audio(is, is->frame->nb_samples);
2123 if (is->frame->format != is->audio_src.fmt ||
2124 dec_channel_layout != is->audio_src.channel_layout ||
2125 is->frame->sample_rate != is->audio_src.freq ||
2126 (wanted_nb_samples != is->frame->nb_samples && !is->swr_ctx)) {
2127 swr_free(&is->swr_ctx);
2128 is->swr_ctx = swr_alloc_set_opts(NULL,
2129 is->audio_tgt.channel_layout, is->audio_tgt.fmt, is->audio_tgt.freq,
2130 dec_channel_layout, is->frame->format, is->frame->sample_rate,
2132 if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
2133 fprintf(stderr, "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
2134 is->frame->sample_rate, av_get_sample_fmt_name(is->frame->format), (int)is->frame->channels,
2135 is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);
2138 is->audio_src.channel_layout = dec_channel_layout;
2139 is->audio_src.channels = is->frame->channels;
2140 is->audio_src.freq = is->frame->sample_rate;
2141 is->audio_src.fmt = is->frame->format;
2145 const uint8_t **in = (const uint8_t **)is->frame->extended_data;
2146 uint8_t *out[] = {is->audio_buf2};
2147 int out_count = sizeof(is->audio_buf2) / is->audio_tgt.channels / av_get_bytes_per_sample(is->audio_tgt.fmt);
2148 if (wanted_nb_samples != is->frame->nb_samples) {
2149 if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * is->audio_tgt.freq / is->frame->sample_rate,
2150 wanted_nb_samples * is->audio_tgt.freq / is->frame->sample_rate) < 0) {
2151 fprintf(stderr, "swr_set_compensation() failed\n");
2155 len2 = swr_convert(is->swr_ctx, out, out_count, in, is->frame->nb_samples);
2157 fprintf(stderr, "swr_convert() failed\n");
2160 if (len2 == out_count) {
2161 fprintf(stderr, "warning: audio buffer is probably too small\n");
2162 swr_init(is->swr_ctx);
2164 is->audio_buf = is->audio_buf2;
2165 resampled_data_size = len2 * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
2167 is->audio_buf = is->frame->data[0];
2168 resampled_data_size = data_size;
2171 /* if no pts, then compute it */
2172 pts = is->audio_clock;
2174 is->audio_clock += (double)data_size /
2175 (is->frame->channels * is->frame->sample_rate * av_get_bytes_per_sample(is->frame->format));
2178 static double last_clock;
2179 printf("audio: delay=%0.3f clock=%0.3f pts=%0.3f\n",
2180 is->audio_clock - last_clock,
2181 is->audio_clock, pts);
2182 last_clock = is->audio_clock;
2185 return resampled_data_size;
2188 /* free the current packet */
2190 av_free_packet(pkt);
2191 memset(pkt_temp, 0, sizeof(*pkt_temp));
2193 if (is->paused || is->audioq.abort_request) {
2197 if (is->audioq.nb_packets == 0)
2198 SDL_CondSignal(is->continue_read_thread);
2200 /* read next packet */
2201 if ((new_packet = packet_queue_get(&is->audioq, pkt, 1, &is->audio_pkt_temp_serial)) < 0)
2204 if (pkt->data == flush_pkt.data) {
2205 avcodec_flush_buffers(dec);
2211 /* if update the audio clock with the pts */
2212 if (pkt->pts != AV_NOPTS_VALUE) {
2213 is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts;
2218 /* prepare a new audio buffer */
2219 static void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
2221 VideoState *is = opaque;
2222 int audio_size, len1;
2224 int frame_size = av_samples_get_buffer_size(NULL, is->audio_tgt.channels, 1, is->audio_tgt.fmt, 1);
2227 audio_callback_time = av_gettime();
2230 if (is->audio_buf_index >= is->audio_buf_size) {
2231 audio_size = audio_decode_frame(is, &pts);
2232 if (audio_size < 0) {
2233 /* if error, just output silence */
2234 is->audio_buf = is->silence_buf;
2235 is->audio_buf_size = sizeof(is->silence_buf) / frame_size * frame_size;
2237 if (is->show_mode != SHOW_MODE_VIDEO)
2238 update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
2239 is->audio_buf_size = audio_size;
2241 is->audio_buf_index = 0;
2243 len1 = is->audio_buf_size - is->audio_buf_index;
2246 memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
2249 is->audio_buf_index += len1;
2251 bytes_per_sec = is->audio_tgt.freq * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
2252 is->audio_write_buf_size = is->audio_buf_size - is->audio_buf_index;
2253 /* Let's assume the audio driver that is used by SDL has two periods. */
2254 is->audio_current_pts = is->audio_clock - (double)(2 * is->audio_hw_buf_size + is->audio_write_buf_size) / bytes_per_sec;
2255 is->audio_current_pts_drift = is->audio_current_pts - audio_callback_time / 1000000.0;
2256 if (is->audioq.serial == is->audio_pkt_temp_serial)
2257 check_external_clock_sync(is, is->audio_current_pts);
2260 static int audio_open(void *opaque, int64_t wanted_channel_layout, int wanted_nb_channels, int wanted_sample_rate, struct AudioParams *audio_hw_params)
2262 SDL_AudioSpec wanted_spec, spec;
2264 const int next_nb_channels[] = {0, 0, 1, 6, 2, 6, 4, 6};
2266 env = SDL_getenv("SDL_AUDIO_CHANNELS");
2268 wanted_nb_channels = atoi(env);
2269 wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
2271 if (!wanted_channel_layout || wanted_nb_channels != av_get_channel_layout_nb_channels(wanted_channel_layout)) {
2272 wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
2273 wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
2275 wanted_spec.channels = av_get_channel_layout_nb_channels(wanted_channel_layout);
2276 wanted_spec.freq = wanted_sample_rate;
2277 if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
2278 fprintf(stderr, "Invalid sample rate or channel count!\n");
2281 wanted_spec.format = AUDIO_S16SYS;
2282 wanted_spec.silence = 0;
2283 wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
2284 wanted_spec.callback = sdl_audio_callback;
2285 wanted_spec.userdata = opaque;
2286 while (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
2287 fprintf(stderr, "SDL_OpenAudio (%d channels): %s\n", wanted_spec.channels, SDL_GetError());
2288 wanted_spec.channels = next_nb_channels[FFMIN(7, wanted_spec.channels)];
2289 if (!wanted_spec.channels) {
2290 fprintf(stderr, "No more channel combinations to try, audio open failed\n");
2293 wanted_channel_layout = av_get_default_channel_layout(wanted_spec.channels);
2295 if (spec.format != AUDIO_S16SYS) {
2296 fprintf(stderr, "SDL advised audio format %d is not supported!\n", spec.format);
2299 if (spec.channels != wanted_spec.channels) {
2300 wanted_channel_layout = av_get_default_channel_layout(spec.channels);
2301 if (!wanted_channel_layout) {
2302 fprintf(stderr, "SDL advised channel count %d is not supported!\n", spec.channels);
2307 audio_hw_params->fmt = AV_SAMPLE_FMT_S16;
2308 audio_hw_params->freq = spec.freq;
2309 audio_hw_params->channel_layout = wanted_channel_layout;
2310 audio_hw_params->channels = spec.channels;
2314 /* open a given stream. Return 0 if OK */
2315 static int stream_component_open(VideoState *is, int stream_index)
2317 AVFormatContext *ic = is->ic;
2318 AVCodecContext *avctx;
2320 const char *forced_codec_name = NULL;
2322 AVDictionaryEntry *t = NULL;
2324 if (stream_index < 0 || stream_index >= ic->nb_streams)
2326 avctx = ic->streams[stream_index]->codec;
2328 codec = avcodec_find_decoder(avctx->codec_id);
2330 switch(avctx->codec_type){
2331 case AVMEDIA_TYPE_AUDIO : is->last_audio_stream = stream_index; forced_codec_name = audio_codec_name; break;
2332 case AVMEDIA_TYPE_SUBTITLE: is->last_subtitle_stream = stream_index; forced_codec_name = subtitle_codec_name; break;
2333 case AVMEDIA_TYPE_VIDEO : is->last_video_stream = stream_index; forced_codec_name = video_codec_name; break;
2335 if (forced_codec_name)
2336 codec = avcodec_find_decoder_by_name(forced_codec_name);
2338 if (forced_codec_name) fprintf(stderr, "No codec could be found with name '%s'\n", forced_codec_name);
2339 else fprintf(stderr, "No codec could be found with id %d\n", avctx->codec_id);
2343 avctx->codec_id = codec->id;
2344 avctx->workaround_bugs = workaround_bugs;
2345 avctx->lowres = lowres;
2346 if(avctx->lowres > codec->max_lowres){
2347 av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
2349 avctx->lowres= codec->max_lowres;
2351 avctx->idct_algo = idct;
2352 avctx->skip_frame = skip_frame;
2353 avctx->skip_idct = skip_idct;
2354 avctx->skip_loop_filter = skip_loop_filter;
2355 avctx->error_concealment = error_concealment;
2357 if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
2358 if (fast) avctx->flags2 |= CODEC_FLAG2_FAST;
2359 if(codec->capabilities & CODEC_CAP_DR1)
2360 avctx->flags |= CODEC_FLAG_EMU_EDGE;
2362 opts = filter_codec_opts(codec_opts, avctx->codec_id, ic, ic->streams[stream_index], codec);
2363 if (!av_dict_get(opts, "threads", NULL, 0))
2364 av_dict_set(&opts, "threads", "auto", 0);
2365 if (avcodec_open2(avctx, codec, &opts) < 0)
2367 if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2368 av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
2369 return AVERROR_OPTION_NOT_FOUND;
2372 /* prepare audio output */
2373 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
2374 int audio_hw_buf_size = audio_open(is, avctx->channel_layout, avctx->channels, avctx->sample_rate, &is->audio_src);
2375 if (audio_hw_buf_size < 0)
2377 is->audio_hw_buf_size = audio_hw_buf_size;
2378 is->audio_tgt = is->audio_src;
2381 ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
2382 switch (avctx->codec_type) {
2383 case AVMEDIA_TYPE_AUDIO:
2384 is->audio_stream = stream_index;
2385 is->audio_st = ic->streams[stream_index];
2386 is->audio_buf_size = 0;
2387 is->audio_buf_index = 0;
2389 /* init averaging filter */
2390 is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
2391 is->audio_diff_avg_count = 0;
2392 /* since we do not have a precise anough audio fifo fullness,
2393 we correct audio sync only if larger than this threshold */
2394 is->audio_diff_threshold = 2.0 * is->audio_hw_buf_size / av_samples_get_buffer_size(NULL, is->audio_tgt.channels, is->audio_tgt.freq, is->audio_tgt.fmt, 1);
2396 memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
2397 memset(&is->audio_pkt_temp, 0, sizeof(is->audio_pkt_temp));
2398 packet_queue_start(&is->audioq);
2401 case AVMEDIA_TYPE_VIDEO:
2402 is->video_stream = stream_index;
2403 is->video_st = ic->streams[stream_index];
2405 packet_queue_start(&is->videoq);
2406 is->video_tid = SDL_CreateThread(video_thread, is);
2408 case AVMEDIA_TYPE_SUBTITLE:
2409 is->subtitle_stream = stream_index;
2410 is->subtitle_st = ic->streams[stream_index];
2411 packet_queue_start(&is->subtitleq);
2413 is->subtitle_tid = SDL_CreateThread(subtitle_thread, is);
2421 static void stream_component_close(VideoState *is, int stream_index)
2423 AVFormatContext *ic = is->ic;
2424 AVCodecContext *avctx;
2426 if (stream_index < 0 || stream_index >= ic->nb_streams)
2428 avctx = ic->streams[stream_index]->codec;
2430 switch (avctx->codec_type) {
2431 case AVMEDIA_TYPE_AUDIO:
2432 packet_queue_abort(&is->audioq);
2436 packet_queue_flush(&is->audioq);
2437 av_free_packet(&is->audio_pkt);
2438 swr_free(&is->swr_ctx);
2439 av_freep(&is->audio_buf1);
2440 is->audio_buf = NULL;
2441 avcodec_free_frame(&is->frame);
2444 av_rdft_end(is->rdft);
2445 av_freep(&is->rdft_data);
2450 case AVMEDIA_TYPE_VIDEO:
2451 packet_queue_abort(&is->videoq);
2453 /* note: we also signal this mutex to make sure we deblock the
2454 video thread in all cases */
2455 SDL_LockMutex(is->pictq_mutex);
2456 SDL_CondSignal(is->pictq_cond);
2457 SDL_UnlockMutex(is->pictq_mutex);
2459 SDL_WaitThread(is->video_tid, NULL);
2461 packet_queue_flush(&is->videoq);
2463 case AVMEDIA_TYPE_SUBTITLE:
2464 packet_queue_abort(&is->subtitleq);
2466 /* note: we also signal this mutex to make sure we deblock the
2467 video thread in all cases */
2468 SDL_LockMutex(is->subpq_mutex);
2469 is->subtitle_stream_changed = 1;
2471 SDL_CondSignal(is->subpq_cond);
2472 SDL_UnlockMutex(is->subpq_mutex);
2474 SDL_WaitThread(is->subtitle_tid, NULL);
2476 packet_queue_flush(&is->subtitleq);
2482 ic->streams[stream_index]->discard = AVDISCARD_ALL;
2483 avcodec_close(avctx);
2485 free_buffer_pool(&is->buffer_pool);
2487 switch (avctx->codec_type) {
2488 case AVMEDIA_TYPE_AUDIO:
2489 is->audio_st = NULL;
2490 is->audio_stream = -1;
2492 case AVMEDIA_TYPE_VIDEO:
2493 is->video_st = NULL;
2494 is->video_stream = -1;
2496 case AVMEDIA_TYPE_SUBTITLE:
2497 is->subtitle_st = NULL;
2498 is->subtitle_stream = -1;
2505 static int decode_interrupt_cb(void *ctx)
2507 VideoState *is = ctx;
2508 return is->abort_request;
2511 static int is_realtime(AVFormatContext *s)
2513 if( !strcmp(s->iformat->name, "rtp")
2514 || !strcmp(s->iformat->name, "rtsp")
2515 || !strcmp(s->iformat->name, "sdp")
2519 if(s->pb && ( !strncmp(s->filename, "rtp:", 4)
2520 || !strncmp(s->filename, "udp:", 4)
2527 /* this thread gets the stream from the disk or the network */
2528 static int read_thread(void *arg)
2530 VideoState *is = arg;
2531 AVFormatContext *ic = NULL;
2533 int st_index[AVMEDIA_TYPE_NB];
2534 AVPacket pkt1, *pkt = &pkt1;
2536 int pkt_in_play_range = 0;
2537 AVDictionaryEntry *t;
2538 AVDictionary **opts;
2539 int orig_nb_streams;
2540 SDL_mutex *wait_mutex = SDL_CreateMutex();
2542 memset(st_index, -1, sizeof(st_index));
2543 is->last_video_stream = is->video_stream = -1;
2544 is->last_audio_stream = is->audio_stream = -1;
2545 is->last_subtitle_stream = is->subtitle_stream = -1;
2547 ic = avformat_alloc_context();
2548 ic->interrupt_callback.callback = decode_interrupt_cb;
2549 ic->interrupt_callback.opaque = is;
2550 err = avformat_open_input(&ic, is->filename, is->iformat, &format_opts);
2552 print_error(is->filename, err);
2556 if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2557 av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
2558 ret = AVERROR_OPTION_NOT_FOUND;
2564 ic->flags |= AVFMT_FLAG_GENPTS;
2566 opts = setup_find_stream_info_opts(ic, codec_opts);
2567 orig_nb_streams = ic->nb_streams;
2569 err = avformat_find_stream_info(ic, opts);
2571 fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
2575 for (i = 0; i < orig_nb_streams; i++)
2576 av_dict_free(&opts[i]);
2580 ic->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
2582 if (seek_by_bytes < 0)
2583 seek_by_bytes = !!(ic->iformat->flags & AVFMT_TS_DISCONT);
2585 is->max_frame_duration = (ic->iformat->flags & AVFMT_TS_DISCONT) ? 10.0 : 3600.0;
2587 /* if seeking requested, we execute it */
2588 if (start_time != AV_NOPTS_VALUE) {
2591 timestamp = start_time;
2592 /* add the stream start time */
2593 if (ic->start_time != AV_NOPTS_VALUE)
2594 timestamp += ic->start_time;
2595 ret = avformat_seek_file(ic, -1, INT64_MIN, timestamp, INT64_MAX, 0);
2597 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2598 is->filename, (double)timestamp / AV_TIME_BASE);
2602 is->realtime = is_realtime(ic);
2604 for (i = 0; i < ic->nb_streams; i++)
2605 ic->streams[i]->discard = AVDISCARD_ALL;
2607 st_index[AVMEDIA_TYPE_VIDEO] =
2608 av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO,
2609 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
2611 st_index[AVMEDIA_TYPE_AUDIO] =
2612 av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO,
2613 wanted_stream[AVMEDIA_TYPE_AUDIO],
2614 st_index[AVMEDIA_TYPE_VIDEO],
2617 st_index[AVMEDIA_TYPE_SUBTITLE] =
2618 av_find_best_stream(ic, AVMEDIA_TYPE_SUBTITLE,
2619 wanted_stream[AVMEDIA_TYPE_SUBTITLE],
2620 (st_index[AVMEDIA_TYPE_AUDIO] >= 0 ?
2621 st_index[AVMEDIA_TYPE_AUDIO] :
2622 st_index[AVMEDIA_TYPE_VIDEO]),
2625 av_dump_format(ic, 0, is->filename, 0);
2628 is->show_mode = show_mode;
2630 /* open the streams */
2631 if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
2632 stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);
2636 if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
2637 ret = stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);
2639 is->refresh_tid = SDL_CreateThread(refresh_thread, is);
2640 if (is->show_mode == SHOW_MODE_NONE)
2641 is->show_mode = ret >= 0 ? SHOW_MODE_VIDEO : SHOW_MODE_RDFT;
2643 if (st_index[AVMEDIA_TYPE_SUBTITLE] >= 0) {
2644 stream_component_open(is, st_index[AVMEDIA_TYPE_SUBTITLE]);
2647 if (is->video_stream < 0 && is->audio_stream < 0) {
2648 fprintf(stderr, "%s: could not open codecs\n", is->filename);
2653 if (infinite_buffer < 0 && is->realtime)
2654 infinite_buffer = 1;
2657 if (is->abort_request)
2659 if (is->paused != is->last_paused) {
2660 is->last_paused = is->paused;
2662 is->read_pause_return = av_read_pause(ic);
2666 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
2668 (!strcmp(ic->iformat->name, "rtsp") ||
2669 (ic->pb && !strncmp(input_filename, "mmsh:", 5)))) {
2670 /* wait 10 ms to avoid trying to get another packet */
2677 int64_t seek_target = is->seek_pos;
2678 int64_t seek_min = is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;
2679 int64_t seek_max = is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;
2680 // FIXME the +-2 is due to rounding being not done in the correct direction in generation
2681 // of the seek_pos/seek_rel variables
2683 ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);
2685 fprintf(stderr, "%s: error while seeking\n", is->ic->filename);
2687 if (is->audio_stream >= 0) {
2688 packet_queue_flush(&is->audioq);
2689 packet_queue_put(&is->audioq, &flush_pkt);
2691 if (is->subtitle_stream >= 0) {
2692 packet_queue_flush(&is->subtitleq);
2693 packet_queue_put(&is->subtitleq, &flush_pkt);
2695 if (is->video_stream >= 0) {
2696 packet_queue_flush(&is->videoq);
2697 packet_queue_put(&is->videoq, &flush_pkt);
2699 if (is->seek_flags & AVSEEK_FLAG_BYTE) {
2700 //FIXME: use a cleaner way to signal obsolete external clock...
2701 update_external_clock_pts(is, (double)AV_NOPTS_VALUE);
2703 update_external_clock_pts(is, seek_target / (double)AV_TIME_BASE);
2709 if (is->queue_attachments_req) {
2710 avformat_queue_attached_pictures(ic);
2711 is->queue_attachments_req = 0;
2714 /* if the queue are full, no need to read more */
2715 if (infinite_buffer<1 &&
2716 (is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE
2717 || ( (is->audioq .nb_packets > MIN_FRAMES || is->audio_stream < 0 || is->audioq.abort_request)
2718 && (is->videoq .nb_packets > MIN_FRAMES || is->video_stream < 0 || is->videoq.abort_request)
2719 && (is->subtitleq.nb_packets > MIN_FRAMES || is->subtitle_stream < 0 || is->subtitleq.abort_request)))) {
2721 SDL_LockMutex(wait_mutex);
2722 SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
2723 SDL_UnlockMutex(wait_mutex);
2727 if (is->video_stream >= 0) {
2728 av_init_packet(pkt);
2731 pkt->stream_index = is->video_stream;
2732 packet_queue_put(&is->videoq, pkt);
2734 if (is->audio_stream >= 0 &&
2735 is->audio_st->codec->codec->capabilities & CODEC_CAP_DELAY) {
2736 av_init_packet(pkt);
2739 pkt->stream_index = is->audio_stream;
2740 packet_queue_put(&is->audioq, pkt);
2743 if (is->audioq.size + is->videoq.size + is->subtitleq.size == 0) {
2744 if (loop != 1 && (!loop || --loop)) {
2745 stream_seek(is, start_time != AV_NOPTS_VALUE ? start_time : 0, 0, 0);
2746 } else if (autoexit) {
2754 ret = av_read_frame(ic, pkt);
2756 if (ret == AVERROR_EOF || url_feof(ic->pb))
2758 if (ic->pb && ic->pb->error)
2760 SDL_LockMutex(wait_mutex);
2761 SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
2762 SDL_UnlockMutex(wait_mutex);
2765 /* check if packet is in play range specified by user, then queue, otherwise discard */
2766 pkt_in_play_range = duration == AV_NOPTS_VALUE ||
2767 (pkt->pts - ic->streams[pkt->stream_index]->start_time) *
2768 av_q2d(ic->streams[pkt->stream_index]->time_base) -
2769 (double)(start_time != AV_NOPTS_VALUE ? start_time : 0) / 1000000
2770 <= ((double)duration / 1000000);
2771 if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {
2772 packet_queue_put(&is->audioq, pkt);
2773 } else if (pkt->stream_index == is->video_stream && pkt_in_play_range) {
2774 packet_queue_put(&is->videoq, pkt);
2775 } else if (pkt->stream_index == is->subtitle_stream && pkt_in_play_range) {
2776 packet_queue_put(&is->subtitleq, pkt);
2778 av_free_packet(pkt);
2781 /* wait until the end */
2782 while (!is->abort_request) {
2788 /* close each stream */
2789 if (is->audio_stream >= 0)
2790 stream_component_close(is, is->audio_stream);
2791 if (is->video_stream >= 0)
2792 stream_component_close(is, is->video_stream);
2793 if (is->subtitle_stream >= 0)
2794 stream_component_close(is, is->subtitle_stream);
2796 avformat_close_input(&is->ic);
2802 event.type = FF_QUIT_EVENT;
2803 event.user.data1 = is;
2804 SDL_PushEvent(&event);
2806 SDL_DestroyMutex(wait_mutex);
2810 static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
2814 is = av_mallocz(sizeof(VideoState));
2817 av_strlcpy(is->filename, filename, sizeof(is->filename));
2818 is->iformat = iformat;
2822 /* start video display */
2823 is->pictq_mutex = SDL_CreateMutex();
2824 is->pictq_cond = SDL_CreateCond();
2826 is->subpq_mutex = SDL_CreateMutex();
2827 is->subpq_cond = SDL_CreateCond();
2829 packet_queue_init(&is->videoq);
2830 packet_queue_init(&is->audioq);
2831 packet_queue_init(&is->subtitleq);
2833 is->continue_read_thread = SDL_CreateCond();
2835 //FIXME: use a cleaner way to signal obsolete external clock...
2836 update_external_clock_pts(is, (double)AV_NOPTS_VALUE);
2837 update_external_clock_speed(is, 1.0);
2838 is->audio_current_pts_drift = -av_gettime() / 1000000.0;
2839 is->video_current_pts_drift = is->audio_current_pts_drift;
2840 is->av_sync_type = av_sync_type;
2841 is->read_tid = SDL_CreateThread(read_thread, is);
2842 if (!is->read_tid) {
2849 static void stream_cycle_channel(VideoState *is, int codec_type)
2851 AVFormatContext *ic = is->ic;
2852 int start_index, stream_index;
2856 if (codec_type == AVMEDIA_TYPE_VIDEO) {
2857 start_index = is->last_video_stream;
2858 old_index = is->video_stream;
2859 } else if (codec_type == AVMEDIA_TYPE_AUDIO) {
2860 start_index = is->last_audio_stream;
2861 old_index = is->audio_stream;
2863 start_index = is->last_subtitle_stream;
2864 old_index = is->subtitle_stream;
2866 stream_index = start_index;
2868 if (++stream_index >= is->ic->nb_streams)
2870 if (codec_type == AVMEDIA_TYPE_SUBTITLE)
2873 is->last_subtitle_stream = -1;
2876 if (start_index == -1)
2880 if (stream_index == start_index)
2882 st = ic->streams[stream_index];
2883 if (st->codec->codec_type == codec_type) {
2884 /* check that parameters are OK */
2885 switch (codec_type) {
2886 case AVMEDIA_TYPE_AUDIO:
2887 if (st->codec->sample_rate != 0 &&
2888 st->codec->channels != 0)
2891 case AVMEDIA_TYPE_VIDEO:
2892 case AVMEDIA_TYPE_SUBTITLE:
2900 stream_component_close(is, old_index);
2901 stream_component_open(is, stream_index);
2902 if (codec_type == AVMEDIA_TYPE_VIDEO)
2903 is->queue_attachments_req = 1;
2907 static void toggle_full_screen(VideoState *is)
2909 #if defined(__APPLE__) && SDL_VERSION_ATLEAST(1, 2, 14)
2910 /* OS X needs to reallocate the SDL overlays */
2912 for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++)
2913 is->pictq[i].reallocate = 1;
2915 is_full_screen = !is_full_screen;
2919 static void toggle_pause(VideoState *is)
2921 stream_toggle_pause(is);
2925 static void step_to_next_frame(VideoState *is)
2927 /* if the stream is paused unpause it, then step */
2929 stream_toggle_pause(is);
2933 static void toggle_audio_display(VideoState *is)
2935 int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
2936 is->show_mode = (is->show_mode + 1) % SHOW_MODE_NB;
2937 fill_rectangle(screen,
2938 is->xleft, is->ytop, is->width, is->height,
2942 /* handle an event sent by the GUI */
2943 static void event_loop(VideoState *cur_stream)
2946 double incr, pos, frac;
2950 SDL_WaitEvent(&event);
2951 switch (event.type) {
2953 if (exit_on_keydown) {
2954 do_exit(cur_stream);
2957 switch (event.key.keysym.sym) {
2960 do_exit(cur_stream);
2963 toggle_full_screen(cur_stream);
2964 cur_stream->force_refresh = 1;
2968 toggle_pause(cur_stream);
2970 case SDLK_s: // S: Step to next frame
2971 step_to_next_frame(cur_stream);
2974 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
2977 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
2980 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
2983 toggle_audio_display(cur_stream);
2984 cur_stream->force_refresh = 1;
3004 if (seek_by_bytes) {
3005 if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos >= 0) {
3006 pos = cur_stream->video_current_pos;
3007 } else if (cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos >= 0) {
3008 pos = cur_stream->audio_pkt.pos;
3010 pos = avio_tell(cur_stream->ic->pb);
3011 if (cur_stream->ic->bit_rate)
3012 incr *= cur_stream->ic->bit_rate / 8.0;
3016 stream_seek(cur_stream, pos, incr, 1);
3018 pos = get_master_clock(cur_stream);
3020 if (cur_stream->ic->start_time != AV_NOPTS_VALUE && pos < cur_stream->ic->start_time / (double)AV_TIME_BASE)
3021 pos = cur_stream->ic->start_time / (double)AV_TIME_BASE;
3022 stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);
3029 case SDL_VIDEOEXPOSE:
3030 cur_stream->force_refresh = 1;
3032 case SDL_MOUSEBUTTONDOWN:
3033 if (exit_on_mousedown) {
3034 do_exit(cur_stream);
3037 case SDL_MOUSEMOTION:
3038 if (cursor_hidden) {
3042 cursor_last_shown = av_gettime();
3043 if (event.type == SDL_MOUSEBUTTONDOWN) {
3046 if (event.motion.state != SDL_PRESSED)
3050 if (seek_by_bytes || cur_stream->ic->duration <= 0) {
3051 uint64_t size = avio_size(cur_stream->ic->pb);
3052 stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);
3056 int tns, thh, tmm, tss;
3057 tns = cur_stream->ic->duration / 1000000LL;
3059 tmm = (tns % 3600) / 60;
3061 frac = x / cur_stream->width;
3064 mm = (ns % 3600) / 60;
3066 fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n", frac*100,
3067 hh, mm, ss, thh, tmm, tss);
3068 ts = frac * cur_stream->ic->duration;
3069 if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
3070 ts += cur_stream->ic->start_time;
3071 stream_seek(cur_stream, ts, 0, 0);
3074 case SDL_VIDEORESIZE:
3075 screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
3076 SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
3077 screen_width = cur_stream->width = event.resize.w;
3078 screen_height = cur_stream->height = event.resize.h;
3079 cur_stream->force_refresh = 1;
3083 do_exit(cur_stream);
3085 case FF_ALLOC_EVENT:
3086 alloc_picture(event.user.data1);
3088 case FF_REFRESH_EVENT:
3089 if (!cursor_hidden && av_gettime() - cursor_last_shown > CURSOR_HIDE_DELAY) {
3093 video_refresh(event.user.data1);
3094 cur_stream->refresh = 0;
3102 static int opt_frame_size(void *optctx, const char *opt, const char *arg)
3104 av_log(NULL, AV_LOG_WARNING, "Option -s is deprecated, use -video_size.\n");
3105 return opt_default(NULL, "video_size", arg);
3108 static int opt_width(void *optctx, const char *opt, const char *arg)
3110 screen_width = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
3114 static int opt_height(void *optctx, const char *opt, const char *arg)
3116 screen_height = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
3120 static int opt_format(void *optctx, const char *opt, const char *arg)
3122 file_iformat = av_find_input_format(arg);
3123 if (!file_iformat) {
3124 fprintf(stderr, "Unknown input format: %s\n", arg);
3125 return AVERROR(EINVAL);
3130 static int opt_frame_pix_fmt(void *optctx, const char *opt, const char *arg)
3132 av_log(NULL, AV_LOG_WARNING, "Option -pix_fmt is deprecated, use -pixel_format.\n");
3133 return opt_default(NULL, "pixel_format", arg);
3136 static int opt_sync(void *optctx, const char *opt, const char *arg)
3138 if (!strcmp(arg, "audio"))
3139 av_sync_type = AV_SYNC_AUDIO_MASTER;
3140 else if (!strcmp(arg, "video"))
3141 av_sync_type = AV_SYNC_VIDEO_MASTER;
3142 else if (!strcmp(arg, "ext"))
3143 av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
3145 fprintf(stderr, "Unknown value for %s: %s\n", opt, arg);
3151 static int opt_seek(void *optctx, const char *opt, const char *arg)
3153 start_time = parse_time_or_die(opt, arg, 1);
3157 static int opt_duration(void *optctx, const char *opt, const char *arg)
3159 duration = parse_time_or_die(opt, arg, 1);
3163 static int opt_show_mode(void *optctx, const char *opt, const char *arg)
3165 show_mode = !strcmp(arg, "video") ? SHOW_MODE_VIDEO :
3166 !strcmp(arg, "waves") ? SHOW_MODE_WAVES :
3167 !strcmp(arg, "rdft" ) ? SHOW_MODE_RDFT :
3168 parse_number_or_die(opt, arg, OPT_INT, 0, SHOW_MODE_NB-1);
3172 static void opt_input_file(void *optctx, const char *filename)
3174 if (input_filename) {
3175 fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
3176 filename, input_filename);
3179 if (!strcmp(filename, "-"))
3181 input_filename = filename;
3184 static int opt_codec(void *optctx, const char *opt, const char *arg)
3186 const char *spec = strchr(opt, ':');
3188 fprintf(stderr, "No media specifier was specified in '%s' in option '%s'\n",
3190 return AVERROR(EINVAL);
3194 case 'a' : audio_codec_name = arg; break;
3195 case 's' : subtitle_codec_name = arg; break;
3196 case 'v' : video_codec_name = arg; break;
3198 fprintf(stderr, "Invalid media specifier '%s' in option '%s'\n", spec, opt);
3199 return AVERROR(EINVAL);
3206 static const OptionDef options[] = {
3207 #include "cmdutils_common_opts.h"
3208 { "x", HAS_ARG, { .func_arg = opt_width }, "force displayed width", "width" },
3209 { "y", HAS_ARG, { .func_arg = opt_height }, "force displayed height", "height" },
3210 { "s", HAS_ARG | OPT_VIDEO, { .func_arg = opt_frame_size }, "set frame size (WxH or abbreviation)", "size" },
3211 { "fs", OPT_BOOL, { &is_full_screen }, "force full screen" },
3212 { "an", OPT_BOOL, { &audio_disable }, "disable audio" },
3213 { "vn", OPT_BOOL, { &video_disable }, "disable video" },
3214 { "ast", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_AUDIO] }, "select desired audio stream", "stream_number" },
3215 { "vst", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_VIDEO] }, "select desired video stream", "stream_number" },
3216 { "sst", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_SUBTITLE] }, "select desired subtitle stream", "stream_number" },
3217 { "ss", HAS_ARG, { .func_arg = opt_seek }, "seek to a given position in seconds", "pos" },
3218 { "t", HAS_ARG, { .func_arg = opt_duration }, "play \"duration\" seconds of audio/video", "duration" },
3219 { "bytes", OPT_INT | HAS_ARG, { &seek_by_bytes }, "seek by bytes 0=off 1=on -1=auto", "val" },
3220 { "nodisp", OPT_BOOL, { &display_disable }, "disable graphical display" },
3221 { "f", HAS_ARG, { .func_arg = opt_format }, "force format", "fmt" },
3222 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_frame_pix_fmt }, "set pixel format", "format" },
3223 { "stats", OPT_BOOL | OPT_EXPERT, { &show_status }, "show status", "" },
3224 { "bug", OPT_INT | HAS_ARG | OPT_EXPERT, { &workaround_bugs }, "workaround bugs", "" },
3225 { "fast", OPT_BOOL | OPT_EXPERT, { &fast }, "non spec compliant optimizations", "" },
3226 { "genpts", OPT_BOOL | OPT_EXPERT, { &genpts }, "generate pts", "" },
3227 { "drp", OPT_INT | HAS_ARG | OPT_EXPERT, { &decoder_reorder_pts }, "let decoder reorder pts 0=off 1=on -1=auto", ""},
3228 { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, { &lowres }, "", "" },
3229 { "skiploop", OPT_INT | HAS_ARG | OPT_EXPERT, { &skip_loop_filter }, "", "" },
3230 { "skipframe", OPT_INT | HAS_ARG | OPT_EXPERT, { &skip_frame }, "", "" },
3231 { "skipidct", OPT_INT | HAS_ARG | OPT_EXPERT, { &skip_idct }, "", "" },
3232 { "idct", OPT_INT | HAS_ARG | OPT_EXPERT, { &idct }, "set idct algo", "algo" },
3233 { "ec", OPT_INT | HAS_ARG | OPT_EXPERT, { &error_concealment }, "set error concealment options", "bit_mask" },
3234 { "sync", HAS_ARG | OPT_EXPERT, { .func_arg = opt_sync }, "set audio-video sync. type (type=audio/video/ext)", "type" },
3235 { "autoexit", OPT_BOOL | OPT_EXPERT, { &autoexit }, "exit at the end", "" },
3236 { "exitonkeydown", OPT_BOOL | OPT_EXPERT, { &exit_on_keydown }, "exit on key down", "" },
3237 { "exitonmousedown", OPT_BOOL | OPT_EXPERT, { &exit_on_mousedown }, "exit on mouse down", "" },
3238 { "loop", OPT_INT | HAS_ARG | OPT_EXPERT, { &loop }, "set number of times the playback shall be looped", "loop count" },
3239 { "framedrop", OPT_BOOL | OPT_EXPERT, { &framedrop }, "drop frames when cpu is too slow", "" },
3240 { "infbuf", OPT_BOOL | OPT_EXPERT, { &infinite_buffer }, "don't limit the input buffer size (useful with realtime streams)", "" },
3241 { "window_title", OPT_STRING | HAS_ARG, { &window_title }, "set window title", "window title" },
3243 { "vf", OPT_STRING | HAS_ARG, { &vfilters }, "set video filters", "filter_graph" },
3245 { "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, { &rdftspeed }, "rdft speed", "msecs" },
3246 { "showmode", HAS_ARG, { .func_arg = opt_show_mode}, "select show mode (0 = video, 1 = waves, 2 = RDFT)", "mode" },
3247 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, { .func_arg = opt_default }, "generic catch all option", "" },
3248 { "i", OPT_BOOL, { &dummy}, "read specified file", "input_file"},
3249 { "codec", HAS_ARG, { .func_arg = opt_codec}, "force decoder", "decoder_name" },
3250 { "acodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &audio_codec_name }, "force audio decoder", "decoder_name" },
3251 { "scodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &subtitle_codec_name }, "force subtitle decoder", "decoder_name" },
3252 { "vcodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &video_codec_name }, "force video decoder", "decoder_name" },
3256 static void show_usage(void)
3258 av_log(NULL, AV_LOG_INFO, "Simple media player\n");
3259 av_log(NULL, AV_LOG_INFO, "usage: %s [options] input_file\n", program_name);
3260 av_log(NULL, AV_LOG_INFO, "\n");
3263 void show_help_default(const char *opt, const char *arg)
3265 av_log_set_callback(log_callback_help);
3267 show_help_options(options, "Main options:", 0, OPT_EXPERT, 0);
3268 show_help_options(options, "Advanced options:", OPT_EXPERT, 0, 0);
3270 show_help_children(avcodec_get_class(), AV_OPT_FLAG_DECODING_PARAM);
3271 show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
3272 #if !CONFIG_AVFILTER
3273 show_help_children(sws_get_class(), AV_OPT_FLAG_ENCODING_PARAM);
3275 show_help_children(avfilter_get_class(), AV_OPT_FLAG_FILTERING_PARAM);
3277 printf("\nWhile playing:\n"
3279 "f toggle full screen\n"
3281 "a cycle audio channel\n"
3282 "v cycle video channel\n"
3283 "t cycle subtitle channel\n"
3284 "w show audio waves\n"
3285 "s activate frame-step mode\n"
3286 "left/right seek backward/forward 10 seconds\n"
3287 "down/up seek backward/forward 1 minute\n"
3288 "page down/page up seek backward/forward 10 minutes\n"
3289 "mouse click seek to percentage in file corresponding to fraction of width\n"
3293 static int lockmgr(void **mtx, enum AVLockOp op)
3296 case AV_LOCK_CREATE:
3297 *mtx = SDL_CreateMutex();
3301 case AV_LOCK_OBTAIN:
3302 return !!SDL_LockMutex(*mtx);
3303 case AV_LOCK_RELEASE:
3304 return !!SDL_UnlockMutex(*mtx);
3305 case AV_LOCK_DESTROY:
3306 SDL_DestroyMutex(*mtx);
3312 /* Called from the main */
3313 int main(int argc, char **argv)
3317 char dummy_videodriver[] = "SDL_VIDEODRIVER=dummy";
3319 av_log_set_flags(AV_LOG_SKIP_REPEATED);
3320 parse_loglevel(argc, argv, options);
3322 /* register all codecs, demux and protocols */
3323 avcodec_register_all();
3325 avdevice_register_all();
3328 avfilter_register_all();
3331 avformat_network_init();
3335 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
3336 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
3338 show_banner(argc, argv, options);
3340 parse_options(NULL, argc, argv, options, opt_input_file);
3342 if (!input_filename) {
3344 fprintf(stderr, "An input file must be specified\n");
3345 fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
3349 if (display_disable) {
3352 flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
3354 flags &= ~SDL_INIT_AUDIO;
3355 if (display_disable)
3356 SDL_putenv(dummy_videodriver); /* For the event queue, we always need a video driver. */
3357 #if !defined(__MINGW32__) && !defined(__APPLE__)
3358 flags |= SDL_INIT_EVENTTHREAD; /* Not supported on Windows or Mac OS X */
3360 if (SDL_Init (flags)) {
3361 fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
3362 fprintf(stderr, "(Did you set the DISPLAY variable?)\n");
3366 if (!display_disable) {
3367 #if HAVE_SDL_VIDEO_SIZE
3368 const SDL_VideoInfo *vi = SDL_GetVideoInfo();
3369 fs_screen_width = vi->current_w;
3370 fs_screen_height = vi->current_h;
3374 SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
3375 SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
3376 SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
3378 if (av_lockmgr_register(lockmgr)) {
3379 fprintf(stderr, "Could not initialize lock manager!\n");
3383 av_init_packet(&flush_pkt);
3384 flush_pkt.data = (char *)(intptr_t)"FLUSH";
3386 is = stream_open(input_filename, file_iformat);
3388 fprintf(stderr, "Failed to initialize VideoState!\n");