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 "libavformat/avformat.h"
41 #include "libavdevice/avdevice.h"
42 #include "libswscale/swscale.h"
43 #include "libavutil/opt.h"
44 #include "libavcodec/avfft.h"
45 #include "libswresample/swresample.h"
48 # include "libavfilter/avcodec.h"
49 # include "libavfilter/avfilter.h"
50 # include "libavfilter/avfiltergraph.h"
51 # include "libavfilter/buffersink.h"
52 # include "libavfilter/buffersrc.h"
56 #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 /* we use about AUDIO_DIFF_AVG_NB A-V differences to make the average */
82 #define AUDIO_DIFF_AVG_NB 20
84 /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
85 #define SAMPLE_ARRAY_SIZE (2 * 65536)
87 static int sws_flags = SWS_BICUBIC;
89 typedef struct PacketQueue {
90 AVPacketList *first_pkt, *last_pkt;
98 #define VIDEO_PICTURE_QUEUE_SIZE 2
99 #define SUBPICTURE_QUEUE_SIZE 4
101 typedef struct VideoPicture {
102 double pts; ///< presentation time stamp for this picture
103 int64_t pos; ///< byte position in file
106 int width, height; /* source height & width */
107 AVRational sample_aspect_ratio;
112 AVFilterBufferRef *picref;
116 typedef struct SubPicture {
117 double pts; /* presentation time stamp for this picture */
121 typedef struct AudioParams {
125 enum AVSampleFormat fmt;
129 AV_SYNC_AUDIO_MASTER, /* default choice */
130 AV_SYNC_VIDEO_MASTER,
131 AV_SYNC_EXTERNAL_CLOCK, /* synchronize to an external clock */
134 typedef struct VideoState {
135 SDL_Thread *read_tid;
136 SDL_Thread *video_tid;
137 SDL_Thread *refresh_tid;
138 AVInputFormat *iformat;
148 int read_pause_return;
154 double external_clock; /* external clock base */
155 int64_t external_clock_time;
158 double audio_diff_cum; /* used for AV difference average computation */
159 double audio_diff_avg_coef;
160 double audio_diff_threshold;
161 int audio_diff_avg_count;
164 int audio_hw_buf_size;
165 DECLARE_ALIGNED(16,uint8_t,audio_buf2)[AVCODEC_MAX_AUDIO_FRAME_SIZE * 4];
166 uint8_t silence_buf[SDL_AUDIO_BUFFER_SIZE];
169 unsigned int audio_buf_size; /* in bytes */
170 int audio_buf_index; /* in bytes */
171 int audio_write_buf_size;
172 AVPacket audio_pkt_temp;
174 struct AudioParams audio_src;
175 struct AudioParams audio_tgt;
176 struct SwrContext *swr_ctx;
177 double audio_current_pts;
178 double audio_current_pts_drift;
179 int frame_drops_early;
180 int frame_drops_late;
184 SHOW_MODE_NONE = -1, SHOW_MODE_VIDEO = 0, SHOW_MODE_WAVES, SHOW_MODE_RDFT, SHOW_MODE_NB
186 int16_t sample_array[SAMPLE_ARRAY_SIZE];
187 int sample_array_index;
191 FFTSample *rdft_data;
194 SDL_Thread *subtitle_tid;
196 int subtitle_stream_changed;
197 AVStream *subtitle_st;
198 PacketQueue subtitleq;
199 SubPicture subpq[SUBPICTURE_QUEUE_SIZE];
200 int subpq_size, subpq_rindex, subpq_windex;
201 SDL_mutex *subpq_mutex;
202 SDL_cond *subpq_cond;
205 double frame_last_pts;
206 double frame_last_duration;
207 double frame_last_dropped_pts;
208 double frame_last_returned_time;
209 double frame_last_filter_delay;
210 int64_t frame_last_dropped_pos;
211 double video_clock; ///< pts of last decoded frame / predicted pts of next decoded frame
215 double video_current_pts; ///< current displayed pts (different from video_clock if frame fifos are used)
216 double video_current_pts_drift; ///< video_current_pts - time (av_gettime) at which we updated video_current_pts - used to have running video pts
217 int64_t video_current_pos; ///< current displayed file pos
218 VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
219 int pictq_size, pictq_rindex, pictq_windex;
220 SDL_mutex *pictq_mutex;
221 SDL_cond *pictq_cond;
223 struct SwsContext *img_convert_ctx;
227 int width, height, xleft, ytop;
231 AVFilterContext *in_video_filter; ///< the first filter in the video chain
232 AVFilterContext *out_video_filter; ///< the last filter in the video chain
234 FrameBuffer *buffer_pool;
238 int last_video_stream, last_audio_stream, last_subtitle_stream;
241 typedef struct AllocEventProps {
246 static int opt_help(const char *opt, const char *arg);
248 /* options specified by the user */
249 static AVInputFormat *file_iformat;
250 static const char *input_filename;
251 static const char *window_title;
252 static int fs_screen_width;
253 static int fs_screen_height;
254 static int screen_width = 0;
255 static int screen_height = 0;
256 static int audio_disable;
257 static int video_disable;
258 static int wanted_stream[AVMEDIA_TYPE_NB] = {
259 [AVMEDIA_TYPE_AUDIO] = -1,
260 [AVMEDIA_TYPE_VIDEO] = -1,
261 [AVMEDIA_TYPE_SUBTITLE] = -1,
263 static int seek_by_bytes = -1;
264 static int display_disable;
265 static int show_status = 1;
266 static int av_sync_type = AV_SYNC_AUDIO_MASTER;
267 static int64_t start_time = AV_NOPTS_VALUE;
268 static int64_t duration = AV_NOPTS_VALUE;
269 static int workaround_bugs = 1;
271 static int genpts = 0;
272 static int lowres = 0;
273 static int idct = FF_IDCT_AUTO;
274 static enum AVDiscard skip_frame = AVDISCARD_DEFAULT;
275 static enum AVDiscard skip_idct = AVDISCARD_DEFAULT;
276 static enum AVDiscard skip_loop_filter = AVDISCARD_DEFAULT;
277 static int error_concealment = 3;
278 static int decoder_reorder_pts = -1;
280 static int exit_on_keydown;
281 static int exit_on_mousedown;
283 static int framedrop = -1;
284 static enum ShowMode show_mode = SHOW_MODE_NONE;
285 static const char *audio_codec_name;
286 static const char *subtitle_codec_name;
287 static const char *video_codec_name;
288 static int rdftspeed = 20;
290 static char *vfilters = NULL;
293 /* current context */
294 static int is_full_screen;
295 static int64_t audio_callback_time;
297 static AVPacket flush_pkt;
299 #define FF_ALLOC_EVENT (SDL_USEREVENT)
300 #define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
301 #define FF_QUIT_EVENT (SDL_USEREVENT + 2)
303 static SDL_Surface *screen;
305 void av_noreturn exit_program(int ret)
310 static int packet_queue_put_private(PacketQueue *q, AVPacket *pkt)
314 if (q->abort_request)
317 pkt1 = av_malloc(sizeof(AVPacketList));
326 q->last_pkt->next = pkt1;
329 q->size += pkt1->pkt.size + sizeof(*pkt1);
330 /* XXX: should duplicate packet data in DV case */
331 SDL_CondSignal(q->cond);
335 static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
339 /* duplicate the packet */
340 if (pkt != &flush_pkt && av_dup_packet(pkt) < 0)
343 SDL_LockMutex(q->mutex);
344 ret = packet_queue_put_private(q, pkt);
345 SDL_UnlockMutex(q->mutex);
347 if (pkt != &flush_pkt && ret < 0)
353 /* packet queue handling */
354 static void packet_queue_init(PacketQueue *q)
356 memset(q, 0, sizeof(PacketQueue));
357 q->mutex = SDL_CreateMutex();
358 q->cond = SDL_CreateCond();
359 q->abort_request = 1;
362 static void packet_queue_flush(PacketQueue *q)
364 AVPacketList *pkt, *pkt1;
366 SDL_LockMutex(q->mutex);
367 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
369 av_free_packet(&pkt->pkt);
376 SDL_UnlockMutex(q->mutex);
379 static void packet_queue_destroy(PacketQueue *q)
381 packet_queue_flush(q);
382 SDL_DestroyMutex(q->mutex);
383 SDL_DestroyCond(q->cond);
386 static void packet_queue_abort(PacketQueue *q)
388 SDL_LockMutex(q->mutex);
390 q->abort_request = 1;
392 SDL_CondSignal(q->cond);
394 SDL_UnlockMutex(q->mutex);
397 static void packet_queue_start(PacketQueue *q)
399 SDL_LockMutex(q->mutex);
400 q->abort_request = 0;
401 packet_queue_put_private(q, &flush_pkt);
402 SDL_UnlockMutex(q->mutex);
405 /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
406 static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
411 SDL_LockMutex(q->mutex);
414 if (q->abort_request) {
421 q->first_pkt = pkt1->next;
425 q->size -= pkt1->pkt.size + sizeof(*pkt1);
434 SDL_CondWait(q->cond, q->mutex);
437 SDL_UnlockMutex(q->mutex);
441 static inline void fill_rectangle(SDL_Surface *screen,
442 int x, int y, int w, int h, int color)
449 SDL_FillRect(screen, &rect, color);
452 #define ALPHA_BLEND(a, oldp, newp, s)\
453 ((((oldp << s) * (255 - (a))) + (newp * (a))) / (255 << s))
455 #define RGBA_IN(r, g, b, a, s)\
457 unsigned int v = ((const uint32_t *)(s))[0];\
458 a = (v >> 24) & 0xff;\
459 r = (v >> 16) & 0xff;\
460 g = (v >> 8) & 0xff;\
464 #define YUVA_IN(y, u, v, a, s, pal)\
466 unsigned int val = ((const uint32_t *)(pal))[*(const uint8_t*)(s)];\
467 a = (val >> 24) & 0xff;\
468 y = (val >> 16) & 0xff;\
469 u = (val >> 8) & 0xff;\
473 #define YUVA_OUT(d, y, u, v, a)\
475 ((uint32_t *)(d))[0] = (a << 24) | (y << 16) | (u << 8) | v;\
481 static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw, int imgh)
483 int wrap, wrap3, width2, skip2;
484 int y, u, v, a, u1, v1, a1, w, h;
485 uint8_t *lum, *cb, *cr;
488 int dstx, dsty, dstw, dsth;
490 dstw = av_clip(rect->w, 0, imgw);
491 dsth = av_clip(rect->h, 0, imgh);
492 dstx = av_clip(rect->x, 0, imgw - dstw);
493 dsty = av_clip(rect->y, 0, imgh - dsth);
494 lum = dst->data[0] + dsty * dst->linesize[0];
495 cb = dst->data[1] + (dsty >> 1) * dst->linesize[1];
496 cr = dst->data[2] + (dsty >> 1) * dst->linesize[2];
498 width2 = ((dstw + 1) >> 1) + (dstx & ~dstw & 1);
500 wrap = dst->linesize[0];
501 wrap3 = rect->pict.linesize[0];
502 p = rect->pict.data[0];
503 pal = (const uint32_t *)rect->pict.data[1]; /* Now in YCrCb! */
511 YUVA_IN(y, u, v, a, p, pal);
512 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
513 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
514 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
520 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
521 YUVA_IN(y, u, v, a, p, pal);
525 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
527 YUVA_IN(y, u, v, a, p + BPP, pal);
531 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
532 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
533 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
540 YUVA_IN(y, u, v, a, p, pal);
541 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
542 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
543 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
547 p += wrap3 - dstw * BPP;
548 lum += wrap - dstw - dstx;
549 cb += dst->linesize[1] - width2 - skip2;
550 cr += dst->linesize[2] - width2 - skip2;
552 for (h = dsth - (dsty & 1); h >= 2; h -= 2) {
558 YUVA_IN(y, u, v, a, p, pal);
562 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
565 YUVA_IN(y, u, v, a, p, pal);
569 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
570 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
571 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
577 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
578 YUVA_IN(y, u, v, a, p, pal);
582 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
584 YUVA_IN(y, u, v, a, p + BPP, pal);
588 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
592 YUVA_IN(y, u, v, a, p, pal);
596 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
598 YUVA_IN(y, u, v, a, p + BPP, pal);
602 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
604 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 2);
605 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 2);
609 p += -wrap3 + 2 * BPP;
613 YUVA_IN(y, u, v, a, p, pal);
617 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
620 YUVA_IN(y, u, v, a, p, pal);
624 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
625 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
626 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
632 p += wrap3 + (wrap3 - dstw * BPP);
633 lum += wrap + (wrap - dstw - dstx);
634 cb += dst->linesize[1] - width2 - skip2;
635 cr += dst->linesize[2] - width2 - skip2;
637 /* handle odd height */
644 YUVA_IN(y, u, v, a, p, pal);
645 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
646 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
647 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
653 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
654 YUVA_IN(y, u, v, a, p, pal);
658 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
660 YUVA_IN(y, u, v, a, p + BPP, pal);
664 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
665 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u, 1);
666 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v, 1);
673 YUVA_IN(y, u, v, a, p, pal);
674 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
675 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
676 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
681 static void free_subpicture(SubPicture *sp)
683 avsubtitle_free(&sp->sub);
686 static void video_image_display(VideoState *is)
692 int width, height, x, y;
696 vp = &is->pictq[is->pictq_rindex];
698 if (vp->sample_aspect_ratio.num == 0)
701 aspect_ratio = av_q2d(vp->sample_aspect_ratio);
703 if (aspect_ratio <= 0.0)
705 aspect_ratio *= (float)vp->width / (float)vp->height;
707 if (is->subtitle_st) {
708 if (is->subpq_size > 0) {
709 sp = &is->subpq[is->subpq_rindex];
711 if (vp->pts >= sp->pts + ((float) sp->sub.start_display_time / 1000)) {
712 SDL_LockYUVOverlay (vp->bmp);
714 pict.data[0] = vp->bmp->pixels[0];
715 pict.data[1] = vp->bmp->pixels[2];
716 pict.data[2] = vp->bmp->pixels[1];
718 pict.linesize[0] = vp->bmp->pitches[0];
719 pict.linesize[1] = vp->bmp->pitches[2];
720 pict.linesize[2] = vp->bmp->pitches[1];
722 for (i = 0; i < sp->sub.num_rects; i++)
723 blend_subrect(&pict, sp->sub.rects[i],
724 vp->bmp->w, vp->bmp->h);
726 SDL_UnlockYUVOverlay (vp->bmp);
732 /* XXX: we suppose the screen has a 1.0 pixel ratio */
734 width = ((int)rint(height * aspect_ratio)) & ~1;
735 if (width > is->width) {
737 height = ((int)rint(width / aspect_ratio)) & ~1;
739 x = (is->width - width) / 2;
740 y = (is->height - height) / 2;
741 is->no_background = 0;
742 rect.x = is->xleft + x;
743 rect.y = is->ytop + y;
744 rect.w = FFMAX(width, 1);
745 rect.h = FFMAX(height, 1);
746 SDL_DisplayYUVOverlay(vp->bmp, &rect);
750 static inline int compute_mod(int a, int b)
752 return a < 0 ? a%b + b : a%b;
755 static void video_audio_display(VideoState *s)
757 int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
758 int ch, channels, h, h2, bgcolor, fgcolor;
760 int rdft_bits, nb_freq;
762 for (rdft_bits = 1; (1 << rdft_bits) < 2 * s->height; rdft_bits++)
764 nb_freq = 1 << (rdft_bits - 1);
766 /* compute display index : center on currently output samples */
767 channels = s->audio_tgt.channels;
768 nb_display_channels = channels;
770 int data_used= s->show_mode == SHOW_MODE_WAVES ? s->width : (2*nb_freq);
772 delay = s->audio_write_buf_size;
775 /* to be more precise, we take into account the time spent since
776 the last buffer computation */
777 if (audio_callback_time) {
778 time_diff = av_gettime() - audio_callback_time;
779 delay -= (time_diff * s->audio_tgt.freq) / 1000000;
782 delay += 2 * data_used;
783 if (delay < data_used)
786 i_start= x = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
787 if (s->show_mode == SHOW_MODE_WAVES) {
789 for (i = 0; i < 1000; i += channels) {
790 int idx = (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;
791 int a = s->sample_array[idx];
792 int b = s->sample_array[(idx + 4 * channels) % SAMPLE_ARRAY_SIZE];
793 int c = s->sample_array[(idx + 5 * channels) % SAMPLE_ARRAY_SIZE];
794 int d = s->sample_array[(idx + 9 * channels) % SAMPLE_ARRAY_SIZE];
796 if (h < score && (b ^ c) < 0) {
803 s->last_i_start = i_start;
805 i_start = s->last_i_start;
808 bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
809 if (s->show_mode == SHOW_MODE_WAVES) {
810 fill_rectangle(screen,
811 s->xleft, s->ytop, s->width, s->height,
814 fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);
816 /* total height for one channel */
817 h = s->height / nb_display_channels;
818 /* graph height / 2 */
820 for (ch = 0; ch < nb_display_channels; ch++) {
822 y1 = s->ytop + ch * h + (h / 2); /* position of center line */
823 for (x = 0; x < s->width; x++) {
824 y = (s->sample_array[i] * h2) >> 15;
831 fill_rectangle(screen,
832 s->xleft + x, ys, 1, y,
835 if (i >= SAMPLE_ARRAY_SIZE)
836 i -= SAMPLE_ARRAY_SIZE;
840 fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);
842 for (ch = 1; ch < nb_display_channels; ch++) {
843 y = s->ytop + ch * h;
844 fill_rectangle(screen,
845 s->xleft, y, s->width, 1,
848 SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
850 nb_display_channels= FFMIN(nb_display_channels, 2);
851 if (rdft_bits != s->rdft_bits) {
852 av_rdft_end(s->rdft);
853 av_free(s->rdft_data);
854 s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
855 s->rdft_bits = rdft_bits;
856 s->rdft_data = av_malloc(4 * nb_freq * sizeof(*s->rdft_data));
860 for (ch = 0; ch < nb_display_channels; ch++) {
861 data[ch] = s->rdft_data + 2 * nb_freq * ch;
863 for (x = 0; x < 2 * nb_freq; x++) {
864 double w = (x-nb_freq) * (1.0 / nb_freq);
865 data[ch][x] = s->sample_array[i] * (1.0 - w * w);
867 if (i >= SAMPLE_ARRAY_SIZE)
868 i -= SAMPLE_ARRAY_SIZE;
870 av_rdft_calc(s->rdft, data[ch]);
872 // least efficient way to do this, we should of course directly access it but its more than fast enough
873 for (y = 0; y < s->height; y++) {
874 double w = 1 / sqrt(nb_freq);
875 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]));
876 int b = (nb_display_channels == 2 ) ? sqrt(w * sqrt(data[1][2 * y + 0] * data[1][2 * y + 0]
877 + data[1][2 * y + 1] * data[1][2 * y + 1])) : a;
880 fgcolor = SDL_MapRGB(screen->format, a, b, (a + b) / 2);
882 fill_rectangle(screen,
883 s->xpos, s->height-y, 1, 1,
887 SDL_UpdateRect(screen, s->xpos, s->ytop, 1, s->height);
890 if (s->xpos >= s->width)
895 static void stream_close(VideoState *is)
899 /* XXX: use a special url_shutdown call to abort parse cleanly */
900 is->abort_request = 1;
901 SDL_WaitThread(is->read_tid, NULL);
902 SDL_WaitThread(is->refresh_tid, NULL);
903 packet_queue_destroy(&is->videoq);
904 packet_queue_destroy(&is->audioq);
905 packet_queue_destroy(&is->subtitleq);
907 /* free all pictures */
908 for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++) {
912 avfilter_unref_buffer(vp->picref);
917 SDL_FreeYUVOverlay(vp->bmp);
921 SDL_DestroyMutex(is->pictq_mutex);
922 SDL_DestroyCond(is->pictq_cond);
923 SDL_DestroyMutex(is->subpq_mutex);
924 SDL_DestroyCond(is->subpq_cond);
926 if (is->img_convert_ctx)
927 sws_freeContext(is->img_convert_ctx);
932 static void do_exit(VideoState *is)
937 av_lockmgr_register(NULL);
942 avformat_network_deinit();
946 av_log(NULL, AV_LOG_QUIET, "%s", "");
950 static void sigterm_handler(int sig)
955 static int video_open(VideoState *is, int force_set_video_mode)
957 int flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;
959 VideoPicture *vp = &is->pictq[is->pictq_rindex];
961 if (is_full_screen) flags |= SDL_FULLSCREEN;
962 else flags |= SDL_RESIZABLE;
964 if (is_full_screen && fs_screen_width) {
966 h = fs_screen_height;
967 } else if (!is_full_screen && screen_width) {
970 } else if (vp->width) {
977 if (screen && is->width == screen->w && screen->w == w
978 && is->height== screen->h && screen->h == h && !force_set_video_mode)
980 screen = SDL_SetVideoMode(w, h, 0, flags);
982 fprintf(stderr, "SDL: could not set video mode - exiting\n");
986 window_title = input_filename;
987 SDL_WM_SetCaption(window_title, window_title);
989 is->width = screen->w;
990 is->height = screen->h;
995 /* display the current picture, if any */
996 static void video_display(VideoState *is)
1000 if (is->audio_st && is->show_mode != SHOW_MODE_VIDEO)
1001 video_audio_display(is);
1002 else if (is->video_st)
1003 video_image_display(is);
1006 static int refresh_thread(void *opaque)
1008 VideoState *is= opaque;
1009 while (!is->abort_request) {
1011 event.type = FF_REFRESH_EVENT;
1012 event.user.data1 = opaque;
1013 if (!is->refresh && (!is->paused || is->force_refresh)) {
1015 SDL_PushEvent(&event);
1017 //FIXME ideally we should wait the correct time but SDLs event passing is so slow it would be silly
1018 usleep(is->audio_st && is->show_mode != SHOW_MODE_VIDEO ? rdftspeed*1000 : 5000);
1023 /* get the current audio clock value */
1024 static double get_audio_clock(VideoState *is)
1027 return is->audio_current_pts;
1029 return is->audio_current_pts_drift + av_gettime() / 1000000.0;
1033 /* get the current video clock value */
1034 static double get_video_clock(VideoState *is)
1037 return is->video_current_pts;
1039 return is->video_current_pts_drift + av_gettime() / 1000000.0;
1043 /* get the current external clock value */
1044 static double get_external_clock(VideoState *is)
1048 return is->external_clock + ((ti - is->external_clock_time) * 1e-6);
1051 /* get the current master clock value */
1052 static double get_master_clock(VideoState *is)
1056 if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
1058 val = get_video_clock(is);
1060 val = get_audio_clock(is);
1061 } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
1063 val = get_audio_clock(is);
1065 val = get_video_clock(is);
1067 val = get_external_clock(is);
1072 /* seek in the stream */
1073 static void stream_seek(VideoState *is, int64_t pos, int64_t rel, int seek_by_bytes)
1075 if (!is->seek_req) {
1078 is->seek_flags &= ~AVSEEK_FLAG_BYTE;
1080 is->seek_flags |= AVSEEK_FLAG_BYTE;
1085 /* pause or resume the video */
1086 static void stream_toggle_pause(VideoState *is)
1089 is->frame_timer += av_gettime() / 1000000.0 + is->video_current_pts_drift - is->video_current_pts;
1090 if (is->read_pause_return != AVERROR(ENOSYS)) {
1091 is->video_current_pts = is->video_current_pts_drift + av_gettime() / 1000000.0;
1093 is->video_current_pts_drift = is->video_current_pts - av_gettime() / 1000000.0;
1095 is->paused = !is->paused;
1098 static double compute_target_delay(double delay, VideoState *is)
1100 double sync_threshold, diff;
1102 /* update delay to follow master synchronisation source */
1103 if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) ||
1104 is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
1105 /* if video is slave, we try to correct big delays by
1106 duplicating or deleting a frame */
1107 diff = get_video_clock(is) - get_master_clock(is);
1109 /* skip or repeat frame. We take into account the
1110 delay to compute the threshold. I still don't know
1111 if it is the best guess */
1112 sync_threshold = FFMAX(AV_SYNC_THRESHOLD, delay);
1113 if (fabs(diff) < AV_NOSYNC_THRESHOLD) {
1114 if (diff <= -sync_threshold)
1116 else if (diff >= sync_threshold)
1121 av_dlog(NULL, "video: delay=%0.3f A-V=%f\n",
1127 static void pictq_next_picture(VideoState *is) {
1128 /* update queue size and signal for next picture */
1129 if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
1130 is->pictq_rindex = 0;
1132 SDL_LockMutex(is->pictq_mutex);
1134 SDL_CondSignal(is->pictq_cond);
1135 SDL_UnlockMutex(is->pictq_mutex);
1138 static void update_video_pts(VideoState *is, double pts, int64_t pos) {
1139 double time = av_gettime() / 1000000.0;
1140 /* update current video pts */
1141 is->video_current_pts = pts;
1142 is->video_current_pts_drift = is->video_current_pts - time;
1143 is->video_current_pos = pos;
1144 is->frame_last_pts = pts;
1147 /* called to display each frame */
1148 static void video_refresh(void *opaque)
1150 VideoState *is = opaque;
1154 SubPicture *sp, *sp2;
1158 if (is->pictq_size == 0) {
1159 SDL_LockMutex(is->pictq_mutex);
1160 if (is->frame_last_dropped_pts != AV_NOPTS_VALUE && is->frame_last_dropped_pts > is->frame_last_pts) {
1161 update_video_pts(is, is->frame_last_dropped_pts, is->frame_last_dropped_pos);
1162 is->frame_last_dropped_pts = AV_NOPTS_VALUE;
1164 SDL_UnlockMutex(is->pictq_mutex);
1165 // nothing to do, no picture to display in the que
1167 double last_duration, duration, delay;
1168 /* dequeue the picture */
1169 vp = &is->pictq[is->pictq_rindex];
1172 pictq_next_picture(is);
1179 /* compute nominal last_duration */
1180 last_duration = vp->pts - is->frame_last_pts;
1181 if (last_duration > 0 && last_duration < 10.0) {
1182 /* if duration of the last frame was sane, update last_duration in video state */
1183 is->frame_last_duration = last_duration;
1185 delay = compute_target_delay(is->frame_last_duration, is);
1187 time= av_gettime()/1000000.0;
1188 if (time < is->frame_timer + delay)
1192 is->frame_timer += delay * FFMAX(1, floor((time-is->frame_timer) / delay));
1194 SDL_LockMutex(is->pictq_mutex);
1195 update_video_pts(is, vp->pts, vp->pos);
1196 SDL_UnlockMutex(is->pictq_mutex);
1198 if (is->pictq_size > 1) {
1199 VideoPicture *nextvp = &is->pictq[(is->pictq_rindex + 1) % VIDEO_PICTURE_QUEUE_SIZE];
1200 duration = nextvp->pts - vp->pts;
1201 if((framedrop>0 || (framedrop && is->audio_st)) && time > is->frame_timer + duration){
1202 is->frame_drops_late++;
1203 pictq_next_picture(is);
1208 if (is->subtitle_st) {
1209 if (is->subtitle_stream_changed) {
1210 SDL_LockMutex(is->subpq_mutex);
1212 while (is->subpq_size) {
1213 free_subpicture(&is->subpq[is->subpq_rindex]);
1215 /* update queue size and signal for next picture */
1216 if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
1217 is->subpq_rindex = 0;
1221 is->subtitle_stream_changed = 0;
1223 SDL_CondSignal(is->subpq_cond);
1224 SDL_UnlockMutex(is->subpq_mutex);
1226 if (is->subpq_size > 0) {
1227 sp = &is->subpq[is->subpq_rindex];
1229 if (is->subpq_size > 1)
1230 sp2 = &is->subpq[(is->subpq_rindex + 1) % SUBPICTURE_QUEUE_SIZE];
1234 if ((is->video_current_pts > (sp->pts + ((float) sp->sub.end_display_time / 1000)))
1235 || (sp2 && is->video_current_pts > (sp2->pts + ((float) sp2->sub.start_display_time / 1000))))
1237 free_subpicture(sp);
1239 /* update queue size and signal for next picture */
1240 if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
1241 is->subpq_rindex = 0;
1243 SDL_LockMutex(is->subpq_mutex);
1245 SDL_CondSignal(is->subpq_cond);
1246 SDL_UnlockMutex(is->subpq_mutex);
1253 /* display picture */
1254 if (!display_disable)
1258 pictq_next_picture(is);
1260 } else if (is->audio_st) {
1261 /* draw the next audio frame */
1263 /* if only audio stream, then display the audio bars (better
1264 than nothing, just to test the implementation */
1266 /* display picture */
1267 if (!display_disable)
1270 is->force_refresh = 0;
1272 static int64_t last_time;
1274 int aqsize, vqsize, sqsize;
1277 cur_time = av_gettime();
1278 if (!last_time || (cur_time - last_time) >= 30000) {
1283 aqsize = is->audioq.size;
1285 vqsize = is->videoq.size;
1286 if (is->subtitle_st)
1287 sqsize = is->subtitleq.size;
1289 if (is->audio_st && is->video_st)
1290 av_diff = get_audio_clock(is) - get_video_clock(is);
1291 printf("%7.2f A-V:%7.3f fd=%4d aq=%5dKB vq=%5dKB sq=%5dB f=%"PRId64"/%"PRId64" \r",
1292 get_master_clock(is),
1294 is->frame_drops_early + is->frame_drops_late,
1298 is->video_st ? is->video_st->codec->pts_correction_num_faulty_dts : 0,
1299 is->video_st ? is->video_st->codec->pts_correction_num_faulty_pts : 0);
1301 last_time = cur_time;
1306 /* allocate a picture (needs to do that in main thread to avoid
1307 potential locking problems */
1308 static void alloc_picture(AllocEventProps *event_props)
1310 VideoState *is = event_props->is;
1311 AVFrame *frame = event_props->frame;
1314 vp = &is->pictq[is->pictq_windex];
1317 SDL_FreeYUVOverlay(vp->bmp);
1321 avfilter_unref_buffer(vp->picref);
1325 vp->width = frame->width;
1326 vp->height = frame->height;
1328 video_open(event_props->is, 0);
1330 vp->bmp = SDL_CreateYUVOverlay(vp->width, vp->height,
1333 if (!vp->bmp || vp->bmp->pitches[0] < vp->width) {
1334 /* SDL allocates a buffer smaller than requested if the video
1335 * overlay hardware is unable to support the requested size. */
1336 fprintf(stderr, "Error: the video system does not support an image\n"
1337 "size of %dx%d pixels. Try using -lowres or -vf \"scale=w:h\"\n"
1338 "to reduce the image size.\n", vp->width, vp->height );
1342 SDL_LockMutex(is->pictq_mutex);
1344 SDL_CondSignal(is->pictq_cond);
1345 SDL_UnlockMutex(is->pictq_mutex);
1348 static int queue_picture(VideoState *is, AVFrame *src_frame, double pts1, int64_t pos)
1351 double frame_delay, pts = pts1;
1353 /* compute the exact PTS for the picture if it is omitted in the stream
1354 * pts1 is the dts of the pkt / pts of the frame */
1356 /* update video clock with pts, if present */
1357 is->video_clock = pts;
1359 pts = is->video_clock;
1361 /* update video clock for next frame */
1362 frame_delay = av_q2d(is->video_st->codec->time_base);
1363 /* for MPEG2, the frame can be repeated, so we update the
1364 clock accordingly */
1365 frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
1366 is->video_clock += frame_delay;
1368 #if defined(DEBUG_SYNC) && 0
1369 printf("frame_type=%c clock=%0.3f pts=%0.3f\n",
1370 av_get_picture_type_char(src_frame->pict_type), pts, pts1);
1373 /* wait until we have space to put a new picture */
1374 SDL_LockMutex(is->pictq_mutex);
1376 while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE &&
1377 !is->videoq.abort_request) {
1378 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1380 SDL_UnlockMutex(is->pictq_mutex);
1382 if (is->videoq.abort_request)
1385 vp = &is->pictq[is->pictq_windex];
1387 /* alloc or resize hardware picture buffer */
1388 if (!vp->bmp || vp->reallocate ||
1389 vp->width != src_frame->width ||
1390 vp->height != src_frame->height) {
1392 AllocEventProps event_props;
1394 event_props.frame = src_frame;
1395 event_props.is = is;
1400 /* the allocation must be done in the main thread to avoid
1401 locking problems. We wait in this block for the event to complete,
1402 so we can pass a pointer to event_props to it. */
1403 event.type = FF_ALLOC_EVENT;
1404 event.user.data1 = &event_props;
1405 SDL_PushEvent(&event);
1407 /* wait until the picture is allocated */
1408 SDL_LockMutex(is->pictq_mutex);
1409 while (!vp->allocated && !is->videoq.abort_request) {
1410 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1412 /* if the queue is aborted, we have to pop the pending ALLOC event or wait for the allocation to complete */
1413 if (is->videoq.abort_request && SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_EVENTMASK(FF_ALLOC_EVENT)) != 1) {
1414 while (!vp->allocated) {
1415 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1418 SDL_UnlockMutex(is->pictq_mutex);
1420 if (is->videoq.abort_request)
1424 /* if the frame is not skipped, then display it */
1426 AVPicture pict = { { 0 } };
1429 avfilter_unref_buffer(vp->picref);
1430 vp->picref = src_frame->opaque;
1433 /* get a pointer on the bitmap */
1434 SDL_LockYUVOverlay (vp->bmp);
1436 pict.data[0] = vp->bmp->pixels[0];
1437 pict.data[1] = vp->bmp->pixels[2];
1438 pict.data[2] = vp->bmp->pixels[1];
1440 pict.linesize[0] = vp->bmp->pitches[0];
1441 pict.linesize[1] = vp->bmp->pitches[2];
1442 pict.linesize[2] = vp->bmp->pitches[1];
1445 // FIXME use direct rendering
1446 av_picture_copy(&pict, (AVPicture *)src_frame,
1447 src_frame->format, vp->width, vp->height);
1448 vp->sample_aspect_ratio = vp->picref->video->sample_aspect_ratio;
1450 sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
1451 is->img_convert_ctx = sws_getCachedContext(is->img_convert_ctx,
1452 vp->width, vp->height, src_frame->format, vp->width, vp->height,
1453 PIX_FMT_YUV420P, sws_flags, NULL, NULL, NULL);
1454 if (is->img_convert_ctx == NULL) {
1455 fprintf(stderr, "Cannot initialize the conversion context\n");
1458 sws_scale(is->img_convert_ctx, src_frame->data, src_frame->linesize,
1459 0, vp->height, pict.data, pict.linesize);
1460 vp->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, src_frame);
1462 /* update the bitmap content */
1463 SDL_UnlockYUVOverlay(vp->bmp);
1469 /* now we can update the picture count */
1470 if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
1471 is->pictq_windex = 0;
1472 SDL_LockMutex(is->pictq_mutex);
1474 SDL_UnlockMutex(is->pictq_mutex);
1479 static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacket *pkt)
1483 if (packet_queue_get(&is->videoq, pkt, 1) < 0)
1486 if (pkt->data == flush_pkt.data) {
1487 avcodec_flush_buffers(is->video_st->codec);
1489 SDL_LockMutex(is->pictq_mutex);
1490 // Make sure there are no long delay timers (ideally we should just flush the que but thats harder)
1491 for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++) {
1492 is->pictq[i].skip = 1;
1494 while (is->pictq_size && !is->videoq.abort_request) {
1495 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1497 is->video_current_pos = -1;
1498 is->frame_last_pts = AV_NOPTS_VALUE;
1499 is->frame_last_duration = 0;
1500 is->frame_timer = (double)av_gettime() / 1000000.0;
1501 is->frame_last_dropped_pts = AV_NOPTS_VALUE;
1502 SDL_UnlockMutex(is->pictq_mutex);
1507 if(avcodec_decode_video2(is->video_st->codec, frame, &got_picture, pkt) < 0)
1513 if (decoder_reorder_pts == -1) {
1514 *pts = av_frame_get_best_effort_timestamp(frame);
1515 } else if (decoder_reorder_pts) {
1516 *pts = frame->pkt_pts;
1518 *pts = frame->pkt_dts;
1521 if (*pts == AV_NOPTS_VALUE) {
1525 if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) || is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK) &&
1526 (framedrop>0 || (framedrop && is->audio_st))) {
1527 SDL_LockMutex(is->pictq_mutex);
1528 if (is->frame_last_pts != AV_NOPTS_VALUE && *pts) {
1529 double clockdiff = get_video_clock(is) - get_master_clock(is);
1530 double dpts = av_q2d(is->video_st->time_base) * *pts;
1531 double ptsdiff = dpts - is->frame_last_pts;
1532 if (fabs(clockdiff) < AV_NOSYNC_THRESHOLD &&
1533 ptsdiff > 0 && ptsdiff < AV_NOSYNC_THRESHOLD &&
1534 clockdiff + ptsdiff - is->frame_last_filter_delay < 0) {
1535 is->frame_last_dropped_pos = pkt->pos;
1536 is->frame_last_dropped_pts = dpts;
1537 is->frame_drops_early++;
1541 SDL_UnlockMutex(is->pictq_mutex);
1550 static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const char *vfilters)
1552 static const enum PixelFormat pix_fmts[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
1553 char sws_flags_str[128];
1554 char buffersrc_args[256];
1556 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
1557 AVFilterContext *filt_src = NULL, *filt_out = NULL, *filt_format;
1558 AVCodecContext *codec = is->video_st->codec;
1560 snprintf(sws_flags_str, sizeof(sws_flags_str), "flags=%d", sws_flags);
1561 graph->scale_sws_opts = av_strdup(sws_flags_str);
1563 snprintf(buffersrc_args, sizeof(buffersrc_args),
1564 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
1565 codec->width, codec->height, codec->pix_fmt,
1566 is->video_st->time_base.num, is->video_st->time_base.den,
1567 codec->sample_aspect_ratio.num, codec->sample_aspect_ratio.den);
1569 if ((ret = avfilter_graph_create_filter(&filt_src,
1570 avfilter_get_by_name("buffer"),
1571 "ffplay_buffer", buffersrc_args, NULL,
1575 #if FF_API_OLD_VSINK_API
1576 ret = avfilter_graph_create_filter(&filt_out,
1577 avfilter_get_by_name("buffersink"),
1578 "out", NULL, pix_fmts, graph);
1580 buffersink_params->pixel_fmts = pix_fmts;
1581 ret = avfilter_graph_create_filter(&filt_out,
1582 avfilter_get_by_name("buffersink"),
1583 "out", NULL, buffersink_params, graph);
1585 av_freep(&buffersink_params);
1589 if ((ret = avfilter_graph_create_filter(&filt_format,
1590 avfilter_get_by_name("format"),
1591 "format", "yuv420p", NULL, graph)) < 0)
1593 if ((ret = avfilter_link(filt_format, 0, filt_out, 0)) < 0)
1598 AVFilterInOut *outputs = avfilter_inout_alloc();
1599 AVFilterInOut *inputs = avfilter_inout_alloc();
1601 outputs->name = av_strdup("in");
1602 outputs->filter_ctx = filt_src;
1603 outputs->pad_idx = 0;
1604 outputs->next = NULL;
1606 inputs->name = av_strdup("out");
1607 inputs->filter_ctx = filt_format;
1608 inputs->pad_idx = 0;
1609 inputs->next = NULL;
1611 if ((ret = avfilter_graph_parse(graph, vfilters, &inputs, &outputs, NULL)) < 0)
1614 if ((ret = avfilter_link(filt_src, 0, filt_format, 0)) < 0)
1618 if ((ret = avfilter_graph_config(graph, NULL)) < 0)
1621 is->in_video_filter = filt_src;
1622 is->out_video_filter = filt_out;
1624 if (codec->codec->capabilities & CODEC_CAP_DR1) {
1626 codec->get_buffer = codec_get_buffer;
1627 codec->release_buffer = codec_release_buffer;
1628 codec->opaque = &is->buffer_pool;
1634 #endif /* CONFIG_AVFILTER */
1636 static int video_thread(void *arg)
1638 VideoState *is = arg;
1639 AVFrame *frame = avcodec_alloc_frame();
1640 int64_t pts_int = AV_NOPTS_VALUE, pos = -1;
1645 AVFilterGraph *graph = avfilter_graph_alloc();
1646 AVFilterContext *filt_out = NULL, *filt_in = NULL;
1647 int last_w = is->video_st->codec->width;
1648 int last_h = is->video_st->codec->height;
1649 enum PixelFormat last_format = is->video_st->codec->pix_fmt;
1651 if ((ret = configure_video_filters(graph, is, vfilters)) < 0) {
1653 event.type = FF_QUIT_EVENT;
1654 event.user.data1 = is;
1655 SDL_PushEvent(&event);
1658 filt_in = is->in_video_filter;
1659 filt_out = is->out_video_filter;
1665 AVFilterBufferRef *picref;
1666 AVRational tb = filt_out->inputs[0]->time_base;
1668 while (is->paused && !is->videoq.abort_request)
1671 avcodec_get_frame_defaults(frame);
1672 ret = get_video_frame(is, frame, &pts_int, &pkt);
1677 av_free_packet(&pkt);
1682 if ( last_w != is->video_st->codec->width
1683 || last_h != is->video_st->codec->height
1684 || last_format != is->video_st->codec->pix_fmt) {
1685 av_log(NULL, AV_LOG_INFO, "Frame changed from size:%dx%d to size:%dx%d\n",
1686 last_w, last_h, is->video_st->codec->width, is->video_st->codec->height);
1687 avfilter_graph_free(&graph);
1688 graph = avfilter_graph_alloc();
1689 if ((ret = configure_video_filters(graph, is, vfilters)) < 0) {
1690 av_free_packet(&pkt);
1693 filt_in = is->in_video_filter;
1694 filt_out = is->out_video_filter;
1695 last_w = is->video_st->codec->width;
1696 last_h = is->video_st->codec->height;
1697 last_format = is->video_st->codec->pix_fmt;
1700 frame->pts = pts_int;
1701 frame->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, frame);
1703 FrameBuffer *buf = frame->opaque;
1704 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
1705 frame->data, frame->linesize,
1706 AV_PERM_READ | AV_PERM_PRESERVE,
1707 frame->width, frame->height,
1710 avfilter_copy_frame_props(fb, frame);
1711 fb->buf->priv = buf;
1712 fb->buf->free = filter_release_buffer;
1715 av_buffersrc_buffer(filt_in, fb);
1718 av_buffersrc_write_frame(filt_in, frame);
1720 av_free_packet(&pkt);
1723 is->frame_last_returned_time = av_gettime() / 1000000.0;
1725 ret = av_buffersink_get_buffer_ref(filt_out, &picref, 0);
1731 is->frame_last_filter_delay = av_gettime() / 1000000.0 - is->frame_last_returned_time;
1732 if (fabs(is->frame_last_filter_delay) > AV_NOSYNC_THRESHOLD / 10.0)
1733 is->frame_last_filter_delay = 0;
1735 avfilter_fill_frame_from_video_buffer_ref(frame, picref);
1737 pts_int = picref->pts;
1738 tb = filt_out->inputs[0]->time_base;
1740 frame->opaque = picref;
1742 if (av_cmp_q(tb, is->video_st->time_base)) {
1743 av_unused int64_t pts1 = pts_int;
1744 pts_int = av_rescale_q(pts_int, tb, is->video_st->time_base);
1745 av_dlog(NULL, "video_thread(): "
1746 "tb:%d/%d pts:%"PRId64" -> tb:%d/%d pts:%"PRId64"\n",
1747 tb.num, tb.den, pts1,
1748 is->video_st->time_base.num, is->video_st->time_base.den, pts_int);
1750 pts = pts_int * av_q2d(is->video_st->time_base);
1751 ret = queue_picture(is, frame, pts, pos);
1754 pts = pts_int * av_q2d(is->video_st->time_base);
1755 ret = queue_picture(is, frame, pts, pkt.pos);
1762 stream_toggle_pause(is);
1765 avcodec_flush_buffers(is->video_st->codec);
1767 av_freep(&vfilters);
1768 avfilter_graph_free(&graph);
1774 static int subtitle_thread(void *arg)
1776 VideoState *is = arg;
1778 AVPacket pkt1, *pkt = &pkt1;
1782 int r, g, b, y, u, v, a;
1785 while (is->paused && !is->subtitleq.abort_request) {
1788 if (packet_queue_get(&is->subtitleq, pkt, 1) < 0)
1791 if (pkt->data == flush_pkt.data) {
1792 avcodec_flush_buffers(is->subtitle_st->codec);
1795 SDL_LockMutex(is->subpq_mutex);
1796 while (is->subpq_size >= SUBPICTURE_QUEUE_SIZE &&
1797 !is->subtitleq.abort_request) {
1798 SDL_CondWait(is->subpq_cond, is->subpq_mutex);
1800 SDL_UnlockMutex(is->subpq_mutex);
1802 if (is->subtitleq.abort_request)
1805 sp = &is->subpq[is->subpq_windex];
1807 /* NOTE: ipts is the PTS of the _first_ picture beginning in
1808 this packet, if any */
1810 if (pkt->pts != AV_NOPTS_VALUE)
1811 pts = av_q2d(is->subtitle_st->time_base) * pkt->pts;
1813 avcodec_decode_subtitle2(is->subtitle_st->codec, &sp->sub,
1814 &got_subtitle, pkt);
1816 if (got_subtitle && sp->sub.format == 0) {
1819 for (i = 0; i < sp->sub.num_rects; i++)
1821 for (j = 0; j < sp->sub.rects[i]->nb_colors; j++)
1823 RGBA_IN(r, g, b, a, (uint32_t*)sp->sub.rects[i]->pict.data[1] + j);
1824 y = RGB_TO_Y_CCIR(r, g, b);
1825 u = RGB_TO_U_CCIR(r, g, b, 0);
1826 v = RGB_TO_V_CCIR(r, g, b, 0);
1827 YUVA_OUT((uint32_t*)sp->sub.rects[i]->pict.data[1] + j, y, u, v, a);
1831 /* now we can update the picture count */
1832 if (++is->subpq_windex == SUBPICTURE_QUEUE_SIZE)
1833 is->subpq_windex = 0;
1834 SDL_LockMutex(is->subpq_mutex);
1836 SDL_UnlockMutex(is->subpq_mutex);
1838 av_free_packet(pkt);
1843 /* copy samples for viewing in editor window */
1844 static void update_sample_display(VideoState *is, short *samples, int samples_size)
1848 size = samples_size / sizeof(short);
1850 len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
1853 memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
1855 is->sample_array_index += len;
1856 if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
1857 is->sample_array_index = 0;
1862 /* return the wanted number of samples to get better sync if sync_type is video
1863 * or external master clock */
1864 static int synchronize_audio(VideoState *is, int nb_samples)
1866 int wanted_nb_samples = nb_samples;
1868 /* if not master, then we try to remove or add samples to correct the clock */
1869 if (((is->av_sync_type == AV_SYNC_VIDEO_MASTER && is->video_st) ||
1870 is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
1871 double diff, avg_diff;
1872 int min_nb_samples, max_nb_samples;
1874 diff = get_audio_clock(is) - get_master_clock(is);
1876 if (diff < AV_NOSYNC_THRESHOLD) {
1877 is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
1878 if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
1879 /* not enough measures to have a correct estimate */
1880 is->audio_diff_avg_count++;
1882 /* estimate the A-V difference */
1883 avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
1885 if (fabs(avg_diff) >= is->audio_diff_threshold) {
1886 wanted_nb_samples = nb_samples + (int)(diff * is->audio_src.freq);
1887 min_nb_samples = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100));
1888 max_nb_samples = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100));
1889 wanted_nb_samples = FFMIN(FFMAX(wanted_nb_samples, min_nb_samples), max_nb_samples);
1891 av_dlog(NULL, "diff=%f adiff=%f sample_diff=%d apts=%0.3f vpts=%0.3f %f\n",
1892 diff, avg_diff, wanted_nb_samples - nb_samples,
1893 is->audio_clock, is->video_clock, is->audio_diff_threshold);
1896 /* too big difference : may be initial PTS errors, so
1898 is->audio_diff_avg_count = 0;
1899 is->audio_diff_cum = 0;
1903 return wanted_nb_samples;
1906 /* decode one audio frame and returns its uncompressed size */
1907 static int audio_decode_frame(VideoState *is, double *pts_ptr)
1909 AVPacket *pkt_temp = &is->audio_pkt_temp;
1910 AVPacket *pkt = &is->audio_pkt;
1911 AVCodecContext *dec = is->audio_st->codec;
1912 int len1, len2, data_size, resampled_data_size;
1913 int64_t dec_channel_layout;
1917 int flush_complete = 0;
1918 int wanted_nb_samples;
1921 /* NOTE: the audio packet can contain several frames */
1922 while (pkt_temp->size > 0 || (!pkt_temp->data && new_packet)) {
1924 if (!(is->frame = avcodec_alloc_frame()))
1925 return AVERROR(ENOMEM);
1927 avcodec_get_frame_defaults(is->frame);
1935 len1 = avcodec_decode_audio4(dec, is->frame, &got_frame, pkt_temp);
1937 /* if error, we skip the frame */
1942 pkt_temp->data += len1;
1943 pkt_temp->size -= len1;
1946 /* stop sending empty packets if the decoder is finished */
1947 if (!pkt_temp->data && dec->codec->capabilities & CODEC_CAP_DELAY)
1951 data_size = av_samples_get_buffer_size(NULL, dec->channels,
1952 is->frame->nb_samples,
1953 dec->sample_fmt, 1);
1955 dec_channel_layout = (dec->channel_layout && dec->channels == av_get_channel_layout_nb_channels(dec->channel_layout)) ? dec->channel_layout : av_get_default_channel_layout(dec->channels);
1956 wanted_nb_samples = synchronize_audio(is, is->frame->nb_samples);
1958 if (dec->sample_fmt != is->audio_src.fmt ||
1959 dec_channel_layout != is->audio_src.channel_layout ||
1960 dec->sample_rate != is->audio_src.freq ||
1961 (wanted_nb_samples != is->frame->nb_samples && !is->swr_ctx)) {
1963 swr_free(&is->swr_ctx);
1964 is->swr_ctx = swr_alloc_set_opts(NULL,
1965 is->audio_tgt.channel_layout, is->audio_tgt.fmt, is->audio_tgt.freq,
1966 dec_channel_layout, dec->sample_fmt, dec->sample_rate,
1968 if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
1969 fprintf(stderr, "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
1971 av_get_sample_fmt_name(dec->sample_fmt),
1974 av_get_sample_fmt_name(is->audio_tgt.fmt),
1975 is->audio_tgt.channels);
1978 is->audio_src.channel_layout = dec_channel_layout;
1979 is->audio_src.channels = dec->channels;
1980 is->audio_src.freq = dec->sample_rate;
1981 is->audio_src.fmt = dec->sample_fmt;
1984 resampled_data_size = data_size;
1986 const uint8_t *in[] = { is->frame->data[0] };
1987 uint8_t *out[] = {is->audio_buf2};
1988 if (wanted_nb_samples != is->frame->nb_samples) {
1989 if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * is->audio_tgt.freq / dec->sample_rate,
1990 wanted_nb_samples * is->audio_tgt.freq / dec->sample_rate) < 0) {
1991 fprintf(stderr, "swr_set_compensation() failed\n");
1995 len2 = swr_convert(is->swr_ctx, out, sizeof(is->audio_buf2) / is->audio_tgt.channels / av_get_bytes_per_sample(is->audio_tgt.fmt),
1996 in, is->frame->nb_samples);
1998 fprintf(stderr, "audio_resample() failed\n");
2001 if (len2 == sizeof(is->audio_buf2) / is->audio_tgt.channels / av_get_bytes_per_sample(is->audio_tgt.fmt)) {
2002 fprintf(stderr, "warning: audio buffer is probably too small\n");
2003 swr_init(is->swr_ctx);
2005 is->audio_buf = is->audio_buf2;
2006 resampled_data_size = len2 * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
2008 is->audio_buf = is->frame->data[0];
2011 /* if no pts, then compute it */
2012 pts = is->audio_clock;
2014 is->audio_clock += (double)data_size /
2015 (dec->channels * dec->sample_rate * av_get_bytes_per_sample(dec->sample_fmt));
2018 static double last_clock;
2019 printf("audio: delay=%0.3f clock=%0.3f pts=%0.3f\n",
2020 is->audio_clock - last_clock,
2021 is->audio_clock, pts);
2022 last_clock = is->audio_clock;
2025 return resampled_data_size;
2028 /* free the current packet */
2030 av_free_packet(pkt);
2031 memset(pkt_temp, 0, sizeof(*pkt_temp));
2033 if (is->paused || is->audioq.abort_request) {
2037 /* read next packet */
2038 if ((new_packet = packet_queue_get(&is->audioq, pkt, 1)) < 0)
2041 if (pkt->data == flush_pkt.data) {
2042 avcodec_flush_buffers(dec);
2048 /* if update the audio clock with the pts */
2049 if (pkt->pts != AV_NOPTS_VALUE) {
2050 is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts;
2055 /* prepare a new audio buffer */
2056 static void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
2058 VideoState *is = opaque;
2059 int audio_size, len1;
2061 int frame_size = av_samples_get_buffer_size(NULL, is->audio_tgt.channels, 1, is->audio_tgt.fmt, 1);
2064 audio_callback_time = av_gettime();
2067 if (is->audio_buf_index >= is->audio_buf_size) {
2068 audio_size = audio_decode_frame(is, &pts);
2069 if (audio_size < 0) {
2070 /* if error, just output silence */
2071 is->audio_buf = is->silence_buf;
2072 is->audio_buf_size = sizeof(is->silence_buf) / frame_size * frame_size;
2074 if (is->show_mode != SHOW_MODE_VIDEO)
2075 update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
2076 is->audio_buf_size = audio_size;
2078 is->audio_buf_index = 0;
2080 len1 = is->audio_buf_size - is->audio_buf_index;
2083 memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
2086 is->audio_buf_index += len1;
2088 bytes_per_sec = is->audio_tgt.freq * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
2089 is->audio_write_buf_size = is->audio_buf_size - is->audio_buf_index;
2090 /* Let's assume the audio driver that is used by SDL has two periods. */
2091 is->audio_current_pts = is->audio_clock - (double)(2 * is->audio_hw_buf_size + is->audio_write_buf_size) / bytes_per_sec;
2092 is->audio_current_pts_drift = is->audio_current_pts - audio_callback_time / 1000000.0;
2095 static int audio_open(void *opaque, int64_t wanted_channel_layout, int wanted_nb_channels, int wanted_sample_rate, struct AudioParams *audio_hw_params)
2097 SDL_AudioSpec wanted_spec, spec;
2099 const int next_nb_channels[] = {0, 0, 1, 6, 2, 6, 4, 6};
2101 env = SDL_getenv("SDL_AUDIO_CHANNELS");
2103 wanted_nb_channels = SDL_atoi(env);
2104 wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
2106 if (!wanted_channel_layout || wanted_nb_channels != av_get_channel_layout_nb_channels(wanted_channel_layout)) {
2107 wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
2108 wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
2110 wanted_spec.channels = av_get_channel_layout_nb_channels(wanted_channel_layout);
2111 wanted_spec.freq = wanted_sample_rate;
2112 if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
2113 fprintf(stderr, "Invalid sample rate or channel count!\n");
2116 wanted_spec.format = AUDIO_S16SYS;
2117 wanted_spec.silence = 0;
2118 wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
2119 wanted_spec.callback = sdl_audio_callback;
2120 wanted_spec.userdata = opaque;
2121 while (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
2122 fprintf(stderr, "SDL_OpenAudio (%d channels): %s\n", wanted_spec.channels, SDL_GetError());
2123 wanted_spec.channels = next_nb_channels[FFMIN(7, wanted_spec.channels)];
2124 if (!wanted_spec.channels) {
2125 fprintf(stderr, "No more channel combinations to try, audio open failed\n");
2128 wanted_channel_layout = av_get_default_channel_layout(wanted_spec.channels);
2130 if (spec.format != AUDIO_S16SYS) {
2131 fprintf(stderr, "SDL advised audio format %d is not supported!\n", spec.format);
2134 if (spec.channels != wanted_spec.channels) {
2135 wanted_channel_layout = av_get_default_channel_layout(spec.channels);
2136 if (!wanted_channel_layout) {
2137 fprintf(stderr, "SDL advised channel count %d is not supported!\n", spec.channels);
2142 audio_hw_params->fmt = AV_SAMPLE_FMT_S16;
2143 audio_hw_params->freq = spec.freq;
2144 audio_hw_params->channel_layout = wanted_channel_layout;
2145 audio_hw_params->channels = spec.channels;
2149 /* open a given stream. Return 0 if OK */
2150 static int stream_component_open(VideoState *is, int stream_index)
2152 AVFormatContext *ic = is->ic;
2153 AVCodecContext *avctx;
2156 AVDictionaryEntry *t = NULL;
2158 if (stream_index < 0 || stream_index >= ic->nb_streams)
2160 avctx = ic->streams[stream_index]->codec;
2162 codec = avcodec_find_decoder(avctx->codec_id);
2163 opts = filter_codec_opts(codec_opts, codec, ic, ic->streams[stream_index]);
2165 switch(avctx->codec_type){
2166 case AVMEDIA_TYPE_AUDIO : is->last_audio_stream = stream_index; if(audio_codec_name ) codec= avcodec_find_decoder_by_name( audio_codec_name); break;
2167 case AVMEDIA_TYPE_SUBTITLE: is->last_subtitle_stream = stream_index; if(subtitle_codec_name) codec= avcodec_find_decoder_by_name(subtitle_codec_name); break;
2168 case AVMEDIA_TYPE_VIDEO : is->last_video_stream = stream_index; if(video_codec_name ) codec= avcodec_find_decoder_by_name( video_codec_name); break;
2173 avctx->workaround_bugs = workaround_bugs;
2174 avctx->lowres = lowres;
2175 if(avctx->lowres > codec->max_lowres){
2176 av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
2178 avctx->lowres= codec->max_lowres;
2180 avctx->idct_algo = idct;
2181 avctx->skip_frame = skip_frame;
2182 avctx->skip_idct = skip_idct;
2183 avctx->skip_loop_filter = skip_loop_filter;
2184 avctx->error_concealment = error_concealment;
2186 if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
2187 if (fast) avctx->flags2 |= CODEC_FLAG2_FAST;
2188 if(codec->capabilities & CODEC_CAP_DR1)
2189 avctx->flags |= CODEC_FLAG_EMU_EDGE;
2191 if (!av_dict_get(opts, "threads", NULL, 0))
2192 av_dict_set(&opts, "threads", "auto", 0);
2194 avcodec_open2(avctx, codec, &opts) < 0)
2196 if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2197 av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
2198 return AVERROR_OPTION_NOT_FOUND;
2201 /* prepare audio output */
2202 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
2203 int audio_hw_buf_size = audio_open(is, avctx->channel_layout, avctx->channels, avctx->sample_rate, &is->audio_src);
2204 if (audio_hw_buf_size < 0)
2206 is->audio_hw_buf_size = audio_hw_buf_size;
2207 is->audio_tgt = is->audio_src;
2210 ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
2211 switch (avctx->codec_type) {
2212 case AVMEDIA_TYPE_AUDIO:
2213 is->audio_stream = stream_index;
2214 is->audio_st = ic->streams[stream_index];
2215 is->audio_buf_size = 0;
2216 is->audio_buf_index = 0;
2218 /* init averaging filter */
2219 is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
2220 is->audio_diff_avg_count = 0;
2221 /* since we do not have a precise anough audio fifo fullness,
2222 we correct audio sync only if larger than this threshold */
2223 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);
2225 memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
2226 memset(&is->audio_pkt_temp, 0, sizeof(is->audio_pkt_temp));
2227 packet_queue_start(&is->audioq);
2230 case AVMEDIA_TYPE_VIDEO:
2231 is->video_stream = stream_index;
2232 is->video_st = ic->streams[stream_index];
2234 packet_queue_start(&is->videoq);
2235 is->video_tid = SDL_CreateThread(video_thread, is);
2237 case AVMEDIA_TYPE_SUBTITLE:
2238 is->subtitle_stream = stream_index;
2239 is->subtitle_st = ic->streams[stream_index];
2240 packet_queue_start(&is->subtitleq);
2242 is->subtitle_tid = SDL_CreateThread(subtitle_thread, is);
2250 static void stream_component_close(VideoState *is, int stream_index)
2252 AVFormatContext *ic = is->ic;
2253 AVCodecContext *avctx;
2255 if (stream_index < 0 || stream_index >= ic->nb_streams)
2257 avctx = ic->streams[stream_index]->codec;
2259 switch (avctx->codec_type) {
2260 case AVMEDIA_TYPE_AUDIO:
2261 packet_queue_abort(&is->audioq);
2265 packet_queue_flush(&is->audioq);
2266 av_free_packet(&is->audio_pkt);
2268 swr_free(&is->swr_ctx);
2269 av_freep(&is->audio_buf1);
2270 is->audio_buf = NULL;
2271 av_freep(&is->frame);
2274 av_rdft_end(is->rdft);
2275 av_freep(&is->rdft_data);
2280 case AVMEDIA_TYPE_VIDEO:
2281 packet_queue_abort(&is->videoq);
2283 /* note: we also signal this mutex to make sure we deblock the
2284 video thread in all cases */
2285 SDL_LockMutex(is->pictq_mutex);
2286 SDL_CondSignal(is->pictq_cond);
2287 SDL_UnlockMutex(is->pictq_mutex);
2289 SDL_WaitThread(is->video_tid, NULL);
2291 packet_queue_flush(&is->videoq);
2293 case AVMEDIA_TYPE_SUBTITLE:
2294 packet_queue_abort(&is->subtitleq);
2296 /* note: we also signal this mutex to make sure we deblock the
2297 video thread in all cases */
2298 SDL_LockMutex(is->subpq_mutex);
2299 is->subtitle_stream_changed = 1;
2301 SDL_CondSignal(is->subpq_cond);
2302 SDL_UnlockMutex(is->subpq_mutex);
2304 SDL_WaitThread(is->subtitle_tid, NULL);
2306 packet_queue_flush(&is->subtitleq);
2312 ic->streams[stream_index]->discard = AVDISCARD_ALL;
2313 avcodec_close(avctx);
2315 free_buffer_pool(&is->buffer_pool);
2317 switch (avctx->codec_type) {
2318 case AVMEDIA_TYPE_AUDIO:
2319 is->audio_st = NULL;
2320 is->audio_stream = -1;
2322 case AVMEDIA_TYPE_VIDEO:
2323 is->video_st = NULL;
2324 is->video_stream = -1;
2326 case AVMEDIA_TYPE_SUBTITLE:
2327 is->subtitle_st = NULL;
2328 is->subtitle_stream = -1;
2335 static int decode_interrupt_cb(void *ctx)
2337 VideoState *is = ctx;
2338 return is->abort_request;
2341 /* this thread gets the stream from the disk or the network */
2342 static int read_thread(void *arg)
2344 VideoState *is = arg;
2345 AVFormatContext *ic = NULL;
2347 int st_index[AVMEDIA_TYPE_NB];
2348 AVPacket pkt1, *pkt = &pkt1;
2350 int pkt_in_play_range = 0;
2351 AVDictionaryEntry *t;
2352 AVDictionary **opts;
2353 int orig_nb_streams;
2355 memset(st_index, -1, sizeof(st_index));
2356 is->last_video_stream = is->video_stream = -1;
2357 is->last_audio_stream = is->audio_stream = -1;
2358 is->last_subtitle_stream = is->subtitle_stream = -1;
2360 ic = avformat_alloc_context();
2361 ic->interrupt_callback.callback = decode_interrupt_cb;
2362 ic->interrupt_callback.opaque = is;
2363 err = avformat_open_input(&ic, is->filename, is->iformat, &format_opts);
2365 print_error(is->filename, err);
2369 if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2370 av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
2371 ret = AVERROR_OPTION_NOT_FOUND;
2377 ic->flags |= AVFMT_FLAG_GENPTS;
2379 opts = setup_find_stream_info_opts(ic, codec_opts);
2380 orig_nb_streams = ic->nb_streams;
2382 err = avformat_find_stream_info(ic, opts);
2384 fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
2388 for (i = 0; i < orig_nb_streams; i++)
2389 av_dict_free(&opts[i]);
2393 ic->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
2395 if (seek_by_bytes < 0)
2396 seek_by_bytes = !!(ic->iformat->flags & AVFMT_TS_DISCONT);
2398 /* if seeking requested, we execute it */
2399 if (start_time != AV_NOPTS_VALUE) {
2402 timestamp = start_time;
2403 /* add the stream start time */
2404 if (ic->start_time != AV_NOPTS_VALUE)
2405 timestamp += ic->start_time;
2406 ret = avformat_seek_file(ic, -1, INT64_MIN, timestamp, INT64_MAX, 0);
2408 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2409 is->filename, (double)timestamp / AV_TIME_BASE);
2413 for (i = 0; i < ic->nb_streams; i++)
2414 ic->streams[i]->discard = AVDISCARD_ALL;
2416 st_index[AVMEDIA_TYPE_VIDEO] =
2417 av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO,
2418 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
2420 st_index[AVMEDIA_TYPE_AUDIO] =
2421 av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO,
2422 wanted_stream[AVMEDIA_TYPE_AUDIO],
2423 st_index[AVMEDIA_TYPE_VIDEO],
2426 st_index[AVMEDIA_TYPE_SUBTITLE] =
2427 av_find_best_stream(ic, AVMEDIA_TYPE_SUBTITLE,
2428 wanted_stream[AVMEDIA_TYPE_SUBTITLE],
2429 (st_index[AVMEDIA_TYPE_AUDIO] >= 0 ?
2430 st_index[AVMEDIA_TYPE_AUDIO] :
2431 st_index[AVMEDIA_TYPE_VIDEO]),
2434 av_dump_format(ic, 0, is->filename, 0);
2437 is->show_mode = show_mode;
2439 /* open the streams */
2440 if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
2441 stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);
2445 if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
2446 ret = stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);
2448 is->refresh_tid = SDL_CreateThread(refresh_thread, is);
2449 if (is->show_mode == SHOW_MODE_NONE)
2450 is->show_mode = ret >= 0 ? SHOW_MODE_VIDEO : SHOW_MODE_RDFT;
2452 if (st_index[AVMEDIA_TYPE_SUBTITLE] >= 0) {
2453 stream_component_open(is, st_index[AVMEDIA_TYPE_SUBTITLE]);
2456 if (is->video_stream < 0 && is->audio_stream < 0) {
2457 fprintf(stderr, "%s: could not open codecs\n", is->filename);
2463 if (is->abort_request)
2465 if (is->paused != is->last_paused) {
2466 is->last_paused = is->paused;
2468 is->read_pause_return = av_read_pause(ic);
2472 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
2474 (!strcmp(ic->iformat->name, "rtsp") ||
2475 (ic->pb && !strncmp(input_filename, "mmsh:", 5)))) {
2476 /* wait 10 ms to avoid trying to get another packet */
2483 int64_t seek_target = is->seek_pos;
2484 int64_t seek_min = is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;
2485 int64_t seek_max = is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;
2486 // FIXME the +-2 is due to rounding being not done in the correct direction in generation
2487 // of the seek_pos/seek_rel variables
2489 ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);
2491 fprintf(stderr, "%s: error while seeking\n", is->ic->filename);
2493 if (is->audio_stream >= 0) {
2494 packet_queue_flush(&is->audioq);
2495 packet_queue_put(&is->audioq, &flush_pkt);
2497 if (is->subtitle_stream >= 0) {
2498 packet_queue_flush(&is->subtitleq);
2499 packet_queue_put(&is->subtitleq, &flush_pkt);
2501 if (is->video_stream >= 0) {
2502 packet_queue_flush(&is->videoq);
2503 packet_queue_put(&is->videoq, &flush_pkt);
2510 /* if the queue are full, no need to read more */
2511 if ( is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE
2512 || ( (is->audioq .nb_packets > MIN_FRAMES || is->audio_stream < 0 || is->audioq.abort_request)
2513 && (is->videoq .nb_packets > MIN_FRAMES || is->video_stream < 0 || is->videoq.abort_request)
2514 && (is->subtitleq.nb_packets > MIN_FRAMES || is->subtitle_stream < 0 || is->subtitleq.abort_request))) {
2520 if (is->video_stream >= 0) {
2521 av_init_packet(pkt);
2524 pkt->stream_index = is->video_stream;
2525 packet_queue_put(&is->videoq, pkt);
2527 if (is->audio_stream >= 0 &&
2528 is->audio_st->codec->codec->capabilities & CODEC_CAP_DELAY) {
2529 av_init_packet(pkt);
2532 pkt->stream_index = is->audio_stream;
2533 packet_queue_put(&is->audioq, pkt);
2536 if (is->audioq.size + is->videoq.size + is->subtitleq.size == 0) {
2537 if (loop != 1 && (!loop || --loop)) {
2538 stream_seek(is, start_time != AV_NOPTS_VALUE ? start_time : 0, 0, 0);
2539 } else if (autoexit) {
2547 ret = av_read_frame(ic, pkt);
2549 if (ret == AVERROR_EOF || url_feof(ic->pb))
2551 if (ic->pb && ic->pb->error)
2553 SDL_Delay(100); /* wait for user event */
2556 /* check if packet is in play range specified by user, then queue, otherwise discard */
2557 pkt_in_play_range = duration == AV_NOPTS_VALUE ||
2558 (pkt->pts - ic->streams[pkt->stream_index]->start_time) *
2559 av_q2d(ic->streams[pkt->stream_index]->time_base) -
2560 (double)(start_time != AV_NOPTS_VALUE ? start_time : 0) / 1000000
2561 <= ((double)duration / 1000000);
2562 if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {
2563 packet_queue_put(&is->audioq, pkt);
2564 } else if (pkt->stream_index == is->video_stream && pkt_in_play_range) {
2565 packet_queue_put(&is->videoq, pkt);
2566 } else if (pkt->stream_index == is->subtitle_stream && pkt_in_play_range) {
2567 packet_queue_put(&is->subtitleq, pkt);
2569 av_free_packet(pkt);
2572 /* wait until the end */
2573 while (!is->abort_request) {
2579 /* close each stream */
2580 if (is->audio_stream >= 0)
2581 stream_component_close(is, is->audio_stream);
2582 if (is->video_stream >= 0)
2583 stream_component_close(is, is->video_stream);
2584 if (is->subtitle_stream >= 0)
2585 stream_component_close(is, is->subtitle_stream);
2587 avformat_close_input(&is->ic);
2593 event.type = FF_QUIT_EVENT;
2594 event.user.data1 = is;
2595 SDL_PushEvent(&event);
2600 static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
2604 is = av_mallocz(sizeof(VideoState));
2607 av_strlcpy(is->filename, filename, sizeof(is->filename));
2608 is->iformat = iformat;
2612 /* start video display */
2613 is->pictq_mutex = SDL_CreateMutex();
2614 is->pictq_cond = SDL_CreateCond();
2616 is->subpq_mutex = SDL_CreateMutex();
2617 is->subpq_cond = SDL_CreateCond();
2619 packet_queue_init(&is->videoq);
2620 packet_queue_init(&is->audioq);
2621 packet_queue_init(&is->subtitleq);
2623 is->av_sync_type = av_sync_type;
2624 is->read_tid = SDL_CreateThread(read_thread, is);
2625 if (!is->read_tid) {
2632 static void stream_cycle_channel(VideoState *is, int codec_type)
2634 AVFormatContext *ic = is->ic;
2635 int start_index, stream_index;
2639 if (codec_type == AVMEDIA_TYPE_VIDEO) {
2640 start_index = is->last_video_stream;
2641 old_index = is->video_stream;
2642 } else if (codec_type == AVMEDIA_TYPE_AUDIO) {
2643 start_index = is->last_audio_stream;
2644 old_index = is->audio_stream;
2646 start_index = is->last_subtitle_stream;
2647 old_index = is->subtitle_stream;
2649 stream_index = start_index;
2651 if (++stream_index >= is->ic->nb_streams)
2653 if (codec_type == AVMEDIA_TYPE_SUBTITLE)
2656 is->last_subtitle_stream = -1;
2659 if (start_index == -1)
2663 if (stream_index == start_index)
2665 st = ic->streams[stream_index];
2666 if (st->codec->codec_type == codec_type) {
2667 /* check that parameters are OK */
2668 switch (codec_type) {
2669 case AVMEDIA_TYPE_AUDIO:
2670 if (st->codec->sample_rate != 0 &&
2671 st->codec->channels != 0)
2674 case AVMEDIA_TYPE_VIDEO:
2675 case AVMEDIA_TYPE_SUBTITLE:
2683 stream_component_close(is, old_index);
2684 stream_component_open(is, stream_index);
2688 static void toggle_full_screen(VideoState *is)
2690 #if defined(__APPLE__) && SDL_VERSION_ATLEAST(1, 2, 14)
2691 /* OS X needs to reallocate the SDL overlays */
2693 for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++)
2694 is->pictq[i].reallocate = 1;
2696 is_full_screen = !is_full_screen;
2700 static void toggle_pause(VideoState *is)
2702 stream_toggle_pause(is);
2706 static void step_to_next_frame(VideoState *is)
2708 /* if the stream is paused unpause it, then step */
2710 stream_toggle_pause(is);
2714 static void toggle_audio_display(VideoState *is)
2716 int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
2717 is->show_mode = (is->show_mode + 1) % SHOW_MODE_NB;
2718 fill_rectangle(screen,
2719 is->xleft, is->ytop, is->width, is->height,
2721 SDL_UpdateRect(screen, is->xleft, is->ytop, is->width, is->height);
2724 /* handle an event sent by the GUI */
2725 static void event_loop(VideoState *cur_stream)
2728 double incr, pos, frac;
2732 SDL_WaitEvent(&event);
2733 switch (event.type) {
2735 if (exit_on_keydown) {
2736 do_exit(cur_stream);
2739 switch (event.key.keysym.sym) {
2742 do_exit(cur_stream);
2745 toggle_full_screen(cur_stream);
2746 cur_stream->force_refresh = 1;
2750 toggle_pause(cur_stream);
2752 case SDLK_s: // S: Step to next frame
2753 step_to_next_frame(cur_stream);
2756 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
2759 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
2762 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
2765 toggle_audio_display(cur_stream);
2766 cur_stream->force_refresh = 1;
2786 if (seek_by_bytes) {
2787 if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos >= 0) {
2788 pos = cur_stream->video_current_pos;
2789 } else if (cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos >= 0) {
2790 pos = cur_stream->audio_pkt.pos;
2792 pos = avio_tell(cur_stream->ic->pb);
2793 if (cur_stream->ic->bit_rate)
2794 incr *= cur_stream->ic->bit_rate / 8.0;
2798 stream_seek(cur_stream, pos, incr, 1);
2800 pos = get_master_clock(cur_stream);
2802 stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);
2809 case SDL_VIDEOEXPOSE:
2810 cur_stream->force_refresh = 1;
2812 case SDL_MOUSEBUTTONDOWN:
2813 if (exit_on_mousedown) {
2814 do_exit(cur_stream);
2817 case SDL_MOUSEMOTION:
2818 if (event.type == SDL_MOUSEBUTTONDOWN) {
2821 if (event.motion.state != SDL_PRESSED)
2825 if (seek_by_bytes || cur_stream->ic->duration <= 0) {
2826 uint64_t size = avio_size(cur_stream->ic->pb);
2827 stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);
2831 int tns, thh, tmm, tss;
2832 tns = cur_stream->ic->duration / 1000000LL;
2834 tmm = (tns % 3600) / 60;
2836 frac = x / cur_stream->width;
2839 mm = (ns % 3600) / 60;
2841 fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n", frac*100,
2842 hh, mm, ss, thh, tmm, tss);
2843 ts = frac * cur_stream->ic->duration;
2844 if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
2845 ts += cur_stream->ic->start_time;
2846 stream_seek(cur_stream, ts, 0, 0);
2849 case SDL_VIDEORESIZE:
2850 screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
2851 SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
2852 screen_width = cur_stream->width = event.resize.w;
2853 screen_height = cur_stream->height = event.resize.h;
2854 cur_stream->force_refresh = 1;
2858 do_exit(cur_stream);
2860 case FF_ALLOC_EVENT:
2861 alloc_picture(event.user.data1);
2863 case FF_REFRESH_EVENT:
2864 video_refresh(event.user.data1);
2865 cur_stream->refresh = 0;
2873 static int opt_frame_size(const char *opt, const char *arg)
2875 av_log(NULL, AV_LOG_WARNING, "Option -s is deprecated, use -video_size.\n");
2876 return opt_default("video_size", arg);
2879 static int opt_width(const char *opt, const char *arg)
2881 screen_width = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
2885 static int opt_height(const char *opt, const char *arg)
2887 screen_height = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
2891 static int opt_format(const char *opt, const char *arg)
2893 file_iformat = av_find_input_format(arg);
2894 if (!file_iformat) {
2895 fprintf(stderr, "Unknown input format: %s\n", arg);
2896 return AVERROR(EINVAL);
2901 static int opt_frame_pix_fmt(const char *opt, const char *arg)
2903 av_log(NULL, AV_LOG_WARNING, "Option -pix_fmt is deprecated, use -pixel_format.\n");
2904 return opt_default("pixel_format", arg);
2907 static int opt_sync(const char *opt, const char *arg)
2909 if (!strcmp(arg, "audio"))
2910 av_sync_type = AV_SYNC_AUDIO_MASTER;
2911 else if (!strcmp(arg, "video"))
2912 av_sync_type = AV_SYNC_VIDEO_MASTER;
2913 else if (!strcmp(arg, "ext"))
2914 av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
2916 fprintf(stderr, "Unknown value for %s: %s\n", opt, arg);
2922 static int opt_seek(const char *opt, const char *arg)
2924 start_time = parse_time_or_die(opt, arg, 1);
2928 static int opt_duration(const char *opt, const char *arg)
2930 duration = parse_time_or_die(opt, arg, 1);
2934 static int opt_show_mode(const char *opt, const char *arg)
2936 show_mode = !strcmp(arg, "video") ? SHOW_MODE_VIDEO :
2937 !strcmp(arg, "waves") ? SHOW_MODE_WAVES :
2938 !strcmp(arg, "rdft" ) ? SHOW_MODE_RDFT :
2939 parse_number_or_die(opt, arg, OPT_INT, 0, SHOW_MODE_NB-1);
2943 static void opt_input_file(void *optctx, const char *filename)
2945 if (input_filename) {
2946 fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
2947 filename, input_filename);
2950 if (!strcmp(filename, "-"))
2952 input_filename = filename;
2955 static int opt_codec(void *o, const char *opt, const char *arg)
2957 switch(opt[strlen(opt)-1]){
2958 case 'a' : audio_codec_name = arg; break;
2959 case 's' : subtitle_codec_name = arg; break;
2960 case 'v' : video_codec_name = arg; break;
2967 static const OptionDef options[] = {
2968 #include "cmdutils_common_opts.h"
2969 { "x", HAS_ARG, { (void*)opt_width }, "force displayed width", "width" },
2970 { "y", HAS_ARG, { (void*)opt_height }, "force displayed height", "height" },
2971 { "s", HAS_ARG | OPT_VIDEO, { (void*)opt_frame_size }, "set frame size (WxH or abbreviation)", "size" },
2972 { "fs", OPT_BOOL, { (void*)&is_full_screen }, "force full screen" },
2973 { "an", OPT_BOOL, { (void*)&audio_disable }, "disable audio" },
2974 { "vn", OPT_BOOL, { (void*)&video_disable }, "disable video" },
2975 { "ast", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&wanted_stream[AVMEDIA_TYPE_AUDIO] }, "select desired audio stream", "stream_number" },
2976 { "vst", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&wanted_stream[AVMEDIA_TYPE_VIDEO] }, "select desired video stream", "stream_number" },
2977 { "sst", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&wanted_stream[AVMEDIA_TYPE_SUBTITLE] }, "select desired subtitle stream", "stream_number" },
2978 { "ss", HAS_ARG, { (void*)&opt_seek }, "seek to a given position in seconds", "pos" },
2979 { "t", HAS_ARG, { (void*)&opt_duration }, "play \"duration\" seconds of audio/video", "duration" },
2980 { "bytes", OPT_INT | HAS_ARG, { (void*)&seek_by_bytes }, "seek by bytes 0=off 1=on -1=auto", "val" },
2981 { "nodisp", OPT_BOOL, { (void*)&display_disable }, "disable graphical display" },
2982 { "f", HAS_ARG, { (void*)opt_format }, "force format", "fmt" },
2983 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { (void*)opt_frame_pix_fmt }, "set pixel format", "format" },
2984 { "stats", OPT_BOOL | OPT_EXPERT, { (void*)&show_status }, "show status", "" },
2985 { "bug", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&workaround_bugs }, "workaround bugs", "" },
2986 { "fast", OPT_BOOL | OPT_EXPERT, { (void*)&fast }, "non spec compliant optimizations", "" },
2987 { "genpts", OPT_BOOL | OPT_EXPERT, { (void*)&genpts }, "generate pts", "" },
2988 { "drp", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&decoder_reorder_pts }, "let decoder reorder pts 0=off 1=on -1=auto", ""},
2989 { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&lowres }, "", "" },
2990 { "skiploop", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&skip_loop_filter }, "", "" },
2991 { "skipframe", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&skip_frame }, "", "" },
2992 { "skipidct", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&skip_idct }, "", "" },
2993 { "idct", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&idct }, "set idct algo", "algo" },
2994 { "ec", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&error_concealment }, "set error concealment options", "bit_mask" },
2995 { "sync", HAS_ARG | OPT_EXPERT, { (void*)opt_sync }, "set audio-video sync. type (type=audio/video/ext)", "type" },
2996 { "autoexit", OPT_BOOL | OPT_EXPERT, { (void*)&autoexit }, "exit at the end", "" },
2997 { "exitonkeydown", OPT_BOOL | OPT_EXPERT, { (void*)&exit_on_keydown }, "exit on key down", "" },
2998 { "exitonmousedown", OPT_BOOL | OPT_EXPERT, { (void*)&exit_on_mousedown }, "exit on mouse down", "" },
2999 { "loop", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&loop }, "set number of times the playback shall be looped", "loop count" },
3000 { "framedrop", OPT_BOOL | OPT_EXPERT, { (void*)&framedrop }, "drop frames when cpu is too slow", "" },
3001 { "window_title", OPT_STRING | HAS_ARG, { (void*)&window_title }, "set window title", "window title" },
3003 { "vf", OPT_STRING | HAS_ARG, { (void*)&vfilters }, "video filters", "filter list" },
3005 { "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, { (void*)&rdftspeed }, "rdft speed", "msecs" },
3006 { "showmode", HAS_ARG, {(void*)opt_show_mode}, "select show mode (0 = video, 1 = waves, 2 = RDFT)", "mode" },
3007 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, { (void*)opt_default }, "generic catch all option", "" },
3008 { "i", OPT_BOOL, {(void *)&dummy}, "read specified file", "input_file"},
3009 { "codec", HAS_ARG | OPT_FUNC2, {(void*)opt_codec}, "force decoder", "decoder" },
3013 static void show_usage(void)
3015 av_log(NULL, AV_LOG_INFO, "Simple media player\n");
3016 av_log(NULL, AV_LOG_INFO, "usage: %s [options] input_file\n", program_name);
3017 av_log(NULL, AV_LOG_INFO, "\n");
3020 static int opt_help(const char *opt, const char *arg)
3022 av_log_set_callback(log_callback_help);
3024 show_help_options(options, "Main options:\n",
3026 show_help_options(options, "\nAdvanced options:\n",
3027 OPT_EXPERT, OPT_EXPERT);
3029 show_help_children(avcodec_get_class(), AV_OPT_FLAG_DECODING_PARAM);
3030 show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
3031 #if !CONFIG_AVFILTER
3032 show_help_children(sws_get_class(), AV_OPT_FLAG_ENCODING_PARAM);
3034 printf("\nWhile playing:\n"
3036 "f toggle full screen\n"
3038 "a cycle audio channel\n"
3039 "v cycle video channel\n"
3040 "t cycle subtitle channel\n"
3041 "w show audio waves\n"
3042 "s activate frame-step mode\n"
3043 "left/right seek backward/forward 10 seconds\n"
3044 "down/up seek backward/forward 1 minute\n"
3045 "page down/page up seek backward/forward 10 minutes\n"
3046 "mouse click seek to percentage in file corresponding to fraction of width\n"
3051 static int lockmgr(void **mtx, enum AVLockOp op)
3054 case AV_LOCK_CREATE:
3055 *mtx = SDL_CreateMutex();
3059 case AV_LOCK_OBTAIN:
3060 return !!SDL_LockMutex(*mtx);
3061 case AV_LOCK_RELEASE:
3062 return !!SDL_UnlockMutex(*mtx);
3063 case AV_LOCK_DESTROY:
3064 SDL_DestroyMutex(*mtx);
3070 /* Called from the main */
3071 int main(int argc, char **argv)
3075 char dummy_videodriver[] = "SDL_VIDEODRIVER=dummy";
3077 av_log_set_flags(AV_LOG_SKIP_REPEATED);
3078 parse_loglevel(argc, argv, options);
3080 /* register all codecs, demux and protocols */
3081 avcodec_register_all();
3083 avdevice_register_all();
3086 avfilter_register_all();
3089 avformat_network_init();
3093 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
3094 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
3096 show_banner(argc, argv, options);
3098 parse_options(NULL, argc, argv, options, opt_input_file);
3100 if (!input_filename) {
3102 fprintf(stderr, "An input file must be specified\n");
3103 fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
3107 if (display_disable) {
3110 flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
3112 flags &= ~SDL_INIT_AUDIO;
3113 if (display_disable)
3114 SDL_putenv(dummy_videodriver); /* For the event queue, we always need a video driver. */
3115 #if !defined(__MINGW32__) && !defined(__APPLE__)
3116 flags |= SDL_INIT_EVENTTHREAD; /* Not supported on Windows or Mac OS X */
3118 if (SDL_Init (flags)) {
3119 fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
3120 fprintf(stderr, "(Did you set the DISPLAY variable?)\n");
3124 if (!display_disable) {
3125 #if HAVE_SDL_VIDEO_SIZE
3126 const SDL_VideoInfo *vi = SDL_GetVideoInfo();
3127 fs_screen_width = vi->current_w;
3128 fs_screen_height = vi->current_h;
3132 SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
3133 SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
3134 SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
3136 if (av_lockmgr_register(lockmgr)) {
3137 fprintf(stderr, "Could not initialize lock manager!\n");
3141 av_init_packet(&flush_pkt);
3142 flush_pkt.data = (char *)(intptr_t)"FLUSH";
3144 is = stream_open(input_filename, file_iformat);
3146 fprintf(stderr, "Failed to initialize VideoState!\n");