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
33 #include "libavutil/avstring.h"
34 #include "libavutil/colorspace.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/imgutils.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/parseutils.h"
40 #include "libavutil/samplefmt.h"
41 #include "libavutil/avassert.h"
42 #include "libavutil/time.h"
43 #include "libavformat/avformat.h"
44 #include "libavdevice/avdevice.h"
45 #include "libswscale/swscale.h"
46 #include "libavutil/opt.h"
47 #include "libavcodec/avfft.h"
48 #include "libswresample/swresample.h"
51 # include "libavfilter/avcodec.h"
52 # include "libavfilter/avfilter.h"
53 # include "libavfilter/buffersink.h"
54 # include "libavfilter/buffersrc.h"
58 #include <SDL_thread.h>
64 const char program_name[] = "ffplay";
65 const int program_birth_year = 2003;
67 #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
70 /* SDL audio buffer size, in samples. Should be small to have precise
71 A/V sync as SDL does not have hardware buffer fullness info. */
72 #define SDL_AUDIO_BUFFER_SIZE 1024
74 /* no AV sync correction is done if below the minimum AV sync threshold */
75 #define AV_SYNC_THRESHOLD_MIN 0.01
76 /* AV sync correction is done if above the maximum AV sync threshold */
77 #define AV_SYNC_THRESHOLD_MAX 0.1
78 /* If a frame duration is longer than this, it will not be duplicated to compensate AV sync */
79 #define AV_SYNC_FRAMEDUP_THRESHOLD 0.1
80 /* no AV correction is done if too big error */
81 #define AV_NOSYNC_THRESHOLD 10.0
83 /* maximum audio speed change to get correct sync */
84 #define SAMPLE_CORRECTION_PERCENT_MAX 10
86 /* external clock speed adjustment constants for realtime sources based on buffer fullness */
87 #define EXTERNAL_CLOCK_SPEED_MIN 0.900
88 #define EXTERNAL_CLOCK_SPEED_MAX 1.010
89 #define EXTERNAL_CLOCK_SPEED_STEP 0.001
91 /* we use about AUDIO_DIFF_AVG_NB A-V differences to make the average */
92 #define AUDIO_DIFF_AVG_NB 20
94 /* polls for possible required screen refresh at least this often, should be less than 1/fps */
95 #define REFRESH_RATE 0.01
97 /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
98 /* TODO: We assume that a decoded and resampled frame fits into this buffer */
99 #define SAMPLE_ARRAY_SIZE (8 * 65536)
101 #define CURSOR_HIDE_DELAY 1000000
103 static int64_t sws_flags = SWS_BICUBIC;
105 typedef struct MyAVPacketList {
107 struct MyAVPacketList *next;
111 typedef struct PacketQueue {
112 MyAVPacketList *first_pkt, *last_pkt;
121 #define VIDEO_PICTURE_QUEUE_SIZE 3
122 #define SUBPICTURE_QUEUE_SIZE 4
124 typedef struct VideoPicture {
125 double pts; // presentation timestamp for this picture
126 double duration; // estimated duration based on frame rate
127 int64_t pos; // byte position in file
129 int width, height; /* source height & width */
137 typedef struct SubPicture {
138 double pts; /* presentation time stamp for this picture */
143 typedef struct AudioParams {
146 int64_t channel_layout;
147 enum AVSampleFormat fmt;
150 typedef struct Clock {
151 double pts; /* clock base */
152 double pts_drift; /* clock base minus time at which we updated the clock */
155 int serial; /* clock is based on a packet with this serial */
157 int *queue_serial; /* pointer to the current packet queue serial, used for obsolete clock detection */
161 AV_SYNC_AUDIO_MASTER, /* default choice */
162 AV_SYNC_VIDEO_MASTER,
163 AV_SYNC_EXTERNAL_CLOCK, /* synchronize to an external clock */
166 typedef struct VideoState {
167 SDL_Thread *read_tid;
168 SDL_Thread *video_tid;
169 AVInputFormat *iformat;
175 int queue_attachments_req;
180 int read_pause_return;
195 int audio_clock_serial;
196 double audio_diff_cum; /* used for AV difference average computation */
197 double audio_diff_avg_coef;
198 double audio_diff_threshold;
199 int audio_diff_avg_count;
202 int audio_hw_buf_size;
203 uint8_t silence_buf[SDL_AUDIO_BUFFER_SIZE];
206 unsigned int audio_buf_size; /* in bytes */
207 unsigned int audio_buf1_size;
208 int audio_buf_index; /* in bytes */
209 int audio_write_buf_size;
210 int audio_buf_frames_pending;
211 AVPacket audio_pkt_temp;
213 int audio_pkt_temp_serial;
214 int audio_last_serial;
215 struct AudioParams audio_src;
217 struct AudioParams audio_filter_src;
219 struct AudioParams audio_tgt;
220 struct SwrContext *swr_ctx;
221 int frame_drops_early;
222 int frame_drops_late;
224 int64_t audio_frame_next_pts;
227 SHOW_MODE_NONE = -1, SHOW_MODE_VIDEO = 0, SHOW_MODE_WAVES, SHOW_MODE_RDFT, SHOW_MODE_NB
229 int16_t sample_array[SAMPLE_ARRAY_SIZE];
230 int sample_array_index;
234 FFTSample *rdft_data;
236 double last_vis_time;
238 SDL_Thread *subtitle_tid;
240 AVStream *subtitle_st;
241 PacketQueue subtitleq;
242 SubPicture subpq[SUBPICTURE_QUEUE_SIZE];
243 int subpq_size, subpq_rindex, subpq_windex;
244 SDL_mutex *subpq_mutex;
245 SDL_cond *subpq_cond;
248 double frame_last_returned_time;
249 double frame_last_filter_delay;
253 int64_t video_current_pos; // current displayed file pos
254 double max_frame_duration; // maximum duration of a frame - above this, we consider the jump a timestamp discontinuity
255 VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
256 int pictq_size, pictq_rindex, pictq_windex;
257 SDL_mutex *pictq_mutex;
258 SDL_cond *pictq_cond;
260 struct SwsContext *img_convert_ctx;
262 SDL_Rect last_display_rect;
265 int width, height, xleft, ytop;
269 AVFilterContext *in_video_filter; // the first filter in the video chain
270 AVFilterContext *out_video_filter; // the last filter in the video chain
271 AVFilterContext *in_audio_filter; // the first filter in the audio chain
272 AVFilterContext *out_audio_filter; // the last filter in the audio chain
273 AVFilterGraph *agraph; // audio filter graph
276 int last_video_stream, last_audio_stream, last_subtitle_stream;
278 SDL_cond *continue_read_thread;
281 /* options specified by the user */
282 static AVInputFormat *file_iformat;
283 static const char *input_filename;
284 static const char *window_title;
285 static int fs_screen_width;
286 static int fs_screen_height;
287 static int default_width = 640;
288 static int default_height = 480;
289 static int screen_width = 0;
290 static int screen_height = 0;
291 static int audio_disable;
292 static int video_disable;
293 static int subtitle_disable;
294 static int wanted_stream[AVMEDIA_TYPE_NB] = {
295 [AVMEDIA_TYPE_AUDIO] = -1,
296 [AVMEDIA_TYPE_VIDEO] = -1,
297 [AVMEDIA_TYPE_SUBTITLE] = -1,
299 static int seek_by_bytes = -1;
300 static int display_disable;
301 static int show_status = 1;
302 static int av_sync_type = AV_SYNC_AUDIO_MASTER;
303 static int64_t start_time = AV_NOPTS_VALUE;
304 static int64_t duration = AV_NOPTS_VALUE;
305 static int workaround_bugs = 1;
307 static int genpts = 0;
308 static int lowres = 0;
309 static int error_concealment = 3;
310 static int decoder_reorder_pts = -1;
312 static int exit_on_keydown;
313 static int exit_on_mousedown;
315 static int framedrop = -1;
316 static int infinite_buffer = -1;
317 static enum ShowMode show_mode = SHOW_MODE_NONE;
318 static const char *audio_codec_name;
319 static const char *subtitle_codec_name;
320 static const char *video_codec_name;
321 double rdftspeed = 0.02;
322 static int64_t cursor_last_shown;
323 static int cursor_hidden = 0;
325 static char *vfilters = NULL;
326 static char *afilters = NULL;
329 /* current context */
330 static int is_full_screen;
331 static int64_t audio_callback_time;
333 static AVPacket flush_pkt;
335 #define FF_ALLOC_EVENT (SDL_USEREVENT)
336 #define FF_QUIT_EVENT (SDL_USEREVENT + 2)
338 static SDL_Surface *screen;
341 int cmp_audio_fmts(enum AVSampleFormat fmt1, int64_t channel_count1,
342 enum AVSampleFormat fmt2, int64_t channel_count2)
344 /* If channel count == 1, planar and non-planar formats are the same */
345 if (channel_count1 == 1 && channel_count2 == 1)
346 return av_get_packed_sample_fmt(fmt1) != av_get_packed_sample_fmt(fmt2);
348 return channel_count1 != channel_count2 || fmt1 != fmt2;
352 int64_t get_valid_channel_layout(int64_t channel_layout, int channels)
354 if (channel_layout && av_get_channel_layout_nb_channels(channel_layout) == channels)
355 return channel_layout;
360 static int packet_queue_put(PacketQueue *q, AVPacket *pkt);
362 static int packet_queue_put_private(PacketQueue *q, AVPacket *pkt)
364 MyAVPacketList *pkt1;
366 if (q->abort_request)
369 pkt1 = av_malloc(sizeof(MyAVPacketList));
374 if (pkt == &flush_pkt)
376 pkt1->serial = q->serial;
381 q->last_pkt->next = pkt1;
384 q->size += pkt1->pkt.size + sizeof(*pkt1);
385 /* XXX: should duplicate packet data in DV case */
386 SDL_CondSignal(q->cond);
390 static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
394 /* duplicate the packet */
395 if (pkt != &flush_pkt && av_dup_packet(pkt) < 0)
398 SDL_LockMutex(q->mutex);
399 ret = packet_queue_put_private(q, pkt);
400 SDL_UnlockMutex(q->mutex);
402 if (pkt != &flush_pkt && ret < 0)
408 static int packet_queue_put_nullpacket(PacketQueue *q, int stream_index)
410 AVPacket pkt1, *pkt = &pkt1;
414 pkt->stream_index = stream_index;
415 return packet_queue_put(q, pkt);
418 /* packet queue handling */
419 static void packet_queue_init(PacketQueue *q)
421 memset(q, 0, sizeof(PacketQueue));
422 q->mutex = SDL_CreateMutex();
423 q->cond = SDL_CreateCond();
424 q->abort_request = 1;
427 static void packet_queue_flush(PacketQueue *q)
429 MyAVPacketList *pkt, *pkt1;
431 SDL_LockMutex(q->mutex);
432 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
434 av_free_packet(&pkt->pkt);
441 SDL_UnlockMutex(q->mutex);
444 static void packet_queue_destroy(PacketQueue *q)
446 packet_queue_flush(q);
447 SDL_DestroyMutex(q->mutex);
448 SDL_DestroyCond(q->cond);
451 static void packet_queue_abort(PacketQueue *q)
453 SDL_LockMutex(q->mutex);
455 q->abort_request = 1;
457 SDL_CondSignal(q->cond);
459 SDL_UnlockMutex(q->mutex);
462 static void packet_queue_start(PacketQueue *q)
464 SDL_LockMutex(q->mutex);
465 q->abort_request = 0;
466 packet_queue_put_private(q, &flush_pkt);
467 SDL_UnlockMutex(q->mutex);
470 /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
471 static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block, int *serial)
473 MyAVPacketList *pkt1;
476 SDL_LockMutex(q->mutex);
479 if (q->abort_request) {
486 q->first_pkt = pkt1->next;
490 q->size -= pkt1->pkt.size + sizeof(*pkt1);
493 *serial = pkt1->serial;
501 SDL_CondWait(q->cond, q->mutex);
504 SDL_UnlockMutex(q->mutex);
508 static inline void fill_rectangle(SDL_Surface *screen,
509 int x, int y, int w, int h, int color, int update)
516 SDL_FillRect(screen, &rect, color);
517 if (update && w > 0 && h > 0)
518 SDL_UpdateRect(screen, x, y, w, h);
521 /* draw only the border of a rectangle */
522 static void fill_border(int xleft, int ytop, int width, int height, int x, int y, int w, int h, int color, int update)
526 /* fill the background */
530 w2 = width - (x + w);
536 h2 = height - (y + h);
539 fill_rectangle(screen,
543 fill_rectangle(screen,
544 xleft + width - w2, ytop,
547 fill_rectangle(screen,
551 fill_rectangle(screen,
552 xleft + w1, ytop + height - h2,
557 #define ALPHA_BLEND(a, oldp, newp, s)\
558 ((((oldp << s) * (255 - (a))) + (newp * (a))) / (255 << s))
560 #define RGBA_IN(r, g, b, a, s)\
562 unsigned int v = ((const uint32_t *)(s))[0];\
563 a = (v >> 24) & 0xff;\
564 r = (v >> 16) & 0xff;\
565 g = (v >> 8) & 0xff;\
569 #define YUVA_IN(y, u, v, a, s, pal)\
571 unsigned int val = ((const uint32_t *)(pal))[*(const uint8_t*)(s)];\
572 a = (val >> 24) & 0xff;\
573 y = (val >> 16) & 0xff;\
574 u = (val >> 8) & 0xff;\
578 #define YUVA_OUT(d, y, u, v, a)\
580 ((uint32_t *)(d))[0] = (a << 24) | (y << 16) | (u << 8) | v;\
586 static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw, int imgh)
588 int wrap, wrap3, width2, skip2;
589 int y, u, v, a, u1, v1, a1, w, h;
590 uint8_t *lum, *cb, *cr;
593 int dstx, dsty, dstw, dsth;
595 dstw = av_clip(rect->w, 0, imgw);
596 dsth = av_clip(rect->h, 0, imgh);
597 dstx = av_clip(rect->x, 0, imgw - dstw);
598 dsty = av_clip(rect->y, 0, imgh - dsth);
599 lum = dst->data[0] + dsty * dst->linesize[0];
600 cb = dst->data[1] + (dsty >> 1) * dst->linesize[1];
601 cr = dst->data[2] + (dsty >> 1) * dst->linesize[2];
603 width2 = ((dstw + 1) >> 1) + (dstx & ~dstw & 1);
605 wrap = dst->linesize[0];
606 wrap3 = rect->pict.linesize[0];
607 p = rect->pict.data[0];
608 pal = (const uint32_t *)rect->pict.data[1]; /* Now in YCrCb! */
616 YUVA_IN(y, u, v, a, p, pal);
617 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
618 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
619 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
625 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
626 YUVA_IN(y, u, v, a, p, pal);
630 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
632 YUVA_IN(y, u, v, a, p + BPP, pal);
636 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
637 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
638 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
645 YUVA_IN(y, u, v, a, p, pal);
646 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
647 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
648 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
652 p += wrap3 - dstw * BPP;
653 lum += wrap - dstw - dstx;
654 cb += dst->linesize[1] - width2 - skip2;
655 cr += dst->linesize[2] - width2 - skip2;
657 for (h = dsth - (dsty & 1); h >= 2; h -= 2) {
663 YUVA_IN(y, u, v, a, p, pal);
667 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
670 YUVA_IN(y, u, v, a, p, pal);
674 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
675 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
676 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
682 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
683 YUVA_IN(y, u, v, a, p, pal);
687 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
689 YUVA_IN(y, u, v, a, p + BPP, pal);
693 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
697 YUVA_IN(y, u, v, a, p, pal);
701 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
703 YUVA_IN(y, u, v, a, p + BPP, pal);
707 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
709 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 2);
710 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 2);
714 p += -wrap3 + 2 * BPP;
718 YUVA_IN(y, u, v, a, p, pal);
722 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
725 YUVA_IN(y, u, v, a, p, pal);
729 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
730 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
731 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
737 p += wrap3 + (wrap3 - dstw * BPP);
738 lum += wrap + (wrap - dstw - dstx);
739 cb += dst->linesize[1] - width2 - skip2;
740 cr += dst->linesize[2] - width2 - skip2;
742 /* handle odd height */
749 YUVA_IN(y, u, v, a, p, pal);
750 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
751 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
752 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
758 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
759 YUVA_IN(y, u, v, a, p, pal);
763 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
765 YUVA_IN(y, u, v, a, p + BPP, pal);
769 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
770 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u, 1);
771 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v, 1);
778 YUVA_IN(y, u, v, a, p, pal);
779 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
780 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
781 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
786 static void free_picture(VideoPicture *vp)
789 SDL_FreeYUVOverlay(vp->bmp);
794 static void free_subpicture(SubPicture *sp)
796 avsubtitle_free(&sp->sub);
799 static void calculate_display_rect(SDL_Rect *rect, int scr_xleft, int scr_ytop, int scr_width, int scr_height, VideoPicture *vp)
802 int width, height, x, y;
804 if (vp->sar.num == 0)
807 aspect_ratio = av_q2d(vp->sar);
809 if (aspect_ratio <= 0.0)
811 aspect_ratio *= (float)vp->width / (float)vp->height;
813 /* XXX: we suppose the screen has a 1.0 pixel ratio */
815 width = ((int)rint(height * aspect_ratio)) & ~1;
816 if (width > scr_width) {
818 height = ((int)rint(width / aspect_ratio)) & ~1;
820 x = (scr_width - width) / 2;
821 y = (scr_height - height) / 2;
822 rect->x = scr_xleft + x;
823 rect->y = scr_ytop + y;
824 rect->w = FFMAX(width, 1);
825 rect->h = FFMAX(height, 1);
828 static void video_image_display(VideoState *is)
836 vp = &is->pictq[is->pictq_rindex];
838 if (is->subtitle_st) {
839 if (is->subpq_size > 0) {
840 sp = &is->subpq[is->subpq_rindex];
842 if (vp->pts >= sp->pts + ((float) sp->sub.start_display_time / 1000)) {
843 SDL_LockYUVOverlay (vp->bmp);
845 pict.data[0] = vp->bmp->pixels[0];
846 pict.data[1] = vp->bmp->pixels[2];
847 pict.data[2] = vp->bmp->pixels[1];
849 pict.linesize[0] = vp->bmp->pitches[0];
850 pict.linesize[1] = vp->bmp->pitches[2];
851 pict.linesize[2] = vp->bmp->pitches[1];
853 for (i = 0; i < sp->sub.num_rects; i++)
854 blend_subrect(&pict, sp->sub.rects[i],
855 vp->bmp->w, vp->bmp->h);
857 SDL_UnlockYUVOverlay (vp->bmp);
862 calculate_display_rect(&rect, is->xleft, is->ytop, is->width, is->height, vp);
864 SDL_DisplayYUVOverlay(vp->bmp, &rect);
866 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) {
867 int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
868 fill_border(is->xleft, is->ytop, is->width, is->height, rect.x, rect.y, rect.w, rect.h, bgcolor, 1);
869 is->last_display_rect = rect;
874 static inline int compute_mod(int a, int b)
876 return a < 0 ? a%b + b : a%b;
879 static void video_audio_display(VideoState *s)
881 int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
882 int ch, channels, h, h2, bgcolor, fgcolor;
884 int rdft_bits, nb_freq;
886 for (rdft_bits = 1; (1 << rdft_bits) < 2 * s->height; rdft_bits++)
888 nb_freq = 1 << (rdft_bits - 1);
890 /* compute display index : center on currently output samples */
891 channels = s->audio_tgt.channels;
892 nb_display_channels = channels;
894 int data_used= s->show_mode == SHOW_MODE_WAVES ? s->width : (2*nb_freq);
896 delay = s->audio_write_buf_size;
899 /* to be more precise, we take into account the time spent since
900 the last buffer computation */
901 if (audio_callback_time) {
902 time_diff = av_gettime() - audio_callback_time;
903 delay -= (time_diff * s->audio_tgt.freq) / 1000000;
906 delay += 2 * data_used;
907 if (delay < data_used)
910 i_start= x = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
911 if (s->show_mode == SHOW_MODE_WAVES) {
913 for (i = 0; i < 1000; i += channels) {
914 int idx = (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;
915 int a = s->sample_array[idx];
916 int b = s->sample_array[(idx + 4 * channels) % SAMPLE_ARRAY_SIZE];
917 int c = s->sample_array[(idx + 5 * channels) % SAMPLE_ARRAY_SIZE];
918 int d = s->sample_array[(idx + 9 * channels) % SAMPLE_ARRAY_SIZE];
920 if (h < score && (b ^ c) < 0) {
927 s->last_i_start = i_start;
929 i_start = s->last_i_start;
932 bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
933 if (s->show_mode == SHOW_MODE_WAVES) {
934 fill_rectangle(screen,
935 s->xleft, s->ytop, s->width, s->height,
938 fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);
940 /* total height for one channel */
941 h = s->height / nb_display_channels;
942 /* graph height / 2 */
944 for (ch = 0; ch < nb_display_channels; ch++) {
946 y1 = s->ytop + ch * h + (h / 2); /* position of center line */
947 for (x = 0; x < s->width; x++) {
948 y = (s->sample_array[i] * h2) >> 15;
955 fill_rectangle(screen,
956 s->xleft + x, ys, 1, y,
959 if (i >= SAMPLE_ARRAY_SIZE)
960 i -= SAMPLE_ARRAY_SIZE;
964 fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);
966 for (ch = 1; ch < nb_display_channels; ch++) {
967 y = s->ytop + ch * h;
968 fill_rectangle(screen,
969 s->xleft, y, s->width, 1,
972 SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
974 nb_display_channels= FFMIN(nb_display_channels, 2);
975 if (rdft_bits != s->rdft_bits) {
976 av_rdft_end(s->rdft);
977 av_free(s->rdft_data);
978 s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
979 s->rdft_bits = rdft_bits;
980 s->rdft_data = av_malloc(4 * nb_freq * sizeof(*s->rdft_data));
984 for (ch = 0; ch < nb_display_channels; ch++) {
985 data[ch] = s->rdft_data + 2 * nb_freq * ch;
987 for (x = 0; x < 2 * nb_freq; x++) {
988 double w = (x-nb_freq) * (1.0 / nb_freq);
989 data[ch][x] = s->sample_array[i] * (1.0 - w * w);
991 if (i >= SAMPLE_ARRAY_SIZE)
992 i -= SAMPLE_ARRAY_SIZE;
994 av_rdft_calc(s->rdft, data[ch]);
996 /* Least efficient way to do this, we should of course
997 * directly access it but it is more than fast enough. */
998 for (y = 0; y < s->height; y++) {
999 double w = 1 / sqrt(nb_freq);
1000 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]));
1001 int b = (nb_display_channels == 2 ) ? sqrt(w * sqrt(data[1][2 * y + 0] * data[1][2 * y + 0]
1002 + data[1][2 * y + 1] * data[1][2 * y + 1])) : a;
1005 fgcolor = SDL_MapRGB(screen->format, a, b, (a + b) / 2);
1007 fill_rectangle(screen,
1008 s->xpos, s->height-y, 1, 1,
1012 SDL_UpdateRect(screen, s->xpos, s->ytop, 1, s->height);
1015 if (s->xpos >= s->width)
1020 static void stream_close(VideoState *is)
1023 /* XXX: use a special url_shutdown call to abort parse cleanly */
1024 is->abort_request = 1;
1025 SDL_WaitThread(is->read_tid, NULL);
1026 packet_queue_destroy(&is->videoq);
1027 packet_queue_destroy(&is->audioq);
1028 packet_queue_destroy(&is->subtitleq);
1030 /* free all pictures */
1031 for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++)
1032 free_picture(&is->pictq[i]);
1033 for (i = 0; i < SUBPICTURE_QUEUE_SIZE; i++)
1034 free_subpicture(&is->subpq[i]);
1035 SDL_DestroyMutex(is->pictq_mutex);
1036 SDL_DestroyCond(is->pictq_cond);
1037 SDL_DestroyMutex(is->subpq_mutex);
1038 SDL_DestroyCond(is->subpq_cond);
1039 SDL_DestroyCond(is->continue_read_thread);
1040 #if !CONFIG_AVFILTER
1041 sws_freeContext(is->img_convert_ctx);
1046 static void do_exit(VideoState *is)
1051 av_lockmgr_register(NULL);
1054 av_freep(&vfilters);
1056 avformat_network_deinit();
1060 av_log(NULL, AV_LOG_QUIET, "%s", "");
1064 static void sigterm_handler(int sig)
1069 static void set_default_window_size(VideoPicture *vp)
1072 calculate_display_rect(&rect, 0, 0, INT_MAX, vp->height, vp);
1073 default_width = rect.w;
1074 default_height = rect.h;
1077 static int video_open(VideoState *is, int force_set_video_mode, VideoPicture *vp)
1079 int flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;
1082 if (is_full_screen) flags |= SDL_FULLSCREEN;
1083 else flags |= SDL_RESIZABLE;
1085 if (vp && vp->width)
1086 set_default_window_size(vp);
1088 if (is_full_screen && fs_screen_width) {
1089 w = fs_screen_width;
1090 h = fs_screen_height;
1091 } else if (!is_full_screen && screen_width) {
1098 w = FFMIN(16383, w);
1099 if (screen && is->width == screen->w && screen->w == w
1100 && is->height== screen->h && screen->h == h && !force_set_video_mode)
1102 screen = SDL_SetVideoMode(w, h, 0, flags);
1104 av_log(NULL, AV_LOG_FATAL, "SDL: could not set video mode - exiting\n");
1108 window_title = input_filename;
1109 SDL_WM_SetCaption(window_title, window_title);
1111 is->width = screen->w;
1112 is->height = screen->h;
1117 /* display the current picture, if any */
1118 static void video_display(VideoState *is)
1121 video_open(is, 0, NULL);
1122 if (is->audio_st && is->show_mode != SHOW_MODE_VIDEO)
1123 video_audio_display(is);
1124 else if (is->video_st)
1125 video_image_display(is);
1128 static double get_clock(Clock *c)
1130 if (*c->queue_serial != c->serial)
1135 double time = av_gettime() / 1000000.0;
1136 return c->pts_drift + time - (time - c->last_updated) * (1.0 - c->speed);
1140 static void set_clock_at(Clock *c, double pts, int serial, double time)
1143 c->last_updated = time;
1144 c->pts_drift = c->pts - time;
1148 static void set_clock(Clock *c, double pts, int serial)
1150 double time = av_gettime() / 1000000.0;
1151 set_clock_at(c, pts, serial, time);
1154 static void set_clock_speed(Clock *c, double speed)
1156 set_clock(c, get_clock(c), c->serial);
1160 static void init_clock(Clock *c, int *queue_serial)
1164 c->queue_serial = queue_serial;
1165 set_clock(c, NAN, -1);
1168 static void sync_clock_to_slave(Clock *c, Clock *slave)
1170 double clock = get_clock(c);
1171 double slave_clock = get_clock(slave);
1172 if (!isnan(slave_clock) && (isnan(clock) || fabs(clock - slave_clock) > AV_NOSYNC_THRESHOLD))
1173 set_clock(c, slave_clock, slave->serial);
1176 static int get_master_sync_type(VideoState *is) {
1177 if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
1179 return AV_SYNC_VIDEO_MASTER;
1181 return AV_SYNC_AUDIO_MASTER;
1182 } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
1184 return AV_SYNC_AUDIO_MASTER;
1186 return AV_SYNC_EXTERNAL_CLOCK;
1188 return AV_SYNC_EXTERNAL_CLOCK;
1192 /* get the current master clock value */
1193 static double get_master_clock(VideoState *is)
1197 switch (get_master_sync_type(is)) {
1198 case AV_SYNC_VIDEO_MASTER:
1199 val = get_clock(&is->vidclk);
1201 case AV_SYNC_AUDIO_MASTER:
1202 val = get_clock(&is->audclk);
1205 val = get_clock(&is->extclk);
1211 static void check_external_clock_speed(VideoState *is) {
1212 if (is->video_stream >= 0 && is->videoq.nb_packets <= MIN_FRAMES / 2 ||
1213 is->audio_stream >= 0 && is->audioq.nb_packets <= MIN_FRAMES / 2) {
1214 set_clock_speed(&is->extclk, FFMAX(EXTERNAL_CLOCK_SPEED_MIN, is->extclk.speed - EXTERNAL_CLOCK_SPEED_STEP));
1215 } else if ((is->video_stream < 0 || is->videoq.nb_packets > MIN_FRAMES * 2) &&
1216 (is->audio_stream < 0 || is->audioq.nb_packets > MIN_FRAMES * 2)) {
1217 set_clock_speed(&is->extclk, FFMIN(EXTERNAL_CLOCK_SPEED_MAX, is->extclk.speed + EXTERNAL_CLOCK_SPEED_STEP));
1219 double speed = is->extclk.speed;
1221 set_clock_speed(&is->extclk, speed + EXTERNAL_CLOCK_SPEED_STEP * (1.0 - speed) / fabs(1.0 - speed));
1225 /* seek in the stream */
1226 static void stream_seek(VideoState *is, int64_t pos, int64_t rel, int seek_by_bytes)
1228 if (!is->seek_req) {
1231 is->seek_flags &= ~AVSEEK_FLAG_BYTE;
1233 is->seek_flags |= AVSEEK_FLAG_BYTE;
1235 SDL_CondSignal(is->continue_read_thread);
1239 /* pause or resume the video */
1240 static void stream_toggle_pause(VideoState *is)
1243 is->frame_timer += av_gettime() / 1000000.0 + is->vidclk.pts_drift - is->vidclk.pts;
1244 if (is->read_pause_return != AVERROR(ENOSYS)) {
1245 is->vidclk.paused = 0;
1247 set_clock(&is->vidclk, get_clock(&is->vidclk), is->vidclk.serial);
1249 set_clock(&is->extclk, get_clock(&is->extclk), is->extclk.serial);
1250 is->paused = is->audclk.paused = is->vidclk.paused = is->extclk.paused = !is->paused;
1253 static void toggle_pause(VideoState *is)
1255 stream_toggle_pause(is);
1259 static void step_to_next_frame(VideoState *is)
1261 /* if the stream is paused unpause it, then step */
1263 stream_toggle_pause(is);
1267 static double compute_target_delay(double delay, VideoState *is)
1269 double sync_threshold, diff;
1271 /* update delay to follow master synchronisation source */
1272 if (get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER) {
1273 /* if video is slave, we try to correct big delays by
1274 duplicating or deleting a frame */
1275 diff = get_clock(&is->vidclk) - get_master_clock(is);
1277 /* skip or repeat frame. We take into account the
1278 delay to compute the threshold. I still don't know
1279 if it is the best guess */
1280 sync_threshold = FFMAX(AV_SYNC_THRESHOLD_MIN, FFMIN(AV_SYNC_THRESHOLD_MAX, delay));
1281 if (!isnan(diff) && fabs(diff) < is->max_frame_duration) {
1282 if (diff <= -sync_threshold)
1283 delay = FFMAX(0, delay + diff);
1284 else if (diff >= sync_threshold && delay > AV_SYNC_FRAMEDUP_THRESHOLD)
1285 delay = delay + diff;
1286 else if (diff >= sync_threshold)
1291 av_dlog(NULL, "video: delay=%0.3f A-V=%f\n",
1297 static double vp_duration(VideoState *is, VideoPicture *vp, VideoPicture *nextvp) {
1298 if (vp->serial == nextvp->serial) {
1299 double duration = nextvp->pts - vp->pts;
1300 if (isnan(duration) || duration <= 0 || duration > is->max_frame_duration)
1301 return vp->duration;
1309 static void pictq_next_picture(VideoState *is) {
1310 /* update queue size and signal for next picture */
1311 if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
1312 is->pictq_rindex = 0;
1314 SDL_LockMutex(is->pictq_mutex);
1316 SDL_CondSignal(is->pictq_cond);
1317 SDL_UnlockMutex(is->pictq_mutex);
1320 static int pictq_prev_picture(VideoState *is) {
1321 VideoPicture *prevvp;
1323 /* update queue size and signal for the previous picture */
1324 prevvp = &is->pictq[(is->pictq_rindex + VIDEO_PICTURE_QUEUE_SIZE - 1) % VIDEO_PICTURE_QUEUE_SIZE];
1325 if (prevvp->allocated && prevvp->serial == is->videoq.serial) {
1326 SDL_LockMutex(is->pictq_mutex);
1327 if (is->pictq_size < VIDEO_PICTURE_QUEUE_SIZE) {
1328 if (--is->pictq_rindex == -1)
1329 is->pictq_rindex = VIDEO_PICTURE_QUEUE_SIZE - 1;
1333 SDL_CondSignal(is->pictq_cond);
1334 SDL_UnlockMutex(is->pictq_mutex);
1339 static void update_video_pts(VideoState *is, double pts, int64_t pos, int serial) {
1340 /* update current video pts */
1341 set_clock(&is->vidclk, pts, serial);
1342 sync_clock_to_slave(&is->extclk, &is->vidclk);
1343 is->video_current_pos = pos;
1346 /* called to display each frame */
1347 static void video_refresh(void *opaque, double *remaining_time)
1349 VideoState *is = opaque;
1352 SubPicture *sp, *sp2;
1354 if (!is->paused && get_master_sync_type(is) == AV_SYNC_EXTERNAL_CLOCK && is->realtime)
1355 check_external_clock_speed(is);
1357 if (!display_disable && is->show_mode != SHOW_MODE_VIDEO && is->audio_st) {
1358 time = av_gettime() / 1000000.0;
1359 if (is->force_refresh || is->last_vis_time + rdftspeed < time) {
1361 is->last_vis_time = time;
1363 *remaining_time = FFMIN(*remaining_time, is->last_vis_time + rdftspeed - time);
1368 if (is->force_refresh)
1369 redisplay = pictq_prev_picture(is);
1371 if (is->pictq_size == 0) {
1372 // nothing to do, no picture to display in the queue
1374 double last_duration, duration, delay;
1375 VideoPicture *vp, *lastvp;
1377 /* dequeue the picture */
1378 vp = &is->pictq[is->pictq_rindex];
1379 lastvp = &is->pictq[(is->pictq_rindex + VIDEO_PICTURE_QUEUE_SIZE - 1) % VIDEO_PICTURE_QUEUE_SIZE];
1381 if (vp->serial != is->videoq.serial) {
1382 pictq_next_picture(is);
1383 is->video_current_pos = -1;
1388 if (lastvp->serial != vp->serial && !redisplay)
1389 is->frame_timer = av_gettime() / 1000000.0;
1394 /* compute nominal last_duration */
1395 last_duration = vp_duration(is, lastvp, vp);
1399 delay = compute_target_delay(last_duration, is);
1401 time= av_gettime()/1000000.0;
1402 if (time < is->frame_timer + delay && !redisplay) {
1403 *remaining_time = FFMIN(is->frame_timer + delay - time, *remaining_time);
1407 is->frame_timer += delay;
1408 if (delay > 0 && time - is->frame_timer > AV_SYNC_THRESHOLD_MAX)
1409 is->frame_timer = time;
1411 SDL_LockMutex(is->pictq_mutex);
1412 if (!redisplay && !isnan(vp->pts))
1413 update_video_pts(is, vp->pts, vp->pos, vp->serial);
1414 SDL_UnlockMutex(is->pictq_mutex);
1416 if (is->pictq_size > 1) {
1417 VideoPicture *nextvp = &is->pictq[(is->pictq_rindex + 1) % VIDEO_PICTURE_QUEUE_SIZE];
1418 duration = vp_duration(is, vp, nextvp);
1419 if(!is->step && (redisplay || framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) && time > is->frame_timer + duration){
1421 is->frame_drops_late++;
1422 pictq_next_picture(is);
1428 if (is->subtitle_st) {
1429 while (is->subpq_size > 0) {
1430 sp = &is->subpq[is->subpq_rindex];
1432 if (is->subpq_size > 1)
1433 sp2 = &is->subpq[(is->subpq_rindex + 1) % SUBPICTURE_QUEUE_SIZE];
1437 if (sp->serial != is->subtitleq.serial
1438 || (is->vidclk.pts > (sp->pts + ((float) sp->sub.end_display_time / 1000)))
1439 || (sp2 && is->vidclk.pts > (sp2->pts + ((float) sp2->sub.start_display_time / 1000))))
1441 free_subpicture(sp);
1443 /* update queue size and signal for next picture */
1444 if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
1445 is->subpq_rindex = 0;
1447 SDL_LockMutex(is->subpq_mutex);
1449 SDL_CondSignal(is->subpq_cond);
1450 SDL_UnlockMutex(is->subpq_mutex);
1458 /* display picture */
1459 if (!display_disable && is->show_mode == SHOW_MODE_VIDEO)
1462 pictq_next_picture(is);
1464 if (is->step && !is->paused)
1465 stream_toggle_pause(is);
1468 is->force_refresh = 0;
1470 static int64_t last_time;
1472 int aqsize, vqsize, sqsize;
1475 cur_time = av_gettime();
1476 if (!last_time || (cur_time - last_time) >= 30000) {
1481 aqsize = is->audioq.size;
1483 vqsize = is->videoq.size;
1484 if (is->subtitle_st)
1485 sqsize = is->subtitleq.size;
1487 if (is->audio_st && is->video_st)
1488 av_diff = get_clock(&is->audclk) - get_clock(&is->vidclk);
1489 else if (is->video_st)
1490 av_diff = get_master_clock(is) - get_clock(&is->vidclk);
1491 else if (is->audio_st)
1492 av_diff = get_master_clock(is) - get_clock(&is->audclk);
1493 av_log(NULL, AV_LOG_INFO,
1494 "%7.2f %s:%7.3f fd=%4d aq=%5dKB vq=%5dKB sq=%5dB f=%"PRId64"/%"PRId64" \r",
1495 get_master_clock(is),
1496 (is->audio_st && is->video_st) ? "A-V" : (is->video_st ? "M-V" : (is->audio_st ? "M-A" : " ")),
1498 is->frame_drops_early + is->frame_drops_late,
1502 is->video_st ? is->video_st->codec->pts_correction_num_faulty_dts : 0,
1503 is->video_st ? is->video_st->codec->pts_correction_num_faulty_pts : 0);
1505 last_time = cur_time;
1510 /* allocate a picture (needs to do that in main thread to avoid
1511 potential locking problems */
1512 static void alloc_picture(VideoState *is)
1517 vp = &is->pictq[is->pictq_windex];
1521 video_open(is, 0, vp);
1523 vp->bmp = SDL_CreateYUVOverlay(vp->width, vp->height,
1526 bufferdiff = vp->bmp ? FFMAX(vp->bmp->pixels[0], vp->bmp->pixels[1]) - FFMIN(vp->bmp->pixels[0], vp->bmp->pixels[1]) : 0;
1527 if (!vp->bmp || vp->bmp->pitches[0] < vp->width || bufferdiff < (int64_t)vp->height * vp->bmp->pitches[0]) {
1528 /* SDL allocates a buffer smaller than requested if the video
1529 * overlay hardware is unable to support the requested size. */
1530 av_log(NULL, AV_LOG_FATAL,
1531 "Error: the video system does not support an image\n"
1532 "size of %dx%d pixels. Try using -lowres or -vf \"scale=w:h\"\n"
1533 "to reduce the image size.\n", vp->width, vp->height );
1537 SDL_LockMutex(is->pictq_mutex);
1539 SDL_CondSignal(is->pictq_cond);
1540 SDL_UnlockMutex(is->pictq_mutex);
1543 static void duplicate_right_border_pixels(SDL_Overlay *bmp) {
1544 int i, width, height;
1546 for (i = 0; i < 3; i++) {
1553 if (bmp->pitches[i] > width) {
1554 maxp = bmp->pixels[i] + bmp->pitches[i] * height - 1;
1555 for (p = bmp->pixels[i] + width - 1; p < maxp; p += bmp->pitches[i])
1561 static int queue_picture(VideoState *is, AVFrame *src_frame, double pts, double duration, int64_t pos, int serial)
1565 #if defined(DEBUG_SYNC) && 0
1566 printf("frame_type=%c pts=%0.3f\n",
1567 av_get_picture_type_char(src_frame->pict_type), pts);
1570 /* wait until we have space to put a new picture */
1571 SDL_LockMutex(is->pictq_mutex);
1573 /* keep the last already displayed picture in the queue */
1574 while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE - 1 &&
1575 !is->videoq.abort_request) {
1576 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1578 SDL_UnlockMutex(is->pictq_mutex);
1580 if (is->videoq.abort_request)
1583 vp = &is->pictq[is->pictq_windex];
1585 vp->sar = src_frame->sample_aspect_ratio;
1587 /* alloc or resize hardware picture buffer */
1588 if (!vp->bmp || vp->reallocate || !vp->allocated ||
1589 vp->width != src_frame->width ||
1590 vp->height != src_frame->height) {
1595 vp->width = src_frame->width;
1596 vp->height = src_frame->height;
1598 /* the allocation must be done in the main thread to avoid
1599 locking problems. */
1600 event.type = FF_ALLOC_EVENT;
1601 event.user.data1 = is;
1602 SDL_PushEvent(&event);
1604 /* wait until the picture is allocated */
1605 SDL_LockMutex(is->pictq_mutex);
1606 while (!vp->allocated && !is->videoq.abort_request) {
1607 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1609 /* if the queue is aborted, we have to pop the pending ALLOC event or wait for the allocation to complete */
1610 if (is->videoq.abort_request && SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_EVENTMASK(FF_ALLOC_EVENT)) != 1) {
1611 while (!vp->allocated) {
1612 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1615 SDL_UnlockMutex(is->pictq_mutex);
1617 if (is->videoq.abort_request)
1621 /* if the frame is not skipped, then display it */
1623 AVPicture pict = { { 0 } };
1625 /* get a pointer on the bitmap */
1626 SDL_LockYUVOverlay (vp->bmp);
1628 pict.data[0] = vp->bmp->pixels[0];
1629 pict.data[1] = vp->bmp->pixels[2];
1630 pict.data[2] = vp->bmp->pixels[1];
1632 pict.linesize[0] = vp->bmp->pitches[0];
1633 pict.linesize[1] = vp->bmp->pitches[2];
1634 pict.linesize[2] = vp->bmp->pitches[1];
1637 // FIXME use direct rendering
1638 av_picture_copy(&pict, (AVPicture *)src_frame,
1639 src_frame->format, vp->width, vp->height);
1641 av_opt_get_int(sws_opts, "sws_flags", 0, &sws_flags);
1642 is->img_convert_ctx = sws_getCachedContext(is->img_convert_ctx,
1643 vp->width, vp->height, src_frame->format, vp->width, vp->height,
1644 AV_PIX_FMT_YUV420P, sws_flags, NULL, NULL, NULL);
1645 if (is->img_convert_ctx == NULL) {
1646 av_log(NULL, AV_LOG_FATAL, "Cannot initialize the conversion context\n");
1649 sws_scale(is->img_convert_ctx, src_frame->data, src_frame->linesize,
1650 0, vp->height, pict.data, pict.linesize);
1652 /* workaround SDL PITCH_WORKAROUND */
1653 duplicate_right_border_pixels(vp->bmp);
1654 /* update the bitmap content */
1655 SDL_UnlockYUVOverlay(vp->bmp);
1658 vp->duration = duration;
1660 vp->serial = serial;
1662 /* now we can update the picture count */
1663 if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
1664 is->pictq_windex = 0;
1665 SDL_LockMutex(is->pictq_mutex);
1667 SDL_UnlockMutex(is->pictq_mutex);
1672 static int get_video_frame(VideoState *is, AVFrame *frame, AVPacket *pkt, int *serial)
1676 if (packet_queue_get(&is->videoq, pkt, 1, serial) < 0)
1679 if (pkt->data == flush_pkt.data) {
1680 avcodec_flush_buffers(is->video_st->codec);
1684 if(avcodec_decode_video2(is->video_st->codec, frame, &got_picture, pkt) < 0)
1687 if (!got_picture && !pkt->data)
1688 is->video_finished = *serial;
1694 if (decoder_reorder_pts == -1) {
1695 frame->pts = av_frame_get_best_effort_timestamp(frame);
1696 } else if (decoder_reorder_pts) {
1697 frame->pts = frame->pkt_pts;
1699 frame->pts = frame->pkt_dts;
1702 if (frame->pts != AV_NOPTS_VALUE)
1703 dpts = av_q2d(is->video_st->time_base) * frame->pts;
1705 frame->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, frame);
1707 if (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) {
1708 if (frame->pts != AV_NOPTS_VALUE) {
1709 double diff = dpts - get_master_clock(is);
1710 if (!isnan(diff) && fabs(diff) < AV_NOSYNC_THRESHOLD &&
1711 diff - is->frame_last_filter_delay < 0 &&
1712 *serial == is->vidclk.serial &&
1713 is->videoq.nb_packets) {
1714 is->frame_drops_early++;
1715 av_frame_unref(frame);
1727 static int configure_filtergraph(AVFilterGraph *graph, const char *filtergraph,
1728 AVFilterContext *source_ctx, AVFilterContext *sink_ctx)
1731 AVFilterInOut *outputs = NULL, *inputs = NULL;
1734 outputs = avfilter_inout_alloc();
1735 inputs = avfilter_inout_alloc();
1736 if (!outputs || !inputs) {
1737 ret = AVERROR(ENOMEM);
1741 outputs->name = av_strdup("in");
1742 outputs->filter_ctx = source_ctx;
1743 outputs->pad_idx = 0;
1744 outputs->next = NULL;
1746 inputs->name = av_strdup("out");
1747 inputs->filter_ctx = sink_ctx;
1748 inputs->pad_idx = 0;
1749 inputs->next = NULL;
1751 if ((ret = avfilter_graph_parse_ptr(graph, filtergraph, &inputs, &outputs, NULL)) < 0)
1754 if ((ret = avfilter_link(source_ctx, 0, sink_ctx, 0)) < 0)
1758 ret = avfilter_graph_config(graph, NULL);
1760 avfilter_inout_free(&outputs);
1761 avfilter_inout_free(&inputs);
1765 static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const char *vfilters, AVFrame *frame)
1767 static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };
1768 char sws_flags_str[128];
1769 char buffersrc_args[256];
1771 AVFilterContext *filt_src = NULL, *filt_out = NULL, *filt_crop;
1772 AVCodecContext *codec = is->video_st->codec;
1773 AVRational fr = av_guess_frame_rate(is->ic, is->video_st, NULL);
1775 av_opt_get_int(sws_opts, "sws_flags", 0, &sws_flags);
1776 snprintf(sws_flags_str, sizeof(sws_flags_str), "flags=%"PRId64, sws_flags);
1777 graph->scale_sws_opts = av_strdup(sws_flags_str);
1779 snprintf(buffersrc_args, sizeof(buffersrc_args),
1780 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
1781 frame->width, frame->height, frame->format,
1782 is->video_st->time_base.num, is->video_st->time_base.den,
1783 codec->sample_aspect_ratio.num, FFMAX(codec->sample_aspect_ratio.den, 1));
1784 if (fr.num && fr.den)
1785 av_strlcatf(buffersrc_args, sizeof(buffersrc_args), ":frame_rate=%d/%d", fr.num, fr.den);
1787 if ((ret = avfilter_graph_create_filter(&filt_src,
1788 avfilter_get_by_name("buffer"),
1789 "ffplay_buffer", buffersrc_args, NULL,
1793 ret = avfilter_graph_create_filter(&filt_out,
1794 avfilter_get_by_name("buffersink"),
1795 "ffplay_buffersink", NULL, NULL, graph);
1799 if ((ret = av_opt_set_int_list(filt_out, "pix_fmts", pix_fmts, AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN)) < 0)
1802 /* SDL YUV code is not handling odd width/height for some driver
1803 * combinations, therefore we crop the picture to an even width/height. */
1804 if ((ret = avfilter_graph_create_filter(&filt_crop,
1805 avfilter_get_by_name("crop"),
1806 "ffplay_crop", "floor(in_w/2)*2:floor(in_h/2)*2", NULL, graph)) < 0)
1808 if ((ret = avfilter_link(filt_crop, 0, filt_out, 0)) < 0)
1811 if ((ret = configure_filtergraph(graph, vfilters, filt_src, filt_crop)) < 0)
1814 is->in_video_filter = filt_src;
1815 is->out_video_filter = filt_out;
1821 static int configure_audio_filters(VideoState *is, const char *afilters, int force_output_format)
1823 static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE };
1824 int sample_rates[2] = { 0, -1 };
1825 int64_t channel_layouts[2] = { 0, -1 };
1826 int channels[2] = { 0, -1 };
1827 AVFilterContext *filt_asrc = NULL, *filt_asink = NULL;
1828 char aresample_swr_opts[512] = "";
1829 AVDictionaryEntry *e = NULL;
1830 char asrc_args[256];
1833 avfilter_graph_free(&is->agraph);
1834 if (!(is->agraph = avfilter_graph_alloc()))
1835 return AVERROR(ENOMEM);
1837 while ((e = av_dict_get(swr_opts, "", e, AV_DICT_IGNORE_SUFFIX)))
1838 av_strlcatf(aresample_swr_opts, sizeof(aresample_swr_opts), "%s=%s:", e->key, e->value);
1839 if (strlen(aresample_swr_opts))
1840 aresample_swr_opts[strlen(aresample_swr_opts)-1] = '\0';
1841 av_opt_set(is->agraph, "aresample_swr_opts", aresample_swr_opts, 0);
1843 ret = snprintf(asrc_args, sizeof(asrc_args),
1844 "sample_rate=%d:sample_fmt=%s:channels=%d:time_base=%d/%d",
1845 is->audio_filter_src.freq, av_get_sample_fmt_name(is->audio_filter_src.fmt),
1846 is->audio_filter_src.channels,
1847 1, is->audio_filter_src.freq);
1848 if (is->audio_filter_src.channel_layout)
1849 snprintf(asrc_args + ret, sizeof(asrc_args) - ret,
1850 ":channel_layout=0x%"PRIx64, is->audio_filter_src.channel_layout);
1852 ret = avfilter_graph_create_filter(&filt_asrc,
1853 avfilter_get_by_name("abuffer"), "ffplay_abuffer",
1854 asrc_args, NULL, is->agraph);
1859 ret = avfilter_graph_create_filter(&filt_asink,
1860 avfilter_get_by_name("abuffersink"), "ffplay_abuffersink",
1861 NULL, NULL, is->agraph);
1865 if ((ret = av_opt_set_int_list(filt_asink, "sample_fmts", sample_fmts, AV_SAMPLE_FMT_NONE, AV_OPT_SEARCH_CHILDREN)) < 0)
1867 if ((ret = av_opt_set_int(filt_asink, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
1870 if (force_output_format) {
1871 channel_layouts[0] = is->audio_tgt.channel_layout;
1872 channels [0] = is->audio_tgt.channels;
1873 sample_rates [0] = is->audio_tgt.freq;
1874 if ((ret = av_opt_set_int(filt_asink, "all_channel_counts", 0, AV_OPT_SEARCH_CHILDREN)) < 0)
1876 if ((ret = av_opt_set_int_list(filt_asink, "channel_layouts", channel_layouts, -1, AV_OPT_SEARCH_CHILDREN)) < 0)
1878 if ((ret = av_opt_set_int_list(filt_asink, "channel_counts" , channels , -1, AV_OPT_SEARCH_CHILDREN)) < 0)
1880 if ((ret = av_opt_set_int_list(filt_asink, "sample_rates" , sample_rates , -1, AV_OPT_SEARCH_CHILDREN)) < 0)
1885 if ((ret = configure_filtergraph(is->agraph, afilters, filt_asrc, filt_asink)) < 0)
1888 is->in_audio_filter = filt_asrc;
1889 is->out_audio_filter = filt_asink;
1893 avfilter_graph_free(&is->agraph);
1896 #endif /* CONFIG_AVFILTER */
1898 static int video_thread(void *arg)
1900 AVPacket pkt = { 0 };
1901 VideoState *is = arg;
1902 AVFrame *frame = av_frame_alloc();
1907 AVRational tb = is->video_st->time_base;
1908 AVRational frame_rate = av_guess_frame_rate(is->ic, is->video_st, NULL);
1911 AVFilterGraph *graph = avfilter_graph_alloc();
1912 AVFilterContext *filt_out = NULL, *filt_in = NULL;
1915 enum AVPixelFormat last_format = -2;
1916 int last_serial = -1;
1920 while (is->paused && !is->videoq.abort_request)
1923 avcodec_get_frame_defaults(frame);
1924 av_free_packet(&pkt);
1926 ret = get_video_frame(is, frame, &pkt, &serial);
1933 if ( last_w != frame->width
1934 || last_h != frame->height
1935 || last_format != frame->format
1936 || last_serial != serial) {
1937 av_log(NULL, AV_LOG_DEBUG,
1938 "Video frame changed from size:%dx%d format:%s serial:%d to size:%dx%d format:%s serial:%d\n",
1940 (const char *)av_x_if_null(av_get_pix_fmt_name(last_format), "none"), last_serial,
1941 frame->width, frame->height,
1942 (const char *)av_x_if_null(av_get_pix_fmt_name(frame->format), "none"), serial);
1943 avfilter_graph_free(&graph);
1944 graph = avfilter_graph_alloc();
1945 if ((ret = configure_video_filters(graph, is, vfilters, frame)) < 0) {
1947 event.type = FF_QUIT_EVENT;
1948 event.user.data1 = is;
1949 SDL_PushEvent(&event);
1950 av_free_packet(&pkt);
1953 filt_in = is->in_video_filter;
1954 filt_out = is->out_video_filter;
1955 last_w = frame->width;
1956 last_h = frame->height;
1957 last_format = frame->format;
1958 last_serial = serial;
1959 frame_rate = filt_out->inputs[0]->frame_rate;
1962 ret = av_buffersrc_add_frame(filt_in, frame);
1965 av_frame_unref(frame);
1966 avcodec_get_frame_defaults(frame);
1967 av_free_packet(&pkt);
1970 is->frame_last_returned_time = av_gettime() / 1000000.0;
1972 ret = av_buffersink_get_frame_flags(filt_out, frame, 0);
1974 if (ret == AVERROR_EOF)
1975 is->video_finished = serial;
1980 is->frame_last_filter_delay = av_gettime() / 1000000.0 - is->frame_last_returned_time;
1981 if (fabs(is->frame_last_filter_delay) > AV_NOSYNC_THRESHOLD / 10.0)
1982 is->frame_last_filter_delay = 0;
1983 tb = filt_out->inputs[0]->time_base;
1985 duration = (frame_rate.num && frame_rate.den ? av_q2d((AVRational){frame_rate.den, frame_rate.num}) : 0);
1986 pts = (frame->pts == AV_NOPTS_VALUE) ? NAN : frame->pts * av_q2d(tb);
1987 ret = queue_picture(is, frame, pts, duration, av_frame_get_pkt_pos(frame), serial);
1988 av_frame_unref(frame);
1998 avfilter_graph_free(&graph);
2000 av_free_packet(&pkt);
2001 av_frame_free(&frame);
2005 static int subtitle_thread(void *arg)
2007 VideoState *is = arg;
2009 AVPacket pkt1, *pkt = &pkt1;
2014 int r, g, b, y, u, v, a;
2017 while (is->paused && !is->subtitleq.abort_request) {
2020 if (packet_queue_get(&is->subtitleq, pkt, 1, &serial) < 0)
2023 if (pkt->data == flush_pkt.data) {
2024 avcodec_flush_buffers(is->subtitle_st->codec);
2027 SDL_LockMutex(is->subpq_mutex);
2028 while (is->subpq_size >= SUBPICTURE_QUEUE_SIZE &&
2029 !is->subtitleq.abort_request) {
2030 SDL_CondWait(is->subpq_cond, is->subpq_mutex);
2032 SDL_UnlockMutex(is->subpq_mutex);
2034 if (is->subtitleq.abort_request)
2037 sp = &is->subpq[is->subpq_windex];
2039 /* NOTE: ipts is the PTS of the _first_ picture beginning in
2040 this packet, if any */
2042 if (pkt->pts != AV_NOPTS_VALUE)
2043 pts = av_q2d(is->subtitle_st->time_base) * pkt->pts;
2045 avcodec_decode_subtitle2(is->subtitle_st->codec, &sp->sub,
2046 &got_subtitle, pkt);
2047 if (got_subtitle && sp->sub.format == 0) {
2048 if (sp->sub.pts != AV_NOPTS_VALUE)
2049 pts = sp->sub.pts / (double)AV_TIME_BASE;
2051 sp->serial = serial;
2053 for (i = 0; i < sp->sub.num_rects; i++)
2055 for (j = 0; j < sp->sub.rects[i]->nb_colors; j++)
2057 RGBA_IN(r, g, b, a, (uint32_t*)sp->sub.rects[i]->pict.data[1] + j);
2058 y = RGB_TO_Y_CCIR(r, g, b);
2059 u = RGB_TO_U_CCIR(r, g, b, 0);
2060 v = RGB_TO_V_CCIR(r, g, b, 0);
2061 YUVA_OUT((uint32_t*)sp->sub.rects[i]->pict.data[1] + j, y, u, v, a);
2065 /* now we can update the picture count */
2066 if (++is->subpq_windex == SUBPICTURE_QUEUE_SIZE)
2067 is->subpq_windex = 0;
2068 SDL_LockMutex(is->subpq_mutex);
2070 SDL_UnlockMutex(is->subpq_mutex);
2071 } else if (got_subtitle) {
2072 avsubtitle_free(&sp->sub);
2074 av_free_packet(pkt);
2079 /* copy samples for viewing in editor window */
2080 static void update_sample_display(VideoState *is, short *samples, int samples_size)
2084 size = samples_size / sizeof(short);
2086 len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
2089 memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
2091 is->sample_array_index += len;
2092 if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
2093 is->sample_array_index = 0;
2098 /* return the wanted number of samples to get better sync if sync_type is video
2099 * or external master clock */
2100 static int synchronize_audio(VideoState *is, int nb_samples)
2102 int wanted_nb_samples = nb_samples;
2104 /* if not master, then we try to remove or add samples to correct the clock */
2105 if (get_master_sync_type(is) != AV_SYNC_AUDIO_MASTER) {
2106 double diff, avg_diff;
2107 int min_nb_samples, max_nb_samples;
2109 diff = get_clock(&is->audclk) - get_master_clock(is);
2111 if (!isnan(diff) && fabs(diff) < AV_NOSYNC_THRESHOLD) {
2112 is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
2113 if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
2114 /* not enough measures to have a correct estimate */
2115 is->audio_diff_avg_count++;
2117 /* estimate the A-V difference */
2118 avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
2120 if (fabs(avg_diff) >= is->audio_diff_threshold) {
2121 wanted_nb_samples = nb_samples + (int)(diff * is->audio_src.freq);
2122 min_nb_samples = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100));
2123 max_nb_samples = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100));
2124 wanted_nb_samples = FFMIN(FFMAX(wanted_nb_samples, min_nb_samples), max_nb_samples);
2126 av_dlog(NULL, "diff=%f adiff=%f sample_diff=%d apts=%0.3f %f\n",
2127 diff, avg_diff, wanted_nb_samples - nb_samples,
2128 is->audio_clock, is->audio_diff_threshold);
2131 /* too big difference : may be initial PTS errors, so
2133 is->audio_diff_avg_count = 0;
2134 is->audio_diff_cum = 0;
2138 return wanted_nb_samples;
2142 * Decode one audio frame and return its uncompressed size.
2144 * The processed audio frame is decoded, converted if required, and
2145 * stored in is->audio_buf, with size in bytes given by the return
2148 static int audio_decode_frame(VideoState *is)
2150 AVPacket *pkt_temp = &is->audio_pkt_temp;
2151 AVPacket *pkt = &is->audio_pkt;
2152 AVCodecContext *dec = is->audio_st->codec;
2153 int len1, data_size, resampled_data_size;
2154 int64_t dec_channel_layout;
2156 av_unused double audio_clock0;
2157 int wanted_nb_samples;
2163 /* NOTE: the audio packet can contain several frames */
2164 while (pkt_temp->stream_index != -1 || is->audio_buf_frames_pending) {
2166 if (!(is->frame = av_frame_alloc()))
2167 return AVERROR(ENOMEM);
2169 av_frame_unref(is->frame);
2172 if (is->audioq.serial != is->audio_pkt_temp_serial)
2178 if (!is->audio_buf_frames_pending) {
2179 len1 = avcodec_decode_audio4(dec, is->frame, &got_frame, pkt_temp);
2181 /* if error, we skip the frame */
2187 pkt_temp->pts = AV_NOPTS_VALUE;
2188 pkt_temp->data += len1;
2189 pkt_temp->size -= len1;
2190 if (pkt_temp->data && pkt_temp->size <= 0 || !pkt_temp->data && !got_frame)
2191 pkt_temp->stream_index = -1;
2192 if (!pkt_temp->data && !got_frame)
2193 is->audio_finished = is->audio_pkt_temp_serial;
2198 tb = (AVRational){1, is->frame->sample_rate};
2199 if (is->frame->pts != AV_NOPTS_VALUE)
2200 is->frame->pts = av_rescale_q(is->frame->pts, dec->time_base, tb);
2201 else if (is->frame->pkt_pts != AV_NOPTS_VALUE)
2202 is->frame->pts = av_rescale_q(is->frame->pkt_pts, is->audio_st->time_base, tb);
2203 else if (is->audio_frame_next_pts != AV_NOPTS_VALUE)
2205 is->frame->pts = av_rescale_q(is->audio_frame_next_pts, (AVRational){1, is->audio_filter_src.freq}, tb);
2207 is->frame->pts = av_rescale_q(is->audio_frame_next_pts, (AVRational){1, is->audio_src.freq}, tb);
2210 if (is->frame->pts != AV_NOPTS_VALUE)
2211 is->audio_frame_next_pts = is->frame->pts + is->frame->nb_samples;
2214 dec_channel_layout = get_valid_channel_layout(is->frame->channel_layout, av_frame_get_channels(is->frame));
2217 cmp_audio_fmts(is->audio_filter_src.fmt, is->audio_filter_src.channels,
2218 is->frame->format, av_frame_get_channels(is->frame)) ||
2219 is->audio_filter_src.channel_layout != dec_channel_layout ||
2220 is->audio_filter_src.freq != is->frame->sample_rate ||
2221 is->audio_pkt_temp_serial != is->audio_last_serial;
2224 char buf1[1024], buf2[1024];
2225 av_get_channel_layout_string(buf1, sizeof(buf1), -1, is->audio_filter_src.channel_layout);
2226 av_get_channel_layout_string(buf2, sizeof(buf2), -1, dec_channel_layout);
2227 av_log(NULL, AV_LOG_DEBUG,
2228 "Audio frame changed from rate:%d ch:%d fmt:%s layout:%s serial:%d to rate:%d ch:%d fmt:%s layout:%s serial:%d\n",
2229 is->audio_filter_src.freq, is->audio_filter_src.channels, av_get_sample_fmt_name(is->audio_filter_src.fmt), buf1, is->audio_last_serial,
2230 is->frame->sample_rate, av_frame_get_channels(is->frame), av_get_sample_fmt_name(is->frame->format), buf2, is->audio_pkt_temp_serial);
2232 is->audio_filter_src.fmt = is->frame->format;
2233 is->audio_filter_src.channels = av_frame_get_channels(is->frame);
2234 is->audio_filter_src.channel_layout = dec_channel_layout;
2235 is->audio_filter_src.freq = is->frame->sample_rate;
2236 is->audio_last_serial = is->audio_pkt_temp_serial;
2238 if ((ret = configure_audio_filters(is, afilters, 1)) < 0)
2242 if ((ret = av_buffersrc_add_frame(is->in_audio_filter, is->frame)) < 0)
2244 av_frame_unref(is->frame);
2248 if ((ret = av_buffersink_get_frame_flags(is->out_audio_filter, is->frame, 0)) < 0) {
2249 if (ret == AVERROR(EAGAIN)) {
2250 is->audio_buf_frames_pending = 0;
2253 if (ret == AVERROR_EOF)
2254 is->audio_finished = is->audio_pkt_temp_serial;
2257 is->audio_buf_frames_pending = 1;
2258 tb = is->out_audio_filter->inputs[0]->time_base;
2261 data_size = av_samples_get_buffer_size(NULL, av_frame_get_channels(is->frame),
2262 is->frame->nb_samples,
2263 is->frame->format, 1);
2265 dec_channel_layout =
2266 (is->frame->channel_layout && av_frame_get_channels(is->frame) == av_get_channel_layout_nb_channels(is->frame->channel_layout)) ?
2267 is->frame->channel_layout : av_get_default_channel_layout(av_frame_get_channels(is->frame));
2268 wanted_nb_samples = synchronize_audio(is, is->frame->nb_samples);
2270 if (is->frame->format != is->audio_src.fmt ||
2271 dec_channel_layout != is->audio_src.channel_layout ||
2272 is->frame->sample_rate != is->audio_src.freq ||
2273 (wanted_nb_samples != is->frame->nb_samples && !is->swr_ctx)) {
2274 swr_free(&is->swr_ctx);
2275 is->swr_ctx = swr_alloc_set_opts(NULL,
2276 is->audio_tgt.channel_layout, is->audio_tgt.fmt, is->audio_tgt.freq,
2277 dec_channel_layout, is->frame->format, is->frame->sample_rate,
2279 if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
2280 av_log(NULL, AV_LOG_ERROR,
2281 "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
2282 is->frame->sample_rate, av_get_sample_fmt_name(is->frame->format), av_frame_get_channels(is->frame),
2283 is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);
2286 is->audio_src.channel_layout = dec_channel_layout;
2287 is->audio_src.channels = av_frame_get_channels(is->frame);
2288 is->audio_src.freq = is->frame->sample_rate;
2289 is->audio_src.fmt = is->frame->format;
2293 const uint8_t **in = (const uint8_t **)is->frame->extended_data;
2294 uint8_t **out = &is->audio_buf1;
2295 int out_count = (int64_t)wanted_nb_samples * is->audio_tgt.freq / is->frame->sample_rate + 256;
2296 int out_size = av_samples_get_buffer_size(NULL, is->audio_tgt.channels, out_count, is->audio_tgt.fmt, 0);
2299 av_log(NULL, AV_LOG_ERROR, "av_samples_get_buffer_size() failed\n");
2302 if (wanted_nb_samples != is->frame->nb_samples) {
2303 if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * is->audio_tgt.freq / is->frame->sample_rate,
2304 wanted_nb_samples * is->audio_tgt.freq / is->frame->sample_rate) < 0) {
2305 av_log(NULL, AV_LOG_ERROR, "swr_set_compensation() failed\n");
2309 av_fast_malloc(&is->audio_buf1, &is->audio_buf1_size, out_size);
2310 if (!is->audio_buf1)
2311 return AVERROR(ENOMEM);
2312 len2 = swr_convert(is->swr_ctx, out, out_count, in, is->frame->nb_samples);
2314 av_log(NULL, AV_LOG_ERROR, "swr_convert() failed\n");
2317 if (len2 == out_count) {
2318 av_log(NULL, AV_LOG_WARNING, "audio buffer is probably too small\n");
2319 swr_init(is->swr_ctx);
2321 is->audio_buf = is->audio_buf1;
2322 resampled_data_size = len2 * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
2324 is->audio_buf = is->frame->data[0];
2325 resampled_data_size = data_size;
2328 audio_clock0 = is->audio_clock;
2329 /* update the audio clock with the pts */
2330 if (is->frame->pts != AV_NOPTS_VALUE)
2331 is->audio_clock = is->frame->pts * av_q2d(tb) + (double) is->frame->nb_samples / is->frame->sample_rate;
2333 is->audio_clock = NAN;
2334 is->audio_clock_serial = is->audio_pkt_temp_serial;
2337 static double last_clock;
2338 printf("audio: delay=%0.3f clock=%0.3f clock0=%0.3f\n",
2339 is->audio_clock - last_clock,
2340 is->audio_clock, audio_clock0);
2341 last_clock = is->audio_clock;
2344 return resampled_data_size;
2347 /* free the current packet */
2349 av_free_packet(pkt);
2350 memset(pkt_temp, 0, sizeof(*pkt_temp));
2351 pkt_temp->stream_index = -1;
2353 if (is->audioq.abort_request) {
2357 if (is->audioq.nb_packets == 0)
2358 SDL_CondSignal(is->continue_read_thread);
2360 /* read next packet */
2361 if ((packet_queue_get(&is->audioq, pkt, 1, &is->audio_pkt_temp_serial)) < 0)
2364 if (pkt->data == flush_pkt.data) {
2365 avcodec_flush_buffers(dec);
2366 is->audio_buf_frames_pending = 0;
2367 is->audio_frame_next_pts = AV_NOPTS_VALUE;
2368 if ((is->ic->iformat->flags & (AVFMT_NOBINSEARCH | AVFMT_NOGENSEARCH | AVFMT_NO_BYTE_SEEK)) && !is->ic->iformat->read_seek)
2369 is->audio_frame_next_pts = is->audio_st->start_time;
2376 /* prepare a new audio buffer */
2377 static void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
2379 VideoState *is = opaque;
2380 int audio_size, len1;
2382 int frame_size = av_samples_get_buffer_size(NULL, is->audio_tgt.channels, 1, is->audio_tgt.fmt, 1);
2384 audio_callback_time = av_gettime();
2387 if (is->audio_buf_index >= is->audio_buf_size) {
2388 audio_size = audio_decode_frame(is);
2389 if (audio_size < 0) {
2390 /* if error, just output silence */
2391 is->audio_buf = is->silence_buf;
2392 is->audio_buf_size = sizeof(is->silence_buf) / frame_size * frame_size;
2394 if (is->show_mode != SHOW_MODE_VIDEO)
2395 update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
2396 is->audio_buf_size = audio_size;
2398 is->audio_buf_index = 0;
2400 len1 = is->audio_buf_size - is->audio_buf_index;
2403 memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
2406 is->audio_buf_index += len1;
2408 bytes_per_sec = is->audio_tgt.freq * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
2409 is->audio_write_buf_size = is->audio_buf_size - is->audio_buf_index;
2410 /* Let's assume the audio driver that is used by SDL has two periods. */
2411 if (!isnan(is->audio_clock)) {
2412 set_clock_at(&is->audclk, is->audio_clock - (double)(2 * is->audio_hw_buf_size + is->audio_write_buf_size) / bytes_per_sec, is->audio_clock_serial, audio_callback_time / 1000000.0);
2413 sync_clock_to_slave(&is->extclk, &is->audclk);
2417 static int audio_open(void *opaque, int64_t wanted_channel_layout, int wanted_nb_channels, int wanted_sample_rate, struct AudioParams *audio_hw_params)
2419 SDL_AudioSpec wanted_spec, spec;
2421 static const int next_nb_channels[] = {0, 0, 1, 6, 2, 6, 4, 6};
2423 env = SDL_getenv("SDL_AUDIO_CHANNELS");
2425 wanted_nb_channels = atoi(env);
2426 wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
2428 if (!wanted_channel_layout || wanted_nb_channels != av_get_channel_layout_nb_channels(wanted_channel_layout)) {
2429 wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
2430 wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
2432 wanted_spec.channels = av_get_channel_layout_nb_channels(wanted_channel_layout);
2433 wanted_spec.freq = wanted_sample_rate;
2434 if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
2435 av_log(NULL, AV_LOG_ERROR, "Invalid sample rate or channel count!\n");
2438 wanted_spec.format = AUDIO_S16SYS;
2439 wanted_spec.silence = 0;
2440 wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
2441 wanted_spec.callback = sdl_audio_callback;
2442 wanted_spec.userdata = opaque;
2443 while (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
2444 av_log(NULL, AV_LOG_WARNING, "SDL_OpenAudio (%d channels): %s\n", wanted_spec.channels, SDL_GetError());
2445 wanted_spec.channels = next_nb_channels[FFMIN(7, wanted_spec.channels)];
2446 if (!wanted_spec.channels) {
2447 av_log(NULL, AV_LOG_ERROR,
2448 "No more channel combinations to try, audio open failed\n");
2451 wanted_channel_layout = av_get_default_channel_layout(wanted_spec.channels);
2453 if (spec.format != AUDIO_S16SYS) {
2454 av_log(NULL, AV_LOG_ERROR,
2455 "SDL advised audio format %d is not supported!\n", spec.format);
2458 if (spec.channels != wanted_spec.channels) {
2459 wanted_channel_layout = av_get_default_channel_layout(spec.channels);
2460 if (!wanted_channel_layout) {
2461 av_log(NULL, AV_LOG_ERROR,
2462 "SDL advised channel count %d is not supported!\n", spec.channels);
2467 audio_hw_params->fmt = AV_SAMPLE_FMT_S16;
2468 audio_hw_params->freq = spec.freq;
2469 audio_hw_params->channel_layout = wanted_channel_layout;
2470 audio_hw_params->channels = spec.channels;
2474 /* open a given stream. Return 0 if OK */
2475 static int stream_component_open(VideoState *is, int stream_index)
2477 AVFormatContext *ic = is->ic;
2478 AVCodecContext *avctx;
2480 const char *forced_codec_name = NULL;
2482 AVDictionaryEntry *t = NULL;
2483 int sample_rate, nb_channels;
2484 int64_t channel_layout;
2486 int stream_lowres = lowres;
2488 if (stream_index < 0 || stream_index >= ic->nb_streams)
2490 avctx = ic->streams[stream_index]->codec;
2492 codec = avcodec_find_decoder(avctx->codec_id);
2494 switch(avctx->codec_type){
2495 case AVMEDIA_TYPE_AUDIO : is->last_audio_stream = stream_index; forced_codec_name = audio_codec_name; break;
2496 case AVMEDIA_TYPE_SUBTITLE: is->last_subtitle_stream = stream_index; forced_codec_name = subtitle_codec_name; break;
2497 case AVMEDIA_TYPE_VIDEO : is->last_video_stream = stream_index; forced_codec_name = video_codec_name; break;
2499 if (forced_codec_name)
2500 codec = avcodec_find_decoder_by_name(forced_codec_name);
2502 if (forced_codec_name) av_log(NULL, AV_LOG_WARNING,
2503 "No codec could be found with name '%s'\n", forced_codec_name);
2504 else av_log(NULL, AV_LOG_WARNING,
2505 "No codec could be found with id %d\n", avctx->codec_id);
2509 avctx->codec_id = codec->id;
2510 avctx->workaround_bugs = workaround_bugs;
2511 if(stream_lowres > av_codec_get_max_lowres(codec)){
2512 av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
2513 av_codec_get_max_lowres(codec));
2514 stream_lowres = av_codec_get_max_lowres(codec);
2516 av_codec_set_lowres(avctx, stream_lowres);
2517 avctx->error_concealment = error_concealment;
2519 if(stream_lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
2520 if (fast) avctx->flags2 |= CODEC_FLAG2_FAST;
2521 if(codec->capabilities & CODEC_CAP_DR1)
2522 avctx->flags |= CODEC_FLAG_EMU_EDGE;
2524 opts = filter_codec_opts(codec_opts, avctx->codec_id, ic, ic->streams[stream_index], codec);
2525 if (!av_dict_get(opts, "threads", NULL, 0))
2526 av_dict_set(&opts, "threads", "auto", 0);
2528 av_dict_set(&opts, "lowres", av_asprintf("%d", stream_lowres), AV_DICT_DONT_STRDUP_VAL);
2529 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
2530 av_dict_set(&opts, "refcounted_frames", "1", 0);
2531 if (avcodec_open2(avctx, codec, &opts) < 0)
2533 if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2534 av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
2535 return AVERROR_OPTION_NOT_FOUND;
2538 ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
2539 switch (avctx->codec_type) {
2540 case AVMEDIA_TYPE_AUDIO:
2545 is->audio_filter_src.freq = avctx->sample_rate;
2546 is->audio_filter_src.channels = avctx->channels;
2547 is->audio_filter_src.channel_layout = get_valid_channel_layout(avctx->channel_layout, avctx->channels);
2548 is->audio_filter_src.fmt = avctx->sample_fmt;
2549 if ((ret = configure_audio_filters(is, afilters, 0)) < 0)
2551 link = is->out_audio_filter->inputs[0];
2552 sample_rate = link->sample_rate;
2553 nb_channels = link->channels;
2554 channel_layout = link->channel_layout;
2557 sample_rate = avctx->sample_rate;
2558 nb_channels = avctx->channels;
2559 channel_layout = avctx->channel_layout;
2562 /* prepare audio output */
2563 if ((ret = audio_open(is, channel_layout, nb_channels, sample_rate, &is->audio_tgt)) < 0)
2565 is->audio_hw_buf_size = ret;
2566 is->audio_src = is->audio_tgt;
2567 is->audio_buf_size = 0;
2568 is->audio_buf_index = 0;
2570 /* init averaging filter */
2571 is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
2572 is->audio_diff_avg_count = 0;
2573 /* since we do not have a precise anough audio fifo fullness,
2574 we correct audio sync only if larger than this threshold */
2575 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);
2577 memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
2578 memset(&is->audio_pkt_temp, 0, sizeof(is->audio_pkt_temp));
2579 is->audio_pkt_temp.stream_index = -1;
2581 is->audio_stream = stream_index;
2582 is->audio_st = ic->streams[stream_index];
2584 packet_queue_start(&is->audioq);
2587 case AVMEDIA_TYPE_VIDEO:
2588 is->video_stream = stream_index;
2589 is->video_st = ic->streams[stream_index];
2591 packet_queue_start(&is->videoq);
2592 is->video_tid = SDL_CreateThread(video_thread, is);
2593 is->queue_attachments_req = 1;
2595 case AVMEDIA_TYPE_SUBTITLE:
2596 is->subtitle_stream = stream_index;
2597 is->subtitle_st = ic->streams[stream_index];
2598 packet_queue_start(&is->subtitleq);
2600 is->subtitle_tid = SDL_CreateThread(subtitle_thread, is);
2608 static void stream_component_close(VideoState *is, int stream_index)
2610 AVFormatContext *ic = is->ic;
2611 AVCodecContext *avctx;
2613 if (stream_index < 0 || stream_index >= ic->nb_streams)
2615 avctx = ic->streams[stream_index]->codec;
2617 switch (avctx->codec_type) {
2618 case AVMEDIA_TYPE_AUDIO:
2619 packet_queue_abort(&is->audioq);
2623 packet_queue_flush(&is->audioq);
2624 av_free_packet(&is->audio_pkt);
2625 swr_free(&is->swr_ctx);
2626 av_freep(&is->audio_buf1);
2627 is->audio_buf1_size = 0;
2628 is->audio_buf = NULL;
2629 av_frame_free(&is->frame);
2632 av_rdft_end(is->rdft);
2633 av_freep(&is->rdft_data);
2638 avfilter_graph_free(&is->agraph);
2641 case AVMEDIA_TYPE_VIDEO:
2642 packet_queue_abort(&is->videoq);
2644 /* note: we also signal this mutex to make sure we deblock the
2645 video thread in all cases */
2646 SDL_LockMutex(is->pictq_mutex);
2647 SDL_CondSignal(is->pictq_cond);
2648 SDL_UnlockMutex(is->pictq_mutex);
2650 SDL_WaitThread(is->video_tid, NULL);
2652 packet_queue_flush(&is->videoq);
2654 case AVMEDIA_TYPE_SUBTITLE:
2655 packet_queue_abort(&is->subtitleq);
2657 /* note: we also signal this mutex to make sure we deblock the
2658 video thread in all cases */
2659 SDL_LockMutex(is->subpq_mutex);
2660 SDL_CondSignal(is->subpq_cond);
2661 SDL_UnlockMutex(is->subpq_mutex);
2663 SDL_WaitThread(is->subtitle_tid, NULL);
2665 packet_queue_flush(&is->subtitleq);
2671 ic->streams[stream_index]->discard = AVDISCARD_ALL;
2672 avcodec_close(avctx);
2673 switch (avctx->codec_type) {
2674 case AVMEDIA_TYPE_AUDIO:
2675 is->audio_st = NULL;
2676 is->audio_stream = -1;
2678 case AVMEDIA_TYPE_VIDEO:
2679 is->video_st = NULL;
2680 is->video_stream = -1;
2682 case AVMEDIA_TYPE_SUBTITLE:
2683 is->subtitle_st = NULL;
2684 is->subtitle_stream = -1;
2691 static int decode_interrupt_cb(void *ctx)
2693 VideoState *is = ctx;
2694 return is->abort_request;
2697 static int is_realtime(AVFormatContext *s)
2699 if( !strcmp(s->iformat->name, "rtp")
2700 || !strcmp(s->iformat->name, "rtsp")
2701 || !strcmp(s->iformat->name, "sdp")
2705 if(s->pb && ( !strncmp(s->filename, "rtp:", 4)
2706 || !strncmp(s->filename, "udp:", 4)
2713 /* this thread gets the stream from the disk or the network */
2714 static int read_thread(void *arg)
2716 VideoState *is = arg;
2717 AVFormatContext *ic = NULL;
2719 int st_index[AVMEDIA_TYPE_NB];
2720 AVPacket pkt1, *pkt = &pkt1;
2722 int64_t stream_start_time;
2723 int pkt_in_play_range = 0;
2724 AVDictionaryEntry *t;
2725 AVDictionary **opts;
2726 int orig_nb_streams;
2727 SDL_mutex *wait_mutex = SDL_CreateMutex();
2729 memset(st_index, -1, sizeof(st_index));
2730 is->last_video_stream = is->video_stream = -1;
2731 is->last_audio_stream = is->audio_stream = -1;
2732 is->last_subtitle_stream = is->subtitle_stream = -1;
2734 ic = avformat_alloc_context();
2735 ic->interrupt_callback.callback = decode_interrupt_cb;
2736 ic->interrupt_callback.opaque = is;
2737 err = avformat_open_input(&ic, is->filename, is->iformat, &format_opts);
2739 print_error(is->filename, err);
2743 if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2744 av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
2745 ret = AVERROR_OPTION_NOT_FOUND;
2751 ic->flags |= AVFMT_FLAG_GENPTS;
2753 opts = setup_find_stream_info_opts(ic, codec_opts);
2754 orig_nb_streams = ic->nb_streams;
2756 err = avformat_find_stream_info(ic, opts);
2758 av_log(NULL, AV_LOG_WARNING,
2759 "%s: could not find codec parameters\n", is->filename);
2763 for (i = 0; i < orig_nb_streams; i++)
2764 av_dict_free(&opts[i]);
2768 ic->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
2770 if (seek_by_bytes < 0)
2771 seek_by_bytes = !!(ic->iformat->flags & AVFMT_TS_DISCONT) && strcmp("ogg", ic->iformat->name);
2773 is->max_frame_duration = (ic->iformat->flags & AVFMT_TS_DISCONT) ? 10.0 : 3600.0;
2775 if (!window_title && (t = av_dict_get(ic->metadata, "title", NULL, 0)))
2776 window_title = av_asprintf("%s - %s", t->value, input_filename);
2778 /* if seeking requested, we execute it */
2779 if (start_time != AV_NOPTS_VALUE) {
2782 timestamp = start_time;
2783 /* add the stream start time */
2784 if (ic->start_time != AV_NOPTS_VALUE)
2785 timestamp += ic->start_time;
2786 ret = avformat_seek_file(ic, -1, INT64_MIN, timestamp, INT64_MAX, 0);
2788 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
2789 is->filename, (double)timestamp / AV_TIME_BASE);
2793 is->realtime = is_realtime(ic);
2795 for (i = 0; i < ic->nb_streams; i++)
2796 ic->streams[i]->discard = AVDISCARD_ALL;
2798 st_index[AVMEDIA_TYPE_VIDEO] =
2799 av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO,
2800 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
2802 st_index[AVMEDIA_TYPE_AUDIO] =
2803 av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO,
2804 wanted_stream[AVMEDIA_TYPE_AUDIO],
2805 st_index[AVMEDIA_TYPE_VIDEO],
2807 if (!video_disable && !subtitle_disable)
2808 st_index[AVMEDIA_TYPE_SUBTITLE] =
2809 av_find_best_stream(ic, AVMEDIA_TYPE_SUBTITLE,
2810 wanted_stream[AVMEDIA_TYPE_SUBTITLE],
2811 (st_index[AVMEDIA_TYPE_AUDIO] >= 0 ?
2812 st_index[AVMEDIA_TYPE_AUDIO] :
2813 st_index[AVMEDIA_TYPE_VIDEO]),
2816 av_dump_format(ic, 0, is->filename, 0);
2819 is->show_mode = show_mode;
2820 if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
2821 AVStream *st = ic->streams[st_index[AVMEDIA_TYPE_VIDEO]];
2822 AVCodecContext *avctx = st->codec;
2823 VideoPicture vp = {.width = avctx->width, .height = avctx->height, .sar = av_guess_sample_aspect_ratio(ic, st, NULL)};
2825 set_default_window_size(&vp);
2828 /* open the streams */
2829 if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
2830 stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);
2834 if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
2835 ret = stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);
2837 if (is->show_mode == SHOW_MODE_NONE)
2838 is->show_mode = ret >= 0 ? SHOW_MODE_VIDEO : SHOW_MODE_RDFT;
2840 if (st_index[AVMEDIA_TYPE_SUBTITLE] >= 0) {
2841 stream_component_open(is, st_index[AVMEDIA_TYPE_SUBTITLE]);
2844 if (is->video_stream < 0 && is->audio_stream < 0) {
2845 av_log(NULL, AV_LOG_FATAL, "Failed to open file '%s' or configure filtergraph\n",
2851 if (infinite_buffer < 0 && is->realtime)
2852 infinite_buffer = 1;
2855 if (is->abort_request)
2857 if (is->paused != is->last_paused) {
2858 is->last_paused = is->paused;
2860 is->read_pause_return = av_read_pause(ic);
2864 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
2866 (!strcmp(ic->iformat->name, "rtsp") ||
2867 (ic->pb && !strncmp(input_filename, "mmsh:", 5)))) {
2868 /* wait 10 ms to avoid trying to get another packet */
2875 int64_t seek_target = is->seek_pos;
2876 int64_t seek_min = is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;
2877 int64_t seek_max = is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;
2878 // FIXME the +-2 is due to rounding being not done in the correct direction in generation
2879 // of the seek_pos/seek_rel variables
2881 ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);
2883 av_log(NULL, AV_LOG_ERROR,
2884 "%s: error while seeking\n", is->ic->filename);
2886 if (is->audio_stream >= 0) {
2887 packet_queue_flush(&is->audioq);
2888 packet_queue_put(&is->audioq, &flush_pkt);
2890 if (is->subtitle_stream >= 0) {
2891 packet_queue_flush(&is->subtitleq);
2892 packet_queue_put(&is->subtitleq, &flush_pkt);
2894 if (is->video_stream >= 0) {
2895 packet_queue_flush(&is->videoq);
2896 packet_queue_put(&is->videoq, &flush_pkt);
2898 if (is->seek_flags & AVSEEK_FLAG_BYTE) {
2899 set_clock(&is->extclk, NAN, 0);
2901 set_clock(&is->extclk, seek_target / (double)AV_TIME_BASE, 0);
2905 is->queue_attachments_req = 1;
2908 step_to_next_frame(is);
2910 if (is->queue_attachments_req) {
2911 if (is->video_st && is->video_st->disposition & AV_DISPOSITION_ATTACHED_PIC) {
2913 if ((ret = av_copy_packet(©, &is->video_st->attached_pic)) < 0)
2915 packet_queue_put(&is->videoq, ©);
2916 packet_queue_put_nullpacket(&is->videoq, is->video_stream);
2918 is->queue_attachments_req = 0;
2921 /* if the queue are full, no need to read more */
2922 if (infinite_buffer<1 &&
2923 (is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE
2924 || ( (is->audioq .nb_packets > MIN_FRAMES || is->audio_stream < 0 || is->audioq.abort_request)
2925 && (is->videoq .nb_packets > MIN_FRAMES || is->video_stream < 0 || is->videoq.abort_request
2926 || (is->video_st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2927 && (is->subtitleq.nb_packets > MIN_FRAMES || is->subtitle_stream < 0 || is->subtitleq.abort_request)))) {
2929 SDL_LockMutex(wait_mutex);
2930 SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
2931 SDL_UnlockMutex(wait_mutex);
2935 (!is->audio_st || is->audio_finished == is->audioq.serial) &&
2936 (!is->video_st || (is->video_finished == is->videoq.serial && is->pictq_size == 0))) {
2937 if (loop != 1 && (!loop || --loop)) {
2938 stream_seek(is, start_time != AV_NOPTS_VALUE ? start_time : 0, 0, 0);
2939 } else if (autoexit) {
2945 if (is->video_stream >= 0)
2946 packet_queue_put_nullpacket(&is->videoq, is->video_stream);
2947 if (is->audio_stream >= 0)
2948 packet_queue_put_nullpacket(&is->audioq, is->audio_stream);
2953 ret = av_read_frame(ic, pkt);
2955 if (ret == AVERROR_EOF || url_feof(ic->pb))
2957 if (ic->pb && ic->pb->error)
2959 SDL_LockMutex(wait_mutex);
2960 SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
2961 SDL_UnlockMutex(wait_mutex);
2964 /* check if packet is in play range specified by user, then queue, otherwise discard */
2965 stream_start_time = ic->streams[pkt->stream_index]->start_time;
2966 pkt_in_play_range = duration == AV_NOPTS_VALUE ||
2967 (pkt->pts - (stream_start_time != AV_NOPTS_VALUE ? stream_start_time : 0)) *
2968 av_q2d(ic->streams[pkt->stream_index]->time_base) -
2969 (double)(start_time != AV_NOPTS_VALUE ? start_time : 0) / 1000000
2970 <= ((double)duration / 1000000);
2971 if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {
2972 packet_queue_put(&is->audioq, pkt);
2973 } else if (pkt->stream_index == is->video_stream && pkt_in_play_range
2974 && !(is->video_st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
2975 packet_queue_put(&is->videoq, pkt);
2976 } else if (pkt->stream_index == is->subtitle_stream && pkt_in_play_range) {
2977 packet_queue_put(&is->subtitleq, pkt);
2979 av_free_packet(pkt);
2982 /* wait until the end */
2983 while (!is->abort_request) {
2989 /* close each stream */
2990 if (is->audio_stream >= 0)
2991 stream_component_close(is, is->audio_stream);
2992 if (is->video_stream >= 0)
2993 stream_component_close(is, is->video_stream);
2994 if (is->subtitle_stream >= 0)
2995 stream_component_close(is, is->subtitle_stream);
2997 avformat_close_input(&is->ic);
3003 event.type = FF_QUIT_EVENT;
3004 event.user.data1 = is;
3005 SDL_PushEvent(&event);
3007 SDL_DestroyMutex(wait_mutex);
3011 static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
3015 is = av_mallocz(sizeof(VideoState));
3018 av_strlcpy(is->filename, filename, sizeof(is->filename));
3019 is->iformat = iformat;
3023 /* start video display */
3024 is->pictq_mutex = SDL_CreateMutex();
3025 is->pictq_cond = SDL_CreateCond();
3027 is->subpq_mutex = SDL_CreateMutex();
3028 is->subpq_cond = SDL_CreateCond();
3030 packet_queue_init(&is->videoq);
3031 packet_queue_init(&is->audioq);
3032 packet_queue_init(&is->subtitleq);
3034 is->continue_read_thread = SDL_CreateCond();
3036 init_clock(&is->vidclk, &is->videoq.serial);
3037 init_clock(&is->audclk, &is->audioq.serial);
3038 init_clock(&is->extclk, &is->extclk.serial);
3039 is->audio_clock_serial = -1;
3040 is->audio_last_serial = -1;
3041 is->av_sync_type = av_sync_type;
3042 is->read_tid = SDL_CreateThread(read_thread, is);
3043 if (!is->read_tid) {
3050 static void stream_cycle_channel(VideoState *is, int codec_type)
3052 AVFormatContext *ic = is->ic;
3053 int start_index, stream_index;
3056 AVProgram *p = NULL;
3057 int nb_streams = is->ic->nb_streams;
3059 if (codec_type == AVMEDIA_TYPE_VIDEO) {
3060 start_index = is->last_video_stream;
3061 old_index = is->video_stream;
3062 } else if (codec_type == AVMEDIA_TYPE_AUDIO) {
3063 start_index = is->last_audio_stream;
3064 old_index = is->audio_stream;
3066 start_index = is->last_subtitle_stream;
3067 old_index = is->subtitle_stream;
3069 stream_index = start_index;
3071 if (codec_type != AVMEDIA_TYPE_VIDEO && is->video_stream != -1) {
3072 p = av_find_program_from_stream(ic, NULL, is->video_stream);
3074 nb_streams = p->nb_stream_indexes;
3075 for (start_index = 0; start_index < nb_streams; start_index++)
3076 if (p->stream_index[start_index] == stream_index)
3078 if (start_index == nb_streams)
3080 stream_index = start_index;
3085 if (++stream_index >= nb_streams)
3087 if (codec_type == AVMEDIA_TYPE_SUBTITLE)
3090 is->last_subtitle_stream = -1;
3093 if (start_index == -1)
3097 if (stream_index == start_index)
3099 st = is->ic->streams[p ? p->stream_index[stream_index] : stream_index];
3100 if (st->codec->codec_type == codec_type) {
3101 /* check that parameters are OK */
3102 switch (codec_type) {
3103 case AVMEDIA_TYPE_AUDIO:
3104 if (st->codec->sample_rate != 0 &&
3105 st->codec->channels != 0)
3108 case AVMEDIA_TYPE_VIDEO:
3109 case AVMEDIA_TYPE_SUBTITLE:
3117 if (p && stream_index != -1)
3118 stream_index = p->stream_index[stream_index];
3119 stream_component_close(is, old_index);
3120 stream_component_open(is, stream_index);
3124 static void toggle_full_screen(VideoState *is)
3126 #if defined(__APPLE__) && SDL_VERSION_ATLEAST(1, 2, 14)
3127 /* OS X needs to reallocate the SDL overlays */
3129 for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++)
3130 is->pictq[i].reallocate = 1;
3132 is_full_screen = !is_full_screen;
3133 video_open(is, 1, NULL);
3136 static void toggle_audio_display(VideoState *is)
3138 int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
3139 int next = is->show_mode;
3141 next = (next + 1) % SHOW_MODE_NB;
3142 } while (next != is->show_mode && (next == SHOW_MODE_VIDEO && !is->video_st || next != SHOW_MODE_VIDEO && !is->audio_st));
3143 if (is->show_mode != next) {
3144 fill_rectangle(screen,
3145 is->xleft, is->ytop, is->width, is->height,
3147 is->force_refresh = 1;
3148 is->show_mode = next;
3152 static void refresh_loop_wait_event(VideoState *is, SDL_Event *event) {
3153 double remaining_time = 0.0;
3155 while (!SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_ALLEVENTS)) {
3156 if (!cursor_hidden && av_gettime() - cursor_last_shown > CURSOR_HIDE_DELAY) {
3160 if (remaining_time > 0.0)
3161 av_usleep((int64_t)(remaining_time * 1000000.0));
3162 remaining_time = REFRESH_RATE;
3163 if (is->show_mode != SHOW_MODE_NONE && (!is->paused || is->force_refresh))
3164 video_refresh(is, &remaining_time);
3169 /* handle an event sent by the GUI */
3170 static void event_loop(VideoState *cur_stream)
3173 double incr, pos, frac;
3177 refresh_loop_wait_event(cur_stream, &event);
3178 switch (event.type) {
3180 if (exit_on_keydown) {
3181 do_exit(cur_stream);
3184 switch (event.key.keysym.sym) {
3187 do_exit(cur_stream);
3190 toggle_full_screen(cur_stream);
3191 cur_stream->force_refresh = 1;
3195 toggle_pause(cur_stream);
3197 case SDLK_s: // S: Step to next frame
3198 step_to_next_frame(cur_stream);
3201 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
3204 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
3207 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
3208 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
3209 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
3212 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
3215 toggle_audio_display(cur_stream);
3235 if (seek_by_bytes) {
3236 if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos >= 0) {
3237 pos = cur_stream->video_current_pos;
3238 } else if (cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos >= 0) {
3239 pos = cur_stream->audio_pkt.pos;
3241 pos = avio_tell(cur_stream->ic->pb);
3242 if (cur_stream->ic->bit_rate)
3243 incr *= cur_stream->ic->bit_rate / 8.0;
3247 stream_seek(cur_stream, pos, incr, 1);
3249 pos = get_master_clock(cur_stream);
3251 pos = (double)cur_stream->seek_pos / AV_TIME_BASE;
3253 if (cur_stream->ic->start_time != AV_NOPTS_VALUE && pos < cur_stream->ic->start_time / (double)AV_TIME_BASE)
3254 pos = cur_stream->ic->start_time / (double)AV_TIME_BASE;
3255 stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);
3262 case SDL_VIDEOEXPOSE:
3263 cur_stream->force_refresh = 1;
3265 case SDL_MOUSEBUTTONDOWN:
3266 if (exit_on_mousedown) {
3267 do_exit(cur_stream);
3270 case SDL_MOUSEMOTION:
3271 if (cursor_hidden) {
3275 cursor_last_shown = av_gettime();
3276 if (event.type == SDL_MOUSEBUTTONDOWN) {
3279 if (event.motion.state != SDL_PRESSED)
3283 if (seek_by_bytes || cur_stream->ic->duration <= 0) {
3284 uint64_t size = avio_size(cur_stream->ic->pb);
3285 stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);
3289 int tns, thh, tmm, tss;
3290 tns = cur_stream->ic->duration / 1000000LL;
3292 tmm = (tns % 3600) / 60;
3294 frac = x / cur_stream->width;
3297 mm = (ns % 3600) / 60;
3299 av_log(NULL, AV_LOG_INFO,
3300 "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n", frac*100,
3301 hh, mm, ss, thh, tmm, tss);
3302 ts = frac * cur_stream->ic->duration;
3303 if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
3304 ts += cur_stream->ic->start_time;
3305 stream_seek(cur_stream, ts, 0, 0);
3308 case SDL_VIDEORESIZE:
3309 screen = SDL_SetVideoMode(FFMIN(16383, event.resize.w), event.resize.h, 0,
3310 SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
3312 av_log(NULL, AV_LOG_FATAL, "Failed to set video mode\n");
3313 do_exit(cur_stream);
3315 screen_width = cur_stream->width = screen->w;
3316 screen_height = cur_stream->height = screen->h;
3317 cur_stream->force_refresh = 1;
3321 do_exit(cur_stream);
3323 case FF_ALLOC_EVENT:
3324 alloc_picture(event.user.data1);
3332 static int opt_frame_size(void *optctx, const char *opt, const char *arg)
3334 av_log(NULL, AV_LOG_WARNING, "Option -s is deprecated, use -video_size.\n");
3335 return opt_default(NULL, "video_size", arg);
3338 static int opt_width(void *optctx, const char *opt, const char *arg)
3340 screen_width = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
3344 static int opt_height(void *optctx, const char *opt, const char *arg)
3346 screen_height = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
3350 static int opt_format(void *optctx, const char *opt, const char *arg)
3352 file_iformat = av_find_input_format(arg);
3353 if (!file_iformat) {
3354 av_log(NULL, AV_LOG_FATAL, "Unknown input format: %s\n", arg);
3355 return AVERROR(EINVAL);
3360 static int opt_frame_pix_fmt(void *optctx, const char *opt, const char *arg)
3362 av_log(NULL, AV_LOG_WARNING, "Option -pix_fmt is deprecated, use -pixel_format.\n");
3363 return opt_default(NULL, "pixel_format", arg);
3366 static int opt_sync(void *optctx, const char *opt, const char *arg)
3368 if (!strcmp(arg, "audio"))
3369 av_sync_type = AV_SYNC_AUDIO_MASTER;
3370 else if (!strcmp(arg, "video"))
3371 av_sync_type = AV_SYNC_VIDEO_MASTER;
3372 else if (!strcmp(arg, "ext"))
3373 av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
3375 av_log(NULL, AV_LOG_ERROR, "Unknown value for %s: %s\n", opt, arg);
3381 static int opt_seek(void *optctx, const char *opt, const char *arg)
3383 start_time = parse_time_or_die(opt, arg, 1);
3387 static int opt_duration(void *optctx, const char *opt, const char *arg)
3389 duration = parse_time_or_die(opt, arg, 1);
3393 static int opt_show_mode(void *optctx, const char *opt, const char *arg)
3395 show_mode = !strcmp(arg, "video") ? SHOW_MODE_VIDEO :
3396 !strcmp(arg, "waves") ? SHOW_MODE_WAVES :
3397 !strcmp(arg, "rdft" ) ? SHOW_MODE_RDFT :
3398 parse_number_or_die(opt, arg, OPT_INT, 0, SHOW_MODE_NB-1);
3402 static void opt_input_file(void *optctx, const char *filename)
3404 if (input_filename) {
3405 av_log(NULL, AV_LOG_FATAL,
3406 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
3407 filename, input_filename);
3410 if (!strcmp(filename, "-"))
3412 input_filename = filename;
3415 static int opt_codec(void *optctx, const char *opt, const char *arg)
3417 const char *spec = strchr(opt, ':');
3419 av_log(NULL, AV_LOG_ERROR,
3420 "No media specifier was specified in '%s' in option '%s'\n",
3422 return AVERROR(EINVAL);
3426 case 'a' : audio_codec_name = arg; break;
3427 case 's' : subtitle_codec_name = arg; break;
3428 case 'v' : video_codec_name = arg; break;
3430 av_log(NULL, AV_LOG_ERROR,
3431 "Invalid media specifier '%s' in option '%s'\n", spec, opt);
3432 return AVERROR(EINVAL);
3439 static const OptionDef options[] = {
3440 #include "cmdutils_common_opts.h"
3441 { "x", HAS_ARG, { .func_arg = opt_width }, "force displayed width", "width" },
3442 { "y", HAS_ARG, { .func_arg = opt_height }, "force displayed height", "height" },
3443 { "s", HAS_ARG | OPT_VIDEO, { .func_arg = opt_frame_size }, "set frame size (WxH or abbreviation)", "size" },
3444 { "fs", OPT_BOOL, { &is_full_screen }, "force full screen" },
3445 { "an", OPT_BOOL, { &audio_disable }, "disable audio" },
3446 { "vn", OPT_BOOL, { &video_disable }, "disable video" },
3447 { "sn", OPT_BOOL, { &subtitle_disable }, "disable subtitling" },
3448 { "ast", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_AUDIO] }, "select desired audio stream", "stream_number" },
3449 { "vst", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_VIDEO] }, "select desired video stream", "stream_number" },
3450 { "sst", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_SUBTITLE] }, "select desired subtitle stream", "stream_number" },
3451 { "ss", HAS_ARG, { .func_arg = opt_seek }, "seek to a given position in seconds", "pos" },
3452 { "t", HAS_ARG, { .func_arg = opt_duration }, "play \"duration\" seconds of audio/video", "duration" },
3453 { "bytes", OPT_INT | HAS_ARG, { &seek_by_bytes }, "seek by bytes 0=off 1=on -1=auto", "val" },
3454 { "nodisp", OPT_BOOL, { &display_disable }, "disable graphical display" },
3455 { "f", HAS_ARG, { .func_arg = opt_format }, "force format", "fmt" },
3456 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_frame_pix_fmt }, "set pixel format", "format" },
3457 { "stats", OPT_BOOL | OPT_EXPERT, { &show_status }, "show status", "" },
3458 { "bug", OPT_INT | HAS_ARG | OPT_EXPERT, { &workaround_bugs }, "workaround bugs", "" },
3459 { "fast", OPT_BOOL | OPT_EXPERT, { &fast }, "non spec compliant optimizations", "" },
3460 { "genpts", OPT_BOOL | OPT_EXPERT, { &genpts }, "generate pts", "" },
3461 { "drp", OPT_INT | HAS_ARG | OPT_EXPERT, { &decoder_reorder_pts }, "let decoder reorder pts 0=off 1=on -1=auto", ""},
3462 { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, { &lowres }, "", "" },
3463 { "ec", OPT_INT | HAS_ARG | OPT_EXPERT, { &error_concealment }, "set error concealment options", "bit_mask" },
3464 { "sync", HAS_ARG | OPT_EXPERT, { .func_arg = opt_sync }, "set audio-video sync. type (type=audio/video/ext)", "type" },
3465 { "autoexit", OPT_BOOL | OPT_EXPERT, { &autoexit }, "exit at the end", "" },
3466 { "exitonkeydown", OPT_BOOL | OPT_EXPERT, { &exit_on_keydown }, "exit on key down", "" },
3467 { "exitonmousedown", OPT_BOOL | OPT_EXPERT, { &exit_on_mousedown }, "exit on mouse down", "" },
3468 { "loop", OPT_INT | HAS_ARG | OPT_EXPERT, { &loop }, "set number of times the playback shall be looped", "loop count" },
3469 { "framedrop", OPT_BOOL | OPT_EXPERT, { &framedrop }, "drop frames when cpu is too slow", "" },
3470 { "infbuf", OPT_BOOL | OPT_EXPERT, { &infinite_buffer }, "don't limit the input buffer size (useful with realtime streams)", "" },
3471 { "window_title", OPT_STRING | HAS_ARG, { &window_title }, "set window title", "window title" },
3473 { "vf", OPT_STRING | HAS_ARG, { &vfilters }, "set video filters", "filter_graph" },
3474 { "af", OPT_STRING | HAS_ARG, { &afilters }, "set audio filters", "filter_graph" },
3476 { "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, { &rdftspeed }, "rdft speed", "msecs" },
3477 { "showmode", HAS_ARG, { .func_arg = opt_show_mode}, "select show mode (0 = video, 1 = waves, 2 = RDFT)", "mode" },
3478 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, { .func_arg = opt_default }, "generic catch all option", "" },
3479 { "i", OPT_BOOL, { &dummy}, "read specified file", "input_file"},
3480 { "codec", HAS_ARG, { .func_arg = opt_codec}, "force decoder", "decoder_name" },
3481 { "acodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &audio_codec_name }, "force audio decoder", "decoder_name" },
3482 { "scodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &subtitle_codec_name }, "force subtitle decoder", "decoder_name" },
3483 { "vcodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &video_codec_name }, "force video decoder", "decoder_name" },
3487 static void show_usage(void)
3489 av_log(NULL, AV_LOG_INFO, "Simple media player\n");
3490 av_log(NULL, AV_LOG_INFO, "usage: %s [options] input_file\n", program_name);
3491 av_log(NULL, AV_LOG_INFO, "\n");
3494 void show_help_default(const char *opt, const char *arg)
3496 av_log_set_callback(log_callback_help);
3498 show_help_options(options, "Main options:", 0, OPT_EXPERT, 0);
3499 show_help_options(options, "Advanced options:", OPT_EXPERT, 0, 0);
3501 show_help_children(avcodec_get_class(), AV_OPT_FLAG_DECODING_PARAM);
3502 show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
3503 #if !CONFIG_AVFILTER
3504 show_help_children(sws_get_class(), AV_OPT_FLAG_ENCODING_PARAM);
3506 show_help_children(avfilter_get_class(), AV_OPT_FLAG_FILTERING_PARAM);
3508 printf("\nWhile playing:\n"
3510 "f toggle full screen\n"
3512 "a cycle audio channel in the current program\n"
3513 "v cycle video channel\n"
3514 "t cycle subtitle channel in the current program\n"
3516 "w show audio waves\n"
3517 "s activate frame-step mode\n"
3518 "left/right seek backward/forward 10 seconds\n"
3519 "down/up seek backward/forward 1 minute\n"
3520 "page down/page up seek backward/forward 10 minutes\n"
3521 "mouse click seek to percentage in file corresponding to fraction of width\n"
3525 static int lockmgr(void **mtx, enum AVLockOp op)
3528 case AV_LOCK_CREATE:
3529 *mtx = SDL_CreateMutex();
3533 case AV_LOCK_OBTAIN:
3534 return !!SDL_LockMutex(*mtx);
3535 case AV_LOCK_RELEASE:
3536 return !!SDL_UnlockMutex(*mtx);
3537 case AV_LOCK_DESTROY:
3538 SDL_DestroyMutex(*mtx);
3544 /* Called from the main */
3545 int main(int argc, char **argv)
3549 char dummy_videodriver[] = "SDL_VIDEODRIVER=dummy";
3551 av_log_set_flags(AV_LOG_SKIP_REPEATED);
3552 parse_loglevel(argc, argv, options);
3554 /* register all codecs, demux and protocols */
3556 avdevice_register_all();
3559 avfilter_register_all();
3562 avformat_network_init();
3566 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
3567 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
3569 show_banner(argc, argv, options);
3571 parse_options(NULL, argc, argv, options, opt_input_file);
3573 if (!input_filename) {
3575 av_log(NULL, AV_LOG_FATAL, "An input file must be specified\n");
3576 av_log(NULL, AV_LOG_FATAL,
3577 "Use -h to get full help or, even better, run 'man %s'\n", program_name);
3581 if (display_disable) {
3584 flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
3586 flags &= ~SDL_INIT_AUDIO;
3587 if (display_disable)
3588 SDL_putenv(dummy_videodriver); /* For the event queue, we always need a video driver. */
3589 #if !defined(__MINGW32__) && !defined(__APPLE__)
3590 flags |= SDL_INIT_EVENTTHREAD; /* Not supported on Windows or Mac OS X */
3592 if (SDL_Init (flags)) {
3593 av_log(NULL, AV_LOG_FATAL, "Could not initialize SDL - %s\n", SDL_GetError());
3594 av_log(NULL, AV_LOG_FATAL, "(Did you set the DISPLAY variable?)\n");
3598 if (!display_disable) {
3599 const SDL_VideoInfo *vi = SDL_GetVideoInfo();
3600 fs_screen_width = vi->current_w;
3601 fs_screen_height = vi->current_h;
3604 SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
3605 SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
3606 SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
3608 if (av_lockmgr_register(lockmgr)) {
3609 av_log(NULL, AV_LOG_FATAL, "Could not initialize lock manager!\n");
3613 av_init_packet(&flush_pkt);
3614 flush_pkt.data = (uint8_t *)&flush_pkt;
3616 is = stream_open(input_filename, file_iformat);
3618 av_log(NULL, AV_LOG_FATAL, "Failed to initialize VideoState!\n");