vo_gl: fix 10 bit with Mesa drivers (Intel/Nouveau on Linux)
[mplayer.git] / mplayer.c
blobdec68c83fd4db178bc4395309cf187db235848cf
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stdbool.h>
22 #include <math.h>
23 #include <assert.h>
25 #include "config.h"
26 #include "talloc.h"
28 #if defined(__MINGW32__) || defined(__CYGWIN__)
29 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
30 #include <windows.h>
31 #endif
32 #include <string.h>
33 #include <unistd.h>
35 // #include <sys/mman.h>
36 #include <sys/types.h>
37 #ifndef __MINGW32__
38 #include <sys/ioctl.h>
39 #include <sys/wait.h>
40 #else
41 #define SIGHUP 1 /* hangup */
42 #define SIGQUIT 3 /* quit */
43 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
44 #define SIGBUS 10 /* bus error */
45 #define SIGPIPE 13 /* broken pipe */
46 #endif
48 #include <sys/time.h>
49 #include <sys/stat.h>
51 #include <signal.h>
52 #include <time.h>
53 #include <fcntl.h>
54 #include <limits.h>
56 #include <errno.h>
58 #include "mp_msg.h"
59 #include "av_log.h"
62 #include "m_option.h"
63 #include "m_config.h"
64 #include "mplayer.h"
65 #include "access_mpcontext.h"
66 #include "m_property.h"
68 #include "libavutil/avstring.h"
70 #include "sub/subreader.h"
71 #include "sub/find_subfiles.h"
72 #include "sub/dec_sub.h"
74 #include "mp_osd.h"
75 #include "libvo/video_out.h"
76 #include "screenshot.h"
78 #include "sub/font_load.h"
79 #include "sub/sub.h"
80 #include "ffmpeg_files/intreadwrite.h"
81 #include "sub/av_sub.h"
82 #include "libmpcodecs/dec_teletext.h"
83 #include "cpudetect.h"
84 #include "version.h"
86 #ifdef CONFIG_X11
87 #include "libvo/x11_common.h"
88 #endif
90 #include "libao2/audio_out.h"
92 #include "codec-cfg.h"
94 #include "edl.h"
96 #include "sub/spudec.h"
97 #include "sub/vobsub.h"
99 #include "osdep/getch2.h"
100 #include "osdep/timer.h"
102 #include "input/input.h"
104 int slave_mode = 0;
105 int enable_mouse_movements = 0;
106 float start_volume = -1;
108 #include "osdep/priority.h"
110 char *heartbeat_cmd;
112 #ifdef HAVE_RTC
113 #ifdef __linux__
114 #include <linux/rtc.h>
115 #else
116 #include <rtc.h>
117 #define RTC_IRQP_SET RTCIO_IRQP_SET
118 #define RTC_PIE_ON RTCIO_PIE_ON
119 #endif /* __linux__ */
120 #endif /* HAVE_RTC */
122 #include "stream/tv.h"
123 #include "stream/stream_radio.h"
124 #ifdef CONFIG_DVBIN
125 #include "stream/dvbin.h"
126 #endif
127 #include "stream/cache2.h"
129 //**************************************************************************//
130 // Playtree
131 //**************************************************************************//
132 #include "playtree.h"
133 #include "playtreeparser.h"
135 //**************************************************************************//
136 // Config
137 //**************************************************************************//
138 #include "parser-cfg.h"
139 #include "parser-mpcmd.h"
141 //**************************************************************************//
142 // Config file
143 //**************************************************************************//
145 static int cfg_inc_verbose(m_option_t *conf)
147 ++verbose;
148 return 0;
151 #include "path.h"
153 //**************************************************************************//
154 //**************************************************************************//
155 // Input media streaming & demultiplexer:
156 //**************************************************************************//
158 static int max_framesize = 0;
160 #include "stream/stream.h"
161 #include "libmpdemux/demuxer.h"
162 #include "libmpdemux/stheader.h"
164 #ifdef CONFIG_DVDREAD
165 #include "stream/stream_dvd.h"
166 #endif
167 #include "stream/stream_dvdnav.h"
169 #include "libmpcodecs/dec_audio.h"
170 #include "libmpcodecs/dec_video.h"
171 #include "libmpcodecs/mp_image.h"
172 #include "libmpcodecs/vf.h"
173 #include "libmpcodecs/vd.h"
175 #include "mixer.h"
177 #include "mp_core.h"
178 #include "options.h"
179 #include "defaultopts.h"
181 static const char help_text[] = _(
182 "Usage: mplayer [options] [url|path/]filename\n"
183 "\n"
184 "Basic options: (complete list in the man page)\n"
185 " -vo <drv> select video output driver ('-vo help' for a list)\n"
186 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
187 #ifdef CONFIG_VCD
188 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
189 #endif
190 #ifdef CONFIG_DVDREAD
191 " dvd://<titleno> play DVD title from device instead of plain file\n"
192 #endif
193 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
194 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
195 " -nosound do not play sound\n"
196 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
197 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
198 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
199 " -playlist <file> specify playlist file\n"
200 " -vid x -aid y select video (x) and audio (y) stream to play\n"
201 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
202 " -pp <quality> enable postprocessing filter (details in the man page)\n"
203 " -framedrop enable frame dropping (for slow machines)\n"
204 "\n"
205 "Basic keys: (complete list in the man page, also check input.conf)\n"
206 " <- or -> seek backward/forward 10 seconds\n"
207 " down or up seek backward/forward 1 minute\n"
208 " pgdown or pgup seek backward/forward 10 minutes\n"
209 " < or > step backward/forward in playlist\n"
210 " p or SPACE pause movie (press any key to continue)\n"
211 " q or ESC stop playing and quit program\n"
212 " + or - adjust audio delay by +/- 0.1 second\n"
213 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
214 " * or / increase or decrease PCM volume\n"
215 " x or z adjust subtitle delay by +/- 0.1 second\n"
216 " r or t adjust subtitle position up/down, also see -vf expand\n"
217 " double click toggle fullscreen\n"
218 " right click pause (press again to continue)\n"
219 "\n"
220 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
221 "\n");
224 #define Exit_SIGILL_RTCpuSel _(\
225 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
226 " It may be a bug in our new runtime CPU-detection code...\n"\
227 " Please read DOCS/HTML/en/bugreports.html.\n")
229 #define Exit_SIGILL _(\
230 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
231 " It usually happens when you run it on a CPU different than the one it was\n"\
232 " compiled/optimized for.\n"\
233 " Verify this!\n")
235 #define Exit_SIGSEGV_SIGFPE _(\
236 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
237 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
238 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
240 #define Exit_SIGCRASH _(\
241 "- MPlayer crashed. This shouldn't happen.\n"\
242 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
243 " gcc version. If you think it's MPlayer's fault, please read\n"\
244 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
245 " won't help unless you provide this information when reporting a possible bug.\n")
247 #define SystemTooSlow _("\n\n"\
248 " ************************************************\n"\
249 " **** Your system is too SLOW to play this! ****\n"\
250 " ************************************************\n\n"\
251 "Possible reasons, problems, workarounds:\n"\
252 "- Most common: broken/buggy _audio_ driver\n"\
253 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
254 " - Experiment with different values for -autosync, 30 is a good start.\n"\
255 "- Slow video output\n"\
256 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
257 "- Slow CPU\n"\
258 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
259 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
260 "- Broken file\n"\
261 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
262 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
263 " - Try -cache 8192.\n"\
264 "- Are you using -cache to play a non-interleaved AVI file?\n"\
265 " - Try -nocache.\n"\
266 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
267 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
270 //**************************************************************************//
271 //**************************************************************************//
273 #include "mp_fifo.h"
275 // benchmark:
276 double video_time_usage;
277 double vout_time_usage;
278 static double audio_time_usage;
279 static int total_time_usage_start;
280 static int total_frame_cnt;
281 static int drop_frame_cnt; // total number of dropped frames
283 // options:
284 static int output_quality;
286 // seek:
287 static off_t seek_to_byte;
288 static off_t step_sec;
290 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
292 // codecs:
293 char **audio_codec_list; // override audio codec
294 char **video_codec_list; // override video codec
295 char **audio_fm_list; // override audio codec family
296 char **video_fm_list; // override video codec family
298 // this dvdsub_id was selected via slang
299 // use this to allow dvdnav to follow -slang across stream resets,
300 // in particular the subtitle ID for a language changes
301 int dvdsub_lang_id;
302 int vobsub_id = -1;
303 static char *spudec_ifo = NULL;
304 int forced_subs_only = 0;
306 // cache2:
307 int stream_cache_size = -1;
309 // dump:
310 int stream_dump_type = 0;
312 // A-V sync:
313 static float default_max_pts_correction = -1;
314 float audio_delay = 0;
315 static int ignore_start = 0;
317 double force_fps = 0;
318 static int force_srate = 0;
319 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
320 static int play_n_frames = -1;
321 static int play_n_frames_mf = -1;
323 // sub:
324 char *font_name = NULL;
325 char *sub_font_name = NULL;
326 extern int font_fontconfig;
327 float font_factor = 0.75;
328 float sub_delay = 0;
329 float sub_fps = 0;
330 int subcc_enabled = 0;
331 int suboverlap_enabled = 1;
333 #include "sub/ass_mp.h"
335 char *current_module; // for debugging
338 // ---
340 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
341 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
342 FILE *edl_fd; // file to write to when in -edlout mode.
343 int use_filedir_conf;
344 int use_filename_title;
346 #include "mpcommon.h"
347 #include "command.h"
349 #include "metadata.h"
351 void *mpctx_get_video_out(MPContext *mpctx)
353 return mpctx->video_out;
356 void *mpctx_get_demuxer(MPContext *mpctx)
358 return mpctx->demuxer;
361 void *mpctx_get_playtree_iter(MPContext *mpctx)
363 return mpctx->playtree_iter;
366 void *mpctx_get_mixer(MPContext *mpctx)
368 return &mpctx->mixer;
371 int mpctx_get_global_sub_size(MPContext *mpctx)
373 return mpctx->global_sub_size;
376 int mpctx_get_osd_function(MPContext *mpctx)
378 return mpctx->osd_function;
381 static float get_relative_time(struct MPContext *mpctx)
383 unsigned int new_time = GetTimer();
384 unsigned int delta = new_time - mpctx->last_time;
385 mpctx->last_time = new_time;
386 return delta * 0.000001;
389 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
391 switch (type) {
392 /* check for valid video stream */
393 case META_VIDEO_CODEC:
394 case META_VIDEO_BITRATE:
395 case META_VIDEO_RESOLUTION:
396 if (!mpctx->sh_video)
397 return 0;
398 break;
400 /* check for valid audio stream */
401 case META_AUDIO_CODEC:
402 case META_AUDIO_BITRATE:
403 case META_AUDIO_SAMPLES:
404 if (!mpctx->sh_audio)
405 return 0;
406 break;
408 /* check for valid demuxer */
409 case META_INFO_TITLE:
410 case META_INFO_ARTIST:
411 case META_INFO_ALBUM:
412 case META_INFO_YEAR:
413 case META_INFO_COMMENT:
414 case META_INFO_TRACK:
415 case META_INFO_GENRE:
416 if (!mpctx->demuxer)
417 return 0;
418 break;
420 default:
421 break;
424 return 1;
427 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
429 char **info = mpctx->demuxer->info;
430 int n;
432 if (!info || !tag)
433 return talloc_strdup(NULL, "");
435 for (n = 0; info[2 * n] != NULL; n++)
436 if (!strcasecmp(info[2 * n], tag))
437 break;
439 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
442 char *get_metadata(struct MPContext *mpctx, metadata_t type)
444 sh_audio_t * const sh_audio = mpctx->sh_audio;
445 sh_video_t * const sh_video = mpctx->sh_video;
447 if (!is_valid_metadata_type(mpctx, type))
448 return NULL;
450 switch (type) {
451 case META_NAME:
452 return talloc_strdup(NULL, mp_basename(mpctx->filename));
453 case META_VIDEO_CODEC:
454 if (sh_video->format == 0x10000001)
455 return talloc_strdup(NULL, "mpeg1");
456 else if (sh_video->format == 0x10000002)
457 return talloc_strdup(NULL, "mpeg2");
458 else if (sh_video->format == 0x10000004)
459 return talloc_strdup(NULL, "mpeg4");
460 else if (sh_video->format == 0x10000005)
461 return talloc_strdup(NULL, "h264");
462 else if (sh_video->format >= 0x20202020)
463 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
464 else
465 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
466 case META_VIDEO_BITRATE:
467 return talloc_asprintf(NULL, "%d kbps",
468 (int) (sh_video->i_bps * 8 / 1024));
469 case META_VIDEO_RESOLUTION:
470 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
471 sh_video->disp_h);
472 case META_AUDIO_CODEC:
473 if (sh_audio->codec && sh_audio->codec->name)
474 return talloc_strdup(NULL, sh_audio->codec->name);
475 return talloc_strdup(NULL, "");
476 case META_AUDIO_BITRATE:
477 return talloc_asprintf(NULL, "%d kbps",
478 (int) (sh_audio->i_bps * 8 / 1000));
479 case META_AUDIO_SAMPLES:
480 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
481 sh_audio->channels);
483 /* check for valid demuxer */
484 case META_INFO_TITLE:
485 return get_demuxer_info(mpctx, "Title");
487 case META_INFO_ARTIST:
488 return get_demuxer_info(mpctx, "Artist");
490 case META_INFO_ALBUM:
491 return get_demuxer_info(mpctx, "Album");
493 case META_INFO_YEAR:
494 return get_demuxer_info(mpctx, "Year");
496 case META_INFO_COMMENT:
497 return get_demuxer_info(mpctx, "Comment");
499 case META_INFO_TRACK:
500 return get_demuxer_info(mpctx, "Track");
502 case META_INFO_GENRE:
503 return get_demuxer_info(mpctx, "Genre");
505 default:
506 break;
509 return talloc_strdup(NULL, "");
512 static void print_file_properties(struct MPContext *mpctx, const char *filename)
514 double start_pts = MP_NOPTS_VALUE;
515 double video_start_pts = MP_NOPTS_VALUE;
516 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
517 filename_recode(filename));
518 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
519 mpctx->demuxer->desc->name);
520 if (mpctx->sh_video) {
521 /* Assume FOURCC if all bytes >= 0x20 (' ') */
522 if (mpctx->sh_video->format >= 0x20202020)
523 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
524 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
525 else
526 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
527 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
528 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
529 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
530 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
531 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
532 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
533 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
534 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
535 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
536 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
537 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
538 video_start_pts = ds_get_next_pts(mpctx->d_video);
540 if (mpctx->sh_audio) {
541 /* Assume FOURCC if all bytes >= 0x20 (' ') */
542 if (mpctx->sh_audio->format >= 0x20202020)
543 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
544 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
545 else
546 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
547 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
548 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
549 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
550 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
551 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
552 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
553 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
554 start_pts = ds_get_next_pts(mpctx->d_audio);
556 if (video_start_pts != MP_NOPTS_VALUE) {
557 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
558 (mpctx->sh_video && video_start_pts < start_pts))
559 start_pts = video_start_pts;
561 if (start_pts != MP_NOPTS_VALUE)
562 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
563 else
564 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
565 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
566 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
567 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
568 mpctx->stream->seek
569 && (!mpctx->demuxer || mpctx->demuxer->seekable));
570 if (mpctx->demuxer) {
571 int chapter_count = get_chapter_count(mpctx);
572 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
573 for (int i = 0; i < chapter_count; i++) {
574 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
575 // in milliseconds
576 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
577 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
578 char *name = chapter_name(mpctx, i);
579 if (name) {
580 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
581 name);
582 talloc_free(name);
588 /// step size of mixer changes
589 int volstep = 3;
591 #ifdef CONFIG_DVDNAV
592 static void mp_dvdnav_context_free(MPContext *ctx)
594 if (ctx->nav_smpi)
595 free_mp_image(ctx->nav_smpi);
596 ctx->nav_smpi = NULL;
597 free(ctx->nav_buffer);
598 ctx->nav_buffer = NULL;
599 ctx->nav_start = NULL;
600 ctx->nav_in_size = 0;
602 #endif
604 static void uninit_subs(struct demuxer *demuxer)
606 for (int i = 0; i < MAX_S_STREAMS; i++) {
607 struct sh_sub *sh = demuxer->s_streams[i];
608 if (sh && sh->initialized)
609 sub_uninit(sh);
613 void uninit_player(struct MPContext *mpctx, unsigned int mask)
615 mask &= mpctx->initialized_flags;
617 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
619 if (mask & INITIALIZED_ACODEC) {
620 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
621 current_module = "uninit_acodec";
622 if (mpctx->sh_audio)
623 uninit_audio(mpctx->sh_audio);
624 mpctx->sh_audio = NULL;
625 mpctx->mixer.afilter = NULL;
628 if (mask & INITIALIZED_SUB) {
629 mpctx->initialized_flags &= ~INITIALIZED_SUB;
630 if (mpctx->d_sub->sh)
631 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
634 if (mask & INITIALIZED_VCODEC) {
635 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
636 current_module = "uninit_vcodec";
637 if (mpctx->sh_video)
638 uninit_video(mpctx->sh_video);
639 mpctx->sh_video = NULL;
642 if (mask & INITIALIZED_DEMUXER) {
643 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
644 current_module = "free_demuxer";
645 if (mpctx->num_sources) {
646 mpctx->demuxer = mpctx->sources[0].demuxer;
647 for (int i = 1; i < mpctx->num_sources; i++) {
648 uninit_subs(mpctx->sources[i].demuxer);
649 free_stream(mpctx->sources[i].stream);
650 free_demuxer(mpctx->sources[i].demuxer);
653 talloc_free(mpctx->sources);
654 mpctx->sources = NULL;
655 mpctx->num_sources = 0;
656 talloc_free(mpctx->timeline);
657 mpctx->timeline = NULL;
658 mpctx->num_timeline_parts = 0;
659 talloc_free(mpctx->chapters);
660 mpctx->chapters = NULL;
661 mpctx->num_chapters = 0;
662 mpctx->video_offset = 0;
663 if (mpctx->demuxer) {
664 mpctx->stream = mpctx->demuxer->stream;
665 uninit_subs(mpctx->demuxer);
666 free_demuxer(mpctx->demuxer);
668 mpctx->demuxer = NULL;
671 // kill the cache process:
672 if (mask & INITIALIZED_STREAM) {
673 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
674 current_module = "uninit_stream";
675 if (mpctx->stream)
676 free_stream(mpctx->stream);
677 mpctx->stream = NULL;
680 if (mask & INITIALIZED_VO) {
681 mpctx->initialized_flags &= ~INITIALIZED_VO;
682 current_module = "uninit_vo";
683 vo_destroy(mpctx->video_out);
684 mpctx->video_out = NULL;
685 #ifdef CONFIG_DVDNAV
686 mp_dvdnav_context_free(mpctx);
687 #endif
690 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
691 if (mask & INITIALIZED_GETCH2) {
692 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
693 current_module = "uninit_getch2";
694 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
695 // restore terminal:
696 getch2_disable();
699 if (mask & INITIALIZED_VOBSUB) {
700 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
701 current_module = "uninit_vobsub";
702 if (vo_vobsub)
703 vobsub_close(vo_vobsub);
704 vo_vobsub = NULL;
707 if (mask & INITIALIZED_SPUDEC) {
708 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
709 current_module = "uninit_spudec";
710 spudec_free(vo_spudec);
711 vo_spudec = NULL;
714 if (mask & INITIALIZED_AO) {
715 mpctx->initialized_flags &= ~INITIALIZED_AO;
716 current_module = "uninit_ao";
717 if (mpctx->edl_muted)
718 mixer_mute(&mpctx->mixer);
719 if (mpctx->ao)
720 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
721 mpctx->ao = NULL;
724 current_module = NULL;
727 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
729 if (mpctx->user_muted && !mpctx->edl_muted)
730 mixer_mute(&mpctx->mixer);
731 uninit_player(mpctx, INITIALIZED_ALL);
732 #if defined(__MINGW32__) || defined(__CYGWIN__)
733 timeEndPeriod(1);
734 #endif
735 #ifdef CONFIG_X11
736 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
737 #endif
739 current_module = "uninit_input";
740 mp_input_uninit(mpctx->input);
742 #ifdef CONFIG_FREETYPE
743 current_module = "uninit_font";
744 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
745 free_font_desc(mpctx->osd->sub_font);
746 free_font_desc(vo_font);
747 vo_font = NULL;
748 done_freetype();
749 #endif
750 osd_free(mpctx->osd);
752 #ifdef CONFIG_ASS
753 ass_library_done(mpctx->ass_library);
754 mpctx->ass_library = NULL;
755 #endif
757 current_module = "exit_player";
759 if (mpctx->playtree_iter)
760 play_tree_iter_free(mpctx->playtree_iter);
761 mpctx->playtree_iter = NULL;
762 if (mpctx->playtree)
763 play_tree_free(mpctx->playtree, 1);
764 mpctx->playtree = NULL;
766 talloc_free(mpctx->key_fifo);
768 free(edl_records); // free mem allocated for EDL
769 edl_records = NULL;
770 switch (how) {
771 case EXIT_QUIT:
772 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
773 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
774 break;
775 case EXIT_EOF:
776 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
777 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
778 break;
779 case EXIT_ERROR:
780 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
781 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
782 break;
783 default:
784 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
786 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
787 "max framesize was %d bytes\n", max_framesize);
789 // must be last since e.g. mp_msg uses option values
790 // that will be freed by this.
791 if (mpctx->mconfig)
792 m_config_free(mpctx->mconfig);
793 mpctx->mconfig = NULL;
795 talloc_free(mpctx);
797 exit(rc);
800 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
802 exit_player_with_rc(mpctx, how, 1);
805 #ifndef __MINGW32__
806 static void child_sighandler(int x)
808 pid_t pid;
809 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
811 #endif
813 #ifdef CONFIG_CRASH_DEBUG
814 static char *prog_path;
815 static int crash_debug = 0;
816 #endif
818 static void exit_sighandler(int x)
820 static int sig_count = 0;
821 #ifdef CONFIG_CRASH_DEBUG
822 if (!crash_debug || x != SIGTRAP)
823 #endif
824 ++sig_count;
825 if (sig_count == 5) {
826 /* We're crashing bad and can't uninit cleanly :(
827 * by popular request, we make one last (dirty)
828 * effort to restore the user's
829 * terminal. */
830 getch2_disable();
831 exit(1);
833 if (sig_count == 6)
834 exit(1);
835 if (sig_count > 6) {
836 // can't stop :(
837 #ifndef __MINGW32__
838 kill(getpid(), SIGKILL);
839 #endif
841 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
842 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
843 "\nMPlayer interrupted by signal %d in module: %s\n", x,
844 current_module ? current_module : "unknown");
845 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
846 if (sig_count <= 1)
847 switch (x) {
848 case SIGINT:
849 case SIGPIPE:
850 case SIGQUIT:
851 case SIGTERM:
852 case SIGKILL:
853 async_quit_request = 1;
854 return; // killed from keyboard (^C) or killed [-9]
855 case SIGILL:
856 #if CONFIG_RUNTIME_CPUDETECT
857 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
858 #else
859 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
860 #endif
861 case SIGFPE:
862 case SIGSEGV:
863 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
864 default:
865 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
866 #ifdef CONFIG_CRASH_DEBUG
867 if (crash_debug) {
868 int gdb_pid;
869 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
870 gdb_pid = fork();
871 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
872 if (gdb_pid == 0) { // We are the child
873 char spid[20];
874 snprintf(spid, sizeof(spid), "%i", getppid());
875 getch2_disable(); // allow terminal to work properly with gdb
876 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
877 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
878 } else if (gdb_pid < 0)
879 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
880 else
881 waitpid(gdb_pid, NULL, 0);
882 if (x == SIGTRAP)
883 return;
885 #endif
887 getch2_disable();
888 exit(1);
891 #include "cfg-mplayer.h"
893 static int cfg_include(m_option_t *conf, char *filename)
895 return m_config_parse_config_file(conf->priv, filename);
898 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
900 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
902 struct MPOpts *opts = &mpctx->opts;
903 char *conffile;
904 int conffile_fd;
905 if (!(opts->noconfig & 2) &&
906 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
907 exit_player(mpctx, EXIT_NONE);
908 if ((conffile = get_path("")) == NULL)
909 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
910 else {
911 #ifdef __MINGW32__
912 mkdir(conffile);
913 #else
914 mkdir(conffile, 0777);
915 #endif
916 free(conffile);
917 if ((conffile = get_path("config")) == NULL)
918 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
919 else {
920 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
921 0666)) != -1) {
922 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
923 "Creating config file: %s\n", conffile);
924 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
925 close(conffile_fd);
927 if (!(opts->noconfig & 1) &&
928 m_config_parse_config_file(conf, conffile) < 0)
929 exit_player(mpctx, EXIT_NONE);
930 free(conffile);
935 #define PROFILE_CFG_PROTOCOL "protocol."
937 static void load_per_protocol_config(m_config_t *conf, const char * const file)
939 char *str;
940 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
941 m_profile_t *p;
943 /* does filename actually uses a protocol ? */
944 str = strstr(file, "://");
945 if (!str)
946 return;
948 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
949 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
950 p = m_config_get_profile(conf, protocol);
951 if (p) {
952 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
953 "Loading protocol-related profile '%s'\n", protocol);
954 m_config_set_profile(conf, p);
958 #define PROFILE_CFG_EXTENSION "extension."
960 static void load_per_extension_config(m_config_t *conf, const char * const file)
962 char *str;
963 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
964 m_profile_t *p;
966 /* does filename actually have an extension ? */
967 str = strrchr(file, '.');
968 if (!str)
969 return;
971 sprintf(extension, PROFILE_CFG_EXTENSION);
972 strncat(extension, ++str, 7);
973 p = m_config_get_profile(conf, extension);
974 if (p) {
975 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
976 "Loading extension-related profile '%s'\n", extension);
977 m_config_set_profile(conf, p);
981 #define PROFILE_CFG_VO "vo."
982 #define PROFILE_CFG_AO "ao."
984 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
986 char profile[strlen(cfg) + strlen(out) + 1];
987 m_profile_t *p;
989 sprintf(profile, "%s%s", cfg, out);
990 p = m_config_get_profile(conf, profile);
991 if (p) {
992 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
993 "Loading extension-related profile '%s'\n", profile);
994 m_config_set_profile(conf, p);
999 * Tries to load a config file
1000 * @return 0 if file was not found, 1 otherwise
1002 static int try_load_config(m_config_t *conf, const char *file)
1004 struct stat st;
1005 if (stat(file, &st))
1006 return 0;
1007 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1008 m_config_parse_config_file(conf, file);
1009 return 1;
1012 static void load_per_file_config(m_config_t *conf, const char * const file)
1014 char *confpath;
1015 char cfg[PATH_MAX];
1016 const char *name;
1018 if (strlen(file) > PATH_MAX - 14) {
1019 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
1020 "can not load file or directory specific config files\n");
1021 return;
1023 sprintf(cfg, "%s.conf", file);
1025 name = mp_basename(cfg);
1026 if (use_filedir_conf) {
1027 char dircfg[PATH_MAX];
1028 strcpy(dircfg, cfg);
1029 strcpy(dircfg + (name - cfg), "mplayer.conf");
1030 try_load_config(conf, dircfg);
1032 if (try_load_config(conf, cfg))
1033 return;
1036 if ((confpath = get_path(name)) != NULL) {
1037 try_load_config(conf, confpath);
1039 free(confpath);
1043 /* When libmpdemux performs a blocking operation (network connection or
1044 * cache filling) if the operation fails we use this function to check
1045 * if it was interrupted by the user.
1046 * The function returns a new value for eof. */
1047 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1049 mp_cmd_t *cmd;
1050 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1051 switch (cmd->id) {
1052 case MP_CMD_QUIT:
1053 exit_player_with_rc(mpctx, EXIT_QUIT,
1054 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1055 case MP_CMD_PLAY_TREE_STEP: {
1056 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1057 mpctx->play_tree_step =
1058 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1059 } break;
1060 case MP_CMD_PLAY_TREE_UP_STEP: {
1061 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1062 } break;
1063 case MP_CMD_PLAY_ALT_SRC_STEP: {
1064 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1065 } break;
1067 mp_cmd_free(cmd);
1069 return stop_play;
1072 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1074 play_tree_add_bpf(entry, bstr(mpctx->filename));
1077 if (!entry) {
1078 entry = mpctx->playtree_iter->tree;
1079 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1080 != PLAY_TREE_ITER_ENTRY)
1081 return PT_NEXT_ENTRY;
1082 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1083 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1084 != PLAY_TREE_ITER_ENTRY)
1085 return PT_NEXT_ENTRY;
1087 play_tree_remove(entry, 1, 1);
1088 return PT_NEXT_SRC;
1090 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1091 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1092 entry = mpctx->playtree_iter->tree;
1093 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1094 != PLAY_TREE_ITER_ENTRY)
1095 return PT_NEXT_ENTRY;
1096 play_tree_remove(entry, 1, 1);
1098 return PT_NEXT_SRC;
1101 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1102 int noerr)
1104 struct MPOpts *opts = &mpctx->opts;
1105 sub_data *subd = NULL;
1106 struct ass_track *asst = NULL;
1107 bool is_native_ass = false;
1109 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1110 return;
1112 #ifdef CONFIG_ASS
1113 if (opts->ass_enabled) {
1114 #ifdef CONFIG_ICONV
1115 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1116 #else
1117 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1118 #endif
1119 is_native_ass = asst;
1120 if (!asst) {
1121 subd = sub_read_file(filename, fps, &mpctx->opts);
1122 if (subd) {
1123 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1124 sub_free(subd);
1125 subd = NULL;
1128 } else
1129 #endif
1130 subd = sub_read_file(filename, fps, &mpctx->opts);
1133 if (!asst && !subd) {
1134 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1135 "Cannot load subtitles: %s\n", filename_recode(filename));
1136 return;
1139 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1140 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1141 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1142 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1143 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1144 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1145 filename_recode(filename));
1146 ++mpctx->set_of_sub_size;
1147 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1148 mpctx->set_of_sub_size, filename_recode(filename));
1151 void init_vo_spudec(struct MPContext *mpctx)
1153 unsigned width, height;
1154 spudec_free(vo_spudec);
1155 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1156 vo_spudec = NULL;
1158 // we currently can't work without video stream
1159 if (!mpctx->sh_video)
1160 return;
1162 if (spudec_ifo) {
1163 unsigned int palette[16];
1164 current_module = "spudec_init_vobsub";
1165 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1166 1, -1, NULL) >= 0)
1167 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1170 width = mpctx->sh_video->disp_w;
1171 height = mpctx->sh_video->disp_h;
1173 #ifdef CONFIG_DVDREAD
1174 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1175 current_module = "spudec_init_dvdread";
1176 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1177 cur_pgc->palette, width, height, NULL, 0);
1179 #endif
1181 #ifdef CONFIG_DVDNAV
1182 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1183 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1184 current_module = "spudec_init_dvdnav";
1185 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1187 #endif
1189 if (vo_spudec == NULL) {
1190 sh_sub_t *sh = mpctx->d_sub->sh;
1191 current_module = "spudec_init_normal";
1192 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1193 sh->extradata_len);
1194 spudec_set_font_factor(vo_spudec, font_factor);
1197 if (vo_spudec != NULL) {
1198 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1199 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1200 mpctx);
1205 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1206 * make it all work is to use the builtin SDL-bootstrap code, which
1207 * will be done automatically by replacing our main() if we include SDL.h.
1209 #if defined(__APPLE__) && defined(CONFIG_SDL)
1210 #ifdef CONFIG_SDL_SDL_H
1211 #include <SDL/SDL.h>
1212 #else
1213 #include <SDL.h>
1214 #endif
1215 #endif
1218 * \brief append a formatted string
1219 * \param buf buffer to print into
1220 * \param pos position of terminating 0 in buf
1221 * \param len maximum number of characters in buf, not including terminating 0
1222 * \param format printf format string
1224 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1226 va_list va;
1227 va_start(va, format);
1228 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1229 va_end(va);
1230 if (*pos >= len) {
1231 buf[len] = 0;
1232 *pos = len;
1237 * \brief append time in the hh:mm:ss.f format
1238 * \param buf buffer to print into
1239 * \param pos position of terminating 0 in buf
1240 * \param len maximum number of characters in buf, not including terminating 0
1241 * \param time time value to convert/append
1243 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1245 int64_t tenths = 10 * time;
1246 int f1 = tenths % 10;
1247 int ss = (tenths / 10) % 60;
1248 int mm = (tenths / 600) % 60;
1249 int hh = tenths / 36000;
1250 if (time < 0) {
1251 saddf(buf, pos, len, "unknown");
1252 return;
1254 if (hh > 0)
1255 saddf(buf, pos, len, "%2d:", hh);
1256 if (hh > 0 || mm > 0)
1257 saddf(buf, pos, len, "%02d:", mm);
1258 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1261 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1263 struct MPOpts *opts = &mpctx->opts;
1264 sh_video_t * const sh_video = mpctx->sh_video;
1266 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1267 a_pos = playing_audio_pts(mpctx);
1268 if (mpctx->sh_audio && sh_video && at_frame) {
1269 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1270 if (mpctx->time_frame > 0)
1271 mpctx->last_av_difference +=
1272 mpctx->time_frame * opts->playback_speed;
1273 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1274 && !mpctx->drop_message_shown) {
1275 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1276 mpctx->drop_message_shown = true;
1279 if (opts->quiet)
1280 return;
1282 if (a_pos == MP_NOPTS_VALUE)
1283 a_pos = -9; // don't print a huge negative number
1285 int width;
1286 char *line;
1287 unsigned pos = 0;
1288 get_screen_size();
1289 if (screen_width > 0)
1290 width = screen_width;
1291 else
1292 width = 80;
1293 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1294 /* Windows command line is broken (MinGW's rxvt works, but we
1295 * should not depend on that). */
1296 width--;
1297 #endif
1298 line = malloc(width + 1); // one additional char for the terminating null
1300 // Audio time
1301 if (mpctx->sh_audio) {
1302 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1303 if (!sh_video) {
1304 float len = get_time_length(mpctx);
1305 saddf(line, &pos, width, "(");
1306 sadd_hhmmssf(line, &pos, width, a_pos);
1307 saddf(line, &pos, width, ") of %.1f (", len);
1308 sadd_hhmmssf(line, &pos, width, len);
1309 saddf(line, &pos, width, ") ");
1313 // Video time
1314 if (sh_video)
1315 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1317 // A-V sync
1318 if (mpctx->sh_audio && sh_video)
1319 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1320 mpctx->last_av_difference, mpctx->total_avsync_change);
1322 // Video stats
1323 if (sh_video)
1324 saddf(line, &pos, width, "%3d/%3d ",
1325 (int)sh_video->num_frames,
1326 (int)sh_video->num_frames_decoded);
1328 // CPU usage
1329 if (sh_video) {
1330 if (sh_video->timer > 0.5)
1331 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1332 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1333 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1334 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1335 else
1336 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1337 } else if (mpctx->sh_audio) {
1338 if (mpctx->delay > 0.5)
1339 saddf(line, &pos, width, "%4.1f%% ",
1340 100.0 * audio_time_usage / (double)mpctx->delay);
1341 else
1342 saddf(line, &pos, width, "??,?%% ");
1345 // VO stats
1346 if (sh_video)
1347 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1349 #ifdef CONFIG_STREAM_CACHE
1350 // cache stats
1351 if (stream_cache_size > 0)
1352 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1353 #endif
1355 // other
1356 if (opts->playback_speed != 1)
1357 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1359 // end
1360 if (erase_to_end_of_line) {
1361 line[pos] = 0;
1362 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1363 "%s%s\r", line, erase_to_end_of_line);
1364 } else {
1365 memset(&line[pos], ' ', width - pos);
1366 line[width] = 0;
1367 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1369 free(line);
1372 struct stream_dump_progress {
1373 uint64_t count;
1374 unsigned start_time;
1375 unsigned last_print_time;
1378 static void stream_dump_progress_start(struct stream_dump_progress *p)
1380 p->start_time = p->last_print_time = GetTimerMS();
1381 p->count = 0;
1384 static void stream_dump_progress(struct stream_dump_progress *p,
1385 uint64_t len, stream_t *stream)
1387 p->count += len;
1388 unsigned t = GetTimerMS();
1389 if (t - p->last_print_time < 1000)
1390 return;
1392 uint64_t start = stream->start_pos;
1393 uint64_t end = stream->end_pos;
1394 uint64_t pos = stream->pos;
1396 p->last_print_time = t;
1397 /* TODO: pretty print sizes; ETA */
1398 if (end > start && pos >= start && pos <= end) {
1399 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1400 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1401 p->count, 100.0 * (pos - start) / (end - start));
1402 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1403 } else {
1404 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1405 "dump: %"PRIu64 " bytes written", p->count);
1406 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1410 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1412 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1413 p->count, name);
1417 * \brief build a chain of audio filters that converts the input format
1418 * to the ao's format, taking into account the current playback_speed.
1419 * sh_audio describes the requested input format of the chain.
1420 * ao describes the requested output format of the chain.
1422 static int build_afilter_chain(struct MPContext *mpctx)
1424 struct sh_audio *sh_audio = mpctx->sh_audio;
1425 struct ao *ao = mpctx->ao;
1426 struct MPOpts *opts = &mpctx->opts;
1427 int new_srate;
1428 int result;
1429 if (!sh_audio) {
1430 mpctx->mixer.afilter = NULL;
1431 return 0;
1433 if (af_control_any_rev(sh_audio->afilter,
1434 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1435 &opts->playback_speed))
1436 new_srate = sh_audio->samplerate;
1437 else {
1438 new_srate = sh_audio->samplerate * opts->playback_speed;
1439 if (new_srate != ao->samplerate) {
1440 // limits are taken from libaf/af_resample.c
1441 if (new_srate < 8000)
1442 new_srate = 8000;
1443 if (new_srate > 192000)
1444 new_srate = 192000;
1445 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1448 result = init_audio_filters(sh_audio, new_srate,
1449 &ao->samplerate, &ao->channels, &ao->format);
1450 mpctx->mixer.afilter = sh_audio->afilter;
1451 return result;
1455 typedef struct mp_osd_msg mp_osd_msg_t;
1456 struct mp_osd_msg {
1457 /// Previous message on the stack.
1458 mp_osd_msg_t *prev;
1459 /// Message text.
1460 char *msg;
1461 int id, level, started;
1462 /// Display duration in ms.
1463 unsigned time;
1466 /// OSD message stack.
1467 static mp_osd_msg_t *osd_msg_stack = NULL;
1470 * \brief Add a message on the OSD message stack
1472 * If a message with the same id is already present in the stack
1473 * it is pulled on top of the stack, otherwise a new message is created.
1476 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1477 va_list ap)
1479 mp_osd_msg_t *msg, *last = NULL;
1481 // look if the id is already in the stack
1482 for (msg = osd_msg_stack; msg && msg->id != id;
1483 last = msg, msg = msg->prev) ;
1484 // not found: alloc it
1485 if (!msg) {
1486 msg = talloc_zero(NULL, mp_osd_msg_t);
1487 msg->prev = osd_msg_stack;
1488 osd_msg_stack = msg;
1489 } else if (last) { // found, but it's not on top of the stack
1490 last->prev = msg->prev;
1491 msg->prev = osd_msg_stack;
1492 osd_msg_stack = msg;
1494 talloc_free(msg->msg);
1495 // write the msg
1496 msg->msg = talloc_vasprintf(msg, fmt, ap);
1497 // set id and time
1498 msg->id = id;
1499 msg->level = level;
1500 msg->time = time;
1504 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1506 va_list ap;
1507 va_start(ap, fmt);
1508 set_osd_msg_va(id, level, time, fmt, ap);
1509 va_end(ap);
1512 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1514 va_list ap;
1515 va_start(ap, fmt);
1516 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1517 va_end(ap);
1521 * \brief Remove a message from the OSD stack
1523 * This function can be used to get rid of a message right away.
1527 void rm_osd_msg(int id)
1529 mp_osd_msg_t *msg, *last = NULL;
1531 // Search for the msg
1532 for (msg = osd_msg_stack; msg && msg->id != id;
1533 last = msg, msg = msg->prev) ;
1534 if (!msg)
1535 return;
1537 // Detach it from the stack and free it
1538 if (last)
1539 last->prev = msg->prev;
1540 else
1541 osd_msg_stack = msg->prev;
1542 talloc_free(msg);
1546 * \brief Remove all messages from the OSD stack
1550 static void clear_osd_msgs(void)
1552 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1553 while (msg) {
1554 prev = msg->prev;
1555 talloc_free(msg);
1556 msg = prev;
1558 osd_msg_stack = NULL;
1562 * \brief Get the current message from the OSD stack.
1564 * This function decrements the message timer and destroys the old ones.
1565 * The message that should be displayed is returned (if any).
1569 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1571 struct MPOpts *opts = &mpctx->opts;
1572 mp_osd_msg_t *msg, *prev, *last = NULL;
1573 static unsigned last_update = 0;
1574 unsigned now = GetTimerMS();
1575 unsigned diff;
1576 char hidden_dec_done = 0;
1578 if (mpctx->osd_visible) {
1579 // 36000000 means max timed visibility is 1 hour into the future, if
1580 // the difference is greater assume it's wrapped around from below 0
1581 if (mpctx->osd_visible - now > 36000000) {
1582 mpctx->osd_visible = 0;
1583 vo_osd_progbar_type = -1; // disable
1584 vo_osd_changed(OSDTYPE_PROGBAR);
1585 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1588 if (mpctx->osd_show_percentage_until - now > 36000000)
1589 mpctx->osd_show_percentage_until = 0;
1591 if (!last_update)
1592 last_update = now;
1593 diff = now >= last_update ? now - last_update : 0;
1595 last_update = now;
1597 // Look for the first message in the stack with high enough level.
1598 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1599 prev = msg->prev;
1600 if (msg->level > opts->osd_level && hidden_dec_done)
1601 continue;
1602 // The message has a high enough level or it is the first hidden one
1603 // in both cases we decrement the timer or kill it.
1604 if (!msg->started || msg->time > diff) {
1605 if (msg->started)
1606 msg->time -= diff;
1607 else
1608 msg->started = 1;
1609 // display it
1610 if (msg->level <= opts->osd_level)
1611 return msg;
1612 hidden_dec_done = 1;
1613 continue;
1615 // kill the message
1616 talloc_free(msg);
1617 if (last) {
1618 last->prev = prev;
1619 msg = last;
1620 } else {
1621 osd_msg_stack = prev;
1622 msg = NULL;
1625 // Nothing found
1626 return NULL;
1630 * \brief Display the OSD bar.
1632 * Display the OSD bar or fall back on a simple message.
1636 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1637 double min, double max, double val)
1639 struct MPOpts *opts = &mpctx->opts;
1640 if (opts->osd_level < 1)
1641 return;
1643 if (mpctx->sh_video) {
1644 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1645 vo_osd_progbar_type = type;
1646 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1647 vo_osd_changed(OSDTYPE_PROGBAR);
1648 return;
1651 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1652 name, ROUND(100 * (val - min) / (max - min)));
1656 * \brief Display text subtitles on the OSD
1658 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1660 int i;
1661 vo_sub = subs;
1662 vo_osd_changed(OSDTYPE_SUBTITLE);
1663 if (!mpctx->sh_video) {
1664 // reverse order, since newest set_osd_msg is displayed first
1665 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1666 if (!subs || i >= subs->lines || !subs->text[i])
1667 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1668 else {
1669 // HACK: currently display time for each sub line
1670 // except the last is set to 2 seconds.
1671 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1672 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1673 "%s", subs->text[i]);
1680 * \brief Update the OSD message line.
1682 * This function displays the current message on the vo OSD or on the term.
1683 * If the stack is empty and the OSD level is high enough the timer
1684 * is displayed (only on the vo OSD).
1688 static void update_osd_msg(struct MPContext *mpctx)
1690 struct MPOpts *opts = &mpctx->opts;
1691 mp_osd_msg_t *msg;
1692 struct osd_state *osd = mpctx->osd;
1693 char osd_text_timer[128];
1695 if (mpctx->add_osd_seek_info) {
1696 double percentage = get_percent_pos(mpctx);
1697 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1698 if (mpctx->sh_video)
1699 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1700 mpctx->add_osd_seek_info = false;
1703 // Look if we have a msg
1704 if ((msg = get_osd_msg(mpctx))) {
1705 if (strcmp(osd->osd_text, msg->msg)) {
1706 osd_set_text(osd, msg->msg);
1707 if (mpctx->sh_video)
1708 vo_osd_changed(OSDTYPE_OSD);
1709 else if (opts->term_osd)
1710 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1711 msg->msg);
1713 return;
1716 if (mpctx->sh_video) {
1717 // fallback on the timer
1718 if (opts->osd_level >= 2) {
1719 int len = get_time_length(mpctx);
1720 int percentage = -1;
1721 char percentage_text[10];
1722 char fractions_text[4];
1723 double fpts = get_current_time(mpctx);
1724 int pts = fpts;
1726 if (mpctx->osd_show_percentage_until)
1727 percentage = get_percent_pos(mpctx);
1729 if (percentage >= 0)
1730 snprintf(percentage_text, 9, " (%d%%)", percentage);
1731 else
1732 percentage_text[0] = 0;
1734 if (opts->osd_fractions == 1) {
1735 //print fractions as sub-second timestamp
1736 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1737 (int)((fpts - pts) * 100));
1738 } else if (opts->osd_fractions == 2) {
1739 /* Print fractions by estimating the frame count within the
1740 * second.
1742 * Rounding or cutting off numbers after the decimal point
1743 * causes problems because of float's precision and movies
1744 * whose first frame is not exactly at timestamp 0. Therefore,
1745 * we add 0.2 and cut off at the decimal point, which proved
1746 * to be good heuristic.
1748 double fps = mpctx->sh_video->fps;
1749 if (fps <= 1 || fps > 99)
1750 strcpy(fractions_text, ".??");
1751 else
1752 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1753 (int) ((fpts - pts) * fps + 0.2));
1754 } else {
1755 //do not print fractions
1756 fractions_text[0] = 0;
1759 if (opts->osd_level == 3)
1760 snprintf(osd_text_timer, sizeof(osd_text_timer),
1761 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1762 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1763 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1764 percentage_text);
1765 else
1766 snprintf(osd_text_timer, sizeof(osd_text_timer),
1767 "%c %02d:%02d:%02d%s%s",
1768 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1769 pts % 60, fractions_text, percentage_text);
1770 } else
1771 osd_text_timer[0] = 0;
1773 if (strcmp(osd->osd_text, osd_text_timer)) {
1774 osd_set_text(osd, osd_text_timer);
1775 vo_osd_changed(OSDTYPE_OSD);
1777 return;
1780 // Clear the term osd line
1781 if (opts->term_osd && osd->osd_text[0]) {
1782 osd->osd_text[0] = 0;
1783 printf("%s\n", opts->term_osd_esc);
1788 void reinit_audio_chain(struct MPContext *mpctx)
1790 struct MPOpts *opts = &mpctx->opts;
1791 struct ao *ao;
1792 if (!mpctx->sh_audio)
1793 return;
1794 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1795 current_module = "init_audio_codec";
1796 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1797 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1798 goto init_error;
1799 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1800 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1804 current_module = "af_preinit";
1805 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1806 mpctx->initialized_flags |= INITIALIZED_AO;
1807 mpctx->ao = ao_create();
1808 mpctx->ao->samplerate = force_srate;
1809 mpctx->ao->format = opts->audio_output_format;
1811 ao = mpctx->ao;
1813 // first init to detect best values
1814 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1815 // input:
1816 mpctx->sh_audio->samplerate,
1817 // output:
1818 &ao->samplerate, &ao->channels, &ao->format)) {
1819 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1820 "pre-init!\n");
1821 exit_player(mpctx, EXIT_ERROR);
1823 if (!ao->initialized) {
1824 current_module = "ao2_init";
1825 ao->buffersize = opts->ao_buffersize;
1826 ao_init(ao, opts->audio_driver_list);
1827 if (!ao->initialized) {
1828 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1829 "Could not open/initialize audio device -> no sound.\n");
1830 goto init_error;
1832 ao->buffer.start = talloc_new(ao);
1833 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1834 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1835 ao->driver->info->short_name,
1836 ao->samplerate, ao->channels,
1837 af_fmt2str_short(ao->format),
1838 af_fmt2bits(ao->format) / 8);
1839 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1840 ao->driver->info->name, ao->driver->info->author);
1841 if (strlen(ao->driver->info->comment) > 0)
1842 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1843 ao->driver->info->comment);
1846 // init audio filters:
1847 current_module = "af_init";
1848 if (!build_afilter_chain(mpctx)) {
1849 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1850 "Couldn't find matching filter/ao format!\n");
1851 goto init_error;
1853 mpctx->mixer.ao = ao;
1854 mpctx->mixer.volstep = volstep;
1855 mpctx->syncing_audio = true;
1856 return;
1858 init_error:
1859 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1860 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1861 mpctx->d_audio->id = -2;
1865 // Return pts value corresponding to the end point of audio written to the
1866 // ao so far.
1867 static double written_audio_pts(struct MPContext *mpctx)
1869 sh_audio_t *sh_audio = mpctx->sh_audio;
1870 demux_stream_t *d_audio = mpctx->d_audio;
1871 // first calculate the end pts of audio that has been output by decoder
1872 double a_pts = sh_audio->pts;
1873 if (a_pts != MP_NOPTS_VALUE)
1874 // Good, decoder supports new way of calculating audio pts.
1875 // sh_audio->pts is the timestamp of the latest input packet with
1876 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1877 // the amount of bytes the decoder has written after that timestamp.
1878 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1879 else {
1880 // Decoder doesn't support new way of calculating pts (or we're
1881 // being called before it has decoded anything with known timestamp).
1882 // Use the old method of audio pts calculation: take the timestamp
1883 // of last packet with known pts the decoder has read data from,
1884 // and add amount of bytes read after the beginning of that packet
1885 // divided by input bps. This will be inaccurate if the input/output
1886 // ratio is not constant for every audio packet or if it is constant
1887 // but not accurately known in sh_audio->i_bps.
1889 a_pts = d_audio->pts;
1890 if (a_pts == MP_NOPTS_VALUE)
1891 return a_pts;
1893 // ds_tell_pts returns bytes read after last timestamp from
1894 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1895 // it has read but not decoded
1896 if (sh_audio->i_bps)
1897 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1898 (double)sh_audio->i_bps;
1900 // Now a_pts hopefully holds the pts for end of audio from decoder.
1901 // Substract data in buffers between decoder and audio out.
1903 // Decoded but not filtered
1904 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1906 // Data buffered in audio filters, measured in bytes of "missing" output
1907 double buffered_output = af_calc_delay(sh_audio->afilter);
1909 // Data that was ready for ao but was buffered because ao didn't fully
1910 // accept everything to internal buffers yet
1911 buffered_output += mpctx->ao->buffer.len;
1913 // Filters divide audio length by playback_speed, so multiply by it
1914 // to get the length in original units without speedup or slowdown
1915 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1917 return a_pts + mpctx->video_offset;
1920 // Return pts value corresponding to currently playing audio.
1921 double playing_audio_pts(struct MPContext *mpctx)
1923 double pts = written_audio_pts(mpctx);
1924 if (pts == MP_NOPTS_VALUE)
1925 return pts;
1926 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1929 static bool is_av_sub(int type)
1931 return type == 'b' || type == 'p' || type == 'x';
1934 void update_subtitles(struct MPContext *mpctx, double refpts,
1935 double sub_offset, bool reset)
1937 struct MPOpts *opts = &mpctx->opts;
1938 struct sh_video *sh_video = mpctx->sh_video;
1939 struct demux_stream *d_sub = mpctx->d_sub;
1940 double curpts = refpts + sub_delay;
1941 unsigned char *packet = NULL;
1942 int len;
1943 struct sh_sub *sh_sub = d_sub->sh;
1944 int type = sh_sub ? sh_sub->type : 'v';
1945 static subtitle subs;
1946 if (reset) {
1947 if (sh_sub)
1948 sub_reset(sh_sub, mpctx->osd);
1949 sub_clear_text(&subs, MP_NOPTS_VALUE);
1950 if (vo_sub)
1951 set_osd_subtitle(mpctx, NULL);
1952 if (vo_spudec) {
1953 spudec_reset(vo_spudec);
1954 vo_osd_changed(OSDTYPE_SPU);
1956 #ifdef CONFIG_FFMPEG
1957 if (is_av_sub(type))
1958 reset_avsub(sh_sub);
1959 #endif
1960 return;
1962 // find sub
1963 if (mpctx->subdata) {
1964 if (sub_fps == 0)
1965 sub_fps = sh_video ? sh_video->fps : 25;
1966 current_module = "find_sub";
1967 find_sub(mpctx, mpctx->subdata, curpts *
1968 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1969 if (vo_sub)
1970 mpctx->vo_sub_last = vo_sub;
1973 // DVD sub:
1974 if (vobsub_id >= 0 || type == 'v') {
1975 int timestamp;
1976 current_module = "spudec";
1977 /* Get a sub packet from the DVD or a vobsub */
1978 while (1) {
1979 // Vobsub
1980 len = 0;
1981 if (vo_vobsub) {
1982 if (curpts >= 0) {
1983 len = vobsub_get_packet(vo_vobsub, curpts,
1984 (void **)&packet, &timestamp);
1985 if (len > 0)
1986 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1987 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1988 len, refpts, sh_video->timer,
1989 timestamp / 90000.0, timestamp);
1991 } else {
1992 // DVD sub
1993 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1994 if (len > 0) {
1995 // XXX This is wrong, sh_video->pts can be arbitrarily
1996 // much behind demuxing position. Unfortunately using
1997 // d_video->pts which would have been the simplest
1998 // improvement doesn't work because mpeg specific hacks
1999 // in video.c set d_video->pts to 0.
2000 float x = d_sub->pts - refpts;
2001 if (x > -20 && x < 20) // prevent missing subs on pts reset
2002 timestamp = 90000 * d_sub->pts;
2003 else
2004 timestamp = 90000 * curpts;
2005 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
2006 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
2007 refpts, d_sub->pts, timestamp);
2010 if (len <= 0 || !packet)
2011 break;
2012 // create it only here, since with some broken demuxers we might
2013 // type = v but no DVD sub and we currently do not change the
2014 // "original frame size" ever after init, leading to wrong-sized
2015 // PGS subtitles.
2016 if (!vo_spudec)
2017 vo_spudec = spudec_new(NULL);
2018 if (vo_vobsub || timestamp >= 0)
2019 spudec_assemble(vo_spudec, packet, len, timestamp);
2021 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
2022 if (type == 'd' && !d_sub->demuxer->teletext) {
2023 tt_stream_props tsp = { 0 };
2024 void *ptr = &tsp;
2025 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
2026 VBI_CONTROL_TRUE)
2027 d_sub->demuxer->teletext = ptr;
2029 if (d_sub->non_interleaved)
2030 ds_get_next_pts(d_sub);
2032 while (d_sub->first) {
2033 double subpts = ds_get_next_pts(d_sub) + sub_offset;
2034 if (subpts > curpts) {
2035 // Libass handled subs can be fed to it in advance
2036 if (!opts->ass_enabled || !is_text_sub(type))
2037 break;
2038 // Try to avoid demuxing whole file at once
2039 if (d_sub->non_interleaved && subpts > curpts + 1)
2040 break;
2042 double duration = d_sub->first->duration;
2043 len = ds_get_packet_sub(d_sub, &packet);
2044 if (is_av_sub(type)) {
2045 #ifdef CONFIG_FFMPEG
2046 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2047 if (ret < 0)
2048 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2049 "subtitle\n");
2050 #endif
2051 continue;
2053 if (type == 'm') {
2054 if (len < 2)
2055 continue;
2056 len = FFMIN(len - 2, AV_RB16(packet));
2057 packet += 2;
2059 if (type == 'd') {
2060 if (d_sub->demuxer->teletext) {
2061 uint8_t *p = packet;
2062 p++;
2063 len--;
2064 while (len >= 46) {
2065 int sublen = p[1];
2066 if (p[0] == 2 || p[0] == 3)
2067 teletext_control(d_sub->demuxer->teletext,
2068 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2069 p += sublen + 2;
2070 len -= sublen + 2;
2073 continue;
2075 if (sh_sub && sh_sub->active) {
2076 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2077 continue;
2079 if (subpts != MP_NOPTS_VALUE) {
2080 if (duration < 0)
2081 sub_clear_text(&subs, MP_NOPTS_VALUE);
2082 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2083 int i;
2084 unsigned char *p = packet;
2085 for (i = 0; i < 8 && *p != '\0'; p++)
2086 if (*p == ',')
2087 i++;
2088 if (*p == '\0') /* Broken line? */
2089 continue;
2090 len -= p - packet;
2091 packet = p;
2093 double endpts = MP_NOPTS_VALUE;
2094 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2095 endpts = subpts + duration;
2096 sub_add_text(&subs, packet, len, endpts);
2097 set_osd_subtitle(mpctx, &subs);
2099 if (d_sub->non_interleaved)
2100 ds_get_next_pts(d_sub);
2102 if (!opts->ass_enabled)
2103 if (sub_clear_text(&subs, curpts))
2104 set_osd_subtitle(mpctx, &subs);
2106 if (vo_spudec) {
2107 spudec_heartbeat(vo_spudec, 90000 * curpts);
2108 if (spudec_changed(vo_spudec))
2109 vo_osd_changed(OSDTYPE_SPU);
2112 current_module = NULL;
2115 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2117 int page_changed;
2119 if (!demuxer->teletext)
2120 return;
2122 //Also forcing page update when such ioctl is not supported or call error occured
2123 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2124 &page_changed) != VBI_CONTROL_TRUE)
2125 page_changed = 1;
2127 if (!page_changed)
2128 return;
2130 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2131 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2132 vo_osd_teletext_page = NULL;
2133 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2134 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2135 vo_osd_teletext_half = 0;
2136 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2137 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2138 vo_osd_teletext_mode = 0;
2139 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2140 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2141 vo_osd_teletext_format = 0;
2142 vo_osd_changed(OSDTYPE_TELETEXT);
2144 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2147 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2149 struct MPOpts *opts = &mpctx->opts;
2150 // check for frame-drop:
2151 current_module = "check_framedrop";
2152 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2153 static int dropped_frames;
2154 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2155 float d = delay - mpctx->delay;
2156 ++total_frame_cnt;
2157 // we should avoid dropping too many frames in sequence unless we
2158 // are too late. and we allow 100ms A-V delay here:
2159 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2160 && !mpctx->restart_playback) {
2161 ++drop_frame_cnt;
2162 ++dropped_frames;
2163 return frame_dropping;
2164 } else
2165 dropped_frames = 0;
2167 return 0;
2171 #ifdef HAVE_RTC
2172 int rtc_fd = -1;
2173 #endif
2175 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2177 #ifdef HAVE_RTC
2178 if (rtc_fd >= 0) {
2179 // -------- RTC -----------
2180 current_module = "sleep_rtc";
2181 while (time_frame > 0.000) {
2182 unsigned long rtc_ts;
2183 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2184 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2185 "Linux RTC read error: %s\n", strerror(errno));
2186 time_frame -= get_relative_time(mpctx);
2188 } else
2189 #endif
2191 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2192 // unnecessarily high CPU usage
2193 struct MPOpts *opts = &mpctx->opts;
2194 float margin = opts->softsleep ? 0.011 : 0;
2195 current_module = "sleep_timer";
2196 while (time_frame > margin) {
2197 usec_sleep(1000000 * (time_frame - margin));
2198 time_frame -= get_relative_time(mpctx);
2200 if (opts->softsleep) {
2201 current_module = "sleep_soft";
2202 if (time_frame < 0)
2203 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2204 "Warning! Softsleep underflow!\n");
2205 while (time_frame > 0)
2206 time_frame -= get_relative_time(mpctx); // burn the CPU
2209 return time_frame;
2212 static int select_subtitle(MPContext *mpctx)
2214 struct MPOpts *opts = &mpctx->opts;
2215 // find the best sub to use
2216 int id;
2217 int found = 0;
2218 mpctx->global_sub_pos = -1; // no subs by default
2219 if (vobsub_id >= 0) {
2220 // if user asks for a vobsub id, use that first.
2221 id = vobsub_id;
2222 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2223 M_PROPERTY_OK;
2226 if (!found && opts->sub_id >= 0) {
2227 // if user asks for a dvd sub id, use that next.
2228 id = opts->sub_id;
2229 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2230 M_PROPERTY_OK;
2233 if (!found) {
2234 // if there are text subs to use, use those. (autosubs come last here)
2235 id = 0;
2236 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2237 M_PROPERTY_OK;
2240 if (!found && opts->sub_id == -1) {
2241 // finally select subs by language and container hints
2242 if (opts->sub_id == -1)
2243 opts->sub_id =
2244 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2245 opts->sub_lang);
2246 if (opts->sub_id >= 0) {
2247 id = opts->sub_id;
2248 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2249 M_PROPERTY_OK;
2252 return found;
2255 #ifdef CONFIG_DVDNAV
2256 #ifndef FF_B_TYPE
2257 #define FF_B_TYPE 3
2258 #endif
2259 /// store decoded video image
2260 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2261 mp_image_t *from_mpi)
2263 mp_image_t *mpi;
2265 /// Do not store B-frames
2266 if (from_mpi->pict_type == FF_B_TYPE)
2267 return to_mpi;
2269 if (to_mpi &&
2270 to_mpi->w == from_mpi->w &&
2271 to_mpi->h == from_mpi->h &&
2272 to_mpi->imgfmt == from_mpi->imgfmt)
2273 mpi = to_mpi;
2274 else {
2275 if (to_mpi)
2276 free_mp_image(to_mpi);
2277 if (from_mpi->w == 0 || from_mpi->h == 0)
2278 return NULL;
2279 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2282 copy_mpi(mpi, from_mpi);
2283 return mpi;
2286 static void mp_dvdnav_reset_stream(MPContext *ctx)
2288 struct MPOpts *opts = &ctx->opts;
2289 if (ctx->sh_video) {
2290 /// clear video pts
2291 ctx->d_video->pts = 0.0f;
2292 ctx->sh_video->pts = 0.0f;
2293 ctx->sh_video->i_pts = 0.0f;
2294 ctx->sh_video->last_pts = 0.0f;
2295 ctx->sh_video->num_buffered_pts = 0;
2296 ctx->sh_video->num_frames = 0;
2297 ctx->sh_video->num_frames_decoded = 0;
2298 ctx->sh_video->timer = 0.0f;
2299 ctx->sh_video->stream_delay = 0.0f;
2300 ctx->sh_video->timer = 0;
2301 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2304 if (ctx->sh_audio) {
2305 /// free audio packets and reset
2306 ds_free_packs(ctx->d_audio);
2307 audio_delay -= ctx->sh_audio->stream_delay;
2308 ctx->delay = -audio_delay;
2309 ao_reset(ctx->ao);
2310 resync_audio_stream(ctx->sh_audio);
2313 audio_delay = 0.0f;
2314 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2315 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2316 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2317 if (dvdsub_lang_id != opts->sub_id) {
2318 opts->sub_id = dvdsub_lang_id;
2319 select_subtitle(ctx);
2323 /// clear all EOF related flags
2324 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2327 /// Restore last decoded DVDNAV (still frame)
2328 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2329 int *in_size,
2330 unsigned char **start,
2331 mp_image_t *decoded_frame)
2333 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2334 return decoded_frame;
2336 /// a change occurred in dvdnav stream
2337 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2338 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2339 mp_dvdnav_context_free(mpctx);
2340 mp_dvdnav_reset_stream(mpctx);
2341 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2342 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2345 if (*in_size < 0) {
2346 float len;
2348 /// Display still frame, if any
2349 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2350 decoded_frame = mpctx->nav_smpi;
2352 /// increment video frame : continue playing after still frame
2353 len = get_time_length(mpctx);
2354 if (mpctx->sh_video->pts >= len &&
2355 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2356 mp_dvdnav_skip_still(mpctx->stream);
2357 mp_dvdnav_skip_wait(mpctx->stream);
2359 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2361 if (mpctx->nav_buffer) {
2362 *start = mpctx->nav_start;
2363 *in_size = mpctx->nav_in_size;
2364 if (mpctx->nav_start)
2365 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2369 return decoded_frame;
2372 /// Save last decoded DVDNAV (still frame)
2373 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2374 unsigned char *start,
2375 mp_image_t *decoded_frame)
2377 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2378 return;
2380 free(mpctx->nav_buffer);
2381 mpctx->nav_buffer = NULL;
2382 mpctx->nav_start = NULL;
2383 mpctx->nav_in_size = -1;
2385 if (in_size > 0)
2386 mpctx->nav_buffer = malloc(in_size);
2387 if (mpctx->nav_buffer) {
2388 mpctx->nav_start = start;
2389 mpctx->nav_in_size = in_size;
2390 memcpy(mpctx->nav_buffer, start, in_size);
2393 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2394 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2396 #endif /* CONFIG_DVDNAV */
2398 /* Modify video timing to match the audio timeline. There are two main
2399 * reasons this is needed. First, video and audio can start from different
2400 * positions at beginning of file or after a seek (MPlayer starts both
2401 * immediately even if they have different pts). Second, the file can have
2402 * audio timestamps that are inconsistent with the duration of the audio
2403 * packets, for example two consecutive timestamp values differing by
2404 * one second but only a packet with enough samples for half a second
2405 * of playback between them.
2407 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2409 current_module = "av_sync";
2411 if (!mpctx->sh_audio || mpctx->syncing_audio)
2412 return;
2414 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2415 double v_pts = mpctx->sh_video->pts;
2416 double av_delay = a_pts - v_pts;
2417 // Try to sync vo_flip() so it will *finish* at given time
2418 av_delay += mpctx->last_vo_flip_duration;
2419 av_delay -= audio_delay; // This much pts difference is desired
2421 double change = av_delay * 0.1;
2422 double max_change = default_max_pts_correction >= 0 ?
2423 default_max_pts_correction : frame_time * 0.1;
2424 if (change < -max_change)
2425 change = -max_change;
2426 else if (change > max_change)
2427 change = max_change;
2428 mpctx->delay += change;
2429 mpctx->total_avsync_change += change;
2432 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2433 double pts)
2435 if (mpctx->paused)
2436 return 0;
2437 struct ao *ao = mpctx->ao;
2438 double bps = ao->bps / mpctx->opts.playback_speed;
2439 ao->pts = pts;
2440 // hack used by some mpeg-writing AOs
2441 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2442 mpctx->delay) * 90000.0;
2443 int played = ao_play(mpctx->ao, data, len, flags);
2444 if (played > 0) {
2445 mpctx->delay += played / bps;
2446 // Keep correct pts for remaining data - could be used to flush
2447 // remaining buffer when closing ao.
2448 ao->pts += played / bps;
2450 return played;
2453 #define ASYNC_PLAY_DONE -3
2454 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2456 struct ao *ao = mpctx->ao;
2457 struct MPOpts *opts = &mpctx->opts;
2458 sh_audio_t * const sh_audio = mpctx->sh_audio;
2459 int res;
2461 // Timing info may not be set without
2462 res = decode_audio(sh_audio, &ao->buffer, 1);
2463 if (res < 0)
2464 return res;
2466 int bytes;
2467 bool did_retry = false;
2468 double written_pts;
2469 double bps = ao->bps / opts->playback_speed;
2470 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2471 mpctx->hrseek_active = false;
2472 while (1) {
2473 written_pts = written_audio_pts(mpctx);
2474 double ptsdiff;
2475 if (hrseek)
2476 ptsdiff = written_pts - mpctx->hrseek_pts;
2477 else
2478 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2479 - audio_delay;
2480 bytes = ptsdiff * bps;
2481 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2483 // ogg demuxers give packets without timing
2484 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2485 if (!did_retry) {
2486 // Try to read more data to see packets that have pts
2487 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2488 if (res < 0)
2489 return res;
2490 did_retry = true;
2491 continue;
2493 bytes = 0;
2496 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2497 bytes = 0;
2499 if (bytes > 0)
2500 break;
2502 mpctx->syncing_audio = false;
2503 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2504 int res = decode_audio(sh_audio, &ao->buffer, a);
2505 bytes += ao->buffer.len;
2506 if (bytes >= 0) {
2507 memmove(ao->buffer.start,
2508 ao->buffer.start + ao->buffer.len - bytes, bytes);
2509 ao->buffer.len = bytes;
2510 if (res < 0)
2511 return res;
2512 return decode_audio(sh_audio, &ao->buffer, playsize);
2514 ao->buffer.len = 0;
2515 if (res < 0)
2516 return res;
2518 if (hrseek)
2519 // Don't add silence in audio-only case even if position is too late
2520 return 0;
2521 int fillbyte = 0;
2522 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2523 fillbyte = 0x80;
2524 if (bytes >= playsize) {
2525 /* This case could fall back to the one below with
2526 * bytes = playsize, but then silence would keep accumulating
2527 * in a_out_buffer if the AO accepts less data than it asks for
2528 * in playsize. */
2529 char *p = malloc(playsize);
2530 memset(p, fillbyte, playsize);
2531 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2532 free(p);
2533 return ASYNC_PLAY_DONE;
2535 mpctx->syncing_audio = false;
2536 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2537 return decode_audio(sh_audio, &ao->buffer, playsize);
2540 static int fill_audio_out_buffers(struct MPContext *mpctx)
2542 struct MPOpts *opts = &mpctx->opts;
2543 struct ao *ao = mpctx->ao;
2544 unsigned int t;
2545 double tt;
2546 int playsize;
2547 int playflags = 0;
2548 bool audio_eof = false;
2549 bool partial_fill = false;
2550 sh_audio_t * const sh_audio = mpctx->sh_audio;
2551 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2552 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2554 current_module = "play_audio";
2556 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2557 return 0;
2559 // hack used by some mpeg-writing AOs
2560 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2561 mpctx->delay) * 90000.0;
2563 if (mpctx->paused)
2564 playsize = 1; // just initialize things (audio pts at least)
2565 else
2566 playsize = ao_get_space(ao);
2568 // Fill buffer if needed:
2569 current_module = "decode_audio";
2570 t = GetTimer();
2572 // Coming here with hrseek_active still set means audio-only
2573 if (!mpctx->sh_video)
2574 mpctx->syncing_audio = false;
2575 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2576 mpctx->syncing_audio = false;
2577 mpctx->hrseek_active = false;
2580 int res;
2581 if (mpctx->syncing_audio || mpctx->hrseek_active)
2582 res = audio_start_sync(mpctx, playsize);
2583 else
2584 res = decode_audio(sh_audio, &ao->buffer, playsize);
2585 if (res < 0) { // EOF, error or format change
2586 if (res == -2) {
2587 /* The format change isn't handled too gracefully. A more precise
2588 * implementation would require draining buffered old-format audio
2589 * while displaying video, then doing the output format switch.
2591 uninit_player(mpctx, INITIALIZED_AO);
2592 reinit_audio_chain(mpctx);
2593 return -1;
2594 } else if (res == ASYNC_PLAY_DONE)
2595 return 0;
2596 else if (mpctx->d_audio->eof)
2597 audio_eof = true;
2599 t = GetTimer() - t;
2600 tt = t * 0.000001f;
2601 audio_time_usage += tt;
2602 if (mpctx->timeline && modifiable_audio_format) {
2603 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2604 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2605 * ao->bps / opts->playback_speed;
2606 if (playsize > bytes) {
2607 playsize = FFMAX(bytes, 0);
2608 playflags |= AOPLAY_FINAL_CHUNK;
2609 audio_eof = true;
2610 partial_fill = true;
2614 assert(ao->buffer.len % unitsize == 0);
2615 if (playsize > ao->buffer.len) {
2616 partial_fill = true;
2617 playsize = ao->buffer.len;
2618 if (audio_eof)
2619 playflags |= AOPLAY_FINAL_CHUNK;
2621 playsize -= playsize % unitsize;
2622 if (!playsize)
2623 return partial_fill && audio_eof ? -2 : -partial_fill;
2625 // play audio:
2626 current_module = "play_audio";
2628 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2629 written_audio_pts(mpctx));
2630 assert(played % unitsize == 0);
2631 ao->buffer_playable_size = playsize - played;
2633 if (played > 0) {
2634 ao->buffer.len -= played;
2635 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2636 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2637 // Sanity check to avoid hanging in case current ao doesn't output
2638 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2639 return -2;
2642 return -partial_fill;
2645 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2646 bool sync_to_audio, float *aq_sleep_time)
2648 struct MPOpts *opts = &mpctx->opts;
2649 double audio_limit = 2;
2650 current_module = "calc_sleep_time";
2652 if (mpctx->restart_playback)
2653 return 0;
2655 *time_frame -= get_relative_time(mpctx); // reset timer
2657 if (sync_to_audio) {
2658 float delay = ao_get_delay(mpctx->ao);
2659 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2661 if (opts->autosync) {
2663 * Adjust this raw delay value by calculating the expected
2664 * delay for this frame and generating a new value which is
2665 * weighted between the two. The higher autosync is, the
2666 * closer to the delay value gets to that which "-nosound"
2667 * would have used, and the longer it will take for A/V
2668 * sync to settle at the right value (but it eventually will.)
2669 * This settling time is very short for values below 100.
2671 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2672 float difference = delay - predicted;
2673 delay = predicted + difference / (float)opts->autosync;
2676 *time_frame = delay - mpctx->delay / opts->playback_speed;
2678 // delay = amount of audio buffered in soundcard/driver
2679 delay = FFMIN(delay, 0.5);
2680 delay = FFMAX(delay, 0.1);
2681 audio_limit = delay;
2682 } else {
2683 // If we're lagging more than 200 ms behind the right playback rate,
2684 // don't try to "catch up".
2685 // If benchmark is set always output frames as fast as possible
2686 // without sleeping.
2687 if (*time_frame < -0.2 || opts->benchmark)
2688 *time_frame = 0;
2691 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2693 if (t <= 0.05)
2694 return 0;
2696 t -= 0.05;
2697 if (t > audio_limit * 0.6)
2698 t = audio_limit * 0.5;
2699 *aq_sleep_time += t;
2700 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2701 return 1;
2704 int reinit_video_chain(struct MPContext *mpctx)
2706 struct MPOpts *opts = &mpctx->opts;
2707 sh_video_t * const sh_video = mpctx->sh_video;
2708 if (!sh_video)
2709 return 0;
2710 double ar = -1.0;
2711 //================== Init VIDEO (codec & libvo) ==========================
2712 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2713 current_module = "preinit_libvo";
2715 //shouldn't we set dvideo->id=-2 when we fail?
2716 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2717 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2718 mpctx->key_fifo,
2719 mpctx->input))) {
2720 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2721 "the selected video_out (-vo) device.\n");
2722 goto err_out;
2724 mpctx->initialized_flags |= INITIALIZED_VO;
2727 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2728 &ar) != STREAM_UNSUPPORTED)
2729 mpctx->sh_video->stream_aspect = ar;
2730 current_module = "init_video_filters";
2732 char *vf_arg[] = {
2733 "_oldargs_", (char *)mpctx->video_out, NULL
2735 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2738 #ifdef CONFIG_ASS
2739 if (opts->ass_enabled) {
2740 int i;
2741 int insert = 1;
2742 if (opts->vf_settings)
2743 for (i = 0; opts->vf_settings[i].name; ++i)
2744 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2745 insert = 0;
2746 break;
2748 if (insert) {
2749 extern vf_info_t vf_info_ass;
2750 const vf_info_t *libass_vfs[] = {
2751 &vf_info_ass, NULL
2753 char *vf_arg[] = {
2754 "auto", "1", NULL
2756 int retcode = 0;
2757 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2758 sh_video->vfilter,
2759 "ass", vf_arg,
2760 &retcode);
2761 if (vf_ass)
2762 sh_video->vfilter = vf_ass;
2763 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2764 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2765 else
2766 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2767 "ASS: cannot add video filter\n");
2770 #endif
2772 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2774 #ifdef CONFIG_ASS
2775 if (opts->ass_enabled)
2776 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2777 mpctx->ass_library);
2778 #endif
2780 current_module = "init_video_codec";
2782 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2783 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2784 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2786 if (!sh_video->initialized) {
2787 if (!opts->fixed_vo)
2788 uninit_player(mpctx, INITIALIZED_VO);
2789 goto err_out;
2792 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2794 if (sh_video->codec)
2795 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2796 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2798 sh_video->last_pts = MP_NOPTS_VALUE;
2799 sh_video->num_buffered_pts = 0;
2800 sh_video->next_frame_time = 0;
2802 if (opts->auto_quality > 0) {
2803 // Auto quality option enabled
2804 output_quality = get_video_quality_max(sh_video);
2805 if (opts->auto_quality > output_quality)
2806 opts->auto_quality = output_quality;
2807 else
2808 output_quality = opts->auto_quality;
2809 mp_msg(MSGT_CPLAYER, MSGL_V,
2810 "AutoQ: setting quality to %d.\n", output_quality);
2811 set_video_quality(sh_video, output_quality);
2814 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2816 current_module = "init_vo";
2818 return 1;
2820 err_out:
2821 mpctx->sh_video = mpctx->d_video->sh = NULL;
2822 return 0;
2825 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2827 struct sh_video *sh_video = mpctx->sh_video;
2828 double frame_time = 0;
2829 struct vo *video_out = mpctx->video_out;
2830 while (1) {
2831 current_module = "filter_video";
2832 // In nocorrect-pts mode there is no way to properly time these frames
2833 if (vo_get_buffered_frame(video_out, 0) >= 0)
2834 break;
2835 if (vf_output_queued_frame(sh_video->vfilter))
2836 break;
2837 unsigned char *packet = NULL;
2838 frame_time = sh_video->next_frame_time;
2839 if (mpctx->restart_playback)
2840 frame_time = 0;
2841 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2842 &packet, force_fps);
2843 if (in_size < 0) {
2844 #ifdef CONFIG_DVDNAV
2845 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2846 if (mp_dvdnav_is_eof(mpctx->stream))
2847 return -1;
2848 if (mpctx->d_video)
2849 mpctx->d_video->eof = 0;
2850 if (mpctx->d_audio)
2851 mpctx->d_audio->eof = 0;
2852 mpctx->stream->eof = 0;
2853 } else
2854 #endif
2855 return -1;
2857 if (in_size > max_framesize)
2858 max_framesize = in_size;
2859 sh_video->timer += frame_time;
2860 if (mpctx->sh_audio)
2861 mpctx->delay -= frame_time;
2862 // video_read_frame can change fps (e.g. for ASF video)
2863 vo_fps = sh_video->fps;
2864 int framedrop_type = check_framedrop(mpctx, frame_time);
2865 current_module = "decode video";
2867 void *decoded_frame;
2868 #ifdef CONFIG_DVDNAV
2869 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2870 if (in_size >= 0 && !decoded_frame)
2871 #endif
2872 decoded_frame = decode_video(sh_video, NULL, packet, in_size,
2873 framedrop_type, sh_video->pts);
2874 #ifdef CONFIG_DVDNAV
2875 // Save last still frame for future display
2876 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2877 #endif
2878 if (decoded_frame) {
2879 current_module = "filter video";
2880 filter_video(sh_video, decoded_frame, sh_video->pts);
2882 break;
2884 return frame_time;
2887 static void determine_frame_pts(struct MPContext *mpctx)
2889 struct sh_video *sh_video = mpctx->sh_video;
2890 struct MPOpts *opts = &mpctx->opts;
2892 if (opts->user_pts_assoc_mode)
2893 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2894 else if (sh_video->pts_assoc_mode == 0) {
2895 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2896 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2897 sh_video->pts_assoc_mode = 1;
2898 else
2899 sh_video->pts_assoc_mode = 2;
2900 } else {
2901 int probcount1 = sh_video->num_reordered_pts_problems;
2902 int probcount2 = sh_video->num_sorted_pts_problems;
2903 if (sh_video->pts_assoc_mode == 2) {
2904 int tmp = probcount1;
2905 probcount1 = probcount2;
2906 probcount2 = tmp;
2908 if (probcount1 >= probcount2 * 1.5 + 2) {
2909 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2910 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2911 "%d.\n", sh_video->pts_assoc_mode);
2914 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2915 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2918 static double update_video(struct MPContext *mpctx)
2920 struct sh_video *sh_video = mpctx->sh_video;
2921 struct vo *video_out = mpctx->video_out;
2922 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2923 mpctx->osd); // hack for vf_expand
2924 if (!mpctx->opts.correct_pts)
2925 return update_video_nocorrect_pts(mpctx);
2927 double pts;
2929 while (1) {
2930 current_module = "filter_video";
2931 if (!mpctx->hrseek_active
2932 && vo_get_buffered_frame(video_out, false) >= 0)
2933 break;
2934 // XXX Time used in this call is not counted in any performance
2935 // timer now
2936 if (vf_output_queued_frame(sh_video->vfilter))
2937 break;
2938 int in_size = 0;
2939 unsigned char *buf = NULL;
2940 pts = MP_NOPTS_VALUE;
2941 struct demux_packet *pkt = ds_get_packet2(mpctx->d_video);
2942 if (pkt) {
2943 in_size = pkt->len;
2944 buf = pkt->buffer;
2945 pts = pkt->pts;
2947 if (pts != MP_NOPTS_VALUE)
2948 pts += mpctx->video_offset;
2949 if (in_size > max_framesize)
2950 max_framesize = in_size;
2951 current_module = "decode video";
2952 if (pts >= mpctx->hrseek_pts - .005)
2953 mpctx->hrseek_framedrop = false;
2954 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2955 check_framedrop(mpctx, sh_video->frametime);
2956 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2957 framedrop_type, pts);
2958 if (decoded_frame) {
2959 determine_frame_pts(mpctx);
2960 current_module = "filter video";
2961 filter_video(sh_video, decoded_frame, sh_video->pts);
2962 } else if (!pkt) {
2963 if (vo_get_buffered_frame(video_out, true) < 0)
2964 return -1;
2966 break;
2969 if (!video_out->frame_loaded)
2970 return 0;
2972 pts = video_out->next_pts;
2973 if (pts == MP_NOPTS_VALUE) {
2974 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2975 // Try to use decoder pts from before filters
2976 pts = sh_video->pts;
2977 if (pts == MP_NOPTS_VALUE)
2978 pts = sh_video->last_pts;
2980 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2981 vo_skip_frame(video_out);
2982 return 0;
2984 mpctx->hrseek_active = false;
2985 sh_video->pts = pts;
2986 if (sh_video->last_pts == MP_NOPTS_VALUE)
2987 sh_video->last_pts = sh_video->pts;
2988 else if (sh_video->last_pts > sh_video->pts) {
2989 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2990 sh_video->pts, sh_video->last_pts);
2991 /* If the difference in pts is small treat it as jitter around the
2992 * right value (possibly caused by incorrect timestamp ordering) and
2993 * just show this frame immediately after the last one.
2994 * Treat bigger differences as timestamp resets and start counting
2995 * timing of later frames from the position of this one. */
2996 if (sh_video->last_pts - sh_video->pts > 0.5)
2997 sh_video->last_pts = sh_video->pts;
2998 else
2999 sh_video->pts = sh_video->last_pts;
3001 double frame_time = sh_video->pts - sh_video->last_pts;
3002 sh_video->last_pts = sh_video->pts;
3003 sh_video->timer += frame_time;
3004 if (mpctx->sh_audio)
3005 mpctx->delay -= frame_time;
3006 return frame_time;
3009 void pause_player(struct MPContext *mpctx)
3011 if (mpctx->paused)
3012 return;
3013 mpctx->paused = 1;
3014 mpctx->step_frames = 0;
3015 mpctx->time_frame -= get_relative_time(mpctx);
3017 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3018 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3020 if (mpctx->ao && mpctx->sh_audio)
3021 ao_pause(mpctx->ao); // pause audio, keep data if possible
3024 void unpause_player(struct MPContext *mpctx)
3026 if (!mpctx->paused)
3027 return;
3028 mpctx->paused = 0;
3030 if (mpctx->ao && mpctx->sh_audio)
3031 ao_resume(mpctx->ao);
3032 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3033 && !mpctx->step_frames)
3034 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3035 (void)get_relative_time(mpctx); // ignore time that passed during pause
3038 void add_step_frame(struct MPContext *mpctx)
3040 mpctx->step_frames++;
3041 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3042 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3043 unpause_player(mpctx);
3046 static void pause_loop(struct MPContext *mpctx)
3048 struct MPOpts *opts = &mpctx->opts;
3049 mp_cmd_t *cmd;
3050 #ifdef CONFIG_STREAM_CACHE
3051 int old_cache_fill = stream_cache_size > 0 ?
3052 cache_fill_status(mpctx->stream) : 0;
3053 #endif
3054 if (!opts->quiet) {
3055 if (opts->term_osd && !mpctx->sh_video) {
3056 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
3057 update_osd_msg(mpctx);
3058 } else
3059 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
3060 mp_gtext(" ===== PAUSE ====="));
3061 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
3064 while ((cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
3065 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
3066 if (cmd) {
3067 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3068 run_command(mpctx, cmd);
3069 mp_cmd_free(cmd);
3070 continue;
3072 if (mpctx->sh_video && mpctx->video_out)
3073 vo_check_events(mpctx->video_out);
3074 usec_sleep(20000);
3075 update_osd_msg(mpctx);
3076 int hack = vo_osd_changed(0);
3077 vo_osd_changed(hack);
3078 if (hack)
3079 break;
3080 #ifdef CONFIG_STREAM_CACHE
3081 if (!opts->quiet && stream_cache_size > 0) {
3082 int new_cache_fill = cache_fill_status(mpctx->stream);
3083 if (new_cache_fill != old_cache_fill) {
3084 if (opts->term_osd && !mpctx->sh_video) {
3085 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
3086 mp_gtext(" ===== PAUSE ====="),
3087 new_cache_fill);
3088 update_osd_msg(mpctx);
3089 } else
3090 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
3091 mp_gtext(" ===== PAUSE ====="),
3092 new_cache_fill);
3093 old_cache_fill = new_cache_fill;
3096 #endif
3101 // Find the right mute status and record position for new file position
3102 static void edl_seek_reset(MPContext *mpctx)
3104 mpctx->edl_muted = 0;
3105 next_edl_record = edl_records;
3107 while (next_edl_record) {
3108 if (next_edl_record->start_sec >= get_current_time(mpctx))
3109 break;
3111 if (next_edl_record->action == EDL_MUTE)
3112 mpctx->edl_muted = !mpctx->edl_muted;
3113 next_edl_record = next_edl_record->next;
3115 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3116 mixer_mute(&mpctx->mixer);
3120 // Execute EDL command for the current position if one exists
3121 static void edl_update(MPContext *mpctx)
3123 if (!next_edl_record)
3124 return;
3126 if (!mpctx->sh_video) {
3127 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
3128 "Cannot use EDL without video, disabling.\n");
3129 free_edl(edl_records);
3130 next_edl_record = NULL;
3131 edl_records = NULL;
3132 return;
3135 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3136 if (next_edl_record->action == EDL_SKIP) {
3137 mpctx->osd_function = OSD_FFW;
3138 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3139 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3140 "[%f], length [%f]\n", next_edl_record->start_sec,
3141 next_edl_record->stop_sec, next_edl_record->length_sec);
3142 } else if (next_edl_record->action == EDL_MUTE) {
3143 mpctx->edl_muted = !mpctx->edl_muted;
3144 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3145 mixer_mute(&mpctx->mixer);
3146 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3147 next_edl_record->start_sec);
3149 next_edl_record = next_edl_record->next;
3153 static void reinit_decoders(struct MPContext *mpctx)
3155 reinit_video_chain(mpctx);
3156 reinit_audio_chain(mpctx);
3157 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3160 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3162 if (mpctx->sh_video) {
3163 current_module = "seek_video_reset";
3164 resync_video_stream(mpctx->sh_video);
3165 mpctx->sh_video->timer = 0;
3166 vo_seek_reset(mpctx->video_out);
3167 mpctx->sh_video->timer = 0;
3168 mpctx->sh_video->num_buffered_pts = 0;
3169 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3170 mpctx->delay = 0;
3171 mpctx->time_frame = 0;
3172 mpctx->restart_playback = true;
3173 // Not all demuxers set d_video->pts during seek, so this value
3174 // (which is used by at least vobsub and edl code below) may
3175 // be completely wrong (probably 0).
3176 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3177 mpctx->video_pts = mpctx->sh_video->pts;
3178 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3179 true);
3180 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3183 if (mpctx->sh_audio) {
3184 current_module = "seek_audio_reset";
3185 resync_audio_stream(mpctx->sh_audio);
3186 if (reset_ao)
3187 ao_reset(mpctx->ao);
3188 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3189 mpctx->sh_audio->a_buffer_len = 0;
3190 if (!mpctx->sh_video)
3191 update_subtitles(mpctx, mpctx->sh_audio->pts,
3192 mpctx->video_offset, true);
3195 if (vo_vobsub && mpctx->sh_video) {
3196 current_module = "seek_vobsub_reset";
3197 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3200 edl_seek_reset(mpctx);
3202 mpctx->hrseek_active = false;
3203 mpctx->hrseek_framedrop = false;
3204 mpctx->total_avsync_change = 0;
3205 audio_time_usage = 0;
3206 video_time_usage = 0;
3207 vout_time_usage = 0;
3208 drop_frame_cnt = 0;
3210 current_module = NULL;
3213 static bool timeline_set_part(struct MPContext *mpctx, int i)
3215 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3216 struct timeline_part *n = mpctx->timeline + i;
3217 mpctx->timeline_part = i;
3218 mpctx->video_offset = n->start - n->source_start;
3219 if (n->source == p->source)
3220 return false;
3221 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3222 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3223 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3224 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3225 mpctx->stop_play = orig_stop_play;
3226 mpctx->demuxer = n->source->demuxer;
3227 mpctx->d_video = mpctx->demuxer->video;
3228 mpctx->d_audio = mpctx->demuxer->audio;
3229 mpctx->d_sub = mpctx->demuxer->sub;
3230 mpctx->sh_video = mpctx->d_video->sh;
3231 mpctx->sh_audio = mpctx->d_audio->sh;
3232 return true;
3235 // Given pts, switch playback to the corresponding part.
3236 // Return offset within that part.
3237 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3238 bool *need_reset)
3240 if (pts < 0)
3241 pts = 0;
3242 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3243 struct timeline_part *p = mpctx->timeline + i;
3244 if (pts < (p + 1)->start) {
3245 *need_reset = timeline_set_part(mpctx, i);
3246 return pts - p->start + p->source_start;
3249 return -1;
3253 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3254 static int seek(MPContext *mpctx, struct seek_params seek,
3255 bool timeline_fallthrough)
3257 struct MPOpts *opts = &mpctx->opts;
3259 current_module = "seek";
3260 if (mpctx->stop_play == AT_END_OF_FILE)
3261 mpctx->stop_play = KEEP_PLAYING;
3262 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3263 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3264 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3265 || opts->hr_seek > 0 || seek.exact > 0;
3266 if (seek.type == MPSEEK_FACTOR
3267 || seek.type == MPSEEK_ABSOLUTE
3268 && seek.amount < mpctx->last_chapter_pts
3269 || seek.amount < 0)
3270 mpctx->last_chapter_seek = -2;
3271 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3272 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3273 seek.type = MPSEEK_ABSOLUTE;
3275 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3276 && seek.type == MPSEEK_RELATIVE) {
3277 seek.type = MPSEEK_ABSOLUTE;
3278 seek.direction = seek.amount > 0 ? 1 : -1;
3279 seek.amount += get_current_time(mpctx);
3282 /* At least the liba52 decoder wants to read from the input stream
3283 * during initialization, so reinit must be done after the demux_seek()
3284 * call that clears possible stream EOF. */
3285 bool need_reset = false;
3286 double demuxer_amount = seek.amount;
3287 if (mpctx->timeline) {
3288 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3289 &need_reset);
3290 if (demuxer_amount == -1) {
3291 mpctx->stop_play = AT_END_OF_FILE;
3292 // Clear audio from current position
3293 if (mpctx->sh_audio) {
3294 ao_reset(mpctx->ao);
3295 mpctx->sh_audio->a_buffer_len = 0;
3297 return -1;
3300 int demuxer_style = 0;
3301 switch (seek.type) {
3302 case MPSEEK_FACTOR:
3303 demuxer_style |= SEEK_FACTOR; // fallthrough
3304 case MPSEEK_ABSOLUTE:
3305 demuxer_style |= SEEK_ABSOLUTE;
3307 if (hr_seek || seek.direction < 0)
3308 demuxer_style |= SEEK_BACKWARD;
3309 else if (seek.direction > 0)
3310 demuxer_style |= SEEK_FORWARD;
3312 if (hr_seek)
3313 demuxer_amount -= opts->hr_seek_demuxer_offset;
3314 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3315 demuxer_style);
3316 if (need_reset)
3317 reinit_decoders(mpctx);
3318 if (seekresult == 0)
3319 return -1;
3321 seek_reset(mpctx, !timeline_fallthrough);
3323 /* Use the target time as "current position" for further relative
3324 * seeks etc until a new video frame has been decoded */
3325 if (seek.type == MPSEEK_ABSOLUTE) {
3326 mpctx->video_pts = seek.amount;
3327 mpctx->last_seek_pts = seek.amount;
3328 } else
3329 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3331 if (hr_seek) {
3332 mpctx->hrseek_active = true;
3333 mpctx->hrseek_framedrop = true;
3334 mpctx->hrseek_pts = seek.amount;
3337 mpctx->start_timestamp = GetTimerMS();
3339 return 0;
3342 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3343 int exact)
3345 struct seek_params *seek = &mpctx->seek;
3346 switch (type) {
3347 case MPSEEK_RELATIVE:
3348 if (seek->type == MPSEEK_FACTOR)
3349 return; // Well... not common enough to bother doing better
3350 seek->amount += amount;
3351 seek->exact = FFMAX(seek->exact, exact);
3352 if (seek->type == MPSEEK_NONE)
3353 seek->exact = exact;
3354 if (seek->type == MPSEEK_ABSOLUTE)
3355 return;
3356 if (seek->amount == 0) {
3357 *seek = (struct seek_params){ 0 };
3358 return;
3360 seek->type = MPSEEK_RELATIVE;
3361 return;
3362 case MPSEEK_ABSOLUTE:
3363 case MPSEEK_FACTOR:
3364 *seek = (struct seek_params) {
3365 .type = type,
3366 .amount = amount,
3367 .exact = exact,
3369 return;
3370 case MPSEEK_NONE:
3371 *seek = (struct seek_params){ 0 };
3372 return;
3374 abort();
3378 double get_time_length(struct MPContext *mpctx)
3380 if (mpctx->timeline)
3381 return mpctx->timeline[mpctx->num_timeline_parts].start;
3383 struct demuxer *demuxer = mpctx->demuxer;
3384 double get_time_ans;
3385 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3386 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3387 (void *) &get_time_ans) > 0)
3388 return get_time_ans;
3390 struct sh_video *sh_video = mpctx->d_video->sh;
3391 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3392 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3393 return (double) (demuxer->movi_end - demuxer->movi_start) /
3394 (sh_video->i_bps + sh_audio->i_bps);
3395 if (sh_video && sh_video->i_bps)
3396 return (double) (demuxer->movi_end - demuxer->movi_start) /
3397 sh_video->i_bps;
3398 if (sh_audio && sh_audio->i_bps)
3399 return (double) (demuxer->movi_end - demuxer->movi_start) /
3400 sh_audio->i_bps;
3401 return 0;
3404 /* If there are timestamps from stream level then use those (for example
3405 * DVDs can have consistent times there while the MPEG-level timestamps
3406 * reset). */
3407 double get_current_time(struct MPContext *mpctx)
3409 struct demuxer *demuxer = mpctx->demuxer;
3410 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3411 return demuxer->stream_pts;
3412 struct sh_video *sh_video = demuxer->video->sh;
3413 if (sh_video)
3414 return mpctx->video_pts;
3415 double apts = playing_audio_pts(mpctx);
3416 if (apts != MP_NOPTS_VALUE)
3417 return apts;
3418 return mpctx->last_seek_pts;
3421 int get_percent_pos(struct MPContext *mpctx)
3423 struct demuxer *demuxer = mpctx->demuxer;
3424 int ans = 0;
3425 if (mpctx->timeline)
3426 ans = get_current_time(mpctx) * 100 /
3427 mpctx->timeline[mpctx->num_timeline_parts].start;
3428 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3430 else {
3431 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3432 off_t pos = demuxer->filepos > 0 ?
3433 demuxer->filepos : stream_tell(demuxer->stream);
3434 if (len > 0)
3435 ans = (pos - demuxer->movi_start) / len;
3436 else
3437 ans = 0;
3439 if (ans < 0)
3440 ans = 0;
3441 if (ans > 100)
3442 ans = 100;
3443 return ans;
3446 // -2 is no chapters, -1 is before first chapter
3447 int get_current_chapter(struct MPContext *mpctx)
3449 double current_pts = get_current_time(mpctx);
3450 if (!mpctx->chapters)
3451 return FFMAX(mpctx->last_chapter_seek,
3452 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3454 int i;
3455 for (i = 1; i < mpctx->num_chapters; i++)
3456 if (current_pts < mpctx->chapters[i].start)
3457 break;
3458 return FFMAX(mpctx->last_chapter_seek, i - 1);
3461 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3463 char *name = chapter_name(mpctx, chapter);
3464 if (name) {
3465 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3466 } else {
3467 int chapter_count = get_chapter_count(mpctx);
3468 if (chapter_count <= 0)
3469 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3470 else
3471 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3472 chapter_count);
3474 return name;
3477 // returns NULL if chapter name unavailable
3478 char *chapter_name(struct MPContext *mpctx, int chapter)
3480 if (!mpctx->chapters)
3481 return demuxer_chapter_name(mpctx->demuxer, chapter);
3482 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3485 // returns the start of the chapter in seconds
3486 double chapter_start_time(struct MPContext *mpctx, int chapter)
3488 if (!mpctx->chapters)
3489 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3490 return mpctx->chapters[chapter].start;
3493 int get_chapter_count(struct MPContext *mpctx)
3495 if (!mpctx->chapters)
3496 return demuxer_chapter_count(mpctx->demuxer);
3497 return mpctx->num_chapters;
3500 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3502 mpctx->last_chapter_seek = -2;
3503 if (!mpctx->chapters) {
3504 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3505 if (res >= 0) {
3506 if (*seek_pts == -1)
3507 seek_reset(mpctx, true);
3508 else {
3509 mpctx->last_chapter_seek = res;
3510 mpctx->last_chapter_pts = *seek_pts;
3513 return res;
3516 if (chapter >= mpctx->num_chapters)
3517 return -1;
3518 if (chapter < 0)
3519 chapter = 0;
3520 *seek_pts = mpctx->chapters[chapter].start;
3521 mpctx->last_chapter_seek = chapter;
3522 mpctx->last_chapter_pts = *seek_pts;
3523 return chapter;
3527 static void run_playloop(struct MPContext *mpctx)
3529 struct MPOpts *opts = &mpctx->opts;
3530 float aq_sleep_time = 0;
3531 bool full_audio_buffers = false;
3533 if (opts->chapterrange[1] > 0) {
3534 int cur_chapter = get_current_chapter(mpctx);
3535 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3536 mpctx->stop_play = PT_NEXT_ENTRY;
3539 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3540 mpctx->sh_audio = mpctx->d_audio->sh;
3541 mpctx->sh_audio->ds = mpctx->d_audio;
3542 reinit_audio_chain(mpctx);
3545 /*========================== PLAY AUDIO ============================*/
3547 if (!mpctx->sh_video)
3548 mpctx->restart_playback = false;
3550 if (mpctx->sh_audio && !mpctx->restart_playback) {
3551 int status = fill_audio_out_buffers(mpctx);
3552 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3553 if (status == -2)
3554 // at eof, all audio at least written to ao
3555 if (!mpctx->sh_video)
3556 mpctx->stop_play = AT_END_OF_FILE;
3560 if (!mpctx->sh_video) {
3561 if (mpctx->step_frames) {
3562 mpctx->step_frames = 0;
3563 pause_player(mpctx);
3565 // handle audio-only case:
3566 double a_pos = 0, a_buf = 0;
3567 // sh_audio can be NULL due to video stream switching
3568 // TODO: handle this better
3569 if (mpctx->sh_audio) {
3570 a_buf = ao_get_delay(mpctx->ao);
3571 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3572 a_buf;
3575 print_status(mpctx, a_pos, false);
3577 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3578 update_osd_msg(mpctx);
3579 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3580 mpctx->stop_play = AT_END_OF_FILE;
3581 else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3582 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3583 && mpctx->sh_audio) {
3584 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3585 if (!opts->gapless_audio && p->source != (p + 1)->source
3586 && a_buf > 0.05) {
3587 mpctx->stop_play = KEEP_PLAYING;
3588 mp_input_get_cmd(mpctx->input, (a_buf - .05) * 1000, true);
3589 } else {
3590 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3591 .amount = (p + 1)->start },
3592 true);
3594 } else if (!mpctx->stop_play) {
3595 int sleep_time = 100;
3596 if (mpctx->sh_audio) {
3597 if (mpctx->ao->untimed)
3598 sleep_time = 0;
3599 else if (full_audio_buffers)
3600 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3601 else
3602 sleep_time = 20;
3603 sleep_time = FFMIN(sleep_time, 100);
3605 mp_input_get_cmd(mpctx->input, sleep_time, true);
3607 } else {
3609 /*========================== PLAY VIDEO ============================*/
3611 vo_pts = mpctx->sh_video->timer * 90000.0;
3612 vo_fps = mpctx->sh_video->fps;
3614 bool blit_frame = mpctx->video_out->frame_loaded;
3615 if (!blit_frame || mpctx->hrseek_active) {
3616 double frame_time = update_video(mpctx);
3617 blit_frame = mpctx->video_out->frame_loaded;
3618 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3619 if (mpctx->sh_video->vf_initialized < 0) {
3620 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3621 "\nFATAL: Could not initialize video filters (-vf) "
3622 "or video output (-vo).\n");
3623 mpctx->stop_play = PT_NEXT_ENTRY;
3624 return;
3626 if (frame_time < 0)
3627 mpctx->stop_play = AT_END_OF_FILE;
3628 else if (!mpctx->restart_playback) {
3629 mpctx->time_frame += frame_time / opts->playback_speed;
3630 adjust_sync(mpctx, frame_time);
3633 if (mpctx->timeline) {
3634 struct timeline_part *next =
3635 mpctx->timeline + mpctx->timeline_part + 1;
3636 if (mpctx->sh_video->pts >= next->start
3637 || mpctx->stop_play == AT_END_OF_FILE
3638 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3639 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3640 .amount = next->start },
3641 true);
3642 return;
3646 // ================================================================
3648 current_module = "vo_check_events";
3649 vo_check_events(mpctx->video_out);
3651 #ifdef CONFIG_X11
3652 if (stop_xscreensaver) {
3653 current_module = "stop_xscreensaver";
3654 xscreensaver_heartbeat(mpctx->x11_state);
3656 #endif
3657 if (heartbeat_cmd) {
3658 static unsigned last_heartbeat;
3659 unsigned now = GetTimerMS();
3660 if (now - last_heartbeat > 30000) {
3661 last_heartbeat = now;
3662 system(heartbeat_cmd);
3666 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3667 &mpctx->time_frame,
3668 full_audio_buffers,
3669 &aq_sleep_time);
3671 //=================== FLIP PAGE (VIDEO BLT): ======================
3673 current_module = "flip_page";
3674 if (!frame_time_remaining && blit_frame) {
3675 struct sh_video *sh_video = mpctx->sh_video;
3676 mpctx->video_pts = sh_video->pts;
3677 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3678 update_teletext(sh_video, mpctx->demuxer, 0);
3679 update_osd_msg(mpctx);
3680 struct vf_instance *vf = sh_video->vfilter;
3681 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3682 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3683 vo_osd_changed(0);
3685 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3686 aq_sleep_time += mpctx->time_frame;
3687 // flag 256 means: libvo driver does its timing (dvb card)
3688 if (mpctx->time_frame > 0.001
3689 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3690 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3691 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3693 unsigned int t2 = GetTimer();
3694 /* Playing with playback speed it's possible to get pathological
3695 * cases with mpctx->time_frame negative enough to cause an
3696 * overflow in pts_us calculation, thus the FFMAX. */
3697 double time_frame = FFMAX(mpctx->time_frame, -1);
3698 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3699 int duration = -1;
3700 double pts2 = mpctx->video_out->next_pts2;
3701 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3702 && !mpctx->restart_playback) {
3703 // expected A/V sync correction is ignored
3704 double diff = (pts2 - mpctx->video_pts);
3705 diff /= opts->playback_speed;
3706 if (mpctx->time_frame < 0)
3707 diff += mpctx->time_frame;
3708 if (diff < 0)
3709 diff = 0;
3710 if (diff > 10)
3711 diff = 10;
3712 duration = diff * 1e6;
3714 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3716 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3717 vout_time_usage += mpctx->last_vo_flip_duration;
3718 if (mpctx->video_out->driver->flip_page_timed) {
3719 // No need to adjust sync based on flip speed
3720 mpctx->last_vo_flip_duration = 0;
3721 // For print_status - VO call finishing early is OK for sync
3722 mpctx->time_frame -= get_relative_time(mpctx);
3724 if (mpctx->restart_playback) {
3725 mpctx->syncing_audio = true;
3726 if (mpctx->sh_audio)
3727 fill_audio_out_buffers(mpctx);
3728 mpctx->restart_playback = false;
3729 mpctx->time_frame = 0;
3730 get_relative_time(mpctx);
3732 print_status(mpctx, MP_NOPTS_VALUE, true);
3733 screenshot_flip(mpctx);
3734 } else
3735 print_status(mpctx, MP_NOPTS_VALUE, false);
3737 if (opts->auto_quality > 0) {
3738 current_module = "autoq";
3739 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3740 ++output_quality;
3741 else if (output_quality > 1 && aq_sleep_time < 0)
3742 --output_quality;
3743 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3744 output_quality = 0;
3745 set_video_quality(mpctx->sh_video, output_quality);
3748 if (!frame_time_remaining && blit_frame) {
3749 if (play_n_frames >= 0) {
3750 --play_n_frames;
3751 if (play_n_frames <= 0)
3752 mpctx->stop_play = PT_NEXT_ENTRY;
3754 if (mpctx->step_frames > 0) {
3755 mpctx->step_frames--;
3756 if (mpctx->step_frames == 0)
3757 pause_player(mpctx);
3761 // FIXME: add size based support for -endpos
3762 if (end_at.type == END_AT_TIME &&
3763 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3764 mpctx->stop_play = PT_NEXT_ENTRY;
3766 } // end if(mpctx->sh_video)
3768 #ifdef CONFIG_DVDNAV
3769 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3770 nav_highlight_t hl;
3771 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3772 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3773 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3774 vo_osd_changed(OSDTYPE_DVDNAV);
3775 } else {
3776 osd_set_nav_box(0, 0, 0, 0);
3777 vo_osd_changed(OSDTYPE_DVDNAV);
3778 vo_osd_changed(OSDTYPE_SPU);
3781 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3782 double ar = -1.0;
3783 if (mpctx->sh_video &&
3784 stream_control(mpctx->demuxer->stream,
3785 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3786 != STREAM_UNSUPPORTED)
3787 mpctx->sh_video->stream_aspect = ar;
3790 #endif
3792 //================= Keyboard events, SEEKing ====================
3794 current_module = "key_events";
3796 while (1) {
3797 mp_cmd_t *cmd;
3798 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3799 /* Allow running consecutive seek commands to combine them,
3800 * but execute the seek before running other commands.
3801 * If the user seeks continuously (keeps arrow key down)
3802 * try to finish showing a frame from one location before doing
3803 * another seek (which could lead to unchanging display). */
3804 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3805 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3806 && GetTimerMS() - mpctx->start_timestamp < 300)
3807 break;
3808 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3809 run_command(mpctx, cmd);
3810 mp_cmd_free(cmd);
3811 if (mpctx->stop_play)
3812 break;
3814 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3815 || mpctx->restart_playback)
3816 break;
3817 if (mpctx->sh_video) {
3818 update_osd_msg(mpctx);
3819 int hack = vo_osd_changed(0);
3820 vo_osd_changed(hack);
3821 if (hack) {
3822 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3823 add_step_frame(mpctx);
3824 break;
3825 } else
3826 vo_osd_changed(0);
3829 pause_loop(mpctx);
3832 // handle -sstep
3833 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3834 mpctx->osd_function = OSD_FFW;
3835 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3838 edl_update(mpctx);
3840 /* Looping. */
3841 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3842 mpctx->stop_play == PT_NEXT_ENTRY)) {
3843 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3845 if (opts->loop_times > 1)
3846 opts->loop_times--;
3847 else if (opts->loop_times == 1)
3848 opts->loop_times = -1;
3849 play_n_frames = play_n_frames_mf;
3850 mpctx->stop_play = 0;
3851 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3854 if (mpctx->seek.type) {
3855 seek(mpctx, mpctx->seek, false);
3856 mpctx->seek = (struct seek_params){ 0 };
3861 static int read_keys(void *ctx, int fd)
3863 getch2(ctx);
3864 return MP_INPUT_NOTHING;
3867 static bool attachment_is_font(struct demux_attachment *att)
3869 if (!att->name || !att->type || !att->data || !att->data_size)
3870 return false;
3871 // match against MIME types
3872 if (strcmp(att->type, "application/x-truetype-font") == 0
3873 || strcmp(att->type, "application/x-font") == 0)
3874 return true;
3875 // fallback: match against file extension
3876 if (strlen(att->name) > 4) {
3877 char *ext = att->name + strlen(att->name) - 4;
3878 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3879 || strcasecmp(ext, ".otf") == 0)
3880 return true;
3882 return false;
3885 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3887 if (audio_id == -1)
3888 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3889 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3890 demuxer_switch_audio(demuxer, audio_id);
3891 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3892 demuxer->audio->id = -2;
3893 demuxer->audio->sh = NULL;
3895 return demuxer->audio->id;
3898 static void print_version(const char *name)
3900 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3902 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3903 GetCpuCaps(&gCpuCaps);
3904 #if ARCH_X86
3905 mp_msg(MSGT_CPLAYER, MSGL_V,
3906 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3907 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3908 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3909 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3910 #if CONFIG_RUNTIME_CPUDETECT
3911 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3912 #else
3913 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3914 if (HAVE_MMX)
3915 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3916 if (HAVE_MMX2)
3917 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3918 if (HAVE_AMD3DNOW)
3919 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3920 if (HAVE_AMD3DNOWEXT)
3921 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3922 if (HAVE_SSE)
3923 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3924 if (HAVE_SSE2)
3925 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3926 if (HAVE_SSSE3)
3927 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3928 if (HAVE_CMOV)
3929 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3930 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3931 #endif /* CONFIG_RUNTIME_CPUDETECT */
3932 #endif /* ARCH_X86 */
3933 print_libav_versions();
3936 #ifdef PTW32_STATIC_LIB
3937 static void detach_ptw32(void)
3939 pthread_win32_thread_detach_np();
3940 pthread_win32_process_detach_np();
3942 #endif
3944 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3945 * file for some tools to link against. */
3946 #ifndef DISABLE_MAIN
3947 int main(int argc, char *argv[])
3949 #ifdef PTW32_STATIC_LIB
3950 pthread_win32_process_attach_np();
3951 pthread_win32_thread_attach_np();
3952 atexit(detach_ptw32);
3953 #endif
3954 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3955 || !strcmp(argv[1], "--leak-report")))
3956 talloc_enable_leak_report();
3958 char *mem_ptr;
3960 // movie info:
3962 /* Flag indicating whether MPlayer should exit without playing anything. */
3963 int opt_exit = 0;
3964 int i;
3966 struct MPContext *mpctx = talloc(NULL, MPContext);
3967 *mpctx = (struct MPContext){
3968 .osd_function = OSD_PLAY,
3969 .begin_skip = MP_NOPTS_VALUE,
3970 .play_tree_step = 1,
3971 .global_sub_pos = -1,
3972 .set_of_sub_pos = -1,
3973 .file_format = DEMUXER_TYPE_UNKNOWN,
3974 .last_dvb_step = 1,
3977 InitTimer();
3978 srand(GetTimerMS());
3980 mp_msg_init();
3981 init_libav();
3983 #ifdef CONFIG_X11
3984 mpctx->x11_state = vo_x11_init_state();
3985 #endif
3986 struct MPOpts *opts = &mpctx->opts;
3987 set_default_mplayer_options(opts);
3988 // Create the config context and register the options
3989 mpctx->mconfig = m_config_new(opts, cfg_include);
3990 m_config_register_options(mpctx->mconfig, mplayer_opts);
3991 m_config_register_options(mpctx->mconfig, common_opts);
3992 mp_input_register_options(mpctx->mconfig);
3994 // Preparse the command line
3995 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
3997 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3998 set_path_env();
3999 #endif
4001 #ifdef CONFIG_TV
4002 stream_tv_defaults.immediate = 1;
4003 #endif
4005 parse_cfgfiles(mpctx, mpctx->mconfig);
4007 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
4008 if (mpctx->playtree == NULL)
4009 opt_exit = 1;
4010 else {
4011 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
4012 if (mpctx->playtree) {
4013 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4014 mpctx->mconfig);
4015 if (mpctx->playtree_iter) {
4016 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4017 PLAY_TREE_ITER_ENTRY) {
4018 play_tree_iter_free(mpctx->playtree_iter);
4019 mpctx->playtree_iter = NULL;
4021 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
4027 print_version("MPlayer2");
4029 #if defined(__MINGW32__) || defined(__CYGWIN__)
4031 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
4032 BOOL WINAPI (*setDEP)(DWORD) = NULL;
4033 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
4034 if (kernel32) {
4035 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
4036 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
4038 if (setDEP)
4039 setDEP(3);
4040 if (setDllDir)
4041 setDllDir("");
4043 // stop Windows from showing all kinds of annoying error dialogs
4044 SetErrorMode(0x8003);
4045 // request 1ms timer resolution
4046 timeBeginPeriod(1);
4047 #endif
4049 #ifdef CONFIG_PRIORITY
4050 set_priority();
4051 #endif
4053 if (opts->video_driver_list &&
4054 strcmp(opts->video_driver_list[0], "help") == 0) {
4055 list_video_out();
4056 opt_exit = 1;
4059 if (opts->audio_driver_list &&
4060 strcmp(opts->audio_driver_list[0], "help") == 0) {
4061 list_audio_out();
4062 opt_exit = 1;
4065 /* Check codecs.conf. */
4066 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4067 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4068 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4069 if (!parse_codec_cfg(NULL))
4070 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4071 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4072 "Using built-in default codecs.conf.\n");
4075 free(mem_ptr); // release the buffer created by get_path()
4078 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4079 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4080 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4081 list_codecs(1);
4082 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4083 opt_exit = 1;
4085 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4086 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4087 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4088 list_codecs(0);
4089 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4090 opt_exit = 1;
4092 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4093 vfm_help();
4094 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4095 opt_exit = 1;
4097 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4098 afm_help();
4099 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4100 opt_exit = 1;
4102 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4103 af_help();
4104 printf("\n");
4105 opt_exit = 1;
4107 #ifdef CONFIG_X11
4108 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4109 fstype_help();
4110 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4111 opt_exit = 1;
4113 #endif
4114 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4115 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4116 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4117 demuxer_help();
4118 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4119 opt_exit = 1;
4121 if (opts->list_properties) {
4122 property_print_help();
4123 opt_exit = 1;
4126 if (opt_exit)
4127 exit_player(mpctx, EXIT_NONE);
4129 if (!mpctx->filename && !opts->player_idle_mode) {
4130 // no file/vcd/dvd -> show HELP:
4131 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4132 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4135 /* Display what configure line was used */
4136 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4138 // Many users forget to include command line in bugreports...
4139 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4140 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4141 for (i = 1; i < argc; i++)
4142 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4143 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4146 //------ load global data first ------
4148 mpctx->osd = osd_create();
4150 // check font
4151 #ifdef CONFIG_FREETYPE
4152 init_freetype();
4153 #endif
4154 #ifdef CONFIG_FONTCONFIG
4155 if (font_fontconfig <= 0) {
4156 #endif
4157 #ifdef CONFIG_BITMAP_FONT
4158 if (font_name) {
4159 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4160 if (!vo_font)
4161 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4162 filename_recode(font_name));
4163 } else {
4164 // try default:
4165 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4166 font_factor, verbose > 1);
4167 free(mem_ptr); // release the buffer created by get_path()
4168 if (!vo_font)
4169 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4170 font_factor, verbose > 1);
4172 if (sub_font_name)
4173 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4174 verbose > 1);
4175 else
4176 mpctx->osd->sub_font = vo_font;
4177 #endif
4178 #ifdef CONFIG_FONTCONFIG
4180 #endif
4182 #ifdef CONFIG_ASS
4183 mpctx->ass_library = mp_ass_init(opts);
4184 mpctx->osd->ass_library = mpctx->ass_library;
4185 #endif
4187 #ifdef HAVE_RTC
4188 if (opts->rtc) {
4189 char *rtc_device = opts->rtc_device;
4190 // seteuid(0); /* Can't hurt to try to get root here */
4191 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4192 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4193 "(it should be readable by the user.)\n",
4194 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4195 else {
4196 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4198 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4199 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4200 "ioctl (rtc_irqp_set %lu): %s\n",
4201 irqp, strerror(errno));
4202 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4203 close(rtc_fd);
4204 rtc_fd = -1;
4205 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4206 /* variable only by the root */
4207 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4208 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4209 close(rtc_fd);
4210 rtc_fd = -1;
4211 } else
4212 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4213 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4216 if (rtc_fd < 0)
4217 #endif /* HAVE_RTC */
4218 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4219 opts->softsleep ? "software" : timer_name);
4221 #ifdef HAVE_TERMCAP
4222 load_termcap(NULL); // load key-codes
4223 #endif
4225 // ========== Init keyboard FIFO (connection to libvo) ============
4227 // Init input system
4228 current_module = "init_input";
4229 mpctx->input = mp_input_init(&opts->input);
4230 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4231 if (slave_mode)
4232 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4233 else if (opts->consolecontrols)
4234 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4235 // Set the libstream interrupt callback
4236 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4238 current_module = NULL;
4240 /// Catch signals
4241 #ifndef __MINGW32__
4242 signal(SIGCHLD, child_sighandler);
4243 #endif
4245 #ifdef CONFIG_CRASH_DEBUG
4246 prog_path = argv[0];
4247 #endif
4248 //========= Catch terminate signals: ================
4249 // terminate requests:
4250 signal(SIGTERM, exit_sighandler); // kill
4251 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4253 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4255 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4256 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4257 #ifdef CONFIG_SIGHANDLER
4258 // fatal errors:
4259 signal(SIGBUS, exit_sighandler); // bus error
4260 signal(SIGSEGV, exit_sighandler); // segfault
4261 signal(SIGILL, exit_sighandler); // illegal instruction
4262 signal(SIGFPE, exit_sighandler); // floating point exc.
4263 signal(SIGABRT, exit_sighandler); // abort()
4264 #ifdef CONFIG_CRASH_DEBUG
4265 if (crash_debug)
4266 signal(SIGTRAP, exit_sighandler);
4267 #endif
4268 #endif
4270 // ***************** Now, let's see the per-file stuff ******************
4272 play_next_file:
4274 // init global sub numbers
4275 mpctx->global_sub_size = 0;
4276 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4278 if (mpctx->filename) {
4279 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4280 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4281 load_per_file_config(mpctx->mconfig, mpctx->filename);
4284 if (opts->video_driver_list)
4285 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4286 opts->video_driver_list[0]);
4287 if (opts->audio_driver_list)
4288 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4289 opts->audio_driver_list[0]);
4291 // We must enable getch2 here to be able to interrupt network connection
4292 // or cache filling
4293 if (opts->consolecontrols && !slave_mode) {
4294 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4295 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4296 "WARNING: getch2_init called twice!\n");
4297 else
4298 getch2_enable(); // prepare stdin for hotkeys...
4299 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4300 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4303 // ================= GUI idle loop (STOP state) =========================
4304 while (opts->player_idle_mode && !mpctx->filename) {
4305 play_tree_t *entry = NULL;
4306 mp_cmd_t *cmd;
4307 if (mpctx->video_out && mpctx->video_out->config_ok)
4308 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4309 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4310 if (mpctx->video_out)
4311 vo_check_events(mpctx->video_out);
4312 usec_sleep(20000);
4314 switch (cmd->id) {
4315 case MP_CMD_LOADFILE:
4316 // prepare a tree entry with the new filename
4317 entry = play_tree_new();
4318 play_tree_add_file(entry, cmd->args[0].v.s);
4319 // The entry is added to the main playtree after the switch().
4320 break;
4321 case MP_CMD_LOADLIST:
4322 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4323 break;
4324 case MP_CMD_QUIT:
4325 exit_player_with_rc(mpctx, EXIT_QUIT,
4326 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4327 break;
4328 case MP_CMD_VO_FULLSCREEN:
4329 case MP_CMD_GET_PROPERTY:
4330 case MP_CMD_SET_PROPERTY:
4331 case MP_CMD_STEP_PROPERTY:
4332 run_command(mpctx, cmd);
4333 break;
4336 mp_cmd_free(cmd);
4338 if (entry) { // user entered a command that gave a valid entry
4339 if (mpctx->playtree)
4340 // the playtree is always a node with one child. let's clear it
4341 play_tree_free_list(mpctx->playtree->child, 1);
4342 else
4343 // .. or make a brand new playtree
4344 mpctx->playtree = play_tree_new();
4346 if (!mpctx->playtree)
4347 continue; // couldn't make playtree! wait for next command
4349 play_tree_set_child(mpctx->playtree, entry);
4351 /* Make iterator start at the top the of tree. */
4352 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4353 mpctx->mconfig);
4354 if (!mpctx->playtree_iter)
4355 continue;
4357 // find the first real item in the tree
4358 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4359 PLAY_TREE_ITER_ENTRY) {
4360 // no items!
4361 play_tree_iter_free(mpctx->playtree_iter);
4362 mpctx->playtree_iter = NULL;
4363 continue; // wait for next command
4365 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4369 #ifdef CONFIG_ASS
4370 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4371 #endif
4372 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4373 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4375 if (mpctx->filename) {
4376 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4377 filename_recode(mpctx->filename));
4378 if (use_filename_title && opts->vo_wintitle == NULL)
4379 opts->vo_wintitle = talloc_strdup(NULL,
4380 mp_basename(mpctx->filename));
4383 if (edl_filename) {
4384 if (edl_records)
4385 free_edl(edl_records);
4386 next_edl_record = edl_records = edl_parse_file();
4388 if (edl_output_filename) {
4389 if (edl_fd)
4390 fclose(edl_fd);
4391 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4392 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4393 "Can't open EDL file [%s] for writing.\n",
4394 filename_recode(edl_output_filename));
4398 //==================== Open VOB-Sub ============================
4400 current_module = "vobsub";
4401 if (opts->vobsub_name) {
4402 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4403 if (vo_vobsub == NULL)
4404 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4405 filename_recode(opts->vobsub_name));
4406 } else if (opts->sub_auto && mpctx->filename) {
4407 char **vob = find_vob_subtitles(opts, mpctx->filename);
4408 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4409 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4410 if (vo_vobsub)
4411 break;
4413 talloc_free(vob);
4415 if (vo_vobsub) {
4416 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4417 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4418 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4419 mpctx);
4421 // setup global sub numbering
4422 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4423 vobsub_get_indexes_count(vo_vobsub);
4426 //============ Open & Sync STREAM --- fork cache2 ====================
4428 mpctx->stream = NULL;
4429 mpctx->demuxer = NULL;
4430 mpctx->d_audio = NULL;
4431 mpctx->d_video = NULL;
4432 mpctx->d_sub = NULL;
4433 mpctx->sh_audio = NULL;
4434 mpctx->sh_video = NULL;
4436 current_module = "open_stream";
4437 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4438 if (!mpctx->stream) { // error...
4439 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4440 goto goto_next_file;
4442 mpctx->initialized_flags |= INITIALIZED_STREAM;
4444 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4445 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4446 "playlist support will not be used automatically.\n"
4447 "MPlayer's playlist code is unsafe and should only be used with "
4448 "trusted sources.\nPlayback will probably fail.\n\n");
4449 #if 0
4450 play_tree_t *entry;
4451 // Handle playlist
4452 current_module = "handle_playlist";
4453 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4454 filename_recode(mpctx->filename));
4455 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4456 mpctx->eof = playtree_add_playlist(mpctx, entry);
4457 goto goto_next_file;
4458 #endif
4460 mpctx->stream->start_pos += seek_to_byte;
4462 if (stream_dump_type == 5) {
4463 unsigned char buf[4096];
4464 int len;
4465 FILE *f;
4466 current_module = "dumpstream";
4467 stream_reset(mpctx->stream);
4468 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4469 f = fopen(opts->stream_dump_name, "wb");
4470 if (!f) {
4471 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4472 exit_player(mpctx, EXIT_ERROR);
4474 if (opts->chapterrange[0] > 1) {
4475 int chapter = opts->chapterrange[0] - 1;
4476 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4478 struct stream_dump_progress info;
4479 stream_dump_progress_start(&info);
4480 while (!mpctx->stream->eof && !async_quit_request) {
4481 len = stream_read(mpctx->stream, buf, 4096);
4482 if (len > 0) {
4483 if (fwrite(buf, len, 1, f) != 1) {
4484 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4485 exit_player(mpctx, EXIT_ERROR);
4488 stream_dump_progress(&info, len, mpctx->stream);
4489 if (opts->chapterrange[1] > 0) {
4490 int chapter = -1;
4491 if (stream_control(mpctx->stream,
4492 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4493 && chapter + 1 > opts->chapterrange[1])
4494 break;
4497 if (fclose(f)) {
4498 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4499 opts->stream_dump_name);
4500 exit_player(mpctx, EXIT_ERROR);
4502 stream_dump_progress_end(&info, opts->stream_dump_name);
4503 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4504 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4507 #ifdef CONFIG_DVDREAD
4508 if (mpctx->stream->type == STREAMTYPE_DVD) {
4509 current_module = "dvd lang->id";
4510 if (opts->audio_lang && opts->audio_id == -1)
4511 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4512 if (opts->sub_lang && opts->sub_id == -1)
4513 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4514 // setup global sub numbering
4515 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4516 current_module = NULL;
4518 #endif
4520 #ifdef CONFIG_DVDNAV
4521 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4522 current_module = "dvdnav lang->id";
4523 if (opts->audio_lang && opts->audio_id == -1)
4524 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4525 opts->audio_lang);
4526 dvdsub_lang_id = -3;
4527 if (opts->sub_lang && opts->sub_id == -1)
4528 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4529 mpctx->stream, opts->sub_lang);
4530 // setup global sub numbering
4531 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4532 mpctx->stream);
4533 current_module = NULL;
4535 #endif
4537 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4538 goto_enable_cache:
4539 if (stream_cache_size > 0) {
4540 int res;
4541 float stream_cache_min_percent = opts->stream_cache_min_percent;
4542 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4543 current_module = "enable_cache";
4544 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4545 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4546 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4547 if (res == 0)
4548 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4549 goto goto_next_file;
4552 //============ Open DEMUXERS --- DETECT file type =======================
4553 current_module = "demux_open";
4555 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4556 opts->audio_id, opts->video_id, opts->sub_id,
4557 mpctx->filename);
4559 // HACK to get MOV Reference Files working
4561 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4562 unsigned char *playlist_entry;
4563 play_tree_t *list = NULL, *entry = NULL;
4565 current_module = "handle_demux_playlist";
4566 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4567 char *temp;
4568 const char *bname;
4570 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4571 filename_recode(playlist_entry));
4573 bname = mp_basename(playlist_entry);
4574 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4575 !strncmp(bname + 3, "gateQT", 6))
4576 continue;
4578 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4579 continue;
4581 entry = play_tree_new();
4583 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4584 playlist_entry)) { // add reference path of current file
4585 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4586 mpctx->filename)) + strlen(playlist_entry) + 1));
4587 if (temp) {
4588 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4589 strlen(mp_basename(mpctx->filename)));
4590 temp[strlen(mpctx->filename) - strlen(mp_basename(
4591 mpctx->filename))] = '\0';
4592 strcat(temp, playlist_entry);
4593 if (!strcmp(temp, mpctx->filename)) {
4594 free(temp);
4595 continue;
4597 play_tree_add_file(entry, temp);
4598 mp_msg(MSGT_CPLAYER, MSGL_V,
4599 "Resolving reference to %s.\n", temp);
4600 free(temp);
4602 } else
4603 play_tree_add_file(entry, playlist_entry);
4605 if (!list)
4606 list = entry;
4607 else
4608 play_tree_append_entry(list, entry);
4610 free_demuxer(mpctx->demuxer);
4611 mpctx->demuxer = NULL;
4613 if (list) {
4614 entry = play_tree_new();
4615 play_tree_set_child(entry, list);
4616 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4617 goto goto_next_file;
4621 if (!mpctx->demuxer) {
4622 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4623 goto goto_next_file;
4626 if (mpctx->demuxer->matroska_data.ordered_chapters)
4627 build_ordered_chapter_timeline(mpctx);
4629 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4630 build_edl_timeline(mpctx);
4632 if (mpctx->timeline) {
4633 mpctx->timeline_part = 0;
4634 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4636 int part_count = mpctx->num_timeline_parts;
4637 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4638 "sources. Total length %.3f seconds.\n", part_count,
4639 mpctx->num_sources, mpctx->timeline[part_count].start);
4640 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4641 for (int i = 0; i < mpctx->num_sources; i++)
4642 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4643 filename_recode(mpctx->sources[i].demuxer->filename));
4644 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4645 "source_start, source):\n");
4646 for (int i = 0; i < part_count; i++) {
4647 struct timeline_part *p = mpctx->timeline + i;
4648 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4649 p->source_start, p->source - mpctx->sources);
4651 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4652 mpctx->timeline[part_count].start);
4655 if (!mpctx->sources) {
4656 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4657 *mpctx->sources = (struct content_source){
4658 .stream = mpctx->stream,
4659 .demuxer = mpctx->demuxer
4661 mpctx->num_sources = 1;
4664 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4666 #ifdef CONFIG_ASS
4667 if (opts->ass_enabled && mpctx->ass_library) {
4668 for (int j = 0; j < mpctx->num_sources; j++) {
4669 struct demuxer *d = mpctx->sources[j].demuxer;
4670 for (int i = 0; i < d->num_attachments; i++) {
4671 struct demux_attachment *att = d->attachments + i;
4672 if (opts->use_embedded_fonts && attachment_is_font(att))
4673 ass_add_font(mpctx->ass_library, att->name, att->data,
4674 att->data_size);
4678 #endif
4680 current_module = "demux_open2";
4682 mpctx->d_audio = mpctx->demuxer->audio;
4683 mpctx->d_video = mpctx->demuxer->video;
4684 mpctx->d_sub = mpctx->demuxer->sub;
4686 if (ts_prog) {
4687 int tmp = ts_prog;
4688 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4690 // select audio stream
4691 for (int i = 0; i < mpctx->num_sources; i++)
4692 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4693 opts->audio_lang);
4695 // DUMP STREAMS:
4696 if ((stream_dump_type) && (stream_dump_type < 4)) {
4697 FILE *f;
4698 demux_stream_t *ds = NULL;
4699 current_module = "dump";
4700 // select stream to dump
4701 switch (stream_dump_type) {
4702 case 1: ds = mpctx->d_audio;
4703 break;
4704 case 2: ds = mpctx->d_video;
4705 break;
4706 case 3: ds = mpctx->d_sub;
4707 break;
4709 if (!ds) {
4710 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4711 "dump: FATAL: Selected stream missing!\n");
4712 exit_player(mpctx, EXIT_ERROR);
4714 // disable other streams:
4715 if (mpctx->d_audio && mpctx->d_audio != ds) {
4716 ds_free_packs(mpctx->d_audio);
4717 mpctx->d_audio->id = -2;
4719 if (mpctx->d_video && mpctx->d_video != ds) {
4720 ds_free_packs(mpctx->d_video);
4721 mpctx->d_video->id = -2;
4723 if (mpctx->d_sub && mpctx->d_sub != ds) {
4724 ds_free_packs(mpctx->d_sub);
4725 mpctx->d_sub->id = -2;
4727 // let's dump it!
4728 f = fopen(opts->stream_dump_name, "wb");
4729 if (!f) {
4730 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4731 exit_player(mpctx, EXIT_ERROR);
4733 struct stream_dump_progress info;
4734 stream_dump_progress_start(&info);
4735 while (!ds->eof) {
4736 unsigned char *start;
4737 int in_size = ds_get_packet(ds, &start);
4738 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4739 && stream_dump_type == 2)
4740 fwrite(&in_size, 1, 4, f);
4741 if (in_size > 0) {
4742 fwrite(start, in_size, 1, f);
4743 stream_dump_progress(&info, in_size, mpctx->stream);
4745 if (opts->chapterrange[1] > 0) {
4746 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4747 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4748 break;
4751 fclose(f);
4752 stream_dump_progress_end(&info, opts->stream_dump_name);
4753 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4754 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4757 mpctx->sh_audio = mpctx->d_audio->sh;
4758 mpctx->sh_video = mpctx->d_video->sh;
4760 if (mpctx->sh_video) {
4761 current_module = "video_read_properties";
4762 if (!video_read_properties(mpctx->sh_video)) {
4763 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4764 mpctx->sh_video = mpctx->d_video->sh = NULL;
4765 } else {
4766 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4767 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4768 mpctx->demuxer->file_format, mpctx->sh_video->format,
4769 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4770 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4771 if (force_fps) {
4772 mpctx->sh_video->fps = force_fps;
4773 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4775 vo_fps = mpctx->sh_video->fps;
4777 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4778 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4779 "header or invalid, use the -fps option.\n");
4785 if (!mpctx->sh_video && !mpctx->sh_audio) {
4786 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4787 #ifdef CONFIG_DVBIN
4788 if (mpctx->stream->type == STREAMTYPE_DVB) {
4789 int dir;
4790 int v = mpctx->last_dvb_step;
4791 if (v > 0)
4792 dir = DVB_CHANNEL_HIGHER;
4793 else
4794 dir = DVB_CHANNEL_LOWER;
4796 if (dvb_step_channel(mpctx->stream, dir)) {
4797 mpctx->stop_play = PT_NEXT_ENTRY;
4798 mpctx->dvbin_reopen = 1;
4801 #endif
4802 goto goto_next_file; // exit_player(_("Fatal error"));
4805 /* display clip info */
4806 demux_info_print(mpctx->demuxer);
4808 //================= Read SUBTITLES (DVD & TEXT) =========================
4809 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4810 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4811 init_vo_spudec(mpctx);
4813 // after reading video params we should load subtitles because
4814 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4815 // check .sub
4816 current_module = "read_subtitles_file";
4817 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4818 if (opts->sub_name) {
4819 for (i = 0; opts->sub_name[i] != NULL; ++i)
4820 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4822 if (opts->sub_auto) { // auto load sub file ...
4823 char **tmp = find_text_subtitles(opts, mpctx->filename);
4824 int nsub = MP_TALLOC_ELEMS(tmp);
4825 for (int i = 0; i < nsub; i++)
4826 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4827 talloc_free(tmp);
4829 if (mpctx->set_of_sub_size > 0)
4830 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4832 if (select_subtitle(mpctx)) {
4833 if (mpctx->subdata)
4834 switch (stream_dump_type) {
4835 case 3: list_sub_file(mpctx->subdata);
4836 break;
4837 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4838 break;
4839 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4840 break;
4841 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4842 break;
4843 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4844 break;
4845 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4846 break;
4850 print_file_properties(mpctx, mpctx->filename);
4852 reinit_video_chain(mpctx);
4853 if (mpctx->sh_video) {
4854 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4855 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4856 #ifdef CONFIG_FREETYPE
4857 force_load_font = 1;
4858 #endif
4859 } else if (!mpctx->sh_audio)
4860 goto goto_next_file;
4862 //================== MAIN: ==========================
4863 current_module = "main";
4865 if (opts->playing_msg) {
4866 char *msg = property_expand_string(mpctx, opts->playing_msg);
4867 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4868 free(msg);
4872 // Disable the term OSD in verbose mode
4873 if (verbose)
4874 opts->term_osd = 0;
4876 // Make sure old OSD does not stay around,
4877 // e.g. with -fixed-vo and same-resolution files
4878 clear_osd_msgs();
4879 update_osd_msg(mpctx);
4881 //================ SETUP AUDIO ==========================
4883 if (mpctx->sh_audio) {
4884 reinit_audio_chain(mpctx);
4885 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4886 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4887 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4890 current_module = "av_init";
4892 if (mpctx->sh_video) {
4893 mpctx->sh_video->timer = 0;
4894 if (!ignore_start)
4895 audio_delay += mpctx->sh_video->stream_delay;
4897 if (mpctx->sh_audio) {
4898 if (start_volume >= 0)
4899 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4900 if (!ignore_start)
4901 audio_delay -= mpctx->sh_audio->stream_delay;
4902 mpctx->delay = -audio_delay;
4905 if (!mpctx->sh_audio) {
4906 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4907 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4908 mpctx->d_audio->packs);
4909 ds_free_packs(mpctx->d_audio); // free buffered chunks
4911 if (!mpctx->sh_video) {
4912 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4913 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4914 mpctx->d_video->packs);
4915 ds_free_packs(mpctx->d_video);
4916 mpctx->d_video->id = -2;
4919 if (!mpctx->sh_video && !mpctx->sh_audio)
4920 goto goto_next_file;
4922 if (force_fps && mpctx->sh_video) {
4923 vo_fps = mpctx->sh_video->fps = force_fps;
4924 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4925 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4926 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4927 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4930 mp_input_set_section(mpctx->input, NULL);
4931 //TODO: add desired (stream-based) sections here
4932 if (mpctx->stream->type == STREAMTYPE_TV)
4933 mp_input_set_section(mpctx->input, "tv");
4934 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4935 mp_input_set_section(mpctx->input, "dvdnav");
4937 //==================== START PLAYING =======================
4939 if (opts->loop_times > 1)
4940 opts->loop_times--;
4941 else if (opts->loop_times == 1)
4942 opts->loop_times = -1;
4944 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4946 total_time_usage_start = GetTimer();
4947 audio_time_usage = 0;
4948 video_time_usage = 0;
4949 vout_time_usage = 0;
4950 total_frame_cnt = 0;
4951 drop_frame_cnt = 0; // fix for multifile fps benchmark
4952 play_n_frames = play_n_frames_mf;
4954 if (play_n_frames == 0) {
4955 mpctx->stop_play = PT_NEXT_ENTRY;
4956 goto goto_next_file;
4959 mpctx->time_frame = 0;
4960 mpctx->drop_message_shown = 0;
4961 mpctx->restart_playback = true;
4962 mpctx->video_pts = 0;
4963 mpctx->last_seek_pts = 0;
4964 mpctx->hrseek_active = false;
4965 mpctx->hrseek_framedrop = false;
4966 mpctx->step_frames = 0;
4967 mpctx->total_avsync_change = 0;
4968 mpctx->last_chapter_seek = -2;
4970 // If there's a timeline force an absolute seek to initialize state
4971 if (opts->seek_to_sec || mpctx->timeline) {
4972 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4973 seek(mpctx, mpctx->seek, false);
4974 end_at.pos += opts->seek_to_sec;
4976 if (opts->chapterrange[0] > 0) {
4977 double pts;
4978 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4979 && pts > -1.0) {
4980 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4981 seek(mpctx, mpctx->seek, false);
4985 if (end_at.type == END_AT_SIZE) {
4986 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4987 "Option -endpos in MPlayer does not yet support size units.\n");
4988 end_at.type = END_AT_NONE;
4991 #ifdef CONFIG_DVDNAV
4992 mp_dvdnav_context_free(mpctx);
4993 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4994 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4995 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4997 #endif
4999 mpctx->seek = (struct seek_params){ 0 };
5000 get_relative_time(mpctx); // reset current delta
5001 // Make sure VO knows current pause state
5002 if (mpctx->sh_video)
5003 vo_control(mpctx->video_out,
5004 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
5006 while (!mpctx->stop_play)
5007 run_playloop(mpctx);
5009 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
5011 #ifdef CONFIG_DVBIN
5012 if (mpctx->dvbin_reopen) {
5013 mpctx->stop_play = 0;
5014 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
5015 cache_uninit(mpctx->stream);
5016 mpctx->dvbin_reopen = 0;
5017 goto goto_enable_cache;
5019 #endif
5021 goto_next_file: // don't jump here after ao/vo/getch initialization!
5023 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
5025 if (opts->benchmark) {
5026 double tot = video_time_usage + vout_time_usage + audio_time_usage;
5027 double total_time_usage;
5028 total_time_usage_start = GetTimer() - total_time_usage_start;
5029 total_time_usage = (float)total_time_usage_start * 0.000001;
5030 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
5031 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
5032 video_time_usage, vout_time_usage, audio_time_usage,
5033 total_time_usage - tot, total_time_usage);
5034 if (total_time_usage > 0.0)
5035 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
5036 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
5037 100.0 * video_time_usage / total_time_usage,
5038 100.0 * vout_time_usage / total_time_usage,
5039 100.0 * audio_time_usage / total_time_usage,
5040 100.0 * (total_time_usage - tot) / total_time_usage,
5041 100.0);
5042 if (total_frame_cnt && frame_dropping)
5043 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
5044 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
5045 total_frame_cnt - drop_frame_cnt,
5046 (total_time_usage > 0.5) ? ((total_frame_cnt -
5047 drop_frame_cnt) / total_time_usage) : 0,
5048 drop_frame_cnt,
5049 100 * drop_frame_cnt / total_frame_cnt,
5050 total_frame_cnt,
5051 (total_time_usage > 0.5) ?
5052 (total_frame_cnt / total_time_usage) : 0);
5055 // time to uninit all, except global stuff:
5056 int uninitialize_parts = INITIALIZED_ALL;
5057 if (opts->fixed_vo)
5058 uninitialize_parts -= INITIALIZED_VO;
5059 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
5060 uninitialize_parts -= INITIALIZED_AO;
5061 uninit_player(mpctx, uninitialize_parts);
5063 if (mpctx->set_of_sub_size > 0) {
5064 current_module = "sub_free";
5065 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5066 sub_free(mpctx->set_of_subtitles[i]);
5067 #ifdef CONFIG_ASS
5068 if (mpctx->set_of_ass_tracks[i])
5069 ass_free_track(mpctx->set_of_ass_tracks[i]);
5070 #endif
5072 mpctx->set_of_sub_size = 0;
5074 mpctx->vo_sub_last = vo_sub = NULL;
5075 mpctx->subdata = NULL;
5076 #ifdef CONFIG_ASS
5077 mpctx->osd->ass_track = NULL;
5078 if (mpctx->ass_library)
5079 ass_clear_fonts(mpctx->ass_library);
5080 #endif
5082 if (!mpctx->stop_play) // In case some goto jumped here...
5083 mpctx->stop_play = PT_NEXT_ENTRY;
5085 int playtree_direction = 1;
5087 if (mpctx->stop_play == PT_NEXT_ENTRY
5088 || mpctx->stop_play == PT_PREV_ENTRY) {
5089 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5090 != PLAY_TREE_ITER_ENTRY) {
5091 play_tree_iter_free(mpctx->playtree_iter);
5092 mpctx->playtree_iter = NULL;
5094 mpctx->play_tree_step = 1;
5095 } else if (mpctx->stop_play == PT_UP_NEXT ||
5096 mpctx->stop_play == PT_UP_PREV) {
5097 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5098 if (mpctx->playtree_iter) {
5099 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5100 PLAY_TREE_ITER_ENTRY) {
5101 play_tree_iter_free(mpctx->playtree_iter);
5102 mpctx->playtree_iter = NULL;
5105 } else if (mpctx->stop_play == PT_STOP) {
5106 play_tree_iter_free(mpctx->playtree_iter);
5107 mpctx->playtree_iter = NULL;
5108 } else // NEXT PREV SRC
5109 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5111 while (mpctx->playtree_iter != NULL) {
5112 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5113 playtree_direction);
5114 if (mpctx->filename == NULL) {
5115 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5116 0) != PLAY_TREE_ITER_ENTRY) {
5117 play_tree_iter_free(mpctx->playtree_iter);
5118 mpctx->playtree_iter = NULL;
5121 } else
5122 break;
5125 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5126 if (!mpctx->playtree_iter)
5127 mpctx->filename = NULL;
5128 mpctx->stop_play = 0;
5129 goto play_next_file;
5132 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5134 return 1;
5136 #endif /* DISABLE_MAIN */