2 * Copyright (c) 2003 Fabrice Bellard
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * simple media player based on the FFmpeg libraries
31 #include "libavutil/avstring.h"
32 #include "libavutil/colorspace.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/imgutils.h"
36 #include "libavutil/dict.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/samplefmt.h"
39 #include "libavutil/avassert.h"
40 #include "libavutil/time.h"
41 #include "libavformat/avformat.h"
42 #include "libavdevice/avdevice.h"
43 #include "libswscale/swscale.h"
44 #include "libavutil/opt.h"
45 #include "libavcodec/avfft.h"
46 #include "libswresample/swresample.h"
49 # include "libavfilter/avcodec.h"
50 # include "libavfilter/avfilter.h"
51 # include "libavfilter/avfiltergraph.h"
52 # include "libavfilter/buffersink.h"
53 # include "libavfilter/buffersrc.h"
57 #include <SDL_thread.h>
63 const char program_name[] = "ffplay";
64 const int program_birth_year = 2003;
66 #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
69 /* SDL audio buffer size, in samples. Should be small to have precise
70 A/V sync as SDL does not have hardware buffer fullness info. */
71 #define SDL_AUDIO_BUFFER_SIZE 1024
73 /* no AV sync correction is done if below the AV sync threshold */
74 #define AV_SYNC_THRESHOLD 0.01
75 /* no AV correction is done if too big error */
76 #define AV_NOSYNC_THRESHOLD 10.0
78 /* maximum audio speed change to get correct sync */
79 #define SAMPLE_CORRECTION_PERCENT_MAX 10
81 /* external clock speed adjustment constants for realtime sources based on buffer fullness */
82 #define EXTERNAL_CLOCK_SPEED_MIN 0.900
83 #define EXTERNAL_CLOCK_SPEED_MAX 1.010
84 #define EXTERNAL_CLOCK_SPEED_STEP 0.001
86 /* we use about AUDIO_DIFF_AVG_NB A-V differences to make the average */
87 #define AUDIO_DIFF_AVG_NB 20
89 /* polls for possible required screen refresh at least this often, should be less than 1/fps */
90 #define REFRESH_RATE 0.01
92 /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
93 /* TODO: We assume that a decoded and resampled frame fits into this buffer */
94 #define SAMPLE_ARRAY_SIZE (8 * 65536)
96 #define CURSOR_HIDE_DELAY 1000000
98 static int64_t sws_flags = SWS_BICUBIC;
100 typedef struct MyAVPacketList {
102 struct MyAVPacketList *next;
106 typedef struct PacketQueue {
107 MyAVPacketList *first_pkt, *last_pkt;
116 #define VIDEO_PICTURE_QUEUE_SIZE 4
117 #define SUBPICTURE_QUEUE_SIZE 4
119 typedef struct VideoPicture {
120 double pts; // presentation timestamp for this picture
121 int64_t pos; // byte position in file
123 int width, height; /* source height & width */
131 typedef struct SubPicture {
132 double pts; /* presentation time stamp for this picture */
136 typedef struct AudioParams {
139 int64_t channel_layout;
140 enum AVSampleFormat fmt;
144 AV_SYNC_AUDIO_MASTER, /* default choice */
145 AV_SYNC_VIDEO_MASTER,
146 AV_SYNC_EXTERNAL_CLOCK, /* synchronize to an external clock */
149 typedef struct VideoState {
150 SDL_Thread *read_tid;
151 SDL_Thread *video_tid;
152 AVInputFormat *iformat;
158 int queue_attachments_req;
163 int read_pause_return;
170 double external_clock; ///< external clock base
171 double external_clock_drift; ///< external clock base - time (av_gettime) at which we updated external_clock
172 int64_t external_clock_time; ///< last reference time
173 double external_clock_speed; ///< speed of the external clock
176 int audio_clock_serial;
177 double audio_diff_cum; /* used for AV difference average computation */
178 double audio_diff_avg_coef;
179 double audio_diff_threshold;
180 int audio_diff_avg_count;
183 int audio_hw_buf_size;
184 uint8_t silence_buf[SDL_AUDIO_BUFFER_SIZE];
187 unsigned int audio_buf_size; /* in bytes */
188 unsigned int audio_buf1_size;
189 int audio_buf_index; /* in bytes */
190 int audio_write_buf_size;
191 AVPacket audio_pkt_temp;
193 int audio_pkt_temp_serial;
194 int audio_last_serial;
195 struct AudioParams audio_src;
197 struct AudioParams audio_filter_src;
199 struct AudioParams audio_tgt;
200 struct SwrContext *swr_ctx;
201 double audio_current_pts;
202 double audio_current_pts_drift;
203 int frame_drops_early;
204 int frame_drops_late;
208 SHOW_MODE_NONE = -1, SHOW_MODE_VIDEO = 0, SHOW_MODE_WAVES, SHOW_MODE_RDFT, SHOW_MODE_NB
210 int16_t sample_array[SAMPLE_ARRAY_SIZE];
211 int sample_array_index;
215 FFTSample *rdft_data;
217 double last_vis_time;
219 SDL_Thread *subtitle_tid;
221 int subtitle_stream_changed;
222 AVStream *subtitle_st;
223 PacketQueue subtitleq;
224 SubPicture subpq[SUBPICTURE_QUEUE_SIZE];
225 int subpq_size, subpq_rindex, subpq_windex;
226 SDL_mutex *subpq_mutex;
227 SDL_cond *subpq_cond;
230 double frame_last_pts;
231 double frame_last_duration;
232 double frame_last_dropped_pts;
233 double frame_last_returned_time;
234 double frame_last_filter_delay;
235 int64_t frame_last_dropped_pos;
239 double video_current_pts; // current displayed pts
240 double video_current_pts_drift; // video_current_pts - time (av_gettime) at which we updated video_current_pts - used to have running video pts
241 int64_t video_current_pos; // current displayed file pos
242 double max_frame_duration; // maximum duration of a frame - above this, we consider the jump a timestamp discontinuity
243 int video_clock_serial;
244 VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
245 int pictq_size, pictq_rindex, pictq_windex;
246 SDL_mutex *pictq_mutex;
247 SDL_cond *pictq_cond;
249 struct SwsContext *img_convert_ctx;
251 SDL_Rect last_display_rect;
254 int width, height, xleft, ytop;
258 AVFilterContext *in_video_filter; // the first filter in the video chain
259 AVFilterContext *out_video_filter; // the last filter in the video chain
260 AVFilterContext *in_audio_filter; // the first filter in the audio chain
261 AVFilterContext *out_audio_filter; // the last filter in the audio chain
262 AVFilterGraph *agraph; // audio filter graph
265 int last_video_stream, last_audio_stream, last_subtitle_stream;
267 SDL_cond *continue_read_thread;
270 /* options specified by the user */
271 static AVInputFormat *file_iformat;
272 static const char *input_filename;
273 static const char *window_title;
274 static int fs_screen_width;
275 static int fs_screen_height;
276 static int default_width = 640;
277 static int default_height = 480;
278 static int screen_width = 0;
279 static int screen_height = 0;
280 static int audio_disable;
281 static int video_disable;
282 static int subtitle_disable;
283 static int wanted_stream[AVMEDIA_TYPE_NB] = {
284 [AVMEDIA_TYPE_AUDIO] = -1,
285 [AVMEDIA_TYPE_VIDEO] = -1,
286 [AVMEDIA_TYPE_SUBTITLE] = -1,
288 static int seek_by_bytes = -1;
289 static int display_disable;
290 static int show_status = 1;
291 static int av_sync_type = AV_SYNC_AUDIO_MASTER;
292 static int64_t start_time = AV_NOPTS_VALUE;
293 static int64_t duration = AV_NOPTS_VALUE;
294 static int workaround_bugs = 1;
296 static int genpts = 0;
297 static int lowres = 0;
298 static int idct = FF_IDCT_AUTO;
299 static int error_concealment = 3;
300 static int decoder_reorder_pts = -1;
302 static int exit_on_keydown;
303 static int exit_on_mousedown;
305 static int framedrop = -1;
306 static int infinite_buffer = -1;
307 static enum ShowMode show_mode = SHOW_MODE_NONE;
308 static const char *audio_codec_name;
309 static const char *subtitle_codec_name;
310 static const char *video_codec_name;
311 double rdftspeed = 0.02;
312 static int64_t cursor_last_shown;
313 static int cursor_hidden = 0;
315 static char *vfilters = NULL;
316 static char *afilters = NULL;
319 /* current context */
320 static int is_full_screen;
321 static int64_t audio_callback_time;
323 static AVPacket flush_pkt;
325 #define FF_ALLOC_EVENT (SDL_USEREVENT)
326 #define FF_QUIT_EVENT (SDL_USEREVENT + 2)
328 static SDL_Surface *screen;
331 int cmp_audio_fmts(enum AVSampleFormat fmt1, int64_t channel_count1,
332 enum AVSampleFormat fmt2, int64_t channel_count2)
334 /* If channel count == 1, planar and non-planar formats are the same */
335 if (channel_count1 == 1 && channel_count2 == 1)
336 return av_get_packed_sample_fmt(fmt1) != av_get_packed_sample_fmt(fmt2);
338 return channel_count1 != channel_count2 || fmt1 != fmt2;
342 int64_t get_valid_channel_layout(int64_t channel_layout, int channels)
344 if (channel_layout && av_get_channel_layout_nb_channels(channel_layout) == channels)
345 return channel_layout;
350 static int packet_queue_put(PacketQueue *q, AVPacket *pkt);
352 static int packet_queue_put_private(PacketQueue *q, AVPacket *pkt)
354 MyAVPacketList *pkt1;
356 if (q->abort_request)
359 pkt1 = av_malloc(sizeof(MyAVPacketList));
364 if (pkt == &flush_pkt)
366 pkt1->serial = q->serial;
371 q->last_pkt->next = pkt1;
374 q->size += pkt1->pkt.size + sizeof(*pkt1);
375 /* XXX: should duplicate packet data in DV case */
376 SDL_CondSignal(q->cond);
380 static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
384 /* duplicate the packet */
385 if (pkt != &flush_pkt && av_dup_packet(pkt) < 0)
388 SDL_LockMutex(q->mutex);
389 ret = packet_queue_put_private(q, pkt);
390 SDL_UnlockMutex(q->mutex);
392 if (pkt != &flush_pkt && ret < 0)
398 /* packet queue handling */
399 static void packet_queue_init(PacketQueue *q)
401 memset(q, 0, sizeof(PacketQueue));
402 q->mutex = SDL_CreateMutex();
403 q->cond = SDL_CreateCond();
404 q->abort_request = 1;
407 static void packet_queue_flush(PacketQueue *q)
409 MyAVPacketList *pkt, *pkt1;
411 SDL_LockMutex(q->mutex);
412 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
414 av_free_packet(&pkt->pkt);
421 SDL_UnlockMutex(q->mutex);
424 static void packet_queue_destroy(PacketQueue *q)
426 packet_queue_flush(q);
427 SDL_DestroyMutex(q->mutex);
428 SDL_DestroyCond(q->cond);
431 static void packet_queue_abort(PacketQueue *q)
433 SDL_LockMutex(q->mutex);
435 q->abort_request = 1;
437 SDL_CondSignal(q->cond);
439 SDL_UnlockMutex(q->mutex);
442 static void packet_queue_start(PacketQueue *q)
444 SDL_LockMutex(q->mutex);
445 q->abort_request = 0;
446 packet_queue_put_private(q, &flush_pkt);
447 SDL_UnlockMutex(q->mutex);
450 /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
451 static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block, int *serial)
453 MyAVPacketList *pkt1;
456 SDL_LockMutex(q->mutex);
459 if (q->abort_request) {
466 q->first_pkt = pkt1->next;
470 q->size -= pkt1->pkt.size + sizeof(*pkt1);
473 *serial = pkt1->serial;
481 SDL_CondWait(q->cond, q->mutex);
484 SDL_UnlockMutex(q->mutex);
488 static inline void fill_rectangle(SDL_Surface *screen,
489 int x, int y, int w, int h, int color, int update)
496 SDL_FillRect(screen, &rect, color);
497 if (update && w > 0 && h > 0)
498 SDL_UpdateRect(screen, x, y, w, h);
501 /* draw only the border of a rectangle */
502 static void fill_border(int xleft, int ytop, int width, int height, int x, int y, int w, int h, int color, int update)
506 /* fill the background */
510 w2 = width - (x + w);
516 h2 = height - (y + h);
519 fill_rectangle(screen,
523 fill_rectangle(screen,
524 xleft + width - w2, ytop,
527 fill_rectangle(screen,
531 fill_rectangle(screen,
532 xleft + w1, ytop + height - h2,
537 #define ALPHA_BLEND(a, oldp, newp, s)\
538 ((((oldp << s) * (255 - (a))) + (newp * (a))) / (255 << s))
540 #define RGBA_IN(r, g, b, a, s)\
542 unsigned int v = ((const uint32_t *)(s))[0];\
543 a = (v >> 24) & 0xff;\
544 r = (v >> 16) & 0xff;\
545 g = (v >> 8) & 0xff;\
549 #define YUVA_IN(y, u, v, a, s, pal)\
551 unsigned int val = ((const uint32_t *)(pal))[*(const uint8_t*)(s)];\
552 a = (val >> 24) & 0xff;\
553 y = (val >> 16) & 0xff;\
554 u = (val >> 8) & 0xff;\
558 #define YUVA_OUT(d, y, u, v, a)\
560 ((uint32_t *)(d))[0] = (a << 24) | (y << 16) | (u << 8) | v;\
566 static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw, int imgh)
568 int wrap, wrap3, width2, skip2;
569 int y, u, v, a, u1, v1, a1, w, h;
570 uint8_t *lum, *cb, *cr;
573 int dstx, dsty, dstw, dsth;
575 dstw = av_clip(rect->w, 0, imgw);
576 dsth = av_clip(rect->h, 0, imgh);
577 dstx = av_clip(rect->x, 0, imgw - dstw);
578 dsty = av_clip(rect->y, 0, imgh - dsth);
579 lum = dst->data[0] + dsty * dst->linesize[0];
580 cb = dst->data[1] + (dsty >> 1) * dst->linesize[1];
581 cr = dst->data[2] + (dsty >> 1) * dst->linesize[2];
583 width2 = ((dstw + 1) >> 1) + (dstx & ~dstw & 1);
585 wrap = dst->linesize[0];
586 wrap3 = rect->pict.linesize[0];
587 p = rect->pict.data[0];
588 pal = (const uint32_t *)rect->pict.data[1]; /* Now in YCrCb! */
596 YUVA_IN(y, u, v, a, p, pal);
597 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
598 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
599 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
605 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
606 YUVA_IN(y, u, v, a, p, pal);
610 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
612 YUVA_IN(y, u, v, a, p + BPP, pal);
616 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
617 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
618 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
625 YUVA_IN(y, u, v, a, p, pal);
626 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
627 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
628 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
632 p += wrap3 - dstw * BPP;
633 lum += wrap - dstw - dstx;
634 cb += dst->linesize[1] - width2 - skip2;
635 cr += dst->linesize[2] - width2 - skip2;
637 for (h = dsth - (dsty & 1); h >= 2; h -= 2) {
643 YUVA_IN(y, u, v, a, p, pal);
647 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
650 YUVA_IN(y, u, v, a, p, pal);
654 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
655 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
656 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
662 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
663 YUVA_IN(y, u, v, a, p, pal);
667 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
669 YUVA_IN(y, u, v, a, p + BPP, pal);
673 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
677 YUVA_IN(y, u, v, a, p, pal);
681 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
683 YUVA_IN(y, u, v, a, p + BPP, pal);
687 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
689 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 2);
690 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 2);
694 p += -wrap3 + 2 * BPP;
698 YUVA_IN(y, u, v, a, p, pal);
702 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
705 YUVA_IN(y, u, v, a, p, pal);
709 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
710 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
711 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
717 p += wrap3 + (wrap3 - dstw * BPP);
718 lum += wrap + (wrap - dstw - dstx);
719 cb += dst->linesize[1] - width2 - skip2;
720 cr += dst->linesize[2] - width2 - skip2;
722 /* handle odd height */
729 YUVA_IN(y, u, v, a, p, pal);
730 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
731 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
732 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
738 for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
739 YUVA_IN(y, u, v, a, p, pal);
743 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
745 YUVA_IN(y, u, v, a, p + BPP, pal);
749 lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
750 cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u, 1);
751 cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v, 1);
758 YUVA_IN(y, u, v, a, p, pal);
759 lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
760 cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
761 cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
766 static void free_subpicture(SubPicture *sp)
768 avsubtitle_free(&sp->sub);
771 static void calculate_display_rect(SDL_Rect *rect, int scr_xleft, int scr_ytop, int scr_width, int scr_height, VideoPicture *vp)
774 int width, height, x, y;
776 if (vp->sar.num == 0)
779 aspect_ratio = av_q2d(vp->sar);
781 if (aspect_ratio <= 0.0)
783 aspect_ratio *= (float)vp->width / (float)vp->height;
785 /* XXX: we suppose the screen has a 1.0 pixel ratio */
787 width = ((int)rint(height * aspect_ratio)) & ~1;
788 if (width > scr_width) {
790 height = ((int)rint(width / aspect_ratio)) & ~1;
792 x = (scr_width - width) / 2;
793 y = (scr_height - height) / 2;
794 rect->x = scr_xleft + x;
795 rect->y = scr_ytop + y;
796 rect->w = FFMAX(width, 1);
797 rect->h = FFMAX(height, 1);
800 static void video_image_display(VideoState *is)
808 vp = &is->pictq[is->pictq_rindex];
810 if (is->subtitle_st) {
811 if (is->subpq_size > 0) {
812 sp = &is->subpq[is->subpq_rindex];
814 if (vp->pts >= sp->pts + ((float) sp->sub.start_display_time / 1000)) {
815 SDL_LockYUVOverlay (vp->bmp);
817 pict.data[0] = vp->bmp->pixels[0];
818 pict.data[1] = vp->bmp->pixels[2];
819 pict.data[2] = vp->bmp->pixels[1];
821 pict.linesize[0] = vp->bmp->pitches[0];
822 pict.linesize[1] = vp->bmp->pitches[2];
823 pict.linesize[2] = vp->bmp->pitches[1];
825 for (i = 0; i < sp->sub.num_rects; i++)
826 blend_subrect(&pict, sp->sub.rects[i],
827 vp->bmp->w, vp->bmp->h);
829 SDL_UnlockYUVOverlay (vp->bmp);
834 calculate_display_rect(&rect, is->xleft, is->ytop, is->width, is->height, vp);
836 SDL_DisplayYUVOverlay(vp->bmp, &rect);
838 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) {
839 int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
840 fill_border(is->xleft, is->ytop, is->width, is->height, rect.x, rect.y, rect.w, rect.h, bgcolor, 1);
841 is->last_display_rect = rect;
846 static inline int compute_mod(int a, int b)
848 return a < 0 ? a%b + b : a%b;
851 static void video_audio_display(VideoState *s)
853 int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
854 int ch, channels, h, h2, bgcolor, fgcolor;
856 int rdft_bits, nb_freq;
858 for (rdft_bits = 1; (1 << rdft_bits) < 2 * s->height; rdft_bits++)
860 nb_freq = 1 << (rdft_bits - 1);
862 /* compute display index : center on currently output samples */
863 channels = s->audio_tgt.channels;
864 nb_display_channels = channels;
866 int data_used= s->show_mode == SHOW_MODE_WAVES ? s->width : (2*nb_freq);
868 delay = s->audio_write_buf_size;
871 /* to be more precise, we take into account the time spent since
872 the last buffer computation */
873 if (audio_callback_time) {
874 time_diff = av_gettime() - audio_callback_time;
875 delay -= (time_diff * s->audio_tgt.freq) / 1000000;
878 delay += 2 * data_used;
879 if (delay < data_used)
882 i_start= x = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
883 if (s->show_mode == SHOW_MODE_WAVES) {
885 for (i = 0; i < 1000; i += channels) {
886 int idx = (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;
887 int a = s->sample_array[idx];
888 int b = s->sample_array[(idx + 4 * channels) % SAMPLE_ARRAY_SIZE];
889 int c = s->sample_array[(idx + 5 * channels) % SAMPLE_ARRAY_SIZE];
890 int d = s->sample_array[(idx + 9 * channels) % SAMPLE_ARRAY_SIZE];
892 if (h < score && (b ^ c) < 0) {
899 s->last_i_start = i_start;
901 i_start = s->last_i_start;
904 bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
905 if (s->show_mode == SHOW_MODE_WAVES) {
906 fill_rectangle(screen,
907 s->xleft, s->ytop, s->width, s->height,
910 fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);
912 /* total height for one channel */
913 h = s->height / nb_display_channels;
914 /* graph height / 2 */
916 for (ch = 0; ch < nb_display_channels; ch++) {
918 y1 = s->ytop + ch * h + (h / 2); /* position of center line */
919 for (x = 0; x < s->width; x++) {
920 y = (s->sample_array[i] * h2) >> 15;
927 fill_rectangle(screen,
928 s->xleft + x, ys, 1, y,
931 if (i >= SAMPLE_ARRAY_SIZE)
932 i -= SAMPLE_ARRAY_SIZE;
936 fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);
938 for (ch = 1; ch < nb_display_channels; ch++) {
939 y = s->ytop + ch * h;
940 fill_rectangle(screen,
941 s->xleft, y, s->width, 1,
944 SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
946 nb_display_channels= FFMIN(nb_display_channels, 2);
947 if (rdft_bits != s->rdft_bits) {
948 av_rdft_end(s->rdft);
949 av_free(s->rdft_data);
950 s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
951 s->rdft_bits = rdft_bits;
952 s->rdft_data = av_malloc(4 * nb_freq * sizeof(*s->rdft_data));
956 for (ch = 0; ch < nb_display_channels; ch++) {
957 data[ch] = s->rdft_data + 2 * nb_freq * ch;
959 for (x = 0; x < 2 * nb_freq; x++) {
960 double w = (x-nb_freq) * (1.0 / nb_freq);
961 data[ch][x] = s->sample_array[i] * (1.0 - w * w);
963 if (i >= SAMPLE_ARRAY_SIZE)
964 i -= SAMPLE_ARRAY_SIZE;
966 av_rdft_calc(s->rdft, data[ch]);
968 // least efficient way to do this, we should of course directly access it but its more than fast enough
969 for (y = 0; y < s->height; y++) {
970 double w = 1 / sqrt(nb_freq);
971 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]));
972 int b = (nb_display_channels == 2 ) ? sqrt(w * sqrt(data[1][2 * y + 0] * data[1][2 * y + 0]
973 + data[1][2 * y + 1] * data[1][2 * y + 1])) : a;
976 fgcolor = SDL_MapRGB(screen->format, a, b, (a + b) / 2);
978 fill_rectangle(screen,
979 s->xpos, s->height-y, 1, 1,
983 SDL_UpdateRect(screen, s->xpos, s->ytop, 1, s->height);
986 if (s->xpos >= s->width)
991 static void stream_close(VideoState *is)
995 /* XXX: use a special url_shutdown call to abort parse cleanly */
996 is->abort_request = 1;
997 SDL_WaitThread(is->read_tid, NULL);
998 packet_queue_destroy(&is->videoq);
999 packet_queue_destroy(&is->audioq);
1000 packet_queue_destroy(&is->subtitleq);
1002 /* free all pictures */
1003 for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++) {
1006 SDL_FreeYUVOverlay(vp->bmp);
1010 SDL_DestroyMutex(is->pictq_mutex);
1011 SDL_DestroyCond(is->pictq_cond);
1012 SDL_DestroyMutex(is->subpq_mutex);
1013 SDL_DestroyCond(is->subpq_cond);
1014 SDL_DestroyCond(is->continue_read_thread);
1015 #if !CONFIG_AVFILTER
1016 sws_freeContext(is->img_convert_ctx);
1021 static void do_exit(VideoState *is)
1026 av_lockmgr_register(NULL);
1030 av_freep(&vfilters);
1032 avformat_network_deinit();
1036 av_log(NULL, AV_LOG_QUIET, "%s", "");
1040 static void sigterm_handler(int sig)
1045 static int video_open(VideoState *is, int force_set_video_mode, VideoPicture *vp)
1047 int flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;
1051 if (is_full_screen) flags |= SDL_FULLSCREEN;
1052 else flags |= SDL_RESIZABLE;
1054 if (vp && vp->width) {
1055 calculate_display_rect(&rect, 0, 0, INT_MAX, vp->height, vp);
1056 default_width = rect.w;
1057 default_height = rect.h;
1060 if (is_full_screen && fs_screen_width) {
1061 w = fs_screen_width;
1062 h = fs_screen_height;
1063 } else if (!is_full_screen && screen_width) {
1070 if (screen && is->width == screen->w && screen->w == w
1071 && is->height== screen->h && screen->h == h && !force_set_video_mode)
1073 screen = SDL_SetVideoMode(w, h, 0, flags);
1075 fprintf(stderr, "SDL: could not set video mode - exiting\n");
1079 window_title = input_filename;
1080 SDL_WM_SetCaption(window_title, window_title);
1082 is->width = screen->w;
1083 is->height = screen->h;
1088 /* display the current picture, if any */
1089 static void video_display(VideoState *is)
1092 video_open(is, 0, NULL);
1093 if (is->audio_st && is->show_mode != SHOW_MODE_VIDEO)
1094 video_audio_display(is);
1095 else if (is->video_st)
1096 video_image_display(is);
1099 /* get the current audio clock value */
1100 static double get_audio_clock(VideoState *is)
1102 if (is->audio_clock_serial != is->audioq.serial)
1105 return is->audio_current_pts;
1107 return is->audio_current_pts_drift + av_gettime() / 1000000.0;
1111 /* get the current video clock value */
1112 static double get_video_clock(VideoState *is)
1114 if (is->video_clock_serial != is->videoq.serial)
1117 return is->video_current_pts;
1119 return is->video_current_pts_drift + av_gettime() / 1000000.0;
1123 /* get the current external clock value */
1124 static double get_external_clock(VideoState *is)
1127 return is->external_clock;
1129 double time = av_gettime() / 1000000.0;
1130 return is->external_clock_drift + time - (time - is->external_clock_time / 1000000.0) * (1.0 - is->external_clock_speed);
1134 static int get_master_sync_type(VideoState *is) {
1135 if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
1137 return AV_SYNC_VIDEO_MASTER;
1139 return AV_SYNC_AUDIO_MASTER;
1140 } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
1142 return AV_SYNC_AUDIO_MASTER;
1144 return AV_SYNC_EXTERNAL_CLOCK;
1146 return AV_SYNC_EXTERNAL_CLOCK;
1150 /* get the current master clock value */
1151 static double get_master_clock(VideoState *is)
1155 switch (get_master_sync_type(is)) {
1156 case AV_SYNC_VIDEO_MASTER:
1157 val = get_video_clock(is);
1159 case AV_SYNC_AUDIO_MASTER:
1160 val = get_audio_clock(is);
1163 val = get_external_clock(is);
1169 static void update_external_clock_pts(VideoState *is, double pts)
1171 is->external_clock_time = av_gettime();
1172 is->external_clock = pts;
1173 is->external_clock_drift = pts - is->external_clock_time / 1000000.0;
1176 static void check_external_clock_sync(VideoState *is, double pts) {
1177 double ext_clock = get_external_clock(is);
1178 if (isnan(ext_clock) || fabs(ext_clock - pts) > AV_NOSYNC_THRESHOLD) {
1179 update_external_clock_pts(is, pts);
1183 static void update_external_clock_speed(VideoState *is, double speed) {
1184 update_external_clock_pts(is, get_external_clock(is));
1185 is->external_clock_speed = speed;
1188 static void check_external_clock_speed(VideoState *is) {
1189 if (is->video_stream >= 0 && is->videoq.nb_packets <= MIN_FRAMES / 2 ||
1190 is->audio_stream >= 0 && is->audioq.nb_packets <= MIN_FRAMES / 2) {
1191 update_external_clock_speed(is, FFMAX(EXTERNAL_CLOCK_SPEED_MIN, is->external_clock_speed - EXTERNAL_CLOCK_SPEED_STEP));
1192 } else if ((is->video_stream < 0 || is->videoq.nb_packets > MIN_FRAMES * 2) &&
1193 (is->audio_stream < 0 || is->audioq.nb_packets > MIN_FRAMES * 2)) {
1194 update_external_clock_speed(is, FFMIN(EXTERNAL_CLOCK_SPEED_MAX, is->external_clock_speed + EXTERNAL_CLOCK_SPEED_STEP));
1196 double speed = is->external_clock_speed;
1198 update_external_clock_speed(is, speed + EXTERNAL_CLOCK_SPEED_STEP * (1.0 - speed) / fabs(1.0 - speed));
1202 /* seek in the stream */
1203 static void stream_seek(VideoState *is, int64_t pos, int64_t rel, int seek_by_bytes)
1205 if (!is->seek_req) {
1208 is->seek_flags &= ~AVSEEK_FLAG_BYTE;
1210 is->seek_flags |= AVSEEK_FLAG_BYTE;
1212 SDL_CondSignal(is->continue_read_thread);
1216 /* pause or resume the video */
1217 static void stream_toggle_pause(VideoState *is)
1220 is->frame_timer += av_gettime() / 1000000.0 + is->video_current_pts_drift - is->video_current_pts;
1221 if (is->read_pause_return != AVERROR(ENOSYS)) {
1222 is->video_current_pts = is->video_current_pts_drift + av_gettime() / 1000000.0;
1224 is->video_current_pts_drift = is->video_current_pts - av_gettime() / 1000000.0;
1226 update_external_clock_pts(is, get_external_clock(is));
1227 is->paused = !is->paused;
1230 static void toggle_pause(VideoState *is)
1232 stream_toggle_pause(is);
1236 static void step_to_next_frame(VideoState *is)
1238 /* if the stream is paused unpause it, then step */
1240 stream_toggle_pause(is);
1244 static double compute_target_delay(double delay, VideoState *is)
1246 double sync_threshold, diff;
1248 /* update delay to follow master synchronisation source */
1249 if (get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER) {
1250 /* if video is slave, we try to correct big delays by
1251 duplicating or deleting a frame */
1252 diff = get_video_clock(is) - get_master_clock(is);
1254 /* skip or repeat frame. We take into account the
1255 delay to compute the threshold. I still don't know
1256 if it is the best guess */
1257 sync_threshold = FFMAX(AV_SYNC_THRESHOLD, delay);
1258 if (!isnan(diff) && fabs(diff) < AV_NOSYNC_THRESHOLD) {
1259 if (diff <= -sync_threshold)
1261 else if (diff >= sync_threshold)
1266 av_dlog(NULL, "video: delay=%0.3f A-V=%f\n",
1272 static void pictq_next_picture(VideoState *is) {
1273 /* update queue size and signal for next picture */
1274 if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
1275 is->pictq_rindex = 0;
1277 SDL_LockMutex(is->pictq_mutex);
1279 SDL_CondSignal(is->pictq_cond);
1280 SDL_UnlockMutex(is->pictq_mutex);
1283 static int pictq_prev_picture(VideoState *is) {
1284 VideoPicture *prevvp;
1286 /* update queue size and signal for the previous picture */
1287 prevvp = &is->pictq[(is->pictq_rindex + VIDEO_PICTURE_QUEUE_SIZE - 1) % VIDEO_PICTURE_QUEUE_SIZE];
1288 if (prevvp->allocated && prevvp->serial == is->videoq.serial) {
1289 SDL_LockMutex(is->pictq_mutex);
1290 if (is->pictq_size < VIDEO_PICTURE_QUEUE_SIZE - 1) {
1291 if (--is->pictq_rindex == -1)
1292 is->pictq_rindex = VIDEO_PICTURE_QUEUE_SIZE - 1;
1296 SDL_CondSignal(is->pictq_cond);
1297 SDL_UnlockMutex(is->pictq_mutex);
1302 static void update_video_pts(VideoState *is, double pts, int64_t pos, int serial) {
1303 double time = av_gettime() / 1000000.0;
1304 /* update current video pts */
1305 is->video_current_pts = pts;
1306 is->video_current_pts_drift = is->video_current_pts - time;
1307 is->video_current_pos = pos;
1308 is->frame_last_pts = pts;
1309 is->video_clock_serial = serial;
1310 if (is->videoq.serial == serial)
1311 check_external_clock_sync(is, is->video_current_pts);
1314 /* called to display each frame */
1315 static void video_refresh(void *opaque, double *remaining_time)
1317 VideoState *is = opaque;
1321 SubPicture *sp, *sp2;
1323 if (!is->paused && get_master_sync_type(is) == AV_SYNC_EXTERNAL_CLOCK && is->realtime)
1324 check_external_clock_speed(is);
1326 if (!display_disable && is->show_mode != SHOW_MODE_VIDEO && is->audio_st) {
1327 time = av_gettime() / 1000000.0;
1328 if (is->force_refresh || is->last_vis_time + rdftspeed < time) {
1330 is->last_vis_time = time;
1332 *remaining_time = FFMIN(*remaining_time, is->last_vis_time + rdftspeed - time);
1337 if (is->force_refresh)
1338 redisplay = pictq_prev_picture(is);
1340 if (is->pictq_size == 0) {
1341 SDL_LockMutex(is->pictq_mutex);
1342 if (is->frame_last_dropped_pts != AV_NOPTS_VALUE && is->frame_last_dropped_pts > is->frame_last_pts) {
1343 update_video_pts(is, is->frame_last_dropped_pts, is->frame_last_dropped_pos, 0);
1344 is->frame_last_dropped_pts = AV_NOPTS_VALUE;
1346 SDL_UnlockMutex(is->pictq_mutex);
1347 // nothing to do, no picture to display in the queue
1349 double last_duration, duration, delay;
1350 /* dequeue the picture */
1351 vp = &is->pictq[is->pictq_rindex];
1353 if (vp->serial != is->videoq.serial) {
1354 pictq_next_picture(is);
1362 /* compute nominal last_duration */
1363 last_duration = vp->pts - is->frame_last_pts;
1364 if (last_duration > 0 && last_duration < is->max_frame_duration) {
1365 /* if duration of the last frame was sane, update last_duration in video state */
1366 is->frame_last_duration = last_duration;
1368 delay = compute_target_delay(is->frame_last_duration, is);
1370 time= av_gettime()/1000000.0;
1371 if (time < is->frame_timer + delay) {
1372 *remaining_time = FFMIN(is->frame_timer + delay - time, *remaining_time);
1377 is->frame_timer += delay * FFMAX(1, floor((time-is->frame_timer) / delay));
1379 SDL_LockMutex(is->pictq_mutex);
1380 update_video_pts(is, vp->pts, vp->pos, vp->serial);
1381 SDL_UnlockMutex(is->pictq_mutex);
1383 if (is->pictq_size > 1) {
1384 VideoPicture *nextvp = &is->pictq[(is->pictq_rindex + 1) % VIDEO_PICTURE_QUEUE_SIZE];
1385 duration = nextvp->pts - vp->pts;
1386 if(!is->step && (redisplay || framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) && time > is->frame_timer + duration){
1388 is->frame_drops_late++;
1389 pictq_next_picture(is);
1395 if (is->subtitle_st) {
1396 if (is->subtitle_stream_changed) {
1397 SDL_LockMutex(is->subpq_mutex);
1399 while (is->subpq_size) {
1400 free_subpicture(&is->subpq[is->subpq_rindex]);
1402 /* update queue size and signal for next picture */
1403 if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
1404 is->subpq_rindex = 0;
1408 is->subtitle_stream_changed = 0;
1410 SDL_CondSignal(is->subpq_cond);
1411 SDL_UnlockMutex(is->subpq_mutex);
1413 if (is->subpq_size > 0) {
1414 sp = &is->subpq[is->subpq_rindex];
1416 if (is->subpq_size > 1)
1417 sp2 = &is->subpq[(is->subpq_rindex + 1) % SUBPICTURE_QUEUE_SIZE];
1421 if ((is->video_current_pts > (sp->pts + ((float) sp->sub.end_display_time / 1000)))
1422 || (sp2 && is->video_current_pts > (sp2->pts + ((float) sp2->sub.start_display_time / 1000))))
1424 free_subpicture(sp);
1426 /* update queue size and signal for next picture */
1427 if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
1428 is->subpq_rindex = 0;
1430 SDL_LockMutex(is->subpq_mutex);
1432 SDL_CondSignal(is->subpq_cond);
1433 SDL_UnlockMutex(is->subpq_mutex);
1440 /* display picture */
1441 if (!display_disable && is->show_mode == SHOW_MODE_VIDEO)
1444 pictq_next_picture(is);
1446 if (is->step && !is->paused)
1447 stream_toggle_pause(is);
1450 is->force_refresh = 0;
1452 static int64_t last_time;
1454 int aqsize, vqsize, sqsize;
1457 cur_time = av_gettime();
1458 if (!last_time || (cur_time - last_time) >= 30000) {
1463 aqsize = is->audioq.size;
1465 vqsize = is->videoq.size;
1466 if (is->subtitle_st)
1467 sqsize = is->subtitleq.size;
1469 if (is->audio_st && is->video_st)
1470 av_diff = get_audio_clock(is) - get_video_clock(is);
1471 printf("%7.2f A-V:%7.3f fd=%4d aq=%5dKB vq=%5dKB sq=%5dB f=%"PRId64"/%"PRId64" \r",
1472 get_master_clock(is),
1474 is->frame_drops_early + is->frame_drops_late,
1478 is->video_st ? is->video_st->codec->pts_correction_num_faulty_dts : 0,
1479 is->video_st ? is->video_st->codec->pts_correction_num_faulty_pts : 0);
1481 last_time = cur_time;
1486 /* allocate a picture (needs to do that in main thread to avoid
1487 potential locking problems */
1488 static void alloc_picture(VideoState *is)
1492 vp = &is->pictq[is->pictq_windex];
1495 SDL_FreeYUVOverlay(vp->bmp);
1497 video_open(is, 0, vp);
1499 vp->bmp = SDL_CreateYUVOverlay(vp->width, vp->height,
1502 if (!vp->bmp || vp->bmp->pitches[0] < vp->width) {
1503 /* SDL allocates a buffer smaller than requested if the video
1504 * overlay hardware is unable to support the requested size. */
1505 fprintf(stderr, "Error: the video system does not support an image\n"
1506 "size of %dx%d pixels. Try using -lowres or -vf \"scale=w:h\"\n"
1507 "to reduce the image size.\n", vp->width, vp->height );
1511 SDL_LockMutex(is->pictq_mutex);
1513 SDL_CondSignal(is->pictq_cond);
1514 SDL_UnlockMutex(is->pictq_mutex);
1517 static void duplicate_right_border_pixels(SDL_Overlay *bmp) {
1518 int i, width, height;
1520 for (i = 0; i < 3; i++) {
1527 if (bmp->pitches[i] > width) {
1528 maxp = bmp->pixels[i] + bmp->pitches[i] * height - 1;
1529 for (p = bmp->pixels[i] + width - 1; p < maxp; p += bmp->pitches[i])
1535 static int queue_picture(VideoState *is, AVFrame *src_frame, double pts, int64_t pos, int serial)
1539 #if defined(DEBUG_SYNC) && 0
1540 printf("frame_type=%c pts=%0.3f\n",
1541 av_get_picture_type_char(src_frame->pict_type), pts);
1544 /* wait until we have space to put a new picture */
1545 SDL_LockMutex(is->pictq_mutex);
1547 /* keep the last already displayed picture in the queue */
1548 while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE - 2 &&
1549 !is->videoq.abort_request) {
1550 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1552 SDL_UnlockMutex(is->pictq_mutex);
1554 if (is->videoq.abort_request)
1557 vp = &is->pictq[is->pictq_windex];
1560 vp->sar = src_frame->sample_aspect_ratio;
1562 vp->sar = av_guess_sample_aspect_ratio(is->ic, is->video_st, src_frame);
1565 /* alloc or resize hardware picture buffer */
1566 if (!vp->bmp || vp->reallocate || !vp->allocated ||
1567 vp->width != src_frame->width ||
1568 vp->height != src_frame->height) {
1573 vp->width = src_frame->width;
1574 vp->height = src_frame->height;
1576 /* the allocation must be done in the main thread to avoid
1577 locking problems. */
1578 event.type = FF_ALLOC_EVENT;
1579 event.user.data1 = is;
1580 SDL_PushEvent(&event);
1582 /* wait until the picture is allocated */
1583 SDL_LockMutex(is->pictq_mutex);
1584 while (!vp->allocated && !is->videoq.abort_request) {
1585 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1587 /* if the queue is aborted, we have to pop the pending ALLOC event or wait for the allocation to complete */
1588 if (is->videoq.abort_request && SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_EVENTMASK(FF_ALLOC_EVENT)) != 1) {
1589 while (!vp->allocated) {
1590 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1593 SDL_UnlockMutex(is->pictq_mutex);
1595 if (is->videoq.abort_request)
1599 /* if the frame is not skipped, then display it */
1601 AVPicture pict = { { 0 } };
1603 /* get a pointer on the bitmap */
1604 SDL_LockYUVOverlay (vp->bmp);
1606 pict.data[0] = vp->bmp->pixels[0];
1607 pict.data[1] = vp->bmp->pixels[2];
1608 pict.data[2] = vp->bmp->pixels[1];
1610 pict.linesize[0] = vp->bmp->pitches[0];
1611 pict.linesize[1] = vp->bmp->pitches[2];
1612 pict.linesize[2] = vp->bmp->pitches[1];
1615 // FIXME use direct rendering
1616 av_picture_copy(&pict, (AVPicture *)src_frame,
1617 src_frame->format, vp->width, vp->height);
1619 av_opt_get_int(sws_opts, "sws_flags", 0, &sws_flags);
1620 is->img_convert_ctx = sws_getCachedContext(is->img_convert_ctx,
1621 vp->width, vp->height, src_frame->format, vp->width, vp->height,
1622 AV_PIX_FMT_YUV420P, sws_flags, NULL, NULL, NULL);
1623 if (is->img_convert_ctx == NULL) {
1624 fprintf(stderr, "Cannot initialize the conversion context\n");
1627 sws_scale(is->img_convert_ctx, src_frame->data, src_frame->linesize,
1628 0, vp->height, pict.data, pict.linesize);
1630 /* workaround SDL PITCH_WORKAROUND */
1631 duplicate_right_border_pixels(vp->bmp);
1632 /* update the bitmap content */
1633 SDL_UnlockYUVOverlay(vp->bmp);
1637 vp->serial = serial;
1639 /* now we can update the picture count */
1640 if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
1641 is->pictq_windex = 0;
1642 SDL_LockMutex(is->pictq_mutex);
1644 SDL_UnlockMutex(is->pictq_mutex);
1649 static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacket *pkt, int *serial)
1653 if (packet_queue_get(&is->videoq, pkt, 1, serial) < 0)
1656 if (pkt->data == flush_pkt.data) {
1657 avcodec_flush_buffers(is->video_st->codec);
1659 SDL_LockMutex(is->pictq_mutex);
1660 // Make sure there are no long delay timers (ideally we should just flush the queue but that's harder)
1661 while (is->pictq_size && !is->videoq.abort_request) {
1662 SDL_CondWait(is->pictq_cond, is->pictq_mutex);
1664 is->video_current_pos = -1;
1665 is->frame_last_pts = AV_NOPTS_VALUE;
1666 is->frame_last_duration = 0;
1667 is->frame_timer = (double)av_gettime() / 1000000.0;
1668 is->frame_last_dropped_pts = AV_NOPTS_VALUE;
1669 SDL_UnlockMutex(is->pictq_mutex);
1673 if(avcodec_decode_video2(is->video_st->codec, frame, &got_picture, pkt) < 0)
1679 if (decoder_reorder_pts == -1) {
1680 *pts = av_frame_get_best_effort_timestamp(frame);
1681 } else if (decoder_reorder_pts) {
1682 *pts = frame->pkt_pts;
1684 *pts = frame->pkt_dts;
1687 if (*pts == AV_NOPTS_VALUE) {
1691 if (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) {
1692 SDL_LockMutex(is->pictq_mutex);
1693 if (is->frame_last_pts != AV_NOPTS_VALUE && *pts) {
1694 double clockdiff = get_video_clock(is) - get_master_clock(is);
1695 double dpts = av_q2d(is->video_st->time_base) * *pts;
1696 double ptsdiff = dpts - is->frame_last_pts;
1697 if (!isnan(clockdiff) && fabs(clockdiff) < AV_NOSYNC_THRESHOLD &&
1698 ptsdiff > 0 && ptsdiff < AV_NOSYNC_THRESHOLD &&
1699 clockdiff + ptsdiff - is->frame_last_filter_delay < 0) {
1700 is->frame_last_dropped_pos = pkt->pos;
1701 is->frame_last_dropped_pts = dpts;
1702 is->frame_drops_early++;
1703 av_frame_unref(frame);
1707 SDL_UnlockMutex(is->pictq_mutex);
1716 static int configure_filtergraph(AVFilterGraph *graph, const char *filtergraph,
1717 AVFilterContext *source_ctx, AVFilterContext *sink_ctx)
1720 AVFilterInOut *outputs = NULL, *inputs = NULL;
1723 outputs = avfilter_inout_alloc();
1724 inputs = avfilter_inout_alloc();
1725 if (!outputs || !inputs) {
1726 ret = AVERROR(ENOMEM);
1730 outputs->name = av_strdup("in");
1731 outputs->filter_ctx = source_ctx;
1732 outputs->pad_idx = 0;
1733 outputs->next = NULL;
1735 inputs->name = av_strdup("out");
1736 inputs->filter_ctx = sink_ctx;
1737 inputs->pad_idx = 0;
1738 inputs->next = NULL;
1740 if ((ret = avfilter_graph_parse(graph, filtergraph, &inputs, &outputs, NULL)) < 0)
1743 if ((ret = avfilter_link(source_ctx, 0, sink_ctx, 0)) < 0)
1747 ret = avfilter_graph_config(graph, NULL);
1749 avfilter_inout_free(&outputs);
1750 avfilter_inout_free(&inputs);
1754 static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const char *vfilters, AVFrame *frame)
1756 static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };
1757 char sws_flags_str[128];
1758 char buffersrc_args[256];
1760 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
1761 AVFilterContext *filt_src = NULL, *filt_out = NULL, *filt_crop;
1762 AVCodecContext *codec = is->video_st->codec;
1764 if (!buffersink_params)
1765 return AVERROR(ENOMEM);
1767 av_opt_get_int(sws_opts, "sws_flags", 0, &sws_flags);
1768 snprintf(sws_flags_str, sizeof(sws_flags_str), "flags=%"PRId64, sws_flags);
1769 graph->scale_sws_opts = av_strdup(sws_flags_str);
1771 snprintf(buffersrc_args, sizeof(buffersrc_args),
1772 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
1773 frame->width, frame->height, frame->format,
1774 is->video_st->time_base.num, is->video_st->time_base.den,
1775 codec->sample_aspect_ratio.num, FFMAX(codec->sample_aspect_ratio.den, 1));
1777 if ((ret = avfilter_graph_create_filter(&filt_src,
1778 avfilter_get_by_name("buffer"),
1779 "ffplay_buffer", buffersrc_args, NULL,
1783 buffersink_params->pixel_fmts = pix_fmts;
1784 ret = avfilter_graph_create_filter(&filt_out,
1785 avfilter_get_by_name("buffersink"),
1786 "ffplay_buffersink", NULL, buffersink_params, graph);
1790 /* SDL YUV code is not handling odd width/height for some driver
1791 * combinations, therefore we crop the picture to an even width/height. */
1792 if ((ret = avfilter_graph_create_filter(&filt_crop,
1793 avfilter_get_by_name("crop"),
1794 "ffplay_crop", "floor(in_w/2)*2:floor(in_h/2)*2", NULL, graph)) < 0)
1796 if ((ret = avfilter_link(filt_crop, 0, filt_out, 0)) < 0)
1799 if ((ret = configure_filtergraph(graph, vfilters, filt_src, filt_crop)) < 0)
1802 is->in_video_filter = filt_src;
1803 is->out_video_filter = filt_out;
1806 av_freep(&buffersink_params);
1810 static int configure_audio_filters(VideoState *is, const char *afilters, int force_output_format)
1812 static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE };
1813 int sample_rates[2] = { 0, -1 };
1814 int64_t channel_layouts[2] = { 0, -1 };
1815 int channels[2] = { 0, -1 };
1816 AVFilterContext *filt_asrc = NULL, *filt_asink = NULL;
1817 char asrc_args[256];
1818 AVABufferSinkParams *asink_params = NULL;
1821 avfilter_graph_free(&is->agraph);
1822 if (!(is->agraph = avfilter_graph_alloc()))
1823 return AVERROR(ENOMEM);
1825 ret = snprintf(asrc_args, sizeof(asrc_args),
1826 "sample_rate=%d:sample_fmt=%s:channels=%d",
1827 is->audio_filter_src.freq, av_get_sample_fmt_name(is->audio_filter_src.fmt),
1828 is->audio_filter_src.channels);
1829 if (is->audio_filter_src.channel_layout)
1830 snprintf(asrc_args + ret, sizeof(asrc_args) - ret,
1831 ":channel_layout=0x%"PRIx64, is->audio_filter_src.channel_layout);
1833 ret = avfilter_graph_create_filter(&filt_asrc,
1834 avfilter_get_by_name("abuffer"), "ffplay_abuffer",
1835 asrc_args, NULL, is->agraph);
1839 if (!(asink_params = av_abuffersink_params_alloc())) {
1840 ret = AVERROR(ENOMEM);
1843 asink_params->sample_fmts = sample_fmts;
1845 asink_params->all_channel_counts = 1;
1846 if (force_output_format) {
1847 channel_layouts[0] = is->audio_tgt.channel_layout;
1848 asink_params->channel_layouts = channel_layouts;
1849 asink_params->all_channel_counts = 0;
1850 channels[0] = is->audio_tgt.channels;
1851 asink_params->channel_counts = channels;
1852 asink_params->all_channel_counts = 0;
1853 sample_rates[0] = is->audio_tgt.freq;
1854 asink_params->sample_rates = sample_rates;
1857 ret = avfilter_graph_create_filter(&filt_asink,
1858 avfilter_get_by_name("abuffersink"), "ffplay_abuffersink",
1859 NULL, asink_params, is->agraph);
1863 if ((ret = configure_filtergraph(is->agraph, afilters, filt_asrc, filt_asink)) < 0)
1866 is->in_audio_filter = filt_asrc;
1867 is->out_audio_filter = filt_asink;
1870 av_freep(&asink_params);
1872 avfilter_graph_free(&is->agraph);
1875 #endif /* CONFIG_AVFILTER */
1877 static int video_thread(void *arg)
1879 AVPacket pkt = { 0 };
1880 VideoState *is = arg;
1881 AVFrame *frame = av_frame_alloc();
1882 int64_t pts_int = AV_NOPTS_VALUE, pos = -1;
1888 AVFilterGraph *graph = avfilter_graph_alloc();
1889 AVFilterContext *filt_out = NULL, *filt_in = NULL;
1892 enum AVPixelFormat last_format = -2;
1893 int last_serial = -1;
1900 while (is->paused && !is->videoq.abort_request)
1903 avcodec_get_frame_defaults(frame);
1904 av_free_packet(&pkt);
1906 ret = get_video_frame(is, frame, &pts_int, &pkt, &serial);
1914 if ( last_w != frame->width
1915 || last_h != frame->height
1916 || last_format != frame->format
1917 || last_serial != serial) {
1918 av_log(NULL, AV_LOG_DEBUG,
1919 "Video frame changed from size:%dx%d format:%s serial:%d to size:%dx%d format:%s serial:%d\n",
1921 (const char *)av_x_if_null(av_get_pix_fmt_name(last_format), "none"), last_serial,
1922 frame->width, frame->height,
1923 (const char *)av_x_if_null(av_get_pix_fmt_name(frame->format), "none"), serial);
1924 avfilter_graph_free(&graph);
1925 graph = avfilter_graph_alloc();
1926 if ((ret = configure_video_filters(graph, is, vfilters, frame)) < 0) {
1928 event.type = FF_QUIT_EVENT;
1929 event.user.data1 = is;
1930 SDL_PushEvent(&event);
1931 av_free_packet(&pkt);
1934 filt_in = is->in_video_filter;
1935 filt_out = is->out_video_filter;
1936 last_w = frame->width;
1937 last_h = frame->height;
1938 last_format = frame->format;
1939 last_serial = serial;
1942 frame->pts = pts_int;
1943 frame->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, frame);
1944 ret = av_buffersrc_add_frame(filt_in, frame);
1947 av_frame_unref(frame);
1948 avcodec_get_frame_defaults(frame);
1949 av_free_packet(&pkt);
1952 is->frame_last_returned_time = av_gettime() / 1000000.0;
1954 ret = av_buffersink_get_frame_flags(filt_out, frame, 0);
1960 is->frame_last_filter_delay = av_gettime() / 1000000.0 - is->frame_last_returned_time;
1961 if (fabs(is->frame_last_filter_delay) > AV_NOSYNC_THRESHOLD / 10.0)
1962 is->frame_last_filter_delay = 0;
1964 pts_int = frame->pts;
1965 tb = filt_out->inputs[0]->time_base;
1966 pos = av_frame_get_pkt_pos(frame);
1967 if (av_cmp_q(tb, is->video_st->time_base)) {
1968 av_unused int64_t pts1 = pts_int;
1969 pts_int = av_rescale_q(pts_int, tb, is->video_st->time_base);
1970 av_dlog(NULL, "video_thread(): "
1971 "tb:%d/%d pts:%"PRId64" -> tb:%d/%d pts:%"PRId64"\n",
1972 tb.num, tb.den, pts1,
1973 is->video_st->time_base.num, is->video_st->time_base.den, pts_int);
1975 pts = pts_int * av_q2d(is->video_st->time_base);
1976 ret = queue_picture(is, frame, pts, pos, serial);
1977 av_frame_unref(frame);
1980 pts = pts_int * av_q2d(is->video_st->time_base);
1981 ret = queue_picture(is, frame, pts, pkt.pos, serial);
1982 av_frame_unref(frame);
1989 avcodec_flush_buffers(is->video_st->codec);
1991 avfilter_graph_free(&graph);
1993 av_free_packet(&pkt);
1994 av_frame_free(&frame);
1998 static int subtitle_thread(void *arg)
2000 VideoState *is = arg;
2002 AVPacket pkt1, *pkt = &pkt1;
2006 int r, g, b, y, u, v, a;
2009 while (is->paused && !is->subtitleq.abort_request) {
2012 if (packet_queue_get(&is->subtitleq, pkt, 1, NULL) < 0)
2015 if (pkt->data == flush_pkt.data) {
2016 avcodec_flush_buffers(is->subtitle_st->codec);
2019 SDL_LockMutex(is->subpq_mutex);
2020 while (is->subpq_size >= SUBPICTURE_QUEUE_SIZE &&
2021 !is->subtitleq.abort_request) {
2022 SDL_CondWait(is->subpq_cond, is->subpq_mutex);
2024 SDL_UnlockMutex(is->subpq_mutex);
2026 if (is->subtitleq.abort_request)
2029 sp = &is->subpq[is->subpq_windex];
2031 /* NOTE: ipts is the PTS of the _first_ picture beginning in
2032 this packet, if any */
2034 if (pkt->pts != AV_NOPTS_VALUE)
2035 pts = av_q2d(is->subtitle_st->time_base) * pkt->pts;
2037 avcodec_decode_subtitle2(is->subtitle_st->codec, &sp->sub,
2038 &got_subtitle, pkt);
2039 if (got_subtitle && sp->sub.format == 0) {
2040 if (sp->sub.pts != AV_NOPTS_VALUE)
2041 pts = sp->sub.pts / (double)AV_TIME_BASE;
2044 for (i = 0; i < sp->sub.num_rects; i++)
2046 for (j = 0; j < sp->sub.rects[i]->nb_colors; j++)
2048 RGBA_IN(r, g, b, a, (uint32_t*)sp->sub.rects[i]->pict.data[1] + j);
2049 y = RGB_TO_Y_CCIR(r, g, b);
2050 u = RGB_TO_U_CCIR(r, g, b, 0);
2051 v = RGB_TO_V_CCIR(r, g, b, 0);
2052 YUVA_OUT((uint32_t*)sp->sub.rects[i]->pict.data[1] + j, y, u, v, a);
2056 /* now we can update the picture count */
2057 if (++is->subpq_windex == SUBPICTURE_QUEUE_SIZE)
2058 is->subpq_windex = 0;
2059 SDL_LockMutex(is->subpq_mutex);
2061 SDL_UnlockMutex(is->subpq_mutex);
2063 av_free_packet(pkt);
2068 /* copy samples for viewing in editor window */
2069 static void update_sample_display(VideoState *is, short *samples, int samples_size)
2073 size = samples_size / sizeof(short);
2075 len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
2078 memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
2080 is->sample_array_index += len;
2081 if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
2082 is->sample_array_index = 0;
2087 /* return the wanted number of samples to get better sync if sync_type is video
2088 * or external master clock */
2089 static int synchronize_audio(VideoState *is, int nb_samples)
2091 int wanted_nb_samples = nb_samples;
2093 /* if not master, then we try to remove or add samples to correct the clock */
2094 if (get_master_sync_type(is) != AV_SYNC_AUDIO_MASTER) {
2095 double diff, avg_diff;
2096 int min_nb_samples, max_nb_samples;
2098 diff = get_audio_clock(is) - get_master_clock(is);
2100 if (!isnan(diff) && fabs(diff) < AV_NOSYNC_THRESHOLD) {
2101 is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
2102 if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
2103 /* not enough measures to have a correct estimate */
2104 is->audio_diff_avg_count++;
2106 /* estimate the A-V difference */
2107 avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
2109 if (fabs(avg_diff) >= is->audio_diff_threshold) {
2110 wanted_nb_samples = nb_samples + (int)(diff * is->audio_src.freq);
2111 min_nb_samples = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100));
2112 max_nb_samples = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100));
2113 wanted_nb_samples = FFMIN(FFMAX(wanted_nb_samples, min_nb_samples), max_nb_samples);
2115 av_dlog(NULL, "diff=%f adiff=%f sample_diff=%d apts=%0.3f %f\n",
2116 diff, avg_diff, wanted_nb_samples - nb_samples,
2117 is->audio_clock, is->audio_diff_threshold);
2120 /* too big difference : may be initial PTS errors, so
2122 is->audio_diff_avg_count = 0;
2123 is->audio_diff_cum = 0;
2127 return wanted_nb_samples;
2131 * Decode one audio frame and return its uncompressed size.
2133 * The processed audio frame is decoded, converted if required, and
2134 * stored in is->audio_buf, with size in bytes given by the return
2137 static int audio_decode_frame(VideoState *is)
2139 AVPacket *pkt_temp = &is->audio_pkt_temp;
2140 AVPacket *pkt = &is->audio_pkt;
2141 AVCodecContext *dec = is->audio_st->codec;
2142 int len1, data_size, resampled_data_size;
2143 int64_t dec_channel_layout;
2145 av_unused double audio_clock0;
2147 int flush_complete = 0;
2148 int wanted_nb_samples;
2152 /* NOTE: the audio packet can contain several frames */
2153 while (pkt_temp->size > 0 || (!pkt_temp->data && new_packet)) {
2155 if (!(is->frame = avcodec_alloc_frame()))
2156 return AVERROR(ENOMEM);
2158 av_frame_unref(is->frame);
2159 avcodec_get_frame_defaults(is->frame);
2162 if (is->audioq.serial != is->audio_pkt_temp_serial)
2171 len1 = avcodec_decode_audio4(dec, is->frame, &got_frame, pkt_temp);
2173 /* if error, we skip the frame */
2178 pkt_temp->data += len1;
2179 pkt_temp->size -= len1;
2182 /* stop sending empty packets if the decoder is finished */
2183 if (!pkt_temp->data && dec->codec->capabilities & CODEC_CAP_DELAY)
2188 if (is->frame->pts == AV_NOPTS_VALUE && pkt_temp->pts != AV_NOPTS_VALUE)
2189 is->frame->pts = av_rescale_q(pkt_temp->pts, is->audio_st->time_base, dec->time_base);
2190 if (pkt_temp->pts != AV_NOPTS_VALUE)
2191 pkt_temp->pts += (double) is->frame->nb_samples / is->frame->sample_rate / av_q2d(is->audio_st->time_base);
2192 tb = dec->time_base;
2199 dec_channel_layout = get_valid_channel_layout(is->frame->channel_layout, av_frame_get_channels(is->frame));
2202 cmp_audio_fmts(is->audio_filter_src.fmt, is->audio_filter_src.channels,
2203 is->frame->format, av_frame_get_channels(is->frame)) ||
2204 is->audio_filter_src.channel_layout != dec_channel_layout ||
2205 is->audio_filter_src.freq != is->frame->sample_rate ||
2206 is->audio_pkt_temp_serial != is->audio_last_serial;
2209 char buf1[1024], buf2[1024];
2210 av_get_channel_layout_string(buf1, sizeof(buf1), -1, is->audio_filter_src.channel_layout);
2211 av_get_channel_layout_string(buf2, sizeof(buf2), -1, dec_channel_layout);
2212 av_log(NULL, AV_LOG_DEBUG,
2213 "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",
2214 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,
2215 is->frame->sample_rate, av_frame_get_channels(is->frame), av_get_sample_fmt_name(is->frame->format), buf2, is->audio_pkt_temp_serial);
2217 is->audio_filter_src.fmt = is->frame->format;
2218 is->audio_filter_src.channels = 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_last_serial = is->audio_pkt_temp_serial;
2223 if ((ret = configure_audio_filters(is, afilters, 1)) < 0)
2227 if ((ret = av_buffersrc_add_frame(is->in_audio_filter, is->frame)) < 0)
2229 av_frame_unref(is->frame);
2230 if ((ret = av_buffersink_get_frame_flags(is->out_audio_filter, is->frame, 0)) < 0)
2232 tb = is->out_audio_filter->inputs[0]->time_base;
2236 data_size = av_samples_get_buffer_size(NULL, av_frame_get_channels(is->frame),
2237 is->frame->nb_samples,
2238 is->frame->format, 1);
2240 dec_channel_layout =
2241 (is->frame->channel_layout && av_frame_get_channels(is->frame) == av_get_channel_layout_nb_channels(is->frame->channel_layout)) ?
2242 is->frame->channel_layout : av_get_default_channel_layout(av_frame_get_channels(is->frame));
2243 wanted_nb_samples = synchronize_audio(is, is->frame->nb_samples);
2245 if (is->frame->format != is->audio_src.fmt ||
2246 dec_channel_layout != is->audio_src.channel_layout ||
2247 is->frame->sample_rate != is->audio_src.freq ||
2248 (wanted_nb_samples != is->frame->nb_samples && !is->swr_ctx)) {
2249 swr_free(&is->swr_ctx);
2250 is->swr_ctx = swr_alloc_set_opts(NULL,
2251 is->audio_tgt.channel_layout, is->audio_tgt.fmt, is->audio_tgt.freq,
2252 dec_channel_layout, is->frame->format, is->frame->sample_rate,
2254 if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
2255 fprintf(stderr, "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
2256 is->frame->sample_rate, av_get_sample_fmt_name(is->frame->format), av_frame_get_channels(is->frame),
2257 is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);
2260 is->audio_src.channel_layout = dec_channel_layout;
2261 is->audio_src.channels = av_frame_get_channels(is->frame);
2262 is->audio_src.freq = is->frame->sample_rate;
2263 is->audio_src.fmt = is->frame->format;
2267 const uint8_t **in = (const uint8_t **)is->frame->extended_data;
2268 uint8_t **out = &is->audio_buf1;
2269 int out_count = (int64_t)wanted_nb_samples * is->audio_tgt.freq / is->frame->sample_rate + 256;
2270 int out_size = av_samples_get_buffer_size(NULL, is->audio_tgt.channels, out_count, is->audio_tgt.fmt, 0);
2272 if (wanted_nb_samples != is->frame->nb_samples) {
2273 if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * is->audio_tgt.freq / is->frame->sample_rate,
2274 wanted_nb_samples * is->audio_tgt.freq / is->frame->sample_rate) < 0) {
2275 fprintf(stderr, "swr_set_compensation() failed\n");
2279 av_fast_malloc(&is->audio_buf1, &is->audio_buf1_size, out_size);
2280 if (!is->audio_buf1)
2281 return AVERROR(ENOMEM);
2282 len2 = swr_convert(is->swr_ctx, out, out_count, in, is->frame->nb_samples);
2284 fprintf(stderr, "swr_convert() failed\n");
2287 if (len2 == out_count) {
2288 fprintf(stderr, "warning: audio buffer is probably too small\n");
2289 swr_init(is->swr_ctx);
2291 is->audio_buf = is->audio_buf1;
2292 resampled_data_size = len2 * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
2294 is->audio_buf = is->frame->data[0];
2295 resampled_data_size = data_size;
2298 audio_clock0 = is->audio_clock;
2299 /* update the audio clock with the pts */
2300 if (is->frame->pts != AV_NOPTS_VALUE) {
2301 is->audio_clock = is->frame->pts * av_q2d(tb) + (double) is->frame->nb_samples / is->frame->sample_rate;
2302 is->audio_clock_serial = is->audio_pkt_temp_serial;
2306 static double last_clock;
2307 printf("audio: delay=%0.3f clock=%0.3f clock0=%0.3f\n",
2308 is->audio_clock - last_clock,
2309 is->audio_clock, audio_clock0);
2310 last_clock = is->audio_clock;
2313 return resampled_data_size;
2316 /* free the current packet */
2318 av_free_packet(pkt);
2319 memset(pkt_temp, 0, sizeof(*pkt_temp));
2321 if (is->audioq.abort_request) {
2325 if (is->audioq.nb_packets == 0)
2326 SDL_CondSignal(is->continue_read_thread);
2328 /* read next packet */
2329 if ((new_packet = packet_queue_get(&is->audioq, pkt, 1, &is->audio_pkt_temp_serial)) < 0)
2332 if (pkt->data == flush_pkt.data) {
2333 avcodec_flush_buffers(dec);
2341 /* prepare a new audio buffer */
2342 static void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
2344 VideoState *is = opaque;
2345 int audio_size, len1;
2347 int frame_size = av_samples_get_buffer_size(NULL, is->audio_tgt.channels, 1, is->audio_tgt.fmt, 1);
2349 audio_callback_time = av_gettime();
2352 if (is->audio_buf_index >= is->audio_buf_size) {
2353 audio_size = audio_decode_frame(is);
2354 if (audio_size < 0) {
2355 /* if error, just output silence */
2356 is->audio_buf = is->silence_buf;
2357 is->audio_buf_size = sizeof(is->silence_buf) / frame_size * frame_size;
2359 if (is->show_mode != SHOW_MODE_VIDEO)
2360 update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
2361 is->audio_buf_size = audio_size;
2363 is->audio_buf_index = 0;
2365 len1 = is->audio_buf_size - is->audio_buf_index;
2368 memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
2371 is->audio_buf_index += len1;
2373 bytes_per_sec = is->audio_tgt.freq * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
2374 is->audio_write_buf_size = is->audio_buf_size - is->audio_buf_index;
2375 /* Let's assume the audio driver that is used by SDL has two periods. */
2376 is->audio_current_pts = is->audio_clock - (double)(2 * is->audio_hw_buf_size + is->audio_write_buf_size) / bytes_per_sec;
2377 is->audio_current_pts_drift = is->audio_current_pts - audio_callback_time / 1000000.0;
2378 if (is->audioq.serial == is->audio_clock_serial)
2379 check_external_clock_sync(is, is->audio_current_pts);
2382 static int audio_open(void *opaque, int64_t wanted_channel_layout, int wanted_nb_channels, int wanted_sample_rate, struct AudioParams *audio_hw_params)
2384 SDL_AudioSpec wanted_spec, spec;
2386 const int next_nb_channels[] = {0, 0, 1, 6, 2, 6, 4, 6};
2388 env = SDL_getenv("SDL_AUDIO_CHANNELS");
2390 wanted_nb_channels = atoi(env);
2391 wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
2393 if (!wanted_channel_layout || wanted_nb_channels != av_get_channel_layout_nb_channels(wanted_channel_layout)) {
2394 wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
2395 wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
2397 wanted_spec.channels = av_get_channel_layout_nb_channels(wanted_channel_layout);
2398 wanted_spec.freq = wanted_sample_rate;
2399 if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
2400 fprintf(stderr, "Invalid sample rate or channel count!\n");
2403 wanted_spec.format = AUDIO_S16SYS;
2404 wanted_spec.silence = 0;
2405 wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
2406 wanted_spec.callback = sdl_audio_callback;
2407 wanted_spec.userdata = opaque;
2408 while (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
2409 fprintf(stderr, "SDL_OpenAudio (%d channels): %s\n", wanted_spec.channels, SDL_GetError());
2410 wanted_spec.channels = next_nb_channels[FFMIN(7, wanted_spec.channels)];
2411 if (!wanted_spec.channels) {
2412 fprintf(stderr, "No more channel combinations to try, audio open failed\n");
2415 wanted_channel_layout = av_get_default_channel_layout(wanted_spec.channels);
2417 if (spec.format != AUDIO_S16SYS) {
2418 fprintf(stderr, "SDL advised audio format %d is not supported!\n", spec.format);
2421 if (spec.channels != wanted_spec.channels) {
2422 wanted_channel_layout = av_get_default_channel_layout(spec.channels);
2423 if (!wanted_channel_layout) {
2424 fprintf(stderr, "SDL advised channel count %d is not supported!\n", spec.channels);
2429 audio_hw_params->fmt = AV_SAMPLE_FMT_S16;
2430 audio_hw_params->freq = spec.freq;
2431 audio_hw_params->channel_layout = wanted_channel_layout;
2432 audio_hw_params->channels = spec.channels;
2436 /* open a given stream. Return 0 if OK */
2437 static int stream_component_open(VideoState *is, int stream_index)
2439 AVFormatContext *ic = is->ic;
2440 AVCodecContext *avctx;
2442 const char *forced_codec_name = NULL;
2444 AVDictionaryEntry *t = NULL;
2445 int sample_rate, nb_channels;
2446 int64_t channel_layout;
2449 if (stream_index < 0 || stream_index >= ic->nb_streams)
2451 avctx = ic->streams[stream_index]->codec;
2453 codec = avcodec_find_decoder(avctx->codec_id);
2455 switch(avctx->codec_type){
2456 case AVMEDIA_TYPE_AUDIO : is->last_audio_stream = stream_index; forced_codec_name = audio_codec_name; break;
2457 case AVMEDIA_TYPE_SUBTITLE: is->last_subtitle_stream = stream_index; forced_codec_name = subtitle_codec_name; break;
2458 case AVMEDIA_TYPE_VIDEO : is->last_video_stream = stream_index; forced_codec_name = video_codec_name; break;
2460 if (forced_codec_name)
2461 codec = avcodec_find_decoder_by_name(forced_codec_name);
2463 if (forced_codec_name) fprintf(stderr, "No codec could be found with name '%s'\n", forced_codec_name);
2464 else fprintf(stderr, "No codec could be found with id %d\n", avctx->codec_id);
2468 avctx->codec_id = codec->id;
2469 avctx->workaround_bugs = workaround_bugs;
2470 avctx->lowres = lowres;
2471 if(avctx->lowres > codec->max_lowres){
2472 av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
2474 avctx->lowres= codec->max_lowres;
2476 avctx->idct_algo = idct;
2477 avctx->error_concealment = error_concealment;
2479 if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
2480 if (fast) avctx->flags2 |= CODEC_FLAG2_FAST;
2481 if(codec->capabilities & CODEC_CAP_DR1)
2482 avctx->flags |= CODEC_FLAG_EMU_EDGE;
2484 opts = filter_codec_opts(codec_opts, avctx->codec_id, ic, ic->streams[stream_index], codec);
2485 if (!av_dict_get(opts, "threads", NULL, 0))
2486 av_dict_set(&opts, "threads", "auto", 0);
2487 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
2488 av_dict_set(&opts, "refcounted_frames", "1", 0);
2489 if (avcodec_open2(avctx, codec, &opts) < 0)
2491 if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2492 av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
2493 return AVERROR_OPTION_NOT_FOUND;
2496 ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
2497 switch (avctx->codec_type) {
2498 case AVMEDIA_TYPE_AUDIO:
2503 is->audio_filter_src.freq = avctx->sample_rate;
2504 is->audio_filter_src.channels = avctx->channels;
2505 is->audio_filter_src.channel_layout = get_valid_channel_layout(avctx->channel_layout, avctx->channels);
2506 is->audio_filter_src.fmt = avctx->sample_fmt;
2507 if ((ret = configure_audio_filters(is, afilters, 0)) < 0)
2509 link = is->out_audio_filter->inputs[0];
2510 sample_rate = link->sample_rate;
2511 nb_channels = link->channels;
2512 channel_layout = link->channel_layout;
2515 sample_rate = avctx->sample_rate;
2516 nb_channels = avctx->channels;
2517 channel_layout = avctx->channel_layout;
2520 /* prepare audio output */
2521 if ((ret = audio_open(is, channel_layout, nb_channels, sample_rate, &is->audio_tgt)) < 0)
2523 is->audio_hw_buf_size = ret;
2524 is->audio_src = is->audio_tgt;
2525 is->audio_buf_size = 0;
2526 is->audio_buf_index = 0;
2528 /* init averaging filter */
2529 is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
2530 is->audio_diff_avg_count = 0;
2531 /* since we do not have a precise anough audio fifo fullness,
2532 we correct audio sync only if larger than this threshold */
2533 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);
2535 memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
2536 memset(&is->audio_pkt_temp, 0, sizeof(is->audio_pkt_temp));
2538 is->audio_stream = stream_index;
2539 is->audio_st = ic->streams[stream_index];
2541 packet_queue_start(&is->audioq);
2544 case AVMEDIA_TYPE_VIDEO:
2545 is->video_stream = stream_index;
2546 is->video_st = ic->streams[stream_index];
2548 packet_queue_start(&is->videoq);
2549 is->video_tid = SDL_CreateThread(video_thread, is);
2551 case AVMEDIA_TYPE_SUBTITLE:
2552 is->subtitle_stream = stream_index;
2553 is->subtitle_st = ic->streams[stream_index];
2554 packet_queue_start(&is->subtitleq);
2556 is->subtitle_tid = SDL_CreateThread(subtitle_thread, is);
2564 static void stream_component_close(VideoState *is, int stream_index)
2566 AVFormatContext *ic = is->ic;
2567 AVCodecContext *avctx;
2569 if (stream_index < 0 || stream_index >= ic->nb_streams)
2571 avctx = ic->streams[stream_index]->codec;
2573 switch (avctx->codec_type) {
2574 case AVMEDIA_TYPE_AUDIO:
2575 packet_queue_abort(&is->audioq);
2579 packet_queue_flush(&is->audioq);
2580 av_free_packet(&is->audio_pkt);
2581 swr_free(&is->swr_ctx);
2582 av_freep(&is->audio_buf1);
2583 is->audio_buf1_size = 0;
2584 is->audio_buf = NULL;
2585 av_frame_free(&is->frame);
2588 av_rdft_end(is->rdft);
2589 av_freep(&is->rdft_data);
2594 avfilter_graph_free(&is->agraph);
2597 case AVMEDIA_TYPE_VIDEO:
2598 packet_queue_abort(&is->videoq);
2600 /* note: we also signal this mutex to make sure we deblock the
2601 video thread in all cases */
2602 SDL_LockMutex(is->pictq_mutex);
2603 SDL_CondSignal(is->pictq_cond);
2604 SDL_UnlockMutex(is->pictq_mutex);
2606 SDL_WaitThread(is->video_tid, NULL);
2608 packet_queue_flush(&is->videoq);
2610 case AVMEDIA_TYPE_SUBTITLE:
2611 packet_queue_abort(&is->subtitleq);
2613 /* note: we also signal this mutex to make sure we deblock the
2614 video thread in all cases */
2615 SDL_LockMutex(is->subpq_mutex);
2616 is->subtitle_stream_changed = 1;
2618 SDL_CondSignal(is->subpq_cond);
2619 SDL_UnlockMutex(is->subpq_mutex);
2621 SDL_WaitThread(is->subtitle_tid, NULL);
2623 packet_queue_flush(&is->subtitleq);
2629 ic->streams[stream_index]->discard = AVDISCARD_ALL;
2630 avcodec_close(avctx);
2631 switch (avctx->codec_type) {
2632 case AVMEDIA_TYPE_AUDIO:
2633 is->audio_st = NULL;
2634 is->audio_stream = -1;
2636 case AVMEDIA_TYPE_VIDEO:
2637 is->video_st = NULL;
2638 is->video_stream = -1;
2640 case AVMEDIA_TYPE_SUBTITLE:
2641 is->subtitle_st = NULL;
2642 is->subtitle_stream = -1;
2649 static int decode_interrupt_cb(void *ctx)
2651 VideoState *is = ctx;
2652 return is->abort_request;
2655 static int is_realtime(AVFormatContext *s)
2657 if( !strcmp(s->iformat->name, "rtp")
2658 || !strcmp(s->iformat->name, "rtsp")
2659 || !strcmp(s->iformat->name, "sdp")
2663 if(s->pb && ( !strncmp(s->filename, "rtp:", 4)
2664 || !strncmp(s->filename, "udp:", 4)
2671 /* this thread gets the stream from the disk or the network */
2672 static int read_thread(void *arg)
2674 VideoState *is = arg;
2675 AVFormatContext *ic = NULL;
2677 int st_index[AVMEDIA_TYPE_NB];
2678 AVPacket pkt1, *pkt = &pkt1;
2680 int pkt_in_play_range = 0;
2681 AVDictionaryEntry *t;
2682 AVDictionary **opts;
2683 int orig_nb_streams;
2684 SDL_mutex *wait_mutex = SDL_CreateMutex();
2686 memset(st_index, -1, sizeof(st_index));
2687 is->last_video_stream = is->video_stream = -1;
2688 is->last_audio_stream = is->audio_stream = -1;
2689 is->last_subtitle_stream = is->subtitle_stream = -1;
2691 ic = avformat_alloc_context();
2692 ic->interrupt_callback.callback = decode_interrupt_cb;
2693 ic->interrupt_callback.opaque = is;
2694 err = avformat_open_input(&ic, is->filename, is->iformat, &format_opts);
2696 print_error(is->filename, err);
2700 if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2701 av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
2702 ret = AVERROR_OPTION_NOT_FOUND;
2708 ic->flags |= AVFMT_FLAG_GENPTS;
2710 opts = setup_find_stream_info_opts(ic, codec_opts);
2711 orig_nb_streams = ic->nb_streams;
2713 err = avformat_find_stream_info(ic, opts);
2715 fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
2719 for (i = 0; i < orig_nb_streams; i++)
2720 av_dict_free(&opts[i]);
2724 ic->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
2726 if (seek_by_bytes < 0)
2727 seek_by_bytes = !!(ic->iformat->flags & AVFMT_TS_DISCONT);
2729 is->max_frame_duration = (ic->iformat->flags & AVFMT_TS_DISCONT) ? 10.0 : 3600.0;
2731 /* if seeking requested, we execute it */
2732 if (start_time != AV_NOPTS_VALUE) {
2735 timestamp = start_time;
2736 /* add the stream start time */
2737 if (ic->start_time != AV_NOPTS_VALUE)
2738 timestamp += ic->start_time;
2739 ret = avformat_seek_file(ic, -1, INT64_MIN, timestamp, INT64_MAX, 0);
2741 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2742 is->filename, (double)timestamp / AV_TIME_BASE);
2746 is->realtime = is_realtime(ic);
2748 for (i = 0; i < ic->nb_streams; i++)
2749 ic->streams[i]->discard = AVDISCARD_ALL;
2751 st_index[AVMEDIA_TYPE_VIDEO] =
2752 av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO,
2753 wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
2755 st_index[AVMEDIA_TYPE_AUDIO] =
2756 av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO,
2757 wanted_stream[AVMEDIA_TYPE_AUDIO],
2758 st_index[AVMEDIA_TYPE_VIDEO],
2760 if (!video_disable && !subtitle_disable)
2761 st_index[AVMEDIA_TYPE_SUBTITLE] =
2762 av_find_best_stream(ic, AVMEDIA_TYPE_SUBTITLE,
2763 wanted_stream[AVMEDIA_TYPE_SUBTITLE],
2764 (st_index[AVMEDIA_TYPE_AUDIO] >= 0 ?
2765 st_index[AVMEDIA_TYPE_AUDIO] :
2766 st_index[AVMEDIA_TYPE_VIDEO]),
2769 av_dump_format(ic, 0, is->filename, 0);
2772 is->show_mode = show_mode;
2774 /* open the streams */
2775 if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
2776 stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);
2780 if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
2781 ret = stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);
2783 if (is->show_mode == SHOW_MODE_NONE)
2784 is->show_mode = ret >= 0 ? SHOW_MODE_VIDEO : SHOW_MODE_RDFT;
2786 if (st_index[AVMEDIA_TYPE_SUBTITLE] >= 0) {
2787 stream_component_open(is, st_index[AVMEDIA_TYPE_SUBTITLE]);
2790 if (is->video_stream < 0 && is->audio_stream < 0) {
2791 fprintf(stderr, "%s: could not open codecs\n", is->filename);
2796 if (infinite_buffer < 0 && is->realtime)
2797 infinite_buffer = 1;
2800 if (is->abort_request)
2802 if (is->paused != is->last_paused) {
2803 is->last_paused = is->paused;
2805 is->read_pause_return = av_read_pause(ic);
2809 #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
2811 (!strcmp(ic->iformat->name, "rtsp") ||
2812 (ic->pb && !strncmp(input_filename, "mmsh:", 5)))) {
2813 /* wait 10 ms to avoid trying to get another packet */
2820 int64_t seek_target = is->seek_pos;
2821 int64_t seek_min = is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;
2822 int64_t seek_max = is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;
2823 // FIXME the +-2 is due to rounding being not done in the correct direction in generation
2824 // of the seek_pos/seek_rel variables
2826 ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);
2828 fprintf(stderr, "%s: error while seeking\n", is->ic->filename);
2830 if (is->audio_stream >= 0) {
2831 packet_queue_flush(&is->audioq);
2832 packet_queue_put(&is->audioq, &flush_pkt);
2834 if (is->subtitle_stream >= 0) {
2835 packet_queue_flush(&is->subtitleq);
2836 packet_queue_put(&is->subtitleq, &flush_pkt);
2838 if (is->video_stream >= 0) {
2839 packet_queue_flush(&is->videoq);
2840 packet_queue_put(&is->videoq, &flush_pkt);
2842 if (is->seek_flags & AVSEEK_FLAG_BYTE) {
2843 update_external_clock_pts(is, NAN);
2845 update_external_clock_pts(is, seek_target / (double)AV_TIME_BASE);
2851 step_to_next_frame(is);
2853 if (is->queue_attachments_req) {
2854 avformat_queue_attached_pictures(ic);
2855 is->queue_attachments_req = 0;
2858 /* if the queue are full, no need to read more */
2859 if (infinite_buffer<1 &&
2860 (is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE
2861 || ( (is->audioq .nb_packets > MIN_FRAMES || is->audio_stream < 0 || is->audioq.abort_request)
2862 && (is->videoq .nb_packets > MIN_FRAMES || is->video_stream < 0 || is->videoq.abort_request)
2863 && (is->subtitleq.nb_packets > MIN_FRAMES || is->subtitle_stream < 0 || is->subtitleq.abort_request)))) {
2865 SDL_LockMutex(wait_mutex);
2866 SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
2867 SDL_UnlockMutex(wait_mutex);
2871 if (is->video_stream >= 0) {
2872 av_init_packet(pkt);
2875 pkt->stream_index = is->video_stream;
2876 packet_queue_put(&is->videoq, pkt);
2878 if (is->audio_stream >= 0 &&
2879 is->audio_st->codec->codec->capabilities & CODEC_CAP_DELAY) {
2880 av_init_packet(pkt);
2883 pkt->stream_index = is->audio_stream;
2884 packet_queue_put(&is->audioq, pkt);
2887 if (is->audioq.size + is->videoq.size + is->subtitleq.size == 0) {
2888 if (loop != 1 && (!loop || --loop)) {
2889 stream_seek(is, start_time != AV_NOPTS_VALUE ? start_time : 0, 0, 0);
2890 } else if (autoexit) {
2898 ret = av_read_frame(ic, pkt);
2900 if (ret == AVERROR_EOF || url_feof(ic->pb))
2902 if (ic->pb && ic->pb->error)
2904 SDL_LockMutex(wait_mutex);
2905 SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
2906 SDL_UnlockMutex(wait_mutex);
2909 /* check if packet is in play range specified by user, then queue, otherwise discard */
2910 pkt_in_play_range = duration == AV_NOPTS_VALUE ||
2911 (pkt->pts - ic->streams[pkt->stream_index]->start_time) *
2912 av_q2d(ic->streams[pkt->stream_index]->time_base) -
2913 (double)(start_time != AV_NOPTS_VALUE ? start_time : 0) / 1000000
2914 <= ((double)duration / 1000000);
2915 if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {
2916 packet_queue_put(&is->audioq, pkt);
2917 } else if (pkt->stream_index == is->video_stream && pkt_in_play_range) {
2918 packet_queue_put(&is->videoq, pkt);
2919 } else if (pkt->stream_index == is->subtitle_stream && pkt_in_play_range) {
2920 packet_queue_put(&is->subtitleq, pkt);
2922 av_free_packet(pkt);
2925 /* wait until the end */
2926 while (!is->abort_request) {
2932 /* close each stream */
2933 if (is->audio_stream >= 0)
2934 stream_component_close(is, is->audio_stream);
2935 if (is->video_stream >= 0)
2936 stream_component_close(is, is->video_stream);
2937 if (is->subtitle_stream >= 0)
2938 stream_component_close(is, is->subtitle_stream);
2940 avformat_close_input(&is->ic);
2946 event.type = FF_QUIT_EVENT;
2947 event.user.data1 = is;
2948 SDL_PushEvent(&event);
2950 SDL_DestroyMutex(wait_mutex);
2954 static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
2958 is = av_mallocz(sizeof(VideoState));
2961 av_strlcpy(is->filename, filename, sizeof(is->filename));
2962 is->iformat = iformat;
2966 /* start video display */
2967 is->pictq_mutex = SDL_CreateMutex();
2968 is->pictq_cond = SDL_CreateCond();
2970 is->subpq_mutex = SDL_CreateMutex();
2971 is->subpq_cond = SDL_CreateCond();
2973 packet_queue_init(&is->videoq);
2974 packet_queue_init(&is->audioq);
2975 packet_queue_init(&is->subtitleq);
2977 is->continue_read_thread = SDL_CreateCond();
2979 update_external_clock_pts(is, NAN);
2980 update_external_clock_speed(is, 1.0);
2981 is->audio_current_pts_drift = -av_gettime() / 1000000.0;
2982 is->video_current_pts_drift = is->audio_current_pts_drift;
2983 is->audio_clock_serial = -1;
2984 is->video_clock_serial = -1;
2985 is->audio_last_serial = -1;
2986 is->av_sync_type = av_sync_type;
2987 is->read_tid = SDL_CreateThread(read_thread, is);
2988 if (!is->read_tid) {
2995 static void stream_cycle_channel(VideoState *is, int codec_type)
2997 AVFormatContext *ic = is->ic;
2998 int start_index, stream_index;
3002 if (codec_type == AVMEDIA_TYPE_VIDEO) {
3003 start_index = is->last_video_stream;
3004 old_index = is->video_stream;
3005 } else if (codec_type == AVMEDIA_TYPE_AUDIO) {
3006 start_index = is->last_audio_stream;
3007 old_index = is->audio_stream;
3009 start_index = is->last_subtitle_stream;
3010 old_index = is->subtitle_stream;
3012 stream_index = start_index;
3014 if (++stream_index >= is->ic->nb_streams)
3016 if (codec_type == AVMEDIA_TYPE_SUBTITLE)
3019 is->last_subtitle_stream = -1;
3022 if (start_index == -1)
3026 if (stream_index == start_index)
3028 st = ic->streams[stream_index];
3029 if (st->codec->codec_type == codec_type) {
3030 /* check that parameters are OK */
3031 switch (codec_type) {
3032 case AVMEDIA_TYPE_AUDIO:
3033 if (st->codec->sample_rate != 0 &&
3034 st->codec->channels != 0)
3037 case AVMEDIA_TYPE_VIDEO:
3038 case AVMEDIA_TYPE_SUBTITLE:
3046 stream_component_close(is, old_index);
3047 stream_component_open(is, stream_index);
3048 if (codec_type == AVMEDIA_TYPE_VIDEO)
3049 is->queue_attachments_req = 1;
3053 static void toggle_full_screen(VideoState *is)
3055 #if defined(__APPLE__) && SDL_VERSION_ATLEAST(1, 2, 14)
3056 /* OS X needs to reallocate the SDL overlays */
3058 for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++)
3059 is->pictq[i].reallocate = 1;
3061 is_full_screen = !is_full_screen;
3062 video_open(is, 1, NULL);
3065 static void toggle_audio_display(VideoState *is)
3067 int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
3068 int next = is->show_mode;
3070 next = (next + 1) % SHOW_MODE_NB;
3071 } while (next != is->show_mode && (next == SHOW_MODE_VIDEO && !is->video_st || next != SHOW_MODE_VIDEO && !is->audio_st));
3072 if (is->show_mode != next) {
3073 fill_rectangle(screen,
3074 is->xleft, is->ytop, is->width, is->height,
3076 is->force_refresh = 1;
3077 is->show_mode = next;
3081 static void refresh_loop_wait_event(VideoState *is, SDL_Event *event) {
3082 double remaining_time = 0.0;
3084 while (!SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_ALLEVENTS)) {
3085 if (!cursor_hidden && av_gettime() - cursor_last_shown > CURSOR_HIDE_DELAY) {
3089 if (remaining_time > 0.0)
3090 av_usleep((int64_t)(remaining_time * 1000000.0));
3091 remaining_time = REFRESH_RATE;
3092 if (is->show_mode != SHOW_MODE_NONE && (!is->paused || is->force_refresh))
3093 video_refresh(is, &remaining_time);
3098 /* handle an event sent by the GUI */
3099 static void event_loop(VideoState *cur_stream)
3102 double incr, pos, frac;
3106 refresh_loop_wait_event(cur_stream, &event);
3107 switch (event.type) {
3109 if (exit_on_keydown) {
3110 do_exit(cur_stream);
3113 switch (event.key.keysym.sym) {
3116 do_exit(cur_stream);
3119 toggle_full_screen(cur_stream);
3120 cur_stream->force_refresh = 1;
3124 toggle_pause(cur_stream);
3126 case SDLK_s: // S: Step to next frame
3127 step_to_next_frame(cur_stream);
3130 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
3133 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
3136 stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
3139 toggle_audio_display(cur_stream);
3159 if (seek_by_bytes) {
3160 if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos >= 0) {
3161 pos = cur_stream->video_current_pos;
3162 } else if (cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos >= 0) {
3163 pos = cur_stream->audio_pkt.pos;
3165 pos = avio_tell(cur_stream->ic->pb);
3166 if (cur_stream->ic->bit_rate)
3167 incr *= cur_stream->ic->bit_rate / 8.0;
3171 stream_seek(cur_stream, pos, incr, 1);
3173 pos = get_master_clock(cur_stream);
3175 pos = (double)cur_stream->seek_pos / AV_TIME_BASE;
3177 if (cur_stream->ic->start_time != AV_NOPTS_VALUE && pos < cur_stream->ic->start_time / (double)AV_TIME_BASE)
3178 pos = cur_stream->ic->start_time / (double)AV_TIME_BASE;
3179 stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);
3186 case SDL_VIDEOEXPOSE:
3187 cur_stream->force_refresh = 1;
3189 case SDL_MOUSEBUTTONDOWN:
3190 if (exit_on_mousedown) {
3191 do_exit(cur_stream);
3194 case SDL_MOUSEMOTION:
3195 if (cursor_hidden) {
3199 cursor_last_shown = av_gettime();
3200 if (event.type == SDL_MOUSEBUTTONDOWN) {
3203 if (event.motion.state != SDL_PRESSED)
3207 if (seek_by_bytes || cur_stream->ic->duration <= 0) {
3208 uint64_t size = avio_size(cur_stream->ic->pb);
3209 stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);
3213 int tns, thh, tmm, tss;
3214 tns = cur_stream->ic->duration / 1000000LL;
3216 tmm = (tns % 3600) / 60;
3218 frac = x / cur_stream->width;
3221 mm = (ns % 3600) / 60;
3223 fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n", frac*100,
3224 hh, mm, ss, thh, tmm, tss);
3225 ts = frac * cur_stream->ic->duration;
3226 if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
3227 ts += cur_stream->ic->start_time;
3228 stream_seek(cur_stream, ts, 0, 0);
3231 case SDL_VIDEORESIZE:
3232 screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
3233 SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
3234 screen_width = cur_stream->width = event.resize.w;
3235 screen_height = cur_stream->height = event.resize.h;
3236 cur_stream->force_refresh = 1;
3240 do_exit(cur_stream);
3242 case FF_ALLOC_EVENT:
3243 alloc_picture(event.user.data1);
3251 static int opt_frame_size(void *optctx, const char *opt, const char *arg)
3253 av_log(NULL, AV_LOG_WARNING, "Option -s is deprecated, use -video_size.\n");
3254 return opt_default(NULL, "video_size", arg);
3257 static int opt_width(void *optctx, const char *opt, const char *arg)
3259 screen_width = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
3263 static int opt_height(void *optctx, const char *opt, const char *arg)
3265 screen_height = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
3269 static int opt_format(void *optctx, const char *opt, const char *arg)
3271 file_iformat = av_find_input_format(arg);
3272 if (!file_iformat) {
3273 fprintf(stderr, "Unknown input format: %s\n", arg);
3274 return AVERROR(EINVAL);
3279 static int opt_frame_pix_fmt(void *optctx, const char *opt, const char *arg)
3281 av_log(NULL, AV_LOG_WARNING, "Option -pix_fmt is deprecated, use -pixel_format.\n");
3282 return opt_default(NULL, "pixel_format", arg);
3285 static int opt_sync(void *optctx, const char *opt, const char *arg)
3287 if (!strcmp(arg, "audio"))
3288 av_sync_type = AV_SYNC_AUDIO_MASTER;
3289 else if (!strcmp(arg, "video"))
3290 av_sync_type = AV_SYNC_VIDEO_MASTER;
3291 else if (!strcmp(arg, "ext"))
3292 av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
3294 fprintf(stderr, "Unknown value for %s: %s\n", opt, arg);
3300 static int opt_seek(void *optctx, const char *opt, const char *arg)
3302 start_time = parse_time_or_die(opt, arg, 1);
3306 static int opt_duration(void *optctx, const char *opt, const char *arg)
3308 duration = parse_time_or_die(opt, arg, 1);
3312 static int opt_show_mode(void *optctx, const char *opt, const char *arg)
3314 show_mode = !strcmp(arg, "video") ? SHOW_MODE_VIDEO :
3315 !strcmp(arg, "waves") ? SHOW_MODE_WAVES :
3316 !strcmp(arg, "rdft" ) ? SHOW_MODE_RDFT :
3317 parse_number_or_die(opt, arg, OPT_INT, 0, SHOW_MODE_NB-1);
3321 static void opt_input_file(void *optctx, const char *filename)
3323 if (input_filename) {
3324 fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
3325 filename, input_filename);
3328 if (!strcmp(filename, "-"))
3330 input_filename = filename;
3333 static int opt_codec(void *optctx, const char *opt, const char *arg)
3335 const char *spec = strchr(opt, ':');
3337 fprintf(stderr, "No media specifier was specified in '%s' in option '%s'\n",
3339 return AVERROR(EINVAL);
3343 case 'a' : audio_codec_name = arg; break;
3344 case 's' : subtitle_codec_name = arg; break;
3345 case 'v' : video_codec_name = arg; break;
3347 fprintf(stderr, "Invalid media specifier '%s' in option '%s'\n", spec, opt);
3348 return AVERROR(EINVAL);
3355 static const OptionDef options[] = {
3356 #include "cmdutils_common_opts.h"
3357 { "x", HAS_ARG, { .func_arg = opt_width }, "force displayed width", "width" },
3358 { "y", HAS_ARG, { .func_arg = opt_height }, "force displayed height", "height" },
3359 { "s", HAS_ARG | OPT_VIDEO, { .func_arg = opt_frame_size }, "set frame size (WxH or abbreviation)", "size" },
3360 { "fs", OPT_BOOL, { &is_full_screen }, "force full screen" },
3361 { "an", OPT_BOOL, { &audio_disable }, "disable audio" },
3362 { "vn", OPT_BOOL, { &video_disable }, "disable video" },
3363 { "sn", OPT_BOOL, { &subtitle_disable }, "disable subtitling" },
3364 { "ast", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_AUDIO] }, "select desired audio stream", "stream_number" },
3365 { "vst", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_VIDEO] }, "select desired video stream", "stream_number" },
3366 { "sst", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_SUBTITLE] }, "select desired subtitle stream", "stream_number" },
3367 { "ss", HAS_ARG, { .func_arg = opt_seek }, "seek to a given position in seconds", "pos" },
3368 { "t", HAS_ARG, { .func_arg = opt_duration }, "play \"duration\" seconds of audio/video", "duration" },
3369 { "bytes", OPT_INT | HAS_ARG, { &seek_by_bytes }, "seek by bytes 0=off 1=on -1=auto", "val" },
3370 { "nodisp", OPT_BOOL, { &display_disable }, "disable graphical display" },
3371 { "f", HAS_ARG, { .func_arg = opt_format }, "force format", "fmt" },
3372 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_frame_pix_fmt }, "set pixel format", "format" },
3373 { "stats", OPT_BOOL | OPT_EXPERT, { &show_status }, "show status", "" },
3374 { "bug", OPT_INT | HAS_ARG | OPT_EXPERT, { &workaround_bugs }, "workaround bugs", "" },
3375 { "fast", OPT_BOOL | OPT_EXPERT, { &fast }, "non spec compliant optimizations", "" },
3376 { "genpts", OPT_BOOL | OPT_EXPERT, { &genpts }, "generate pts", "" },
3377 { "drp", OPT_INT | HAS_ARG | OPT_EXPERT, { &decoder_reorder_pts }, "let decoder reorder pts 0=off 1=on -1=auto", ""},
3378 { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, { &lowres }, "", "" },
3379 { "idct", OPT_INT | HAS_ARG | OPT_EXPERT, { &idct }, "set idct algo", "algo" },
3380 { "ec", OPT_INT | HAS_ARG | OPT_EXPERT, { &error_concealment }, "set error concealment options", "bit_mask" },
3381 { "sync", HAS_ARG | OPT_EXPERT, { .func_arg = opt_sync }, "set audio-video sync. type (type=audio/video/ext)", "type" },
3382 { "autoexit", OPT_BOOL | OPT_EXPERT, { &autoexit }, "exit at the end", "" },
3383 { "exitonkeydown", OPT_BOOL | OPT_EXPERT, { &exit_on_keydown }, "exit on key down", "" },
3384 { "exitonmousedown", OPT_BOOL | OPT_EXPERT, { &exit_on_mousedown }, "exit on mouse down", "" },
3385 { "loop", OPT_INT | HAS_ARG | OPT_EXPERT, { &loop }, "set number of times the playback shall be looped", "loop count" },
3386 { "framedrop", OPT_BOOL | OPT_EXPERT, { &framedrop }, "drop frames when cpu is too slow", "" },
3387 { "infbuf", OPT_BOOL | OPT_EXPERT, { &infinite_buffer }, "don't limit the input buffer size (useful with realtime streams)", "" },
3388 { "window_title", OPT_STRING | HAS_ARG, { &window_title }, "set window title", "window title" },
3390 { "vf", OPT_STRING | HAS_ARG, { &vfilters }, "set video filters", "filter_graph" },
3391 { "af", OPT_STRING | HAS_ARG, { &afilters }, "set audio filters", "filter_graph" },
3393 { "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, { &rdftspeed }, "rdft speed", "msecs" },
3394 { "showmode", HAS_ARG, { .func_arg = opt_show_mode}, "select show mode (0 = video, 1 = waves, 2 = RDFT)", "mode" },
3395 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, { .func_arg = opt_default }, "generic catch all option", "" },
3396 { "i", OPT_BOOL, { &dummy}, "read specified file", "input_file"},
3397 { "codec", HAS_ARG, { .func_arg = opt_codec}, "force decoder", "decoder_name" },
3398 { "acodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &audio_codec_name }, "force audio decoder", "decoder_name" },
3399 { "scodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &subtitle_codec_name }, "force subtitle decoder", "decoder_name" },
3400 { "vcodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &video_codec_name }, "force video decoder", "decoder_name" },
3404 static void show_usage(void)
3406 av_log(NULL, AV_LOG_INFO, "Simple media player\n");
3407 av_log(NULL, AV_LOG_INFO, "usage: %s [options] input_file\n", program_name);
3408 av_log(NULL, AV_LOG_INFO, "\n");
3411 void show_help_default(const char *opt, const char *arg)
3413 av_log_set_callback(log_callback_help);
3415 show_help_options(options, "Main options:", 0, OPT_EXPERT, 0);
3416 show_help_options(options, "Advanced options:", OPT_EXPERT, 0, 0);
3418 show_help_children(avcodec_get_class(), AV_OPT_FLAG_DECODING_PARAM);
3419 show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
3420 #if !CONFIG_AVFILTER
3421 show_help_children(sws_get_class(), AV_OPT_FLAG_ENCODING_PARAM);
3423 show_help_children(avfilter_get_class(), AV_OPT_FLAG_FILTERING_PARAM);
3425 printf("\nWhile playing:\n"
3427 "f toggle full screen\n"
3429 "a cycle audio channel\n"
3430 "v cycle video channel\n"
3431 "t cycle subtitle channel\n"
3432 "w show audio waves\n"
3433 "s activate frame-step mode\n"
3434 "left/right seek backward/forward 10 seconds\n"
3435 "down/up seek backward/forward 1 minute\n"
3436 "page down/page up seek backward/forward 10 minutes\n"
3437 "mouse click seek to percentage in file corresponding to fraction of width\n"
3441 static int lockmgr(void **mtx, enum AVLockOp op)
3444 case AV_LOCK_CREATE:
3445 *mtx = SDL_CreateMutex();
3449 case AV_LOCK_OBTAIN:
3450 return !!SDL_LockMutex(*mtx);
3451 case AV_LOCK_RELEASE:
3452 return !!SDL_UnlockMutex(*mtx);
3453 case AV_LOCK_DESTROY:
3454 SDL_DestroyMutex(*mtx);
3460 /* Called from the main */
3461 int main(int argc, char **argv)
3465 char dummy_videodriver[] = "SDL_VIDEODRIVER=dummy";
3467 av_log_set_flags(AV_LOG_SKIP_REPEATED);
3468 parse_loglevel(argc, argv, options);
3470 /* register all codecs, demux and protocols */
3471 avcodec_register_all();
3473 avdevice_register_all();
3476 avfilter_register_all();
3479 avformat_network_init();
3483 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
3484 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
3486 show_banner(argc, argv, options);
3488 parse_options(NULL, argc, argv, options, opt_input_file);
3490 if (!input_filename) {
3492 fprintf(stderr, "An input file must be specified\n");
3493 fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
3497 if (display_disable) {
3500 flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
3502 flags &= ~SDL_INIT_AUDIO;
3503 if (display_disable)
3504 SDL_putenv(dummy_videodriver); /* For the event queue, we always need a video driver. */
3505 #if !defined(__MINGW32__) && !defined(__APPLE__)
3506 flags |= SDL_INIT_EVENTTHREAD; /* Not supported on Windows or Mac OS X */
3508 if (SDL_Init (flags)) {
3509 fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
3510 fprintf(stderr, "(Did you set the DISPLAY variable?)\n");
3514 if (!display_disable) {
3515 const SDL_VideoInfo *vi = SDL_GetVideoInfo();
3516 fs_screen_width = vi->current_w;
3517 fs_screen_height = vi->current_h;
3520 SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
3521 SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
3522 SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
3524 if (av_lockmgr_register(lockmgr)) {
3525 fprintf(stderr, "Could not initialize lock manager!\n");
3529 av_init_packet(&flush_pkt);
3530 flush_pkt.data = (char *)(intptr_t)"FLUSH";
3532 is = stream_open(input_filename, file_iformat);
3534 fprintf(stderr, "Failed to initialize VideoState!\n");