libmenu: remove OSD menu functionality (--menu)
[mplayer.git] / mplayer.c
blob55638191122a8959a8caeb398942fc4788cbffac
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"
77 #include "sub/font_load.h"
78 #include "sub/sub.h"
79 #include "ffmpeg_files/intreadwrite.h"
80 #include "sub/av_sub.h"
81 #include "libmpcodecs/dec_teletext.h"
82 #include "cpudetect.h"
83 #include "version.h"
85 #ifdef CONFIG_X11
86 #include "libvo/x11_common.h"
87 #endif
89 #include "libao2/audio_out.h"
91 #include "codec-cfg.h"
93 #include "edl.h"
95 #include "sub/spudec.h"
96 #include "sub/vobsub.h"
98 #include "osdep/getch2.h"
99 #include "osdep/timer.h"
101 #include "input/input.h"
103 int slave_mode = 0;
104 int enable_mouse_movements = 0;
105 float start_volume = -1;
107 #include "osdep/priority.h"
109 char *heartbeat_cmd;
111 #ifdef HAVE_RTC
112 #ifdef __linux__
113 #include <linux/rtc.h>
114 #else
115 #include <rtc.h>
116 #define RTC_IRQP_SET RTCIO_IRQP_SET
117 #define RTC_PIE_ON RTCIO_PIE_ON
118 #endif /* __linux__ */
119 #endif /* HAVE_RTC */
121 #include "stream/tv.h"
122 #include "stream/stream_radio.h"
123 #ifdef CONFIG_DVBIN
124 #include "stream/dvbin.h"
125 #endif
126 #include "stream/cache2.h"
128 //**************************************************************************//
129 // Playtree
130 //**************************************************************************//
131 #include "playtree.h"
132 #include "playtreeparser.h"
134 //**************************************************************************//
135 // Config
136 //**************************************************************************//
137 #include "parser-cfg.h"
138 #include "parser-mpcmd.h"
140 //**************************************************************************//
141 // Config file
142 //**************************************************************************//
144 static int cfg_inc_verbose(m_option_t *conf)
146 ++verbose;
147 return 0;
150 #include "path.h"
152 //**************************************************************************//
153 //**************************************************************************//
154 // Input media streaming & demultiplexer:
155 //**************************************************************************//
157 static int max_framesize = 0;
159 #include "stream/stream.h"
160 #include "libmpdemux/demuxer.h"
161 #include "libmpdemux/stheader.h"
163 #ifdef CONFIG_DVDREAD
164 #include "stream/stream_dvd.h"
165 #endif
166 #include "stream/stream_dvdnav.h"
168 #include "libmpcodecs/dec_audio.h"
169 #include "libmpcodecs/dec_video.h"
170 #include "libmpcodecs/mp_image.h"
171 #include "libmpcodecs/vf.h"
172 #include "libmpcodecs/vd.h"
174 #include "mixer.h"
176 #include "mp_core.h"
177 #include "options.h"
178 #include "defaultopts.h"
180 static const char help_text[] = _(
181 "Usage: mplayer [options] [url|path/]filename\n"
182 "\n"
183 "Basic options: (complete list in the man page)\n"
184 " -vo <drv> select video output driver ('-vo help' for a list)\n"
185 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
186 #ifdef CONFIG_VCD
187 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
188 #endif
189 #ifdef CONFIG_DVDREAD
190 " dvd://<titleno> play DVD title from device instead of plain file\n"
191 #endif
192 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
193 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
194 " -nosound do not play sound\n"
195 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
196 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
197 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
198 " -playlist <file> specify playlist file\n"
199 " -vid x -aid y select video (x) and audio (y) stream to play\n"
200 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
201 " -pp <quality> enable postprocessing filter (details in the man page)\n"
202 " -framedrop enable frame dropping (for slow machines)\n"
203 "\n"
204 "Basic keys: (complete list in the man page, also check input.conf)\n"
205 " <- or -> seek backward/forward 10 seconds\n"
206 " down or up seek backward/forward 1 minute\n"
207 " pgdown or pgup seek backward/forward 10 minutes\n"
208 " < or > step backward/forward in playlist\n"
209 " p or SPACE pause movie (press any key to continue)\n"
210 " q or ESC stop playing and quit program\n"
211 " + or - adjust audio delay by +/- 0.1 second\n"
212 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
213 " * or / increase or decrease PCM volume\n"
214 " x or z adjust subtitle delay by +/- 0.1 second\n"
215 " r or t adjust subtitle position up/down, also see -vf expand\n"
216 " double click toggle fullscreen\n"
217 " right click pause (press again to continue)\n"
218 "\n"
219 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
220 "\n");
223 #define Exit_SIGILL_RTCpuSel _(\
224 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
225 " It may be a bug in our new runtime CPU-detection code...\n"\
226 " Please read DOCS/HTML/en/bugreports.html.\n")
228 #define Exit_SIGILL _(\
229 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
230 " It usually happens when you run it on a CPU different than the one it was\n"\
231 " compiled/optimized for.\n"\
232 " Verify this!\n")
234 #define Exit_SIGSEGV_SIGFPE _(\
235 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
236 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
237 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
239 #define Exit_SIGCRASH _(\
240 "- MPlayer crashed. This shouldn't happen.\n"\
241 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
242 " gcc version. If you think it's MPlayer's fault, please read\n"\
243 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
244 " won't help unless you provide this information when reporting a possible bug.\n")
246 #define SystemTooSlow _("\n\n"\
247 " ************************************************\n"\
248 " **** Your system is too SLOW to play this! ****\n"\
249 " ************************************************\n\n"\
250 "Possible reasons, problems, workarounds:\n"\
251 "- Most common: broken/buggy _audio_ driver\n"\
252 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
253 " - Experiment with different values for -autosync, 30 is a good start.\n"\
254 "- Slow video output\n"\
255 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
256 "- Slow CPU\n"\
257 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
258 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
259 "- Broken file\n"\
260 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
261 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
262 " - Try -cache 8192.\n"\
263 "- Are you using -cache to play a non-interleaved AVI file?\n"\
264 " - Try -nocache.\n"\
265 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
266 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
269 //**************************************************************************//
270 //**************************************************************************//
272 #include "mp_fifo.h"
274 // benchmark:
275 double video_time_usage;
276 double vout_time_usage;
277 static double audio_time_usage;
278 static int total_time_usage_start;
279 static int total_frame_cnt;
280 static int drop_frame_cnt; // total number of dropped frames
282 // options:
283 static int output_quality;
285 // seek:
286 static off_t seek_to_byte;
287 static off_t step_sec;
289 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
291 // codecs:
292 char **audio_codec_list; // override audio codec
293 char **video_codec_list; // override video codec
294 char **audio_fm_list; // override audio codec family
295 char **video_fm_list; // override video codec family
297 // this dvdsub_id was selected via slang
298 // use this to allow dvdnav to follow -slang across stream resets,
299 // in particular the subtitle ID for a language changes
300 int dvdsub_lang_id;
301 int vobsub_id = -1;
302 static char *spudec_ifo = NULL;
303 int forced_subs_only = 0;
305 // cache2:
306 int stream_cache_size = -1;
308 // dump:
309 int stream_dump_type = 0;
311 // A-V sync:
312 static float default_max_pts_correction = -1;
313 float audio_delay = 0;
314 static int ignore_start = 0;
316 double force_fps = 0;
317 static int force_srate = 0;
318 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
319 static int play_n_frames = -1;
320 static int play_n_frames_mf = -1;
322 // sub:
323 char *font_name = NULL;
324 char *sub_font_name = NULL;
325 extern int font_fontconfig;
326 float font_factor = 0.75;
327 float sub_delay = 0;
328 float sub_fps = 0;
329 int subcc_enabled = 0;
330 int suboverlap_enabled = 1;
332 #include "sub/ass_mp.h"
334 char *current_module; // for debugging
337 // ---
339 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
340 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
341 FILE *edl_fd; // file to write to when in -edlout mode.
342 int use_filedir_conf;
343 int use_filename_title;
345 #include "mpcommon.h"
346 #include "command.h"
348 #include "metadata.h"
350 void *mpctx_get_video_out(MPContext *mpctx)
352 return mpctx->video_out;
355 void *mpctx_get_demuxer(MPContext *mpctx)
357 return mpctx->demuxer;
360 void *mpctx_get_playtree_iter(MPContext *mpctx)
362 return mpctx->playtree_iter;
365 void *mpctx_get_mixer(MPContext *mpctx)
367 return &mpctx->mixer;
370 int mpctx_get_global_sub_size(MPContext *mpctx)
372 return mpctx->global_sub_size;
375 int mpctx_get_osd_function(MPContext *mpctx)
377 return mpctx->osd_function;
380 static float get_relative_time(struct MPContext *mpctx)
382 unsigned int new_time = GetTimer();
383 unsigned int delta = new_time - mpctx->last_time;
384 mpctx->last_time = new_time;
385 return delta * 0.000001;
388 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
390 switch (type) {
391 /* check for valid video stream */
392 case META_VIDEO_CODEC:
393 case META_VIDEO_BITRATE:
394 case META_VIDEO_RESOLUTION:
395 if (!mpctx->sh_video)
396 return 0;
397 break;
399 /* check for valid audio stream */
400 case META_AUDIO_CODEC:
401 case META_AUDIO_BITRATE:
402 case META_AUDIO_SAMPLES:
403 if (!mpctx->sh_audio)
404 return 0;
405 break;
407 /* check for valid demuxer */
408 case META_INFO_TITLE:
409 case META_INFO_ARTIST:
410 case META_INFO_ALBUM:
411 case META_INFO_YEAR:
412 case META_INFO_COMMENT:
413 case META_INFO_TRACK:
414 case META_INFO_GENRE:
415 if (!mpctx->demuxer)
416 return 0;
417 break;
419 default:
420 break;
423 return 1;
426 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
428 char **info = mpctx->demuxer->info;
429 int n;
431 if (!info || !tag)
432 return talloc_strdup(NULL, "");
434 for (n = 0; info[2 * n] != NULL; n++)
435 if (!strcasecmp(info[2 * n], tag))
436 break;
438 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
441 char *get_metadata(struct MPContext *mpctx, metadata_t type)
443 sh_audio_t * const sh_audio = mpctx->sh_audio;
444 sh_video_t * const sh_video = mpctx->sh_video;
446 if (!is_valid_metadata_type(mpctx, type))
447 return NULL;
449 switch (type) {
450 case META_NAME:
451 return talloc_strdup(NULL, mp_basename(mpctx->filename));
452 case META_VIDEO_CODEC:
453 if (sh_video->format == 0x10000001)
454 return talloc_strdup(NULL, "mpeg1");
455 else if (sh_video->format == 0x10000002)
456 return talloc_strdup(NULL, "mpeg2");
457 else if (sh_video->format == 0x10000004)
458 return talloc_strdup(NULL, "mpeg4");
459 else if (sh_video->format == 0x10000005)
460 return talloc_strdup(NULL, "h264");
461 else if (sh_video->format >= 0x20202020)
462 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
463 else
464 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
465 case META_VIDEO_BITRATE:
466 return talloc_asprintf(NULL, "%d kbps",
467 (int) (sh_video->i_bps * 8 / 1024));
468 case META_VIDEO_RESOLUTION:
469 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
470 sh_video->disp_h);
471 case META_AUDIO_CODEC:
472 if (sh_audio->codec && sh_audio->codec->name)
473 return talloc_strdup(NULL, sh_audio->codec->name);
474 return talloc_strdup(NULL, "");
475 case META_AUDIO_BITRATE:
476 return talloc_asprintf(NULL, "%d kbps",
477 (int) (sh_audio->i_bps * 8 / 1000));
478 case META_AUDIO_SAMPLES:
479 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
480 sh_audio->channels);
482 /* check for valid demuxer */
483 case META_INFO_TITLE:
484 return get_demuxer_info(mpctx, "Title");
486 case META_INFO_ARTIST:
487 return get_demuxer_info(mpctx, "Artist");
489 case META_INFO_ALBUM:
490 return get_demuxer_info(mpctx, "Album");
492 case META_INFO_YEAR:
493 return get_demuxer_info(mpctx, "Year");
495 case META_INFO_COMMENT:
496 return get_demuxer_info(mpctx, "Comment");
498 case META_INFO_TRACK:
499 return get_demuxer_info(mpctx, "Track");
501 case META_INFO_GENRE:
502 return get_demuxer_info(mpctx, "Genre");
504 default:
505 break;
508 return talloc_strdup(NULL, "");
511 static void print_file_properties(struct MPContext *mpctx, const char *filename)
513 double start_pts = MP_NOPTS_VALUE;
514 double video_start_pts = MP_NOPTS_VALUE;
515 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
516 filename_recode(filename));
517 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
518 mpctx->demuxer->desc->name);
519 if (mpctx->sh_video) {
520 /* Assume FOURCC if all bytes >= 0x20 (' ') */
521 if (mpctx->sh_video->format >= 0x20202020)
522 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
523 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
524 else
525 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
526 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
527 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
528 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
529 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
530 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
531 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
532 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
533 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
534 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
535 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
536 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
537 video_start_pts = ds_get_next_pts(mpctx->d_video);
539 if (mpctx->sh_audio) {
540 /* Assume FOURCC if all bytes >= 0x20 (' ') */
541 if (mpctx->sh_audio->format >= 0x20202020)
542 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
543 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
544 else
545 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
546 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
547 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
548 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
549 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
550 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
551 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
552 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
553 start_pts = ds_get_next_pts(mpctx->d_audio);
555 if (video_start_pts != MP_NOPTS_VALUE) {
556 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
557 (mpctx->sh_video && video_start_pts < start_pts))
558 start_pts = video_start_pts;
560 if (start_pts != MP_NOPTS_VALUE)
561 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
562 else
563 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
564 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
565 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
566 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
567 mpctx->stream->seek
568 && (!mpctx->demuxer || mpctx->demuxer->seekable));
569 if (mpctx->demuxer) {
570 if (mpctx->demuxer->num_chapters == 0)
571 stream_control(mpctx->demuxer->stream,
572 STREAM_CTRL_GET_NUM_CHAPTERS,
573 &mpctx->demuxer->num_chapters);
574 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
575 "ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
579 /// step size of mixer changes
580 int volstep = 3;
582 #ifdef CONFIG_DVDNAV
583 static void mp_dvdnav_context_free(MPContext *ctx)
585 if (ctx->nav_smpi)
586 free_mp_image(ctx->nav_smpi);
587 ctx->nav_smpi = NULL;
588 free(ctx->nav_buffer);
589 ctx->nav_buffer = NULL;
590 ctx->nav_start = NULL;
591 ctx->nav_in_size = 0;
593 #endif
595 static void uninit_subs(struct demuxer *demuxer)
597 for (int i = 0; i < MAX_S_STREAMS; i++) {
598 struct sh_sub *sh = demuxer->s_streams[i];
599 if (sh && sh->initialized)
600 sub_uninit(sh);
604 void uninit_player(struct MPContext *mpctx, unsigned int mask)
606 mask &= mpctx->initialized_flags;
608 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
610 if (mask & INITIALIZED_ACODEC) {
611 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
612 current_module = "uninit_acodec";
613 if (mpctx->sh_audio)
614 uninit_audio(mpctx->sh_audio);
615 mpctx->sh_audio = NULL;
616 mpctx->mixer.afilter = NULL;
619 if (mask & INITIALIZED_SUB) {
620 mpctx->initialized_flags &= ~INITIALIZED_SUB;
621 if (mpctx->d_sub->sh)
622 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
625 if (mask & INITIALIZED_VCODEC) {
626 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
627 current_module = "uninit_vcodec";
628 if (mpctx->sh_video)
629 uninit_video(mpctx->sh_video);
630 mpctx->sh_video = NULL;
633 if (mask & INITIALIZED_DEMUXER) {
634 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
635 current_module = "free_demuxer";
636 if (mpctx->num_sources) {
637 mpctx->demuxer = mpctx->sources[0].demuxer;
638 for (int i = 1; i < mpctx->num_sources; i++) {
639 uninit_subs(mpctx->sources[i].demuxer);
640 free_stream(mpctx->sources[i].stream);
641 free_demuxer(mpctx->sources[i].demuxer);
644 talloc_free(mpctx->sources);
645 mpctx->sources = NULL;
646 mpctx->num_sources = 0;
647 talloc_free(mpctx->timeline);
648 mpctx->timeline = NULL;
649 mpctx->num_timeline_parts = 0;
650 talloc_free(mpctx->chapters);
651 mpctx->chapters = NULL;
652 mpctx->num_chapters = 0;
653 mpctx->video_offset = 0;
654 if (mpctx->demuxer) {
655 mpctx->stream = mpctx->demuxer->stream;
656 uninit_subs(mpctx->demuxer);
657 free_demuxer(mpctx->demuxer);
659 mpctx->demuxer = NULL;
662 // kill the cache process:
663 if (mask & INITIALIZED_STREAM) {
664 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
665 current_module = "uninit_stream";
666 if (mpctx->stream)
667 free_stream(mpctx->stream);
668 mpctx->stream = NULL;
671 if (mask & INITIALIZED_VO) {
672 mpctx->initialized_flags &= ~INITIALIZED_VO;
673 current_module = "uninit_vo";
674 vo_destroy(mpctx->video_out);
675 mpctx->video_out = NULL;
676 #ifdef CONFIG_DVDNAV
677 mp_dvdnav_context_free(mpctx);
678 #endif
681 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
682 if (mask & INITIALIZED_GETCH2) {
683 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
684 current_module = "uninit_getch2";
685 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
686 // restore terminal:
687 getch2_disable();
690 if (mask & INITIALIZED_VOBSUB) {
691 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
692 current_module = "uninit_vobsub";
693 if (vo_vobsub)
694 vobsub_close(vo_vobsub);
695 vo_vobsub = NULL;
698 if (mask & INITIALIZED_SPUDEC) {
699 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
700 current_module = "uninit_spudec";
701 spudec_free(vo_spudec);
702 vo_spudec = NULL;
705 if (mask & INITIALIZED_AO) {
706 mpctx->initialized_flags &= ~INITIALIZED_AO;
707 current_module = "uninit_ao";
708 if (mpctx->edl_muted)
709 mixer_mute(&mpctx->mixer);
710 if (mpctx->ao)
711 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
712 mpctx->ao = NULL;
715 current_module = NULL;
718 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
720 if (mpctx->user_muted && !mpctx->edl_muted)
721 mixer_mute(&mpctx->mixer);
722 uninit_player(mpctx, INITIALIZED_ALL);
723 #if defined(__MINGW32__) || defined(__CYGWIN__)
724 timeEndPeriod(1);
725 #endif
726 #ifdef CONFIG_X11
727 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
728 #endif
730 current_module = "uninit_input";
731 mp_input_uninit(mpctx->input);
733 #ifdef CONFIG_FREETYPE
734 current_module = "uninit_font";
735 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
736 free_font_desc(mpctx->osd->sub_font);
737 free_font_desc(vo_font);
738 vo_font = NULL;
739 done_freetype();
740 #endif
741 osd_free(mpctx->osd);
743 #ifdef CONFIG_ASS
744 ass_library_done(mpctx->ass_library);
745 mpctx->ass_library = NULL;
746 #endif
748 current_module = "exit_player";
750 if (mpctx->playtree_iter)
751 play_tree_iter_free(mpctx->playtree_iter);
752 mpctx->playtree_iter = NULL;
753 if (mpctx->playtree)
754 play_tree_free(mpctx->playtree, 1);
755 mpctx->playtree = NULL;
757 talloc_free(mpctx->key_fifo);
759 free(edl_records); // free mem allocated for EDL
760 edl_records = NULL;
761 switch (how) {
762 case EXIT_QUIT:
763 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
764 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
765 break;
766 case EXIT_EOF:
767 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
768 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
769 break;
770 case EXIT_ERROR:
771 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
772 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
773 break;
774 default:
775 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
777 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
778 "max framesize was %d bytes\n", max_framesize);
780 // must be last since e.g. mp_msg uses option values
781 // that will be freed by this.
782 if (mpctx->mconfig)
783 m_config_free(mpctx->mconfig);
784 mpctx->mconfig = NULL;
786 exit(rc);
789 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
791 exit_player_with_rc(mpctx, how, 1);
794 #ifndef __MINGW32__
795 static void child_sighandler(int x)
797 pid_t pid;
798 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
800 #endif
802 #ifdef CONFIG_CRASH_DEBUG
803 static char *prog_path;
804 static int crash_debug = 0;
805 #endif
807 static void exit_sighandler(int x)
809 static int sig_count = 0;
810 #ifdef CONFIG_CRASH_DEBUG
811 if (!crash_debug || x != SIGTRAP)
812 #endif
813 ++sig_count;
814 if (sig_count == 5) {
815 /* We're crashing bad and can't uninit cleanly :(
816 * by popular request, we make one last (dirty)
817 * effort to restore the user's
818 * terminal. */
819 getch2_disable();
820 exit(1);
822 if (sig_count == 6)
823 exit(1);
824 if (sig_count > 6) {
825 // can't stop :(
826 #ifndef __MINGW32__
827 kill(getpid(), SIGKILL);
828 #endif
830 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
831 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
832 "\nMPlayer interrupted by signal %d in module: %s\n", x,
833 current_module ? current_module : "unknown");
834 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
835 if (sig_count <= 1)
836 switch (x) {
837 case SIGINT:
838 case SIGPIPE:
839 case SIGQUIT:
840 case SIGTERM:
841 case SIGKILL:
842 async_quit_request = 1;
843 return; // killed from keyboard (^C) or killed [-9]
844 case SIGILL:
845 #if CONFIG_RUNTIME_CPUDETECT
846 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
847 #else
848 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
849 #endif
850 case SIGFPE:
851 case SIGSEGV:
852 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
853 default:
854 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
855 #ifdef CONFIG_CRASH_DEBUG
856 if (crash_debug) {
857 int gdb_pid;
858 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
859 gdb_pid = fork();
860 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
861 if (gdb_pid == 0) { // We are the child
862 char spid[20];
863 snprintf(spid, sizeof(spid), "%i", getppid());
864 getch2_disable(); // allow terminal to work properly with gdb
865 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
866 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
867 } else if (gdb_pid < 0)
868 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
869 else
870 waitpid(gdb_pid, NULL, 0);
871 if (x == SIGTRAP)
872 return;
874 #endif
876 getch2_disable();
877 exit(1);
880 #include "cfg-mplayer.h"
882 static int cfg_include(m_option_t *conf, char *filename)
884 return m_config_parse_config_file(conf->priv, filename);
887 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
889 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
891 struct MPOpts *opts = &mpctx->opts;
892 char *conffile;
893 int conffile_fd;
894 if (!(opts->noconfig & 2) &&
895 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
896 exit_player(mpctx, EXIT_NONE);
897 if ((conffile = get_path("")) == NULL)
898 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
899 else {
900 #ifdef __MINGW32__
901 mkdir(conffile);
902 #else
903 mkdir(conffile, 0777);
904 #endif
905 free(conffile);
906 if ((conffile = get_path("config")) == NULL)
907 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
908 else {
909 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
910 0666)) != -1) {
911 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
912 "Creating config file: %s\n", conffile);
913 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
914 close(conffile_fd);
916 if (!(opts->noconfig & 1) &&
917 m_config_parse_config_file(conf, conffile) < 0)
918 exit_player(mpctx, EXIT_NONE);
919 free(conffile);
924 #define PROFILE_CFG_PROTOCOL "protocol."
926 static void load_per_protocol_config(m_config_t *conf, const char * const file)
928 char *str;
929 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
930 m_profile_t *p;
932 /* does filename actually uses a protocol ? */
933 str = strstr(file, "://");
934 if (!str)
935 return;
937 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
938 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
939 p = m_config_get_profile(conf, protocol);
940 if (p) {
941 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
942 "Loading protocol-related profile '%s'\n", protocol);
943 m_config_set_profile(conf, p);
947 #define PROFILE_CFG_EXTENSION "extension."
949 static void load_per_extension_config(m_config_t *conf, const char * const file)
951 char *str;
952 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
953 m_profile_t *p;
955 /* does filename actually have an extension ? */
956 str = strrchr(file, '.');
957 if (!str)
958 return;
960 sprintf(extension, PROFILE_CFG_EXTENSION);
961 strncat(extension, ++str, 7);
962 p = m_config_get_profile(conf, extension);
963 if (p) {
964 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
965 "Loading extension-related profile '%s'\n", extension);
966 m_config_set_profile(conf, p);
970 #define PROFILE_CFG_VO "vo."
971 #define PROFILE_CFG_AO "ao."
973 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
975 char profile[strlen(cfg) + strlen(out) + 1];
976 m_profile_t *p;
978 sprintf(profile, "%s%s", cfg, out);
979 p = m_config_get_profile(conf, profile);
980 if (p) {
981 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
982 "Loading extension-related profile '%s'\n", profile);
983 m_config_set_profile(conf, p);
988 * Tries to load a config file
989 * @return 0 if file was not found, 1 otherwise
991 static int try_load_config(m_config_t *conf, const char *file)
993 struct stat st;
994 if (stat(file, &st))
995 return 0;
996 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
997 m_config_parse_config_file(conf, file);
998 return 1;
1001 static void load_per_file_config(m_config_t *conf, const char * const file)
1003 char *confpath;
1004 char cfg[PATH_MAX];
1005 const char *name;
1007 if (strlen(file) > PATH_MAX - 14) {
1008 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
1009 "can not load file or directory specific config files\n");
1010 return;
1012 sprintf(cfg, "%s.conf", file);
1014 name = mp_basename(cfg);
1015 if (use_filedir_conf) {
1016 char dircfg[PATH_MAX];
1017 strcpy(dircfg, cfg);
1018 strcpy(dircfg + (name - cfg), "mplayer.conf");
1019 try_load_config(conf, dircfg);
1021 if (try_load_config(conf, cfg))
1022 return;
1025 if ((confpath = get_path(name)) != NULL) {
1026 try_load_config(conf, confpath);
1028 free(confpath);
1032 /* When libmpdemux performs a blocking operation (network connection or
1033 * cache filling) if the operation fails we use this function to check
1034 * if it was interrupted by the user.
1035 * The function returns a new value for eof. */
1036 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1038 mp_cmd_t *cmd;
1039 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1040 switch (cmd->id) {
1041 case MP_CMD_QUIT:
1042 exit_player_with_rc(mpctx, EXIT_QUIT,
1043 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1044 case MP_CMD_PLAY_TREE_STEP: {
1045 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1046 mpctx->play_tree_step =
1047 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1048 } break;
1049 case MP_CMD_PLAY_TREE_UP_STEP: {
1050 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1051 } break;
1052 case MP_CMD_PLAY_ALT_SRC_STEP: {
1053 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1054 } break;
1056 mp_cmd_free(cmd);
1058 return stop_play;
1061 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1063 play_tree_add_bpf(entry, bstr(mpctx->filename));
1066 if (!entry) {
1067 entry = mpctx->playtree_iter->tree;
1068 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1069 != PLAY_TREE_ITER_ENTRY)
1070 return PT_NEXT_ENTRY;
1071 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1072 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1073 != PLAY_TREE_ITER_ENTRY)
1074 return PT_NEXT_ENTRY;
1076 play_tree_remove(entry, 1, 1);
1077 return PT_NEXT_SRC;
1079 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1080 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1081 entry = mpctx->playtree_iter->tree;
1082 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1083 != PLAY_TREE_ITER_ENTRY)
1084 return PT_NEXT_ENTRY;
1085 play_tree_remove(entry, 1, 1);
1087 return PT_NEXT_SRC;
1090 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1091 int noerr)
1093 struct MPOpts *opts = &mpctx->opts;
1094 sub_data *subd = NULL;
1095 struct ass_track *asst = NULL;
1096 bool is_native_ass = false;
1098 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1099 return;
1101 #ifdef CONFIG_ASS
1102 if (opts->ass_enabled) {
1103 #ifdef CONFIG_ICONV
1104 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1105 #else
1106 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1107 #endif
1108 is_native_ass = asst;
1109 if (!asst) {
1110 subd = sub_read_file(filename, fps, &mpctx->opts);
1111 if (subd) {
1112 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1113 sub_free(subd);
1114 subd = NULL;
1117 } else
1118 #endif
1119 subd = sub_read_file(filename, fps, &mpctx->opts);
1122 if (!asst && !subd) {
1123 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1124 "Cannot load subtitles: %s\n", filename_recode(filename));
1125 return;
1128 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1129 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1130 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1131 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1132 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1133 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1134 filename_recode(filename));
1135 ++mpctx->set_of_sub_size;
1136 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1137 mpctx->set_of_sub_size, filename_recode(filename));
1140 void init_vo_spudec(struct MPContext *mpctx)
1142 unsigned width, height;
1143 spudec_free(vo_spudec);
1144 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1145 vo_spudec = NULL;
1147 // we currently can't work without video stream
1148 if (!mpctx->sh_video)
1149 return;
1151 if (spudec_ifo) {
1152 unsigned int palette[16];
1153 current_module = "spudec_init_vobsub";
1154 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1155 1, -1, NULL) >= 0)
1156 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1159 width = mpctx->sh_video->disp_w;
1160 height = mpctx->sh_video->disp_h;
1162 #ifdef CONFIG_DVDREAD
1163 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1164 current_module = "spudec_init_dvdread";
1165 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1166 cur_pgc->palette, width, height, NULL, 0);
1168 #endif
1170 #ifdef CONFIG_DVDNAV
1171 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1172 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1173 current_module = "spudec_init_dvdnav";
1174 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1176 #endif
1178 if (vo_spudec == NULL) {
1179 sh_sub_t *sh = mpctx->d_sub->sh;
1180 current_module = "spudec_init_normal";
1181 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1182 sh->extradata_len);
1183 spudec_set_font_factor(vo_spudec, font_factor);
1186 if (vo_spudec != NULL) {
1187 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1188 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1189 mpctx);
1194 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1195 * make it all work is to use the builtin SDL-bootstrap code, which
1196 * will be done automatically by replacing our main() if we include SDL.h.
1198 #if defined(__APPLE__) && defined(CONFIG_SDL)
1199 #ifdef CONFIG_SDL_SDL_H
1200 #include <SDL/SDL.h>
1201 #else
1202 #include <SDL.h>
1203 #endif
1204 #endif
1207 * \brief append a formatted string
1208 * \param buf buffer to print into
1209 * \param pos position of terminating 0 in buf
1210 * \param len maximum number of characters in buf, not including terminating 0
1211 * \param format printf format string
1213 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1215 va_list va;
1216 va_start(va, format);
1217 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1218 va_end(va);
1219 if (*pos >= len) {
1220 buf[len] = 0;
1221 *pos = len;
1226 * \brief append time in the hh:mm:ss.f format
1227 * \param buf buffer to print into
1228 * \param pos position of terminating 0 in buf
1229 * \param len maximum number of characters in buf, not including terminating 0
1230 * \param time time value to convert/append
1232 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1234 int64_t tenths = 10 * time;
1235 int f1 = tenths % 10;
1236 int ss = (tenths / 10) % 60;
1237 int mm = (tenths / 600) % 60;
1238 int hh = tenths / 36000;
1239 if (time < 0) {
1240 saddf(buf, pos, len, "unknown");
1241 return;
1243 if (hh > 0)
1244 saddf(buf, pos, len, "%2d:", hh);
1245 if (hh > 0 || mm > 0)
1246 saddf(buf, pos, len, "%02d:", mm);
1247 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1250 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1252 struct MPOpts *opts = &mpctx->opts;
1253 sh_video_t * const sh_video = mpctx->sh_video;
1255 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1256 a_pos = playing_audio_pts(mpctx);
1257 if (mpctx->sh_audio && sh_video && at_frame) {
1258 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1259 if (mpctx->time_frame > 0)
1260 mpctx->last_av_difference +=
1261 mpctx->time_frame * opts->playback_speed;
1262 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1263 && !mpctx->drop_message_shown) {
1264 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1265 mpctx->drop_message_shown = true;
1268 if (opts->quiet)
1269 return;
1271 if (a_pos == MP_NOPTS_VALUE)
1272 a_pos = -9; // don't print a huge negative number
1274 int width;
1275 char *line;
1276 unsigned pos = 0;
1277 get_screen_size();
1278 if (screen_width > 0)
1279 width = screen_width;
1280 else
1281 width = 80;
1282 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1283 /* Windows command line is broken (MinGW's rxvt works, but we
1284 * should not depend on that). */
1285 width--;
1286 #endif
1287 line = malloc(width + 1); // one additional char for the terminating null
1289 // Audio time
1290 if (mpctx->sh_audio) {
1291 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1292 if (!sh_video) {
1293 float len = get_time_length(mpctx);
1294 saddf(line, &pos, width, "(");
1295 sadd_hhmmssf(line, &pos, width, a_pos);
1296 saddf(line, &pos, width, ") of %.1f (", len);
1297 sadd_hhmmssf(line, &pos, width, len);
1298 saddf(line, &pos, width, ") ");
1302 // Video time
1303 if (sh_video)
1304 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1306 // A-V sync
1307 if (mpctx->sh_audio && sh_video)
1308 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1309 mpctx->last_av_difference, mpctx->total_avsync_change);
1311 // Video stats
1312 if (sh_video)
1313 saddf(line, &pos, width, "%3d/%3d ",
1314 (int)sh_video->num_frames,
1315 (int)sh_video->num_frames_decoded);
1317 // CPU usage
1318 if (sh_video) {
1319 if (sh_video->timer > 0.5)
1320 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1321 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1322 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1323 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1324 else
1325 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1326 } else if (mpctx->sh_audio) {
1327 if (mpctx->delay > 0.5)
1328 saddf(line, &pos, width, "%4.1f%% ",
1329 100.0 * audio_time_usage / (double)mpctx->delay);
1330 else
1331 saddf(line, &pos, width, "??,?%% ");
1334 // VO stats
1335 if (sh_video)
1336 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1338 #ifdef CONFIG_STREAM_CACHE
1339 // cache stats
1340 if (stream_cache_size > 0)
1341 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1342 #endif
1344 // other
1345 if (opts->playback_speed != 1)
1346 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1348 // end
1349 if (erase_to_end_of_line) {
1350 line[pos] = 0;
1351 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1352 "%s%s\r", line, erase_to_end_of_line);
1353 } else {
1354 memset(&line[pos], ' ', width - pos);
1355 line[width] = 0;
1356 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1358 free(line);
1361 struct stream_dump_progress {
1362 uint64_t count;
1363 unsigned start_time;
1364 unsigned last_print_time;
1367 static void stream_dump_progress_start(struct stream_dump_progress *p)
1369 p->start_time = p->last_print_time = GetTimerMS();
1370 p->count = 0;
1373 static void stream_dump_progress(struct stream_dump_progress *p,
1374 uint64_t len, stream_t *stream)
1376 p->count += len;
1377 unsigned t = GetTimerMS();
1378 if (t - p->last_print_time < 1000)
1379 return;
1381 uint64_t start = stream->start_pos;
1382 uint64_t end = stream->end_pos;
1383 uint64_t pos = stream->pos;
1385 p->last_print_time = t;
1386 /* TODO: pretty print sizes; ETA */
1387 if (end > start && pos >= start && pos <= end) {
1388 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1389 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1390 p->count, 100.0 * (pos - start) / (end - start));
1391 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1392 } else {
1393 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1394 "dump: %"PRIu64 " bytes written", p->count);
1395 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1399 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1401 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1402 p->count, name);
1406 * \brief build a chain of audio filters that converts the input format
1407 * to the ao's format, taking into account the current playback_speed.
1408 * sh_audio describes the requested input format of the chain.
1409 * ao describes the requested output format of the chain.
1411 static int build_afilter_chain(struct MPContext *mpctx)
1413 struct sh_audio *sh_audio = mpctx->sh_audio;
1414 struct ao *ao = mpctx->ao;
1415 struct MPOpts *opts = &mpctx->opts;
1416 int new_srate;
1417 int result;
1418 if (!sh_audio) {
1419 mpctx->mixer.afilter = NULL;
1420 return 0;
1422 if (af_control_any_rev(sh_audio->afilter,
1423 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1424 &opts->playback_speed))
1425 new_srate = sh_audio->samplerate;
1426 else {
1427 new_srate = sh_audio->samplerate * opts->playback_speed;
1428 if (new_srate != ao->samplerate) {
1429 // limits are taken from libaf/af_resample.c
1430 if (new_srate < 8000)
1431 new_srate = 8000;
1432 if (new_srate > 192000)
1433 new_srate = 192000;
1434 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1437 result = init_audio_filters(sh_audio, new_srate,
1438 &ao->samplerate, &ao->channels, &ao->format);
1439 mpctx->mixer.afilter = sh_audio->afilter;
1440 return result;
1444 typedef struct mp_osd_msg mp_osd_msg_t;
1445 struct mp_osd_msg {
1446 /// Previous message on the stack.
1447 mp_osd_msg_t *prev;
1448 /// Message text.
1449 char *msg;
1450 int id, level, started;
1451 /// Display duration in ms.
1452 unsigned time;
1455 /// OSD message stack.
1456 static mp_osd_msg_t *osd_msg_stack = NULL;
1459 * \brief Add a message on the OSD message stack
1461 * If a message with the same id is already present in the stack
1462 * it is pulled on top of the stack, otherwise a new message is created.
1465 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1466 va_list ap)
1468 mp_osd_msg_t *msg, *last = NULL;
1470 // look if the id is already in the stack
1471 for (msg = osd_msg_stack; msg && msg->id != id;
1472 last = msg, msg = msg->prev) ;
1473 // not found: alloc it
1474 if (!msg) {
1475 msg = talloc_zero(NULL, mp_osd_msg_t);
1476 msg->prev = osd_msg_stack;
1477 osd_msg_stack = msg;
1478 } else if (last) { // found, but it's not on top of the stack
1479 last->prev = msg->prev;
1480 msg->prev = osd_msg_stack;
1481 osd_msg_stack = msg;
1483 talloc_free(msg->msg);
1484 // write the msg
1485 msg->msg = talloc_vasprintf(msg, fmt, ap);
1486 // set id and time
1487 msg->id = id;
1488 msg->level = level;
1489 msg->time = time;
1493 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1495 va_list ap;
1496 va_start(ap, fmt);
1497 set_osd_msg_va(id, level, time, fmt, ap);
1498 va_end(ap);
1501 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1503 va_list ap;
1504 va_start(ap, fmt);
1505 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1506 va_end(ap);
1510 * \brief Remove a message from the OSD stack
1512 * This function can be used to get rid of a message right away.
1516 void rm_osd_msg(int id)
1518 mp_osd_msg_t *msg, *last = NULL;
1520 // Search for the msg
1521 for (msg = osd_msg_stack; msg && msg->id != id;
1522 last = msg, msg = msg->prev) ;
1523 if (!msg)
1524 return;
1526 // Detach it from the stack and free it
1527 if (last)
1528 last->prev = msg->prev;
1529 else
1530 osd_msg_stack = msg->prev;
1531 talloc_free(msg);
1535 * \brief Remove all messages from the OSD stack
1539 static void clear_osd_msgs(void)
1541 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1542 while (msg) {
1543 prev = msg->prev;
1544 talloc_free(msg);
1545 msg = prev;
1547 osd_msg_stack = NULL;
1551 * \brief Get the current message from the OSD stack.
1553 * This function decrements the message timer and destroys the old ones.
1554 * The message that should be displayed is returned (if any).
1558 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1560 struct MPOpts *opts = &mpctx->opts;
1561 mp_osd_msg_t *msg, *prev, *last = NULL;
1562 static unsigned last_update = 0;
1563 unsigned now = GetTimerMS();
1564 unsigned diff;
1565 char hidden_dec_done = 0;
1567 if (mpctx->osd_visible) {
1568 // 36000000 means max timed visibility is 1 hour into the future, if
1569 // the difference is greater assume it's wrapped around from below 0
1570 if (mpctx->osd_visible - now > 36000000) {
1571 mpctx->osd_visible = 0;
1572 vo_osd_progbar_type = -1; // disable
1573 vo_osd_changed(OSDTYPE_PROGBAR);
1574 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1577 if (mpctx->osd_show_percentage_until - now > 36000000)
1578 mpctx->osd_show_percentage_until = 0;
1580 if (!last_update)
1581 last_update = now;
1582 diff = now >= last_update ? now - last_update : 0;
1584 last_update = now;
1586 // Look for the first message in the stack with high enough level.
1587 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1588 prev = msg->prev;
1589 if (msg->level > opts->osd_level && hidden_dec_done)
1590 continue;
1591 // The message has a high enough level or it is the first hidden one
1592 // in both cases we decrement the timer or kill it.
1593 if (!msg->started || msg->time > diff) {
1594 if (msg->started)
1595 msg->time -= diff;
1596 else
1597 msg->started = 1;
1598 // display it
1599 if (msg->level <= opts->osd_level)
1600 return msg;
1601 hidden_dec_done = 1;
1602 continue;
1604 // kill the message
1605 talloc_free(msg);
1606 if (last) {
1607 last->prev = prev;
1608 msg = last;
1609 } else {
1610 osd_msg_stack = prev;
1611 msg = NULL;
1614 // Nothing found
1615 return NULL;
1619 * \brief Display the OSD bar.
1621 * Display the OSD bar or fall back on a simple message.
1625 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1626 double min, double max, double val)
1628 struct MPOpts *opts = &mpctx->opts;
1629 if (opts->osd_level < 1)
1630 return;
1632 if (mpctx->sh_video) {
1633 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1634 vo_osd_progbar_type = type;
1635 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1636 vo_osd_changed(OSDTYPE_PROGBAR);
1637 return;
1640 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1641 name, ROUND(100 * (val - min) / (max - min)));
1645 * \brief Display text subtitles on the OSD
1647 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1649 int i;
1650 vo_sub = subs;
1651 vo_osd_changed(OSDTYPE_SUBTITLE);
1652 if (!mpctx->sh_video) {
1653 // reverse order, since newest set_osd_msg is displayed first
1654 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1655 if (!subs || i >= subs->lines || !subs->text[i])
1656 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1657 else {
1658 // HACK: currently display time for each sub line
1659 // except the last is set to 2 seconds.
1660 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1661 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1662 "%s", subs->text[i]);
1669 * \brief Update the OSD message line.
1671 * This function displays the current message on the vo OSD or on the term.
1672 * If the stack is empty and the OSD level is high enough the timer
1673 * is displayed (only on the vo OSD).
1677 static void update_osd_msg(struct MPContext *mpctx)
1679 struct MPOpts *opts = &mpctx->opts;
1680 mp_osd_msg_t *msg;
1681 struct osd_state *osd = mpctx->osd;
1682 char osd_text_timer[128];
1684 if (mpctx->add_osd_seek_info) {
1685 double percentage = get_percent_pos(mpctx);
1686 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1687 if (mpctx->sh_video)
1688 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1689 mpctx->add_osd_seek_info = false;
1692 // Look if we have a msg
1693 if ((msg = get_osd_msg(mpctx))) {
1694 if (strcmp(osd->osd_text, msg->msg)) {
1695 osd_set_text(osd, msg->msg);
1696 if (mpctx->sh_video)
1697 vo_osd_changed(OSDTYPE_OSD);
1698 else if (opts->term_osd)
1699 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1700 msg->msg);
1702 return;
1705 if (mpctx->sh_video) {
1706 // fallback on the timer
1707 if (opts->osd_level >= 2) {
1708 int len = get_time_length(mpctx);
1709 int percentage = -1;
1710 char percentage_text[10];
1711 char fractions_text[4];
1712 double fpts = get_current_time(mpctx);
1713 int pts = fpts;
1715 if (mpctx->osd_show_percentage_until)
1716 percentage = get_percent_pos(mpctx);
1718 if (percentage >= 0)
1719 snprintf(percentage_text, 9, " (%d%%)", percentage);
1720 else
1721 percentage_text[0] = 0;
1723 if (opts->osd_fractions == 1) {
1724 //print fractions as sub-second timestamp
1725 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1726 (int)((fpts - pts) * 100));
1727 } else if (opts->osd_fractions == 2) {
1728 /* Print fractions by estimating the frame count within the
1729 * second.
1731 * Rounding or cutting off numbers after the decimal point
1732 * causes problems because of float's precision and movies
1733 * whose first frame is not exactly at timestamp 0. Therefore,
1734 * we add 0.2 and cut off at the decimal point, which proved
1735 * to be good heuristic.
1737 double fps = mpctx->sh_video->fps;
1738 if (fps <= 1 || fps > 99)
1739 strcpy(fractions_text, ".??");
1740 else
1741 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1742 (int) ((fpts - pts) * fps + 0.2));
1743 } else {
1744 //do not print fractions
1745 fractions_text[0] = 0;
1748 if (opts->osd_level == 3)
1749 snprintf(osd_text_timer, sizeof(osd_text_timer),
1750 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1751 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1752 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1753 percentage_text);
1754 else
1755 snprintf(osd_text_timer, sizeof(osd_text_timer),
1756 "%c %02d:%02d:%02d%s%s",
1757 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1758 pts % 60, fractions_text, percentage_text);
1759 } else
1760 osd_text_timer[0] = 0;
1762 if (strcmp(osd->osd_text, osd_text_timer)) {
1763 osd_set_text(osd, osd_text_timer);
1764 vo_osd_changed(OSDTYPE_OSD);
1766 return;
1769 // Clear the term osd line
1770 if (opts->term_osd && osd->osd_text[0]) {
1771 osd->osd_text[0] = 0;
1772 printf("%s\n", opts->term_osd_esc);
1777 void reinit_audio_chain(struct MPContext *mpctx)
1779 struct MPOpts *opts = &mpctx->opts;
1780 struct ao *ao;
1781 if (!mpctx->sh_audio)
1782 return;
1783 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1784 current_module = "init_audio_codec";
1785 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1786 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1787 goto init_error;
1788 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1789 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1793 current_module = "af_preinit";
1794 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1795 mpctx->initialized_flags |= INITIALIZED_AO;
1796 mpctx->ao = ao_create();
1797 mpctx->ao->samplerate = force_srate;
1798 mpctx->ao->format = opts->audio_output_format;
1800 ao = mpctx->ao;
1802 // first init to detect best values
1803 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1804 // input:
1805 mpctx->sh_audio->samplerate,
1806 // output:
1807 &ao->samplerate, &ao->channels, &ao->format)) {
1808 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1809 "pre-init!\n");
1810 exit_player(mpctx, EXIT_ERROR);
1812 if (!ao->initialized) {
1813 current_module = "ao2_init";
1814 ao->buffersize = opts->ao_buffersize;
1815 ao_init(ao, opts->audio_driver_list);
1816 if (!ao->initialized) {
1817 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1818 "Could not open/initialize audio device -> no sound.\n");
1819 goto init_error;
1821 ao->buffer.start = talloc_new(ao);
1822 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1823 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1824 ao->driver->info->short_name,
1825 ao->samplerate, ao->channels,
1826 af_fmt2str_short(ao->format),
1827 af_fmt2bits(ao->format) / 8);
1828 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1829 ao->driver->info->name, ao->driver->info->author);
1830 if (strlen(ao->driver->info->comment) > 0)
1831 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1832 ao->driver->info->comment);
1835 // init audio filters:
1836 current_module = "af_init";
1837 if (!build_afilter_chain(mpctx)) {
1838 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1839 "Couldn't find matching filter/ao format!\n");
1840 goto init_error;
1842 mpctx->mixer.ao = ao;
1843 mpctx->mixer.volstep = volstep;
1844 mpctx->syncing_audio = true;
1845 return;
1847 init_error:
1848 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1849 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1850 mpctx->d_audio->id = -2;
1854 // Return pts value corresponding to the end point of audio written to the
1855 // ao so far.
1856 static double written_audio_pts(struct MPContext *mpctx)
1858 sh_audio_t *sh_audio = mpctx->sh_audio;
1859 demux_stream_t *d_audio = mpctx->d_audio;
1860 // first calculate the end pts of audio that has been output by decoder
1861 double a_pts = sh_audio->pts;
1862 if (a_pts != MP_NOPTS_VALUE)
1863 // Good, decoder supports new way of calculating audio pts.
1864 // sh_audio->pts is the timestamp of the latest input packet with
1865 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1866 // the amount of bytes the decoder has written after that timestamp.
1867 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1868 else {
1869 // Decoder doesn't support new way of calculating pts (or we're
1870 // being called before it has decoded anything with known timestamp).
1871 // Use the old method of audio pts calculation: take the timestamp
1872 // of last packet with known pts the decoder has read data from,
1873 // and add amount of bytes read after the beginning of that packet
1874 // divided by input bps. This will be inaccurate if the input/output
1875 // ratio is not constant for every audio packet or if it is constant
1876 // but not accurately known in sh_audio->i_bps.
1878 a_pts = d_audio->pts;
1879 if (a_pts == MP_NOPTS_VALUE)
1880 return a_pts;
1882 // ds_tell_pts returns bytes read after last timestamp from
1883 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1884 // it has read but not decoded
1885 if (sh_audio->i_bps)
1886 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1887 (double)sh_audio->i_bps;
1889 // Now a_pts hopefully holds the pts for end of audio from decoder.
1890 // Substract data in buffers between decoder and audio out.
1892 // Decoded but not filtered
1893 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1895 // Data buffered in audio filters, measured in bytes of "missing" output
1896 double buffered_output = af_calc_delay(sh_audio->afilter);
1898 // Data that was ready for ao but was buffered because ao didn't fully
1899 // accept everything to internal buffers yet
1900 buffered_output += mpctx->ao->buffer.len;
1902 // Filters divide audio length by playback_speed, so multiply by it
1903 // to get the length in original units without speedup or slowdown
1904 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1906 return a_pts + mpctx->video_offset;
1909 // Return pts value corresponding to currently playing audio.
1910 double playing_audio_pts(struct MPContext *mpctx)
1912 double pts = written_audio_pts(mpctx);
1913 if (pts == MP_NOPTS_VALUE)
1914 return pts;
1915 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1918 static bool is_av_sub(int type)
1920 return type == 'b' || type == 'p' || type == 'x';
1923 void update_subtitles(struct MPContext *mpctx, double refpts,
1924 double sub_offset, bool reset)
1926 struct MPOpts *opts = &mpctx->opts;
1927 struct sh_video *sh_video = mpctx->sh_video;
1928 struct demux_stream *d_sub = mpctx->d_sub;
1929 double curpts = refpts + sub_delay;
1930 unsigned char *packet = NULL;
1931 int len;
1932 struct sh_sub *sh_sub = d_sub->sh;
1933 int type = sh_sub ? sh_sub->type : 'v';
1934 static subtitle subs;
1935 if (reset) {
1936 if (sh_sub)
1937 sub_reset(sh_sub, mpctx->osd);
1938 sub_clear_text(&subs, MP_NOPTS_VALUE);
1939 if (vo_sub)
1940 set_osd_subtitle(mpctx, NULL);
1941 if (vo_spudec) {
1942 spudec_reset(vo_spudec);
1943 vo_osd_changed(OSDTYPE_SPU);
1945 #ifdef CONFIG_FFMPEG
1946 if (is_av_sub(type))
1947 reset_avsub(sh_sub);
1948 #endif
1949 return;
1951 // find sub
1952 if (mpctx->subdata) {
1953 if (sub_fps == 0)
1954 sub_fps = sh_video ? sh_video->fps : 25;
1955 current_module = "find_sub";
1956 find_sub(mpctx, mpctx->subdata, curpts *
1957 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1958 if (vo_sub)
1959 mpctx->vo_sub_last = vo_sub;
1962 // DVD sub:
1963 if (vobsub_id >= 0 || type == 'v') {
1964 int timestamp;
1965 current_module = "spudec";
1966 /* Get a sub packet from the DVD or a vobsub */
1967 while (1) {
1968 // Vobsub
1969 len = 0;
1970 if (vo_vobsub) {
1971 if (curpts >= 0) {
1972 len = vobsub_get_packet(vo_vobsub, curpts,
1973 (void **)&packet, &timestamp);
1974 if (len > 0)
1975 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1976 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1977 len, refpts, sh_video->timer,
1978 timestamp / 90000.0, timestamp);
1980 } else {
1981 // DVD sub
1982 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1983 if (len > 0) {
1984 // XXX This is wrong, sh_video->pts can be arbitrarily
1985 // much behind demuxing position. Unfortunately using
1986 // d_video->pts which would have been the simplest
1987 // improvement doesn't work because mpeg specific hacks
1988 // in video.c set d_video->pts to 0.
1989 float x = d_sub->pts - refpts;
1990 if (x > -20 && x < 20) // prevent missing subs on pts reset
1991 timestamp = 90000 * d_sub->pts;
1992 else
1993 timestamp = 90000 * curpts;
1994 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1995 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1996 refpts, d_sub->pts, timestamp);
1999 if (len <= 0 || !packet)
2000 break;
2001 // create it only here, since with some broken demuxers we might
2002 // type = v but no DVD sub and we currently do not change the
2003 // "original frame size" ever after init, leading to wrong-sized
2004 // PGS subtitles.
2005 if (!vo_spudec)
2006 vo_spudec = spudec_new(NULL);
2007 if (vo_vobsub || timestamp >= 0)
2008 spudec_assemble(vo_spudec, packet, len, timestamp);
2010 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
2011 if (type == 'd' && !d_sub->demuxer->teletext) {
2012 tt_stream_props tsp = { 0 };
2013 void *ptr = &tsp;
2014 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
2015 VBI_CONTROL_TRUE)
2016 d_sub->demuxer->teletext = ptr;
2018 if (d_sub->non_interleaved)
2019 ds_get_next_pts(d_sub);
2021 while (d_sub->first) {
2022 double subpts = ds_get_next_pts(d_sub) + sub_offset;
2023 if (subpts > curpts) {
2024 // Libass handled subs can be fed to it in advance
2025 if (!opts->ass_enabled || !is_text_sub(type))
2026 break;
2027 // Try to avoid demuxing whole file at once
2028 if (d_sub->non_interleaved && subpts > curpts + 1)
2029 break;
2031 double duration = d_sub->first->duration;
2032 len = ds_get_packet_sub(d_sub, &packet);
2033 if (is_av_sub(type)) {
2034 #ifdef CONFIG_FFMPEG
2035 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2036 if (ret < 0)
2037 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2038 "subtitle\n");
2039 #endif
2040 continue;
2042 if (type == 'm') {
2043 if (len < 2)
2044 continue;
2045 len = FFMIN(len - 2, AV_RB16(packet));
2046 packet += 2;
2048 if (type == 'd') {
2049 if (d_sub->demuxer->teletext) {
2050 uint8_t *p = packet;
2051 p++;
2052 len--;
2053 while (len >= 46) {
2054 int sublen = p[1];
2055 if (p[0] == 2 || p[0] == 3)
2056 teletext_control(d_sub->demuxer->teletext,
2057 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2058 p += sublen + 2;
2059 len -= sublen + 2;
2062 continue;
2064 if (sh_sub && sh_sub->active) {
2065 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2066 continue;
2068 if (subpts != MP_NOPTS_VALUE) {
2069 if (duration < 0)
2070 sub_clear_text(&subs, MP_NOPTS_VALUE);
2071 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2072 int i;
2073 unsigned char *p = packet;
2074 for (i = 0; i < 8 && *p != '\0'; p++)
2075 if (*p == ',')
2076 i++;
2077 if (*p == '\0') /* Broken line? */
2078 continue;
2079 len -= p - packet;
2080 packet = p;
2082 double endpts = MP_NOPTS_VALUE;
2083 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2084 endpts = subpts + duration;
2085 sub_add_text(&subs, packet, len, endpts);
2086 set_osd_subtitle(mpctx, &subs);
2088 if (d_sub->non_interleaved)
2089 ds_get_next_pts(d_sub);
2091 if (!opts->ass_enabled)
2092 if (sub_clear_text(&subs, curpts))
2093 set_osd_subtitle(mpctx, &subs);
2095 if (vo_spudec) {
2096 spudec_heartbeat(vo_spudec, 90000 * curpts);
2097 if (spudec_changed(vo_spudec))
2098 vo_osd_changed(OSDTYPE_SPU);
2101 current_module = NULL;
2104 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2106 int page_changed;
2108 if (!demuxer->teletext)
2109 return;
2111 //Also forcing page update when such ioctl is not supported or call error occured
2112 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2113 &page_changed) != VBI_CONTROL_TRUE)
2114 page_changed = 1;
2116 if (!page_changed)
2117 return;
2119 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2120 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2121 vo_osd_teletext_page = NULL;
2122 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2123 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2124 vo_osd_teletext_half = 0;
2125 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2126 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2127 vo_osd_teletext_mode = 0;
2128 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2129 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2130 vo_osd_teletext_format = 0;
2131 vo_osd_changed(OSDTYPE_TELETEXT);
2133 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2136 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2138 struct MPOpts *opts = &mpctx->opts;
2139 // check for frame-drop:
2140 current_module = "check_framedrop";
2141 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2142 static int dropped_frames;
2143 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2144 float d = delay - mpctx->delay;
2145 ++total_frame_cnt;
2146 // we should avoid dropping too many frames in sequence unless we
2147 // are too late. and we allow 100ms A-V delay here:
2148 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2149 && !mpctx->restart_playback) {
2150 ++drop_frame_cnt;
2151 ++dropped_frames;
2152 return frame_dropping;
2153 } else
2154 dropped_frames = 0;
2156 return 0;
2160 #ifdef HAVE_RTC
2161 int rtc_fd = -1;
2162 #endif
2164 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2166 #ifdef HAVE_RTC
2167 if (rtc_fd >= 0) {
2168 // -------- RTC -----------
2169 current_module = "sleep_rtc";
2170 while (time_frame > 0.000) {
2171 unsigned long rtc_ts;
2172 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2173 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2174 "Linux RTC read error: %s\n", strerror(errno));
2175 time_frame -= get_relative_time(mpctx);
2177 } else
2178 #endif
2180 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2181 // unnecessarily high CPU usage
2182 struct MPOpts *opts = &mpctx->opts;
2183 float margin = opts->softsleep ? 0.011 : 0;
2184 current_module = "sleep_timer";
2185 while (time_frame > margin) {
2186 usec_sleep(1000000 * (time_frame - margin));
2187 time_frame -= get_relative_time(mpctx);
2189 if (opts->softsleep) {
2190 current_module = "sleep_soft";
2191 if (time_frame < 0)
2192 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2193 "Warning! Softsleep underflow!\n");
2194 while (time_frame > 0)
2195 time_frame -= get_relative_time(mpctx); // burn the CPU
2198 return time_frame;
2201 static int select_subtitle(MPContext *mpctx)
2203 struct MPOpts *opts = &mpctx->opts;
2204 // find the best sub to use
2205 int id;
2206 int found = 0;
2207 mpctx->global_sub_pos = -1; // no subs by default
2208 if (vobsub_id >= 0) {
2209 // if user asks for a vobsub id, use that first.
2210 id = vobsub_id;
2211 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2212 M_PROPERTY_OK;
2215 if (!found && opts->sub_id >= 0) {
2216 // if user asks for a dvd sub id, use that next.
2217 id = opts->sub_id;
2218 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2219 M_PROPERTY_OK;
2222 if (!found) {
2223 // if there are text subs to use, use those. (autosubs come last here)
2224 id = 0;
2225 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2226 M_PROPERTY_OK;
2229 if (!found && opts->sub_id == -1) {
2230 // finally select subs by language and container hints
2231 if (opts->sub_id == -1)
2232 opts->sub_id =
2233 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2234 opts->sub_lang);
2235 if (opts->sub_id >= 0) {
2236 id = opts->sub_id;
2237 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2238 M_PROPERTY_OK;
2241 return found;
2244 #ifdef CONFIG_DVDNAV
2245 #ifndef FF_B_TYPE
2246 #define FF_B_TYPE 3
2247 #endif
2248 /// store decoded video image
2249 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2250 mp_image_t *from_mpi)
2252 mp_image_t *mpi;
2254 /// Do not store B-frames
2255 if (from_mpi->pict_type == FF_B_TYPE)
2256 return to_mpi;
2258 if (to_mpi &&
2259 to_mpi->w == from_mpi->w &&
2260 to_mpi->h == from_mpi->h &&
2261 to_mpi->imgfmt == from_mpi->imgfmt)
2262 mpi = to_mpi;
2263 else {
2264 if (to_mpi)
2265 free_mp_image(to_mpi);
2266 if (from_mpi->w == 0 || from_mpi->h == 0)
2267 return NULL;
2268 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2271 copy_mpi(mpi, from_mpi);
2272 return mpi;
2275 static void mp_dvdnav_reset_stream(MPContext *ctx)
2277 struct MPOpts *opts = &ctx->opts;
2278 if (ctx->sh_video) {
2279 /// clear video pts
2280 ctx->d_video->pts = 0.0f;
2281 ctx->sh_video->pts = 0.0f;
2282 ctx->sh_video->i_pts = 0.0f;
2283 ctx->sh_video->last_pts = 0.0f;
2284 ctx->sh_video->num_buffered_pts = 0;
2285 ctx->sh_video->num_frames = 0;
2286 ctx->sh_video->num_frames_decoded = 0;
2287 ctx->sh_video->timer = 0.0f;
2288 ctx->sh_video->stream_delay = 0.0f;
2289 ctx->sh_video->timer = 0;
2290 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2293 if (ctx->sh_audio) {
2294 /// free audio packets and reset
2295 ds_free_packs(ctx->d_audio);
2296 audio_delay -= ctx->sh_audio->stream_delay;
2297 ctx->delay = -audio_delay;
2298 ao_reset(ctx->ao);
2299 resync_audio_stream(ctx->sh_audio);
2302 audio_delay = 0.0f;
2303 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2304 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2305 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2306 if (dvdsub_lang_id != opts->sub_id) {
2307 opts->sub_id = dvdsub_lang_id;
2308 select_subtitle(ctx);
2312 /// clear all EOF related flags
2313 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2316 /// Restore last decoded DVDNAV (still frame)
2317 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2318 int *in_size,
2319 unsigned char **start,
2320 mp_image_t *decoded_frame)
2322 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2323 return decoded_frame;
2325 /// a change occurred in dvdnav stream
2326 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2327 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2328 mp_dvdnav_context_free(mpctx);
2329 mp_dvdnav_reset_stream(mpctx);
2330 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2331 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2334 if (*in_size < 0) {
2335 float len;
2337 /// Display still frame, if any
2338 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2339 decoded_frame = mpctx->nav_smpi;
2341 /// increment video frame : continue playing after still frame
2342 len = get_time_length(mpctx);
2343 if (mpctx->sh_video->pts >= len &&
2344 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2345 mp_dvdnav_skip_still(mpctx->stream);
2346 mp_dvdnav_skip_wait(mpctx->stream);
2348 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2350 if (mpctx->nav_buffer) {
2351 *start = mpctx->nav_start;
2352 *in_size = mpctx->nav_in_size;
2353 if (mpctx->nav_start)
2354 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2358 return decoded_frame;
2361 /// Save last decoded DVDNAV (still frame)
2362 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2363 unsigned char *start,
2364 mp_image_t *decoded_frame)
2366 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2367 return;
2369 free(mpctx->nav_buffer);
2370 mpctx->nav_buffer = NULL;
2371 mpctx->nav_start = NULL;
2372 mpctx->nav_in_size = -1;
2374 if (in_size > 0)
2375 mpctx->nav_buffer = malloc(in_size);
2376 if (mpctx->nav_buffer) {
2377 mpctx->nav_start = start;
2378 mpctx->nav_in_size = in_size;
2379 memcpy(mpctx->nav_buffer, start, in_size);
2382 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2383 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2385 #endif /* CONFIG_DVDNAV */
2387 /* Modify video timing to match the audio timeline. There are two main
2388 * reasons this is needed. First, video and audio can start from different
2389 * positions at beginning of file or after a seek (MPlayer starts both
2390 * immediately even if they have different pts). Second, the file can have
2391 * audio timestamps that are inconsistent with the duration of the audio
2392 * packets, for example two consecutive timestamp values differing by
2393 * one second but only a packet with enough samples for half a second
2394 * of playback between them.
2396 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2398 current_module = "av_sync";
2400 if (!mpctx->sh_audio || mpctx->syncing_audio)
2401 return;
2403 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2404 double v_pts = mpctx->sh_video->pts;
2405 double av_delay = a_pts - v_pts;
2406 // Try to sync vo_flip() so it will *finish* at given time
2407 av_delay += mpctx->last_vo_flip_duration;
2408 av_delay -= audio_delay; // This much pts difference is desired
2410 double change = av_delay * 0.1;
2411 double max_change = default_max_pts_correction >= 0 ?
2412 default_max_pts_correction : frame_time * 0.1;
2413 if (change < -max_change)
2414 change = -max_change;
2415 else if (change > max_change)
2416 change = max_change;
2417 mpctx->delay += change;
2418 mpctx->total_avsync_change += change;
2421 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2422 double pts)
2424 if (mpctx->paused)
2425 return 0;
2426 struct ao *ao = mpctx->ao;
2427 double bps = ao->bps / mpctx->opts.playback_speed;
2428 ao->pts = pts;
2429 // hack used by some mpeg-writing AOs
2430 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2431 mpctx->delay) * 90000.0;
2432 int played = ao_play(mpctx->ao, data, len, flags);
2433 if (played > 0) {
2434 mpctx->delay += played / bps;
2435 // Keep correct pts for remaining data - could be used to flush
2436 // remaining buffer when closing ao.
2437 ao->pts += played / bps;
2439 return played;
2442 #define ASYNC_PLAY_DONE -3
2443 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2445 struct ao *ao = mpctx->ao;
2446 struct MPOpts *opts = &mpctx->opts;
2447 sh_audio_t * const sh_audio = mpctx->sh_audio;
2448 int res;
2450 // Timing info may not be set without
2451 res = decode_audio(sh_audio, &ao->buffer, 1);
2452 if (res < 0)
2453 return res;
2455 int bytes;
2456 bool did_retry = false;
2457 double written_pts;
2458 double bps = ao->bps / opts->playback_speed;
2459 while (1) {
2460 written_pts = written_audio_pts(mpctx);
2461 double ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2462 - audio_delay;
2463 bytes = ptsdiff * bps;
2464 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2466 // ogg demuxers give packets without timing
2467 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2468 if (!did_retry) {
2469 // Try to read more data to see packets that have pts
2470 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2471 if (res < 0)
2472 return res;
2473 did_retry = true;
2474 continue;
2476 bytes = 0;
2479 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2480 bytes = 0;
2482 if (bytes > 0)
2483 break;
2485 mpctx->syncing_audio = false;
2486 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2487 int res = decode_audio(sh_audio, &ao->buffer, a);
2488 bytes += ao->buffer.len;
2489 if (bytes >= 0) {
2490 memmove(ao->buffer.start,
2491 ao->buffer.start + ao->buffer.len - bytes, bytes);
2492 ao->buffer.len = bytes;
2493 if (res < 0)
2494 return res;
2495 return decode_audio(sh_audio, &ao->buffer, playsize);
2497 ao->buffer.len = 0;
2498 if (res < 0)
2499 return res;
2501 int fillbyte = 0;
2502 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2503 fillbyte = 0x80;
2504 if (bytes >= playsize) {
2505 /* This case could fall back to the one below with
2506 * bytes = playsize, but then silence would keep accumulating
2507 * in a_out_buffer if the AO accepts less data than it asks for
2508 * in playsize. */
2509 char *p = malloc(playsize);
2510 memset(p, fillbyte, playsize);
2511 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2512 free(p);
2513 return ASYNC_PLAY_DONE;
2515 mpctx->syncing_audio = false;
2516 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2517 return decode_audio(sh_audio, &ao->buffer, playsize);
2520 static int fill_audio_out_buffers(struct MPContext *mpctx)
2522 struct MPOpts *opts = &mpctx->opts;
2523 struct ao *ao = mpctx->ao;
2524 unsigned int t;
2525 double tt;
2526 int playsize;
2527 int playflags = 0;
2528 bool audio_eof = false;
2529 bool partial_fill = false;
2530 sh_audio_t * const sh_audio = mpctx->sh_audio;
2531 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2532 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2534 current_module = "play_audio";
2536 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2537 return 0;
2539 // hack used by some mpeg-writing AOs
2540 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2541 mpctx->delay) * 90000.0;
2543 if (mpctx->paused)
2544 playsize = 1; // just initialize things (audio pts at least)
2545 else
2546 playsize = ao_get_space(ao);
2548 // Fill buffer if needed:
2549 current_module = "decode_audio";
2550 t = GetTimer();
2552 if (!opts->initial_audio_sync || !modifiable_audio_format)
2553 mpctx->syncing_audio = false;
2555 int res;
2556 if (mpctx->syncing_audio && mpctx->sh_video)
2557 res = audio_start_sync(mpctx, playsize);
2558 else
2559 res = decode_audio(sh_audio, &ao->buffer, playsize);
2560 if (res < 0) { // EOF, error or format change
2561 if (res == -2) {
2562 /* The format change isn't handled too gracefully. A more precise
2563 * implementation would require draining buffered old-format audio
2564 * while displaying video, then doing the output format switch.
2566 uninit_player(mpctx, INITIALIZED_AO);
2567 reinit_audio_chain(mpctx);
2568 return -1;
2569 } else if (res == ASYNC_PLAY_DONE)
2570 return 0;
2571 else if (mpctx->d_audio->eof)
2572 audio_eof = true;
2574 t = GetTimer() - t;
2575 tt = t * 0.000001f;
2576 audio_time_usage += tt;
2577 if (mpctx->timeline && modifiable_audio_format) {
2578 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2579 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2580 * ao->bps / opts->playback_speed;
2581 if (playsize > bytes) {
2582 playsize = FFMAX(bytes, 0);
2583 playflags |= AOPLAY_FINAL_CHUNK;
2584 audio_eof = true;
2585 partial_fill = true;
2589 assert(ao->buffer.len % unitsize == 0);
2590 if (playsize > ao->buffer.len) {
2591 partial_fill = true;
2592 playsize = ao->buffer.len;
2593 if (audio_eof)
2594 playflags |= AOPLAY_FINAL_CHUNK;
2596 playsize -= playsize % unitsize;
2597 if (!playsize)
2598 return partial_fill && audio_eof ? -2 : -partial_fill;
2600 // play audio:
2601 current_module = "play_audio";
2603 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2604 written_audio_pts(mpctx));
2605 assert(played % unitsize == 0);
2606 ao->buffer_playable_size = playsize - played;
2608 if (played > 0) {
2609 ao->buffer.len -= played;
2610 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2611 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2612 // Sanity check to avoid hanging in case current ao doesn't output
2613 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2614 return -2;
2617 return -partial_fill;
2620 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2621 bool sync_to_audio, float *aq_sleep_time)
2623 struct MPOpts *opts = &mpctx->opts;
2624 double audio_limit = 2;
2625 current_module = "calc_sleep_time";
2627 if (mpctx->restart_playback)
2628 return 0;
2630 *time_frame -= get_relative_time(mpctx); // reset timer
2632 if (sync_to_audio) {
2633 float delay = ao_get_delay(mpctx->ao);
2634 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2636 if (opts->autosync) {
2638 * Adjust this raw delay value by calculating the expected
2639 * delay for this frame and generating a new value which is
2640 * weighted between the two. The higher autosync is, the
2641 * closer to the delay value gets to that which "-nosound"
2642 * would have used, and the longer it will take for A/V
2643 * sync to settle at the right value (but it eventually will.)
2644 * This settling time is very short for values below 100.
2646 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2647 float difference = delay - predicted;
2648 delay = predicted + difference / (float)opts->autosync;
2651 *time_frame = delay - mpctx->delay / opts->playback_speed;
2653 // delay = amount of audio buffered in soundcard/driver
2654 delay = FFMIN(delay, 0.5);
2655 delay = FFMAX(delay, 0.1);
2656 audio_limit = delay;
2657 } else {
2658 // If we're lagging more than 200 ms behind the right playback rate,
2659 // don't try to "catch up".
2660 // If benchmark is set always output frames as fast as possible
2661 // without sleeping.
2662 if (*time_frame < -0.2 || opts->benchmark)
2663 *time_frame = 0;
2666 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2668 if (t <= 0.05)
2669 return 0;
2671 t -= 0.05;
2672 if (t > audio_limit * 0.6)
2673 t = audio_limit * 0.5;
2674 *aq_sleep_time += t;
2675 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2676 return 1;
2679 int reinit_video_chain(struct MPContext *mpctx)
2681 struct MPOpts *opts = &mpctx->opts;
2682 sh_video_t * const sh_video = mpctx->sh_video;
2683 if (!sh_video)
2684 return 0;
2685 double ar = -1.0;
2686 //================== Init VIDEO (codec & libvo) ==========================
2687 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2688 current_module = "preinit_libvo";
2690 //shouldn't we set dvideo->id=-2 when we fail?
2691 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2692 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2693 mpctx->key_fifo,
2694 mpctx->input))) {
2695 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2696 "the selected video_out (-vo) device.\n");
2697 goto err_out;
2699 mpctx->initialized_flags |= INITIALIZED_VO;
2702 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2703 &ar) != STREAM_UNSUPPORTED)
2704 mpctx->sh_video->stream_aspect = ar;
2705 current_module = "init_video_filters";
2707 char *vf_arg[] = {
2708 "_oldargs_", (char *)mpctx->video_out, NULL
2710 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2713 #ifdef CONFIG_ASS
2714 if (opts->ass_enabled) {
2715 int i;
2716 int insert = 1;
2717 if (opts->vf_settings)
2718 for (i = 0; opts->vf_settings[i].name; ++i)
2719 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2720 insert = 0;
2721 break;
2723 if (insert) {
2724 extern vf_info_t vf_info_ass;
2725 const vf_info_t *libass_vfs[] = {
2726 &vf_info_ass, NULL
2728 char *vf_arg[] = {
2729 "auto", "1", NULL
2731 int retcode = 0;
2732 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2733 sh_video->vfilter,
2734 "ass", vf_arg,
2735 &retcode);
2736 if (vf_ass)
2737 sh_video->vfilter = vf_ass;
2738 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2739 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2740 else
2741 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2742 "ASS: cannot add video filter\n");
2745 #endif
2747 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2749 #ifdef CONFIG_ASS
2750 if (opts->ass_enabled)
2751 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2752 mpctx->ass_library);
2753 #endif
2755 current_module = "init_video_codec";
2757 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2758 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2759 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2761 if (!sh_video->initialized) {
2762 if (!opts->fixed_vo)
2763 uninit_player(mpctx, INITIALIZED_VO);
2764 goto err_out;
2767 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2769 if (sh_video->codec)
2770 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2771 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2773 sh_video->last_pts = MP_NOPTS_VALUE;
2774 sh_video->num_buffered_pts = 0;
2775 sh_video->next_frame_time = 0;
2777 if (opts->auto_quality > 0) {
2778 // Auto quality option enabled
2779 output_quality = get_video_quality_max(sh_video);
2780 if (opts->auto_quality > output_quality)
2781 opts->auto_quality = output_quality;
2782 else
2783 output_quality = opts->auto_quality;
2784 mp_msg(MSGT_CPLAYER, MSGL_V,
2785 "AutoQ: setting quality to %d.\n", output_quality);
2786 set_video_quality(sh_video, output_quality);
2789 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2791 current_module = "init_vo";
2793 return 1;
2795 err_out:
2796 mpctx->sh_video = mpctx->d_video->sh = NULL;
2797 return 0;
2800 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2802 struct sh_video *sh_video = mpctx->sh_video;
2803 double frame_time = 0;
2804 struct vo *video_out = mpctx->video_out;
2805 while (1) {
2806 current_module = "filter_video";
2807 // In nocorrect-pts mode there is no way to properly time these frames
2808 if (vo_get_buffered_frame(video_out, 0) >= 0)
2809 break;
2810 if (vf_output_queued_frame(sh_video->vfilter))
2811 break;
2812 unsigned char *packet = NULL;
2813 frame_time = sh_video->next_frame_time;
2814 if (mpctx->restart_playback)
2815 frame_time = 0;
2816 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2817 &packet, force_fps);
2818 if (in_size < 0) {
2819 #ifdef CONFIG_DVDNAV
2820 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2821 if (mp_dvdnav_is_eof(mpctx->stream))
2822 return -1;
2823 if (mpctx->d_video)
2824 mpctx->d_video->eof = 0;
2825 if (mpctx->d_audio)
2826 mpctx->d_audio->eof = 0;
2827 mpctx->stream->eof = 0;
2828 } else
2829 #endif
2830 return -1;
2832 if (in_size > max_framesize)
2833 max_framesize = in_size;
2834 sh_video->timer += frame_time;
2835 if (mpctx->sh_audio)
2836 mpctx->delay -= frame_time;
2837 // video_read_frame can change fps (e.g. for ASF video)
2838 vo_fps = sh_video->fps;
2839 int framedrop_type = check_framedrop(mpctx, frame_time);
2840 current_module = "decode video";
2842 void *decoded_frame;
2843 #ifdef CONFIG_DVDNAV
2844 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2845 if (in_size >= 0 && !decoded_frame)
2846 #endif
2847 decoded_frame = decode_video(sh_video, NULL, packet, in_size,
2848 framedrop_type, sh_video->pts);
2849 #ifdef CONFIG_DVDNAV
2850 // Save last still frame for future display
2851 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2852 #endif
2853 if (decoded_frame) {
2854 current_module = "filter video";
2855 filter_video(sh_video, decoded_frame, sh_video->pts);
2857 break;
2859 return frame_time;
2862 static void determine_frame_pts(struct MPContext *mpctx)
2864 struct sh_video *sh_video = mpctx->sh_video;
2865 struct MPOpts *opts = &mpctx->opts;
2867 if (opts->user_pts_assoc_mode)
2868 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2869 else if (sh_video->pts_assoc_mode == 0) {
2870 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2871 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2872 sh_video->pts_assoc_mode = 1;
2873 else
2874 sh_video->pts_assoc_mode = 2;
2875 } else {
2876 int probcount1 = sh_video->num_reordered_pts_problems;
2877 int probcount2 = sh_video->num_sorted_pts_problems;
2878 if (sh_video->pts_assoc_mode == 2) {
2879 int tmp = probcount1;
2880 probcount1 = probcount2;
2881 probcount2 = tmp;
2883 if (probcount1 >= probcount2 * 1.5 + 2) {
2884 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2885 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2886 "%d.\n", sh_video->pts_assoc_mode);
2889 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2890 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2893 static double update_video(struct MPContext *mpctx)
2895 struct sh_video *sh_video = mpctx->sh_video;
2896 struct vo *video_out = mpctx->video_out;
2897 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2898 mpctx->osd); // hack for vf_expand
2899 if (!mpctx->opts.correct_pts)
2900 return update_video_nocorrect_pts(mpctx);
2902 double pts;
2904 while (1) {
2905 current_module = "filter_video";
2906 if (!mpctx->hrseek_active
2907 && vo_get_buffered_frame(video_out, false) >= 0)
2908 break;
2909 // XXX Time used in this call is not counted in any performance
2910 // timer now
2911 if (vf_output_queued_frame(sh_video->vfilter))
2912 break;
2913 int in_size = 0;
2914 unsigned char *buf = NULL;
2915 pts = MP_NOPTS_VALUE;
2916 struct demux_packet *pkt = ds_get_packet2(mpctx->d_video);
2917 if (pkt) {
2918 in_size = pkt->len;
2919 buf = pkt->buffer;
2920 pts = pkt->pts;
2922 if (pts != MP_NOPTS_VALUE)
2923 pts += mpctx->video_offset;
2924 if (in_size > max_framesize)
2925 max_framesize = in_size;
2926 current_module = "decode video";
2927 if (pts >= mpctx->hrseek_pts - .005)
2928 mpctx->hrseek_framedrop = false;
2929 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2930 check_framedrop(mpctx, sh_video->frametime);
2931 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2932 framedrop_type, pts);
2933 if (decoded_frame) {
2934 determine_frame_pts(mpctx);
2935 current_module = "filter video";
2936 filter_video(sh_video, decoded_frame, sh_video->pts);
2937 } else if (!pkt) {
2938 if (vo_get_buffered_frame(video_out, true) < 0)
2939 return -1;
2941 break;
2944 if (!video_out->frame_loaded)
2945 return 0;
2947 pts = video_out->next_pts;
2948 if (pts == MP_NOPTS_VALUE) {
2949 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2950 // Try to use decoder pts from before filters
2951 pts = sh_video->pts;
2952 if (pts == MP_NOPTS_VALUE)
2953 pts = sh_video->last_pts;
2955 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2956 vo_skip_frame(video_out);
2957 return 0;
2959 mpctx->hrseek_active = false;
2960 sh_video->pts = pts;
2961 if (sh_video->last_pts == MP_NOPTS_VALUE)
2962 sh_video->last_pts = sh_video->pts;
2963 else if (sh_video->last_pts > sh_video->pts) {
2964 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2965 sh_video->pts, sh_video->last_pts);
2966 /* If the difference in pts is small treat it as jitter around the
2967 * right value (possibly caused by incorrect timestamp ordering) and
2968 * just show this frame immediately after the last one.
2969 * Treat bigger differences as timestamp resets and start counting
2970 * timing of later frames from the position of this one. */
2971 if (sh_video->last_pts - sh_video->pts > 0.5)
2972 sh_video->last_pts = sh_video->pts;
2973 else
2974 sh_video->pts = sh_video->last_pts;
2976 double frame_time = sh_video->pts - sh_video->last_pts;
2977 sh_video->last_pts = sh_video->pts;
2978 sh_video->timer += frame_time;
2979 if (mpctx->sh_audio)
2980 mpctx->delay -= frame_time;
2981 return frame_time;
2984 void pause_player(struct MPContext *mpctx)
2986 if (mpctx->paused)
2987 return;
2988 mpctx->paused = 1;
2989 mpctx->step_frames = 0;
2990 mpctx->time_frame -= get_relative_time(mpctx);
2992 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2993 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2995 if (mpctx->ao && mpctx->sh_audio)
2996 ao_pause(mpctx->ao); // pause audio, keep data if possible
2999 void unpause_player(struct MPContext *mpctx)
3001 if (!mpctx->paused)
3002 return;
3003 mpctx->paused = 0;
3005 if (mpctx->ao && mpctx->sh_audio)
3006 ao_resume(mpctx->ao);
3007 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3008 && !mpctx->step_frames)
3009 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3010 (void)get_relative_time(mpctx); // ignore time that passed during pause
3013 void add_step_frame(struct MPContext *mpctx)
3015 mpctx->step_frames++;
3016 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3017 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3018 unpause_player(mpctx);
3021 static void pause_loop(struct MPContext *mpctx)
3023 struct MPOpts *opts = &mpctx->opts;
3024 mp_cmd_t *cmd;
3025 #ifdef CONFIG_STREAM_CACHE
3026 int old_cache_fill = stream_cache_size > 0 ?
3027 cache_fill_status(mpctx->stream) : 0;
3028 #endif
3029 if (!opts->quiet) {
3030 if (opts->term_osd && !mpctx->sh_video) {
3031 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
3032 update_osd_msg(mpctx);
3033 } else
3034 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
3035 mp_gtext(" ===== PAUSE ====="));
3036 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
3039 while ((cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
3040 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
3041 if (cmd) {
3042 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3043 run_command(mpctx, cmd);
3044 mp_cmd_free(cmd);
3045 continue;
3047 if (mpctx->sh_video && mpctx->video_out)
3048 vo_check_events(mpctx->video_out);
3049 usec_sleep(20000);
3050 update_osd_msg(mpctx);
3051 int hack = vo_osd_changed(0);
3052 vo_osd_changed(hack);
3053 if (hack)
3054 break;
3055 #ifdef CONFIG_STREAM_CACHE
3056 if (!opts->quiet && stream_cache_size > 0) {
3057 int new_cache_fill = cache_fill_status(mpctx->stream);
3058 if (new_cache_fill != old_cache_fill) {
3059 if (opts->term_osd && !mpctx->sh_video) {
3060 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
3061 mp_gtext(" ===== PAUSE ====="),
3062 new_cache_fill);
3063 update_osd_msg(mpctx);
3064 } else
3065 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
3066 mp_gtext(" ===== PAUSE ====="),
3067 new_cache_fill);
3068 old_cache_fill = new_cache_fill;
3071 #endif
3076 // Find the right mute status and record position for new file position
3077 static void edl_seek_reset(MPContext *mpctx)
3079 mpctx->edl_muted = 0;
3080 next_edl_record = edl_records;
3082 while (next_edl_record) {
3083 if (next_edl_record->start_sec >= get_current_time(mpctx))
3084 break;
3086 if (next_edl_record->action == EDL_MUTE)
3087 mpctx->edl_muted = !mpctx->edl_muted;
3088 next_edl_record = next_edl_record->next;
3090 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3091 mixer_mute(&mpctx->mixer);
3095 // Execute EDL command for the current position if one exists
3096 static void edl_update(MPContext *mpctx)
3098 if (!next_edl_record)
3099 return;
3101 if (!mpctx->sh_video) {
3102 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
3103 "Cannot use EDL without video, disabling.\n");
3104 free_edl(edl_records);
3105 next_edl_record = NULL;
3106 edl_records = NULL;
3107 return;
3110 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3111 if (next_edl_record->action == EDL_SKIP) {
3112 mpctx->osd_function = OSD_FFW;
3113 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3114 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3115 "[%f], length [%f]\n", next_edl_record->start_sec,
3116 next_edl_record->stop_sec, next_edl_record->length_sec);
3117 } else if (next_edl_record->action == EDL_MUTE) {
3118 mpctx->edl_muted = !mpctx->edl_muted;
3119 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3120 mixer_mute(&mpctx->mixer);
3121 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3122 next_edl_record->start_sec);
3124 next_edl_record = next_edl_record->next;
3128 static void reinit_decoders(struct MPContext *mpctx)
3130 reinit_video_chain(mpctx);
3131 reinit_audio_chain(mpctx);
3132 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3135 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3137 if (mpctx->sh_video) {
3138 current_module = "seek_video_reset";
3139 resync_video_stream(mpctx->sh_video);
3140 mpctx->sh_video->timer = 0;
3141 vo_seek_reset(mpctx->video_out);
3142 mpctx->sh_video->timer = 0;
3143 mpctx->sh_video->num_buffered_pts = 0;
3144 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3145 mpctx->delay = 0;
3146 mpctx->time_frame = 0;
3147 mpctx->restart_playback = true;
3148 // Not all demuxers set d_video->pts during seek, so this value
3149 // (which is used by at least vobsub and edl code below) may
3150 // be completely wrong (probably 0).
3151 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3152 mpctx->video_pts = mpctx->sh_video->pts;
3153 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3154 true);
3155 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3158 if (mpctx->sh_audio) {
3159 current_module = "seek_audio_reset";
3160 resync_audio_stream(mpctx->sh_audio);
3161 if (reset_ao)
3162 ao_reset(mpctx->ao);
3163 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3164 mpctx->sh_audio->a_buffer_len = 0;
3165 if (!mpctx->sh_video)
3166 update_subtitles(mpctx, mpctx->sh_audio->pts,
3167 mpctx->video_offset, true);
3170 if (vo_vobsub && mpctx->sh_video) {
3171 current_module = "seek_vobsub_reset";
3172 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3175 edl_seek_reset(mpctx);
3177 mpctx->hrseek_active = false;
3178 mpctx->hrseek_framedrop = false;
3179 mpctx->total_avsync_change = 0;
3180 audio_time_usage = 0;
3181 video_time_usage = 0;
3182 vout_time_usage = 0;
3183 drop_frame_cnt = 0;
3185 current_module = NULL;
3188 static bool timeline_set_part(struct MPContext *mpctx, int i)
3190 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3191 struct timeline_part *n = mpctx->timeline + i;
3192 mpctx->timeline_part = i;
3193 mpctx->video_offset = n->start - n->source_start;
3194 if (n->source == p->source)
3195 return false;
3196 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3197 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3198 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3199 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3200 mpctx->stop_play = orig_stop_play;
3201 mpctx->demuxer = n->source->demuxer;
3202 mpctx->d_video = mpctx->demuxer->video;
3203 mpctx->d_audio = mpctx->demuxer->audio;
3204 mpctx->d_sub = mpctx->demuxer->sub;
3205 mpctx->sh_video = mpctx->d_video->sh;
3206 mpctx->sh_audio = mpctx->d_audio->sh;
3207 return true;
3210 // Given pts, switch playback to the corresponding part.
3211 // Return offset within that part.
3212 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3213 bool *need_reset)
3215 if (pts < 0)
3216 pts = 0;
3217 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3218 struct timeline_part *p = mpctx->timeline + i;
3219 if (pts < (p + 1)->start) {
3220 *need_reset = timeline_set_part(mpctx, i);
3221 return pts - p->start + p->source_start;
3224 return -1;
3228 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3229 static int seek(MPContext *mpctx, struct seek_params seek,
3230 bool timeline_fallthrough)
3232 struct MPOpts *opts = &mpctx->opts;
3234 current_module = "seek";
3235 if (mpctx->stop_play == AT_END_OF_FILE)
3236 mpctx->stop_play = KEEP_PLAYING;
3237 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3238 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3239 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3240 || opts->hr_seek > 0 || seek.exact > 0;
3241 if (seek.type == MPSEEK_FACTOR
3242 || seek.type == MPSEEK_ABSOLUTE
3243 && seek.amount < mpctx->last_chapter_pts
3244 || seek.amount < 0)
3245 mpctx->last_chapter_seek = -2;
3246 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3247 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3248 seek.type = MPSEEK_ABSOLUTE;
3250 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3251 && seek.type == MPSEEK_RELATIVE) {
3252 seek.type = MPSEEK_ABSOLUTE;
3253 seek.direction = seek.amount > 0 ? 1 : -1;
3254 seek.amount += get_current_time(mpctx);
3257 /* At least the liba52 decoder wants to read from the input stream
3258 * during initialization, so reinit must be done after the demux_seek()
3259 * call that clears possible stream EOF. */
3260 bool need_reset = false;
3261 double demuxer_amount = seek.amount;
3262 if (mpctx->timeline) {
3263 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3264 &need_reset);
3265 if (demuxer_amount == -1) {
3266 mpctx->stop_play = AT_END_OF_FILE;
3267 // Clear audio from current position
3268 if (mpctx->sh_audio) {
3269 ao_reset(mpctx->ao);
3270 mpctx->sh_audio->a_buffer_len = 0;
3272 return -1;
3275 int demuxer_style = 0;
3276 switch (seek.type) {
3277 case MPSEEK_FACTOR:
3278 demuxer_style |= SEEK_FACTOR; // fallthrough
3279 case MPSEEK_ABSOLUTE:
3280 demuxer_style |= SEEK_ABSOLUTE;
3282 if (hr_seek || seek.direction < 0)
3283 demuxer_style |= SEEK_BACKWARD;
3284 else if (seek.direction > 0)
3285 demuxer_style |= SEEK_FORWARD;
3287 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3288 demuxer_style);
3289 if (need_reset)
3290 reinit_decoders(mpctx);
3291 if (seekresult == 0)
3292 return -1;
3294 seek_reset(mpctx, !timeline_fallthrough);
3296 /* Use the target time as "current position" for further relative
3297 * seeks etc until a new video frame has been decoded */
3298 if (seek.type == MPSEEK_ABSOLUTE) {
3299 mpctx->video_pts = seek.amount;
3300 mpctx->last_seek_pts = seek.amount;
3301 } else
3302 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3304 if (hr_seek) {
3305 mpctx->hrseek_active = true;
3306 mpctx->hrseek_framedrop = true;
3307 mpctx->hrseek_pts = seek.amount;
3310 mpctx->start_timestamp = GetTimerMS();
3312 return 0;
3315 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3316 int exact)
3318 struct seek_params *seek = &mpctx->seek;
3319 switch (type) {
3320 case MPSEEK_RELATIVE:
3321 if (seek->type == MPSEEK_FACTOR)
3322 return; // Well... not common enough to bother doing better
3323 seek->amount += amount;
3324 seek->exact = FFMAX(seek->exact, exact);
3325 if (seek->type == MPSEEK_NONE)
3326 seek->exact = exact;
3327 if (seek->type == MPSEEK_ABSOLUTE)
3328 return;
3329 if (seek->amount == 0) {
3330 *seek = (struct seek_params){ 0 };
3331 return;
3333 seek->type = MPSEEK_RELATIVE;
3334 return;
3335 case MPSEEK_ABSOLUTE:
3336 case MPSEEK_FACTOR:
3337 *seek = (struct seek_params) {
3338 .type = type,
3339 .amount = amount,
3340 .exact = exact,
3342 return;
3343 case MPSEEK_NONE:
3344 *seek = (struct seek_params){ 0 };
3345 return;
3347 abort();
3351 double get_time_length(struct MPContext *mpctx)
3353 if (mpctx->timeline)
3354 return mpctx->timeline[mpctx->num_timeline_parts].start;
3356 struct demuxer *demuxer = mpctx->demuxer;
3357 double get_time_ans;
3358 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3359 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3360 (void *) &get_time_ans) > 0)
3361 return get_time_ans;
3363 struct sh_video *sh_video = mpctx->d_video->sh;
3364 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3365 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3366 return (double) (demuxer->movi_end - demuxer->movi_start) /
3367 (sh_video->i_bps + sh_audio->i_bps);
3368 if (sh_video && sh_video->i_bps)
3369 return (double) (demuxer->movi_end - demuxer->movi_start) /
3370 sh_video->i_bps;
3371 if (sh_audio && sh_audio->i_bps)
3372 return (double) (demuxer->movi_end - demuxer->movi_start) /
3373 sh_audio->i_bps;
3374 return 0;
3377 /* If there are timestamps from stream level then use those (for example
3378 * DVDs can have consistent times there while the MPEG-level timestamps
3379 * reset). */
3380 double get_current_time(struct MPContext *mpctx)
3382 struct demuxer *demuxer = mpctx->demuxer;
3383 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3384 return demuxer->stream_pts;
3385 struct sh_video *sh_video = demuxer->video->sh;
3386 if (sh_video)
3387 return mpctx->video_pts;
3388 double apts = playing_audio_pts(mpctx);
3389 if (apts != MP_NOPTS_VALUE)
3390 return apts;
3391 return mpctx->last_seek_pts;
3394 int get_percent_pos(struct MPContext *mpctx)
3396 struct demuxer *demuxer = mpctx->demuxer;
3397 int ans = 0;
3398 if (mpctx->timeline)
3399 ans = get_current_time(mpctx) * 100 /
3400 mpctx->timeline[mpctx->num_timeline_parts].start;
3401 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3403 else {
3404 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3405 off_t pos = demuxer->filepos > 0 ?
3406 demuxer->filepos : stream_tell(demuxer->stream);
3407 if (len > 0)
3408 ans = (pos - demuxer->movi_start) / len;
3409 else
3410 ans = 0;
3412 if (ans < 0)
3413 ans = 0;
3414 if (ans > 100)
3415 ans = 100;
3416 return ans;
3419 // -2 is no chapters, -1 is before first chapter
3420 int get_current_chapter(struct MPContext *mpctx)
3422 double current_pts = get_current_time(mpctx);
3423 if (!mpctx->chapters)
3424 return FFMAX(mpctx->last_chapter_seek,
3425 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3427 int i;
3428 for (i = 1; i < mpctx->num_chapters; i++)
3429 if (current_pts < mpctx->chapters[i].start)
3430 break;
3431 return FFMAX(mpctx->last_chapter_seek, i - 1);
3434 // currently returns a string allocated with malloc, not talloc
3435 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3437 if (!mpctx->chapters)
3438 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3439 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3442 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3443 char **chapter_name)
3445 mpctx->last_chapter_seek = -2;
3446 if (!mpctx->chapters) {
3447 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3448 chapter_name);
3449 if (res >= 0) {
3450 if (*seek_pts == -1)
3451 seek_reset(mpctx, true);
3452 else {
3453 mpctx->last_chapter_seek = res;
3454 mpctx->last_chapter_pts = *seek_pts;
3457 return res;
3460 if (chapter >= mpctx->num_chapters)
3461 return -1;
3462 if (chapter < 0)
3463 chapter = 0;
3464 *seek_pts = mpctx->chapters[chapter].start;
3465 mpctx->last_chapter_seek = chapter;
3466 mpctx->last_chapter_pts = *seek_pts;
3467 if (chapter_name)
3468 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3469 return chapter;
3473 static void run_playloop(struct MPContext *mpctx)
3475 struct MPOpts *opts = &mpctx->opts;
3476 float aq_sleep_time = 0;
3477 bool full_audio_buffers = false;
3479 if (opts->chapterrange[1] > 0) {
3480 int cur_chapter = get_current_chapter(mpctx);
3481 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3482 mpctx->stop_play = PT_NEXT_ENTRY;
3485 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3486 mpctx->sh_audio = mpctx->d_audio->sh;
3487 mpctx->sh_audio->ds = mpctx->d_audio;
3488 reinit_audio_chain(mpctx);
3491 /*========================== PLAY AUDIO ============================*/
3493 if (!mpctx->sh_video)
3494 mpctx->restart_playback = false;
3496 if (mpctx->sh_audio && !mpctx->restart_playback) {
3497 int status = fill_audio_out_buffers(mpctx);
3498 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3499 if (status == -2)
3500 // at eof, all audio at least written to ao
3501 if (!mpctx->sh_video)
3502 mpctx->stop_play = AT_END_OF_FILE;
3506 if (!mpctx->sh_video) {
3507 if (mpctx->step_frames) {
3508 mpctx->step_frames = 0;
3509 pause_player(mpctx);
3511 // handle audio-only case:
3512 double a_pos = 0, a_buf = 0;
3513 // sh_audio can be NULL due to video stream switching
3514 // TODO: handle this better
3515 if (mpctx->sh_audio) {
3516 a_buf = ao_get_delay(mpctx->ao);
3517 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3518 a_buf;
3521 print_status(mpctx, a_pos, false);
3523 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3524 update_osd_msg(mpctx);
3525 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3526 mpctx->stop_play = AT_END_OF_FILE;
3527 else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3528 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3529 && mpctx->sh_audio) {
3530 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3531 if (!opts->gapless_audio && p->source != (p + 1)->source
3532 && a_buf > 0.05) {
3533 mpctx->stop_play = KEEP_PLAYING;
3534 mp_input_get_cmd(mpctx->input, (a_buf - .05) * 1000, true);
3535 } else {
3536 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3537 .amount = (p + 1)->start },
3538 true);
3540 } else if (!mpctx->stop_play) {
3541 int sleep_time = 100;
3542 if (mpctx->sh_audio) {
3543 if (mpctx->ao->untimed)
3544 sleep_time = 0;
3545 else if (full_audio_buffers)
3546 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3547 else
3548 sleep_time = 20;
3549 sleep_time = FFMIN(sleep_time, 100);
3551 mp_input_get_cmd(mpctx->input, sleep_time, true);
3553 } else {
3555 /*========================== PLAY VIDEO ============================*/
3557 vo_pts = mpctx->sh_video->timer * 90000.0;
3558 vo_fps = mpctx->sh_video->fps;
3560 bool blit_frame = mpctx->video_out->frame_loaded;
3561 if (!blit_frame || mpctx->hrseek_active) {
3562 double frame_time = update_video(mpctx);
3563 blit_frame = mpctx->video_out->frame_loaded;
3564 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3565 if (mpctx->sh_video->vf_initialized < 0) {
3566 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3567 "\nFATAL: Could not initialize video filters (-vf) "
3568 "or video output (-vo).\n");
3569 mpctx->stop_play = PT_NEXT_ENTRY;
3570 return;
3572 if (frame_time < 0)
3573 mpctx->stop_play = AT_END_OF_FILE;
3574 else if (!mpctx->restart_playback) {
3575 mpctx->time_frame += frame_time / opts->playback_speed;
3576 adjust_sync(mpctx, frame_time);
3579 if (mpctx->timeline) {
3580 struct timeline_part *next =
3581 mpctx->timeline + mpctx->timeline_part + 1;
3582 if (mpctx->sh_video->pts >= next->start
3583 || mpctx->stop_play == AT_END_OF_FILE
3584 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3585 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3586 .amount = next->start },
3587 true);
3588 return;
3592 // ================================================================
3594 current_module = "vo_check_events";
3595 vo_check_events(mpctx->video_out);
3597 #ifdef CONFIG_X11
3598 if (stop_xscreensaver) {
3599 current_module = "stop_xscreensaver";
3600 xscreensaver_heartbeat(mpctx->x11_state);
3602 #endif
3603 if (heartbeat_cmd) {
3604 static unsigned last_heartbeat;
3605 unsigned now = GetTimerMS();
3606 if (now - last_heartbeat > 30000) {
3607 last_heartbeat = now;
3608 system(heartbeat_cmd);
3612 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3613 &mpctx->time_frame,
3614 full_audio_buffers,
3615 &aq_sleep_time);
3617 //=================== FLIP PAGE (VIDEO BLT): ======================
3619 current_module = "flip_page";
3620 if (!frame_time_remaining && blit_frame) {
3621 struct sh_video *sh_video = mpctx->sh_video;
3622 mpctx->video_pts = sh_video->pts;
3623 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3624 update_teletext(sh_video, mpctx->demuxer, 0);
3625 update_osd_msg(mpctx);
3626 struct vf_instance *vf = sh_video->vfilter;
3627 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3628 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3629 vo_osd_changed(0);
3631 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3632 aq_sleep_time += mpctx->time_frame;
3633 // flag 256 means: libvo driver does its timing (dvb card)
3634 if (mpctx->time_frame > 0.001
3635 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3636 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3637 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3639 unsigned int t2 = GetTimer();
3640 /* Playing with playback speed it's possible to get pathological
3641 * cases with mpctx->time_frame negative enough to cause an
3642 * overflow in pts_us calculation, thus the FFMAX. */
3643 double time_frame = FFMAX(mpctx->time_frame, -1);
3644 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3645 int duration = -1;
3646 double pts2 = mpctx->video_out->next_pts2;
3647 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3648 && !mpctx->restart_playback) {
3649 // expected A/V sync correction is ignored
3650 double diff = (pts2 - mpctx->video_pts);
3651 diff /= opts->playback_speed;
3652 if (mpctx->time_frame < 0)
3653 diff += mpctx->time_frame;
3654 if (diff < 0)
3655 diff = 0;
3656 if (diff > 10)
3657 diff = 10;
3658 duration = diff * 1e6;
3660 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3662 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3663 vout_time_usage += mpctx->last_vo_flip_duration;
3664 if (mpctx->video_out->driver->flip_page_timed) {
3665 // No need to adjust sync based on flip speed
3666 mpctx->last_vo_flip_duration = 0;
3667 // For print_status - VO call finishing early is OK for sync
3668 mpctx->time_frame -= get_relative_time(mpctx);
3670 if (mpctx->restart_playback) {
3671 mpctx->syncing_audio = true;
3672 if (mpctx->sh_audio)
3673 fill_audio_out_buffers(mpctx);
3674 mpctx->restart_playback = false;
3675 mpctx->time_frame = 0;
3676 get_relative_time(mpctx);
3678 print_status(mpctx, MP_NOPTS_VALUE, true);
3679 } else
3680 print_status(mpctx, MP_NOPTS_VALUE, false);
3682 if (opts->auto_quality > 0) {
3683 current_module = "autoq";
3684 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3685 ++output_quality;
3686 else if (output_quality > 1 && aq_sleep_time < 0)
3687 --output_quality;
3688 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3689 output_quality = 0;
3690 set_video_quality(mpctx->sh_video, output_quality);
3693 if (!frame_time_remaining && blit_frame) {
3694 if (play_n_frames >= 0) {
3695 --play_n_frames;
3696 if (play_n_frames <= 0)
3697 mpctx->stop_play = PT_NEXT_ENTRY;
3699 if (mpctx->step_frames > 0) {
3700 mpctx->step_frames--;
3701 if (mpctx->step_frames == 0)
3702 pause_player(mpctx);
3706 // FIXME: add size based support for -endpos
3707 if (end_at.type == END_AT_TIME &&
3708 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3709 mpctx->stop_play = PT_NEXT_ENTRY;
3711 } // end if(mpctx->sh_video)
3713 #ifdef CONFIG_DVDNAV
3714 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3715 nav_highlight_t hl;
3716 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3717 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3718 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3719 vo_osd_changed(OSDTYPE_DVDNAV);
3720 } else {
3721 osd_set_nav_box(0, 0, 0, 0);
3722 vo_osd_changed(OSDTYPE_DVDNAV);
3723 vo_osd_changed(OSDTYPE_SPU);
3726 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3727 double ar = -1.0;
3728 if (mpctx->sh_video &&
3729 stream_control(mpctx->demuxer->stream,
3730 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3731 != STREAM_UNSUPPORTED)
3732 mpctx->sh_video->stream_aspect = ar;
3735 #endif
3737 //================= Keyboard events, SEEKing ====================
3739 current_module = "key_events";
3741 while (1) {
3742 mp_cmd_t *cmd;
3743 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3744 /* Allow running consecutive seek commands to combine them,
3745 * but execute the seek before running other commands.
3746 * If the user seeks continuously (keeps arrow key down)
3747 * try to finish showing a frame from one location before doing
3748 * another seek (which could lead to unchanging display). */
3749 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3750 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3751 && GetTimerMS() - mpctx->start_timestamp < 300)
3752 break;
3753 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3754 run_command(mpctx, cmd);
3755 mp_cmd_free(cmd);
3756 if (mpctx->stop_play)
3757 break;
3759 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3760 || mpctx->restart_playback)
3761 break;
3762 if (mpctx->sh_video) {
3763 update_osd_msg(mpctx);
3764 int hack = vo_osd_changed(0);
3765 vo_osd_changed(hack);
3766 if (hack) {
3767 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3768 add_step_frame(mpctx);
3769 break;
3770 } else
3771 vo_osd_changed(0);
3774 pause_loop(mpctx);
3777 // handle -sstep
3778 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3779 mpctx->osd_function = OSD_FFW;
3780 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3783 edl_update(mpctx);
3785 /* Looping. */
3786 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3787 mpctx->stop_play == PT_NEXT_ENTRY)) {
3788 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3790 if (opts->loop_times > 1)
3791 opts->loop_times--;
3792 else if (opts->loop_times == 1)
3793 opts->loop_times = -1;
3794 play_n_frames = play_n_frames_mf;
3795 mpctx->stop_play = 0;
3796 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3799 if (mpctx->seek.type) {
3800 seek(mpctx, mpctx->seek, false);
3801 mpctx->seek = (struct seek_params){ 0 };
3806 static int read_keys(void *ctx, int fd)
3808 getch2(ctx);
3809 return MP_INPUT_NOTHING;
3812 static bool attachment_is_font(struct demux_attachment *att)
3814 if (!att->name || !att->type || !att->data || !att->data_size)
3815 return false;
3816 // match against MIME types
3817 if (strcmp(att->type, "application/x-truetype-font") == 0
3818 || strcmp(att->type, "application/x-font") == 0)
3819 return true;
3820 // fallback: match against file extension
3821 if (strlen(att->name) > 4) {
3822 char *ext = att->name + strlen(att->name) - 4;
3823 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3824 || strcasecmp(ext, ".otf") == 0)
3825 return true;
3827 return false;
3830 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3832 if (audio_id == -1)
3833 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3834 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3835 demuxer_switch_audio(demuxer, audio_id);
3836 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3837 demuxer->audio->id = -2;
3838 demuxer->audio->sh = NULL;
3840 return demuxer->audio->id;
3843 static void print_version(const char *name)
3845 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3847 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3848 GetCpuCaps(&gCpuCaps);
3849 #if ARCH_X86
3850 mp_msg(MSGT_CPLAYER, MSGL_V,
3851 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3852 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3853 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3854 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3855 #if CONFIG_RUNTIME_CPUDETECT
3856 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3857 #else
3858 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3859 if (HAVE_MMX)
3860 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3861 if (HAVE_MMX2)
3862 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3863 if (HAVE_AMD3DNOW)
3864 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3865 if (HAVE_AMD3DNOWEXT)
3866 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3867 if (HAVE_SSE)
3868 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3869 if (HAVE_SSE2)
3870 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3871 if (HAVE_SSSE3)
3872 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3873 if (HAVE_CMOV)
3874 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3875 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3876 #endif /* CONFIG_RUNTIME_CPUDETECT */
3877 #endif /* ARCH_X86 */
3878 print_libav_versions();
3881 #ifdef PTW32_STATIC_LIB
3882 static void detach_ptw32(void)
3884 pthread_win32_thread_detach_np();
3885 pthread_win32_process_detach_np();
3887 #endif
3889 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3890 * file for some tools to link against. */
3891 #ifndef DISABLE_MAIN
3892 int main(int argc, char *argv[])
3894 #ifdef PTW32_STATIC_LIB
3895 pthread_win32_process_attach_np();
3896 pthread_win32_thread_attach_np();
3897 atexit(detach_ptw32);
3898 #endif
3899 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3900 || !strcmp(argv[1], "--leak-report")))
3901 talloc_enable_leak_report();
3903 char *mem_ptr;
3905 // movie info:
3907 /* Flag indicating whether MPlayer should exit without playing anything. */
3908 int opt_exit = 0;
3909 int i;
3911 struct MPContext *mpctx = &(struct MPContext){
3912 .osd_function = OSD_PLAY,
3913 .begin_skip = MP_NOPTS_VALUE,
3914 .play_tree_step = 1,
3915 .global_sub_pos = -1,
3916 .set_of_sub_pos = -1,
3917 .file_format = DEMUXER_TYPE_UNKNOWN,
3918 .last_dvb_step = 1,
3921 InitTimer();
3922 srand(GetTimerMS());
3924 mp_msg_init();
3925 init_libav();
3927 #ifdef CONFIG_X11
3928 mpctx->x11_state = vo_x11_init_state();
3929 #endif
3930 struct MPOpts *opts = &mpctx->opts;
3931 set_default_mplayer_options(opts);
3932 // Create the config context and register the options
3933 mpctx->mconfig = m_config_new(opts, cfg_include);
3934 m_config_register_options(mpctx->mconfig, mplayer_opts);
3935 m_config_register_options(mpctx->mconfig, common_opts);
3936 mp_input_register_options(mpctx->mconfig);
3938 // Preparse the command line
3939 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
3941 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3942 set_path_env();
3943 #endif
3945 #ifdef CONFIG_TV
3946 stream_tv_defaults.immediate = 1;
3947 #endif
3949 parse_cfgfiles(mpctx, mpctx->mconfig);
3951 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3952 if (mpctx->playtree == NULL)
3953 opt_exit = 1;
3954 else {
3955 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3956 if (mpctx->playtree) {
3957 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3958 mpctx->mconfig);
3959 if (mpctx->playtree_iter) {
3960 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3961 PLAY_TREE_ITER_ENTRY) {
3962 play_tree_iter_free(mpctx->playtree_iter);
3963 mpctx->playtree_iter = NULL;
3965 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3971 print_version("MPlayer2");
3973 #if defined(__MINGW32__) || defined(__CYGWIN__)
3975 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3976 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3977 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3978 if (kernel32) {
3979 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3980 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3982 if (setDEP)
3983 setDEP(3);
3984 if (setDllDir)
3985 setDllDir("");
3987 // stop Windows from showing all kinds of annoying error dialogs
3988 SetErrorMode(0x8003);
3989 // request 1ms timer resolution
3990 timeBeginPeriod(1);
3991 #endif
3993 #ifdef CONFIG_PRIORITY
3994 set_priority();
3995 #endif
3997 if (opts->video_driver_list &&
3998 strcmp(opts->video_driver_list[0], "help") == 0) {
3999 list_video_out();
4000 opt_exit = 1;
4003 if (opts->audio_driver_list &&
4004 strcmp(opts->audio_driver_list[0], "help") == 0) {
4005 list_audio_out();
4006 opt_exit = 1;
4009 /* Check codecs.conf. */
4010 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4011 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4012 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4013 if (!parse_codec_cfg(NULL))
4014 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4015 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4016 "Using built-in default codecs.conf.\n");
4019 free(mem_ptr); // release the buffer created by get_path()
4022 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4023 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4024 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4025 list_codecs(1);
4026 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4027 opt_exit = 1;
4029 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4030 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4031 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4032 list_codecs(0);
4033 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4034 opt_exit = 1;
4036 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4037 vfm_help();
4038 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4039 opt_exit = 1;
4041 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4042 afm_help();
4043 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4044 opt_exit = 1;
4046 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4047 af_help();
4048 printf("\n");
4049 opt_exit = 1;
4051 #ifdef CONFIG_X11
4052 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4053 fstype_help();
4054 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4055 opt_exit = 1;
4057 #endif
4058 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4059 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4060 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4061 demuxer_help();
4062 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4063 opt_exit = 1;
4065 if (opts->list_properties) {
4066 property_print_help();
4067 opt_exit = 1;
4070 if (opt_exit)
4071 exit_player(mpctx, EXIT_NONE);
4073 if (!mpctx->filename && !opts->player_idle_mode) {
4074 // no file/vcd/dvd -> show HELP:
4075 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4076 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4079 /* Display what configure line was used */
4080 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4082 // Many users forget to include command line in bugreports...
4083 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4084 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4085 for (i = 1; i < argc; i++)
4086 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4087 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4090 //------ load global data first ------
4092 mpctx->osd = osd_create();
4094 // check font
4095 #ifdef CONFIG_FREETYPE
4096 init_freetype();
4097 #endif
4098 #ifdef CONFIG_FONTCONFIG
4099 if (font_fontconfig <= 0) {
4100 #endif
4101 #ifdef CONFIG_BITMAP_FONT
4102 if (font_name) {
4103 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4104 if (!vo_font)
4105 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4106 filename_recode(font_name));
4107 } else {
4108 // try default:
4109 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4110 font_factor, verbose > 1);
4111 free(mem_ptr); // release the buffer created by get_path()
4112 if (!vo_font)
4113 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4114 font_factor, verbose > 1);
4116 if (sub_font_name)
4117 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4118 verbose > 1);
4119 else
4120 mpctx->osd->sub_font = vo_font;
4121 #endif
4122 #ifdef CONFIG_FONTCONFIG
4124 #endif
4126 #ifdef CONFIG_ASS
4127 mpctx->ass_library = mp_ass_init(opts);
4128 mpctx->osd->ass_library = mpctx->ass_library;
4129 #endif
4131 #ifdef HAVE_RTC
4132 if (opts->rtc) {
4133 char *rtc_device = opts->rtc_device;
4134 // seteuid(0); /* Can't hurt to try to get root here */
4135 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4136 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4137 "(it should be readable by the user.)\n",
4138 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4139 else {
4140 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4142 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4143 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4144 "ioctl (rtc_irqp_set %lu): %s\n",
4145 irqp, strerror(errno));
4146 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4147 close(rtc_fd);
4148 rtc_fd = -1;
4149 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4150 /* variable only by the root */
4151 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4152 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4153 close(rtc_fd);
4154 rtc_fd = -1;
4155 } else
4156 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4157 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4160 if (rtc_fd < 0)
4161 #endif /* HAVE_RTC */
4162 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4163 opts->softsleep ? "software" : timer_name);
4165 #ifdef HAVE_TERMCAP
4166 load_termcap(NULL); // load key-codes
4167 #endif
4169 // ========== Init keyboard FIFO (connection to libvo) ============
4171 // Init input system
4172 current_module = "init_input";
4173 mpctx->input = mp_input_init(&opts->input);
4174 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4175 if (slave_mode)
4176 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4177 else if (opts->consolecontrols)
4178 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4179 // Set the libstream interrupt callback
4180 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4182 current_module = NULL;
4184 /// Catch signals
4185 #ifndef __MINGW32__
4186 signal(SIGCHLD, child_sighandler);
4187 #endif
4189 #ifdef CONFIG_CRASH_DEBUG
4190 prog_path = argv[0];
4191 #endif
4192 //========= Catch terminate signals: ================
4193 // terminate requests:
4194 signal(SIGTERM, exit_sighandler); // kill
4195 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4197 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4199 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4200 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4201 #ifdef CONFIG_SIGHANDLER
4202 // fatal errors:
4203 signal(SIGBUS, exit_sighandler); // bus error
4204 signal(SIGSEGV, exit_sighandler); // segfault
4205 signal(SIGILL, exit_sighandler); // illegal instruction
4206 signal(SIGFPE, exit_sighandler); // floating point exc.
4207 signal(SIGABRT, exit_sighandler); // abort()
4208 #ifdef CONFIG_CRASH_DEBUG
4209 if (crash_debug)
4210 signal(SIGTRAP, exit_sighandler);
4211 #endif
4212 #endif
4214 // ***************** Now, let's see the per-file stuff ******************
4216 play_next_file:
4218 // init global sub numbers
4219 mpctx->global_sub_size = 0;
4220 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4222 if (mpctx->filename) {
4223 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4224 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4225 load_per_file_config(mpctx->mconfig, mpctx->filename);
4228 if (opts->video_driver_list)
4229 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4230 opts->video_driver_list[0]);
4231 if (opts->audio_driver_list)
4232 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4233 opts->audio_driver_list[0]);
4235 // We must enable getch2 here to be able to interrupt network connection
4236 // or cache filling
4237 if (opts->consolecontrols && !slave_mode) {
4238 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4239 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4240 "WARNING: getch2_init called twice!\n");
4241 else
4242 getch2_enable(); // prepare stdin for hotkeys...
4243 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4244 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4247 // ================= GUI idle loop (STOP state) =========================
4248 while (opts->player_idle_mode && !mpctx->filename) {
4249 play_tree_t *entry = NULL;
4250 mp_cmd_t *cmd;
4251 if (mpctx->video_out && mpctx->video_out->config_ok)
4252 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4253 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4254 if (mpctx->video_out)
4255 vo_check_events(mpctx->video_out);
4256 usec_sleep(20000);
4258 switch (cmd->id) {
4259 case MP_CMD_LOADFILE:
4260 // prepare a tree entry with the new filename
4261 entry = play_tree_new();
4262 play_tree_add_file(entry, cmd->args[0].v.s);
4263 // The entry is added to the main playtree after the switch().
4264 break;
4265 case MP_CMD_LOADLIST:
4266 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4267 break;
4268 case MP_CMD_QUIT:
4269 exit_player_with_rc(mpctx, EXIT_QUIT,
4270 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4271 break;
4272 case MP_CMD_VO_FULLSCREEN:
4273 case MP_CMD_GET_PROPERTY:
4274 case MP_CMD_SET_PROPERTY:
4275 case MP_CMD_STEP_PROPERTY:
4276 run_command(mpctx, cmd);
4277 break;
4280 mp_cmd_free(cmd);
4282 if (entry) { // user entered a command that gave a valid entry
4283 if (mpctx->playtree)
4284 // the playtree is always a node with one child. let's clear it
4285 play_tree_free_list(mpctx->playtree->child, 1);
4286 else
4287 // .. or make a brand new playtree
4288 mpctx->playtree = play_tree_new();
4290 if (!mpctx->playtree)
4291 continue; // couldn't make playtree! wait for next command
4293 play_tree_set_child(mpctx->playtree, entry);
4295 /* Make iterator start at the top the of tree. */
4296 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4297 mpctx->mconfig);
4298 if (!mpctx->playtree_iter)
4299 continue;
4301 // find the first real item in the tree
4302 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4303 PLAY_TREE_ITER_ENTRY) {
4304 // no items!
4305 play_tree_iter_free(mpctx->playtree_iter);
4306 mpctx->playtree_iter = NULL;
4307 continue; // wait for next command
4309 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4313 #ifdef CONFIG_ASS
4314 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4315 #endif
4316 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4317 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4319 if (mpctx->filename) {
4320 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4321 filename_recode(mpctx->filename));
4322 if (use_filename_title && opts->vo_wintitle == NULL)
4323 opts->vo_wintitle = talloc_strdup(NULL,
4324 mp_basename(mpctx->filename));
4327 if (edl_filename) {
4328 if (edl_records)
4329 free_edl(edl_records);
4330 next_edl_record = edl_records = edl_parse_file();
4332 if (edl_output_filename) {
4333 if (edl_fd)
4334 fclose(edl_fd);
4335 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4336 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4337 "Can't open EDL file [%s] for writing.\n",
4338 filename_recode(edl_output_filename));
4342 //==================== Open VOB-Sub ============================
4344 current_module = "vobsub";
4345 if (opts->vobsub_name) {
4346 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4347 if (vo_vobsub == NULL)
4348 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4349 filename_recode(opts->vobsub_name));
4350 } else if (opts->sub_auto && mpctx->filename) {
4351 char **vob = find_vob_subtitles(opts, mpctx->filename);
4352 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4353 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4354 if (vo_vobsub)
4355 break;
4357 talloc_free(vob);
4359 if (vo_vobsub) {
4360 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4361 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4362 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4363 mpctx);
4365 // setup global sub numbering
4366 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4367 vobsub_get_indexes_count(vo_vobsub);
4370 //============ Open & Sync STREAM --- fork cache2 ====================
4372 mpctx->stream = NULL;
4373 mpctx->demuxer = NULL;
4374 mpctx->d_audio = NULL;
4375 mpctx->d_video = NULL;
4376 mpctx->d_sub = NULL;
4377 mpctx->sh_audio = NULL;
4378 mpctx->sh_video = NULL;
4380 current_module = "open_stream";
4381 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4382 if (!mpctx->stream) { // error...
4383 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4384 goto goto_next_file;
4386 mpctx->initialized_flags |= INITIALIZED_STREAM;
4388 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4389 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4390 "playlist support will not be used automatically.\n"
4391 "MPlayer's playlist code is unsafe and should only be used with "
4392 "trusted sources.\nPlayback will probably fail.\n\n");
4393 #if 0
4394 play_tree_t *entry;
4395 // Handle playlist
4396 current_module = "handle_playlist";
4397 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4398 filename_recode(mpctx->filename));
4399 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4400 mpctx->eof = playtree_add_playlist(mpctx, entry);
4401 goto goto_next_file;
4402 #endif
4404 mpctx->stream->start_pos += seek_to_byte;
4406 if (stream_dump_type == 5) {
4407 unsigned char buf[4096];
4408 int len;
4409 FILE *f;
4410 current_module = "dumpstream";
4411 stream_reset(mpctx->stream);
4412 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4413 f = fopen(opts->stream_dump_name, "wb");
4414 if (!f) {
4415 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4416 exit_player(mpctx, EXIT_ERROR);
4418 if (opts->chapterrange[0] > 1) {
4419 int chapter = opts->chapterrange[0] - 1;
4420 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4422 struct stream_dump_progress info;
4423 stream_dump_progress_start(&info);
4424 while (!mpctx->stream->eof && !async_quit_request) {
4425 len = stream_read(mpctx->stream, buf, 4096);
4426 if (len > 0) {
4427 if (fwrite(buf, len, 1, f) != 1) {
4428 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4429 exit_player(mpctx, EXIT_ERROR);
4432 stream_dump_progress(&info, len, mpctx->stream);
4433 if (opts->chapterrange[1] > 0) {
4434 int chapter = -1;
4435 if (stream_control(mpctx->stream,
4436 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4437 && chapter + 1 > opts->chapterrange[1])
4438 break;
4441 if (fclose(f)) {
4442 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4443 opts->stream_dump_name);
4444 exit_player(mpctx, EXIT_ERROR);
4446 stream_dump_progress_end(&info, opts->stream_dump_name);
4447 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4448 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4451 #ifdef CONFIG_DVDREAD
4452 if (mpctx->stream->type == STREAMTYPE_DVD) {
4453 current_module = "dvd lang->id";
4454 if (opts->audio_lang && opts->audio_id == -1)
4455 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4456 if (opts->sub_lang && opts->sub_id == -1)
4457 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4458 // setup global sub numbering
4459 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4460 current_module = NULL;
4462 #endif
4464 #ifdef CONFIG_DVDNAV
4465 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4466 current_module = "dvdnav lang->id";
4467 if (opts->audio_lang && opts->audio_id == -1)
4468 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4469 opts->audio_lang);
4470 dvdsub_lang_id = -3;
4471 if (opts->sub_lang && opts->sub_id == -1)
4472 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4473 mpctx->stream, opts->sub_lang);
4474 // setup global sub numbering
4475 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4476 mpctx->stream);
4477 current_module = NULL;
4479 #endif
4481 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4482 goto_enable_cache:
4483 if (stream_cache_size > 0) {
4484 int res;
4485 float stream_cache_min_percent = opts->stream_cache_min_percent;
4486 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4487 current_module = "enable_cache";
4488 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4489 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4490 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4491 if (res == 0)
4492 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4493 goto goto_next_file;
4496 //============ Open DEMUXERS --- DETECT file type =======================
4497 current_module = "demux_open";
4499 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4500 opts->audio_id, opts->video_id, opts->sub_id,
4501 mpctx->filename);
4503 // HACK to get MOV Reference Files working
4505 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4506 unsigned char *playlist_entry;
4507 play_tree_t *list = NULL, *entry = NULL;
4509 current_module = "handle_demux_playlist";
4510 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4511 char *temp;
4512 const char *bname;
4514 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4515 filename_recode(playlist_entry));
4517 bname = mp_basename(playlist_entry);
4518 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4519 !strncmp(bname + 3, "gateQT", 6))
4520 continue;
4522 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4523 continue;
4525 entry = play_tree_new();
4527 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4528 playlist_entry)) { // add reference path of current file
4529 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4530 mpctx->filename)) + strlen(playlist_entry) + 1));
4531 if (temp) {
4532 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4533 strlen(mp_basename(mpctx->filename)));
4534 temp[strlen(mpctx->filename) - strlen(mp_basename(
4535 mpctx->filename))] = '\0';
4536 strcat(temp, playlist_entry);
4537 if (!strcmp(temp, mpctx->filename)) {
4538 free(temp);
4539 continue;
4541 play_tree_add_file(entry, temp);
4542 mp_msg(MSGT_CPLAYER, MSGL_V,
4543 "Resolving reference to %s.\n", temp);
4544 free(temp);
4546 } else
4547 play_tree_add_file(entry, playlist_entry);
4549 if (!list)
4550 list = entry;
4551 else
4552 play_tree_append_entry(list, entry);
4554 free_demuxer(mpctx->demuxer);
4555 mpctx->demuxer = NULL;
4557 if (list) {
4558 entry = play_tree_new();
4559 play_tree_set_child(entry, list);
4560 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4561 goto goto_next_file;
4565 if (!mpctx->demuxer) {
4566 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4567 goto goto_next_file;
4570 if (mpctx->demuxer->matroska_data.ordered_chapters)
4571 build_ordered_chapter_timeline(mpctx);
4573 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4574 build_edl_timeline(mpctx);
4576 if (mpctx->timeline) {
4577 mpctx->timeline_part = 0;
4578 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4580 int part_count = mpctx->num_timeline_parts;
4581 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4582 "sources. Total length %.3f seconds.\n", part_count,
4583 mpctx->num_sources, mpctx->timeline[part_count].start);
4584 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4585 for (int i = 0; i < mpctx->num_sources; i++)
4586 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4587 filename_recode(mpctx->sources[i].demuxer->filename));
4588 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4589 "source_start, source):\n");
4590 for (int i = 0; i < part_count; i++) {
4591 struct timeline_part *p = mpctx->timeline + i;
4592 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4593 p->source_start, p->source - mpctx->sources);
4595 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4596 mpctx->timeline[part_count].start);
4599 if (!mpctx->sources) {
4600 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4601 *mpctx->sources = (struct content_source){
4602 .stream = mpctx->stream,
4603 .demuxer = mpctx->demuxer
4605 mpctx->num_sources = 1;
4608 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4610 #ifdef CONFIG_ASS
4611 if (opts->ass_enabled && mpctx->ass_library) {
4612 for (int j = 0; j < mpctx->num_sources; j++) {
4613 struct demuxer *d = mpctx->sources[j].demuxer;
4614 for (int i = 0; i < d->num_attachments; i++) {
4615 struct demux_attachment *att = d->attachments + i;
4616 if (opts->use_embedded_fonts && attachment_is_font(att))
4617 ass_add_font(mpctx->ass_library, att->name, att->data,
4618 att->data_size);
4622 #endif
4624 current_module = "demux_open2";
4626 mpctx->d_audio = mpctx->demuxer->audio;
4627 mpctx->d_video = mpctx->demuxer->video;
4628 mpctx->d_sub = mpctx->demuxer->sub;
4630 if (ts_prog) {
4631 int tmp = ts_prog;
4632 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4634 // select audio stream
4635 for (int i = 0; i < mpctx->num_sources; i++)
4636 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4637 opts->audio_lang);
4639 // DUMP STREAMS:
4640 if ((stream_dump_type) && (stream_dump_type < 4)) {
4641 FILE *f;
4642 demux_stream_t *ds = NULL;
4643 current_module = "dump";
4644 // select stream to dump
4645 switch (stream_dump_type) {
4646 case 1: ds = mpctx->d_audio;
4647 break;
4648 case 2: ds = mpctx->d_video;
4649 break;
4650 case 3: ds = mpctx->d_sub;
4651 break;
4653 if (!ds) {
4654 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4655 "dump: FATAL: Selected stream missing!\n");
4656 exit_player(mpctx, EXIT_ERROR);
4658 // disable other streams:
4659 if (mpctx->d_audio && mpctx->d_audio != ds) {
4660 ds_free_packs(mpctx->d_audio);
4661 mpctx->d_audio->id = -2;
4663 if (mpctx->d_video && mpctx->d_video != ds) {
4664 ds_free_packs(mpctx->d_video);
4665 mpctx->d_video->id = -2;
4667 if (mpctx->d_sub && mpctx->d_sub != ds) {
4668 ds_free_packs(mpctx->d_sub);
4669 mpctx->d_sub->id = -2;
4671 // let's dump it!
4672 f = fopen(opts->stream_dump_name, "wb");
4673 if (!f) {
4674 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4675 exit_player(mpctx, EXIT_ERROR);
4677 struct stream_dump_progress info;
4678 stream_dump_progress_start(&info);
4679 while (!ds->eof) {
4680 unsigned char *start;
4681 int in_size = ds_get_packet(ds, &start);
4682 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4683 && stream_dump_type == 2)
4684 fwrite(&in_size, 1, 4, f);
4685 if (in_size > 0) {
4686 fwrite(start, in_size, 1, f);
4687 stream_dump_progress(&info, in_size, mpctx->stream);
4689 if (opts->chapterrange[1] > 0) {
4690 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4691 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4692 break;
4695 fclose(f);
4696 stream_dump_progress_end(&info, opts->stream_dump_name);
4697 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4698 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4701 mpctx->sh_audio = mpctx->d_audio->sh;
4702 mpctx->sh_video = mpctx->d_video->sh;
4704 if (mpctx->sh_video) {
4705 current_module = "video_read_properties";
4706 if (!video_read_properties(mpctx->sh_video)) {
4707 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4708 mpctx->sh_video = mpctx->d_video->sh = NULL;
4709 } else {
4710 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4711 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4712 mpctx->demuxer->file_format, mpctx->sh_video->format,
4713 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4714 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4715 if (force_fps) {
4716 mpctx->sh_video->fps = force_fps;
4717 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4719 vo_fps = mpctx->sh_video->fps;
4721 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4722 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4723 "header or invalid, use the -fps option.\n");
4729 if (!mpctx->sh_video && !mpctx->sh_audio) {
4730 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4731 #ifdef CONFIG_DVBIN
4732 if (mpctx->stream->type == STREAMTYPE_DVB) {
4733 int dir;
4734 int v = mpctx->last_dvb_step;
4735 if (v > 0)
4736 dir = DVB_CHANNEL_HIGHER;
4737 else
4738 dir = DVB_CHANNEL_LOWER;
4740 if (dvb_step_channel(mpctx->stream, dir)) {
4741 mpctx->stop_play = PT_NEXT_ENTRY;
4742 mpctx->dvbin_reopen = 1;
4745 #endif
4746 goto goto_next_file; // exit_player(_("Fatal error"));
4749 /* display clip info */
4750 demux_info_print(mpctx->demuxer);
4752 //================= Read SUBTITLES (DVD & TEXT) =========================
4753 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4754 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4755 init_vo_spudec(mpctx);
4757 // after reading video params we should load subtitles because
4758 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4759 // check .sub
4760 current_module = "read_subtitles_file";
4761 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4762 if (opts->sub_name) {
4763 for (i = 0; opts->sub_name[i] != NULL; ++i)
4764 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4766 if (opts->sub_auto) { // auto load sub file ...
4767 char **tmp = find_text_subtitles(opts, mpctx->filename);
4768 int nsub = MP_TALLOC_ELEMS(tmp);
4769 for (int i = 0; i < nsub; i++)
4770 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4771 talloc_free(tmp);
4773 if (mpctx->set_of_sub_size > 0)
4774 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4776 if (select_subtitle(mpctx)) {
4777 if (mpctx->subdata)
4778 switch (stream_dump_type) {
4779 case 3: list_sub_file(mpctx->subdata);
4780 break;
4781 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4782 break;
4783 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4784 break;
4785 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4786 break;
4787 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4788 break;
4789 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4790 break;
4794 print_file_properties(mpctx, mpctx->filename);
4796 reinit_video_chain(mpctx);
4797 if (mpctx->sh_video) {
4798 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4799 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4800 #ifdef CONFIG_FREETYPE
4801 force_load_font = 1;
4802 #endif
4803 } else if (!mpctx->sh_audio)
4804 goto goto_next_file;
4806 //================== MAIN: ==========================
4807 current_module = "main";
4809 if (opts->playing_msg) {
4810 char *msg = property_expand_string(mpctx, opts->playing_msg);
4811 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4812 free(msg);
4816 // Disable the term OSD in verbose mode
4817 if (verbose)
4818 opts->term_osd = 0;
4820 // Make sure old OSD does not stay around,
4821 // e.g. with -fixed-vo and same-resolution files
4822 clear_osd_msgs();
4823 update_osd_msg(mpctx);
4825 //================ SETUP AUDIO ==========================
4827 if (mpctx->sh_audio) {
4828 reinit_audio_chain(mpctx);
4829 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4830 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4831 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4834 current_module = "av_init";
4836 if (mpctx->sh_video) {
4837 mpctx->sh_video->timer = 0;
4838 if (!ignore_start)
4839 audio_delay += mpctx->sh_video->stream_delay;
4841 if (mpctx->sh_audio) {
4842 if (start_volume >= 0)
4843 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4844 if (!ignore_start)
4845 audio_delay -= mpctx->sh_audio->stream_delay;
4846 mpctx->delay = -audio_delay;
4849 if (!mpctx->sh_audio) {
4850 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4851 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4852 mpctx->d_audio->packs);
4853 ds_free_packs(mpctx->d_audio); // free buffered chunks
4855 if (!mpctx->sh_video) {
4856 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4857 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4858 mpctx->d_video->packs);
4859 ds_free_packs(mpctx->d_video);
4860 mpctx->d_video->id = -2;
4863 if (!mpctx->sh_video && !mpctx->sh_audio)
4864 goto goto_next_file;
4866 if (force_fps && mpctx->sh_video) {
4867 vo_fps = mpctx->sh_video->fps = force_fps;
4868 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4869 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4870 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4871 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4874 mp_input_set_section(mpctx->input, NULL);
4875 //TODO: add desired (stream-based) sections here
4876 if (mpctx->stream->type == STREAMTYPE_TV)
4877 mp_input_set_section(mpctx->input, "tv");
4878 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4879 mp_input_set_section(mpctx->input, "dvdnav");
4881 //==================== START PLAYING =======================
4883 if (opts->loop_times > 1)
4884 opts->loop_times--;
4885 else if (opts->loop_times == 1)
4886 opts->loop_times = -1;
4888 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4890 total_time_usage_start = GetTimer();
4891 audio_time_usage = 0;
4892 video_time_usage = 0;
4893 vout_time_usage = 0;
4894 total_frame_cnt = 0;
4895 drop_frame_cnt = 0; // fix for multifile fps benchmark
4896 play_n_frames = play_n_frames_mf;
4898 if (play_n_frames == 0) {
4899 mpctx->stop_play = PT_NEXT_ENTRY;
4900 goto goto_next_file;
4903 mpctx->time_frame = 0;
4904 mpctx->drop_message_shown = 0;
4905 mpctx->restart_playback = true;
4906 mpctx->video_pts = 0;
4907 mpctx->last_seek_pts = 0;
4908 mpctx->hrseek_active = false;
4909 mpctx->hrseek_framedrop = false;
4910 mpctx->step_frames = 0;
4911 mpctx->total_avsync_change = 0;
4912 mpctx->last_chapter_seek = -2;
4914 // If there's a timeline force an absolute seek to initialize state
4915 if (opts->seek_to_sec || mpctx->timeline) {
4916 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4917 seek(mpctx, mpctx->seek, false);
4918 end_at.pos += opts->seek_to_sec;
4920 if (opts->chapterrange[0] > 0) {
4921 double pts;
4922 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts, NULL) >= 0
4923 && pts > -1.0) {
4924 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4925 seek(mpctx, mpctx->seek, false);
4929 if (end_at.type == END_AT_SIZE) {
4930 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4931 "Option -endpos in MPlayer does not yet support size units.\n");
4932 end_at.type = END_AT_NONE;
4935 #ifdef CONFIG_DVDNAV
4936 mp_dvdnav_context_free(mpctx);
4937 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4938 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4939 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4941 #endif
4943 mpctx->seek = (struct seek_params){ 0 };
4944 get_relative_time(mpctx); // reset current delta
4945 // Make sure VO knows current pause state
4946 if (mpctx->sh_video)
4947 vo_control(mpctx->video_out,
4948 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4950 while (!mpctx->stop_play)
4951 run_playloop(mpctx);
4953 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4955 #ifdef CONFIG_DVBIN
4956 if (mpctx->dvbin_reopen) {
4957 mpctx->stop_play = 0;
4958 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4959 cache_uninit(mpctx->stream);
4960 mpctx->dvbin_reopen = 0;
4961 goto goto_enable_cache;
4963 #endif
4965 goto_next_file: // don't jump here after ao/vo/getch initialization!
4967 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4969 if (opts->benchmark) {
4970 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4971 double total_time_usage;
4972 total_time_usage_start = GetTimer() - total_time_usage_start;
4973 total_time_usage = (float)total_time_usage_start * 0.000001;
4974 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4975 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4976 video_time_usage, vout_time_usage, audio_time_usage,
4977 total_time_usage - tot, total_time_usage);
4978 if (total_time_usage > 0.0)
4979 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4980 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4981 100.0 * video_time_usage / total_time_usage,
4982 100.0 * vout_time_usage / total_time_usage,
4983 100.0 * audio_time_usage / total_time_usage,
4984 100.0 * (total_time_usage - tot) / total_time_usage,
4985 100.0);
4986 if (total_frame_cnt && frame_dropping)
4987 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4988 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4989 total_frame_cnt - drop_frame_cnt,
4990 (total_time_usage > 0.5) ? ((total_frame_cnt -
4991 drop_frame_cnt) / total_time_usage) : 0,
4992 drop_frame_cnt,
4993 100 * drop_frame_cnt / total_frame_cnt,
4994 total_frame_cnt,
4995 (total_time_usage > 0.5) ?
4996 (total_frame_cnt / total_time_usage) : 0);
4999 // time to uninit all, except global stuff:
5000 int uninitialize_parts = INITIALIZED_ALL;
5001 if (opts->fixed_vo)
5002 uninitialize_parts -= INITIALIZED_VO;
5003 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
5004 uninitialize_parts -= INITIALIZED_AO;
5005 uninit_player(mpctx, uninitialize_parts);
5007 if (mpctx->set_of_sub_size > 0) {
5008 current_module = "sub_free";
5009 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5010 sub_free(mpctx->set_of_subtitles[i]);
5011 #ifdef CONFIG_ASS
5012 if (mpctx->set_of_ass_tracks[i])
5013 ass_free_track(mpctx->set_of_ass_tracks[i]);
5014 #endif
5016 mpctx->set_of_sub_size = 0;
5018 mpctx->vo_sub_last = vo_sub = NULL;
5019 mpctx->subdata = NULL;
5020 #ifdef CONFIG_ASS
5021 mpctx->osd->ass_track = NULL;
5022 if (mpctx->ass_library)
5023 ass_clear_fonts(mpctx->ass_library);
5024 #endif
5026 if (!mpctx->stop_play) // In case some goto jumped here...
5027 mpctx->stop_play = PT_NEXT_ENTRY;
5029 int playtree_direction = 1;
5031 if (mpctx->stop_play == PT_NEXT_ENTRY
5032 || mpctx->stop_play == PT_PREV_ENTRY) {
5033 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5034 != PLAY_TREE_ITER_ENTRY) {
5035 play_tree_iter_free(mpctx->playtree_iter);
5036 mpctx->playtree_iter = NULL;
5038 mpctx->play_tree_step = 1;
5039 } else if (mpctx->stop_play == PT_UP_NEXT ||
5040 mpctx->stop_play == PT_UP_PREV) {
5041 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5042 if (mpctx->playtree_iter) {
5043 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5044 PLAY_TREE_ITER_ENTRY) {
5045 play_tree_iter_free(mpctx->playtree_iter);
5046 mpctx->playtree_iter = NULL;
5049 } else if (mpctx->stop_play == PT_STOP) {
5050 play_tree_iter_free(mpctx->playtree_iter);
5051 mpctx->playtree_iter = NULL;
5052 } else // NEXT PREV SRC
5053 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5055 while (mpctx->playtree_iter != NULL) {
5056 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5057 playtree_direction);
5058 if (mpctx->filename == NULL) {
5059 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5060 0) != PLAY_TREE_ITER_ENTRY) {
5061 play_tree_iter_free(mpctx->playtree_iter);
5062 mpctx->playtree_iter = NULL;
5065 } else
5066 break;
5069 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5070 if (!mpctx->playtree_iter)
5071 mpctx->filename = NULL;
5072 mpctx->stop_play = 0;
5073 goto play_next_file;
5076 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5078 return 1;
5080 #endif /* DISABLE_MAIN */