af: fix crash when trying to use volume controls with AC3 pass-through
[mplayer.git] / mplayer.c
blobf8b24a12858bf60784fe58bd0cefd9f7a6a0f12d
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 <libavutil/intreadwrite.h>
27 #include "config.h"
28 #include "talloc.h"
30 #include "osdep/io.h"
32 #if defined(__MINGW32__) || defined(__CYGWIN__)
33 #include <windows.h>
34 #endif
35 #include <string.h>
36 #include <unistd.h>
38 // #include <sys/mman.h>
39 #include <sys/types.h>
40 #ifndef __MINGW32__
41 #include <sys/ioctl.h>
42 #include <sys/wait.h>
43 #else
44 #define SIGHUP 1 /* hangup */
45 #define SIGQUIT 3 /* quit */
46 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
47 #define SIGBUS 10 /* bus error */
48 #define SIGPIPE 13 /* broken pipe */
49 #endif
51 #include <sys/time.h>
52 #include <sys/stat.h>
54 #include <signal.h>
55 #include <time.h>
56 #include <fcntl.h>
57 #include <limits.h>
59 #include <errno.h>
61 #include "mp_msg.h"
62 #include "av_log.h"
65 #include "m_option.h"
66 #include "m_config.h"
67 #include "mplayer.h"
68 #include "m_property.h"
70 #include "sub/subreader.h"
71 #include "sub/find_subfiles.h"
72 #include "sub/dec_sub.h"
74 #include "mp_osd.h"
75 #include "libvo/video_out.h"
76 #include "screenshot.h"
78 #include "sub/font_load.h"
79 #include "sub/sub.h"
80 #include "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 static float get_relative_time(struct MPContext *mpctx)
352 unsigned int new_time = GetTimer();
353 unsigned int delta = new_time - mpctx->last_time;
354 mpctx->last_time = new_time;
355 return delta * 0.000001;
358 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
360 switch (type) {
361 /* check for valid video stream */
362 case META_VIDEO_CODEC:
363 case META_VIDEO_BITRATE:
364 case META_VIDEO_RESOLUTION:
365 if (!mpctx->sh_video)
366 return 0;
367 break;
369 /* check for valid audio stream */
370 case META_AUDIO_CODEC:
371 case META_AUDIO_BITRATE:
372 case META_AUDIO_SAMPLES:
373 if (!mpctx->sh_audio)
374 return 0;
375 break;
377 /* check for valid demuxer */
378 case META_INFO_TITLE:
379 case META_INFO_ARTIST:
380 case META_INFO_ALBUM:
381 case META_INFO_YEAR:
382 case META_INFO_COMMENT:
383 case META_INFO_TRACK:
384 case META_INFO_GENRE:
385 if (!mpctx->demuxer)
386 return 0;
387 break;
389 default:
390 break;
393 return 1;
396 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
398 char **info = mpctx->demuxer->info;
399 int n;
401 if (!info || !tag)
402 return talloc_strdup(NULL, "");
404 for (n = 0; info[2 * n] != NULL; n++)
405 if (!strcasecmp(info[2 * n], tag))
406 break;
408 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
411 char *get_metadata(struct MPContext *mpctx, metadata_t type)
413 sh_audio_t * const sh_audio = mpctx->sh_audio;
414 sh_video_t * const sh_video = mpctx->sh_video;
416 if (!is_valid_metadata_type(mpctx, type))
417 return NULL;
419 switch (type) {
420 case META_NAME:
421 return talloc_strdup(NULL, mp_basename(mpctx->filename));
422 case META_VIDEO_CODEC:
423 if (sh_video->format == 0x10000001)
424 return talloc_strdup(NULL, "mpeg1");
425 else if (sh_video->format == 0x10000002)
426 return talloc_strdup(NULL, "mpeg2");
427 else if (sh_video->format == 0x10000004)
428 return talloc_strdup(NULL, "mpeg4");
429 else if (sh_video->format == 0x10000005)
430 return talloc_strdup(NULL, "h264");
431 else if (sh_video->format >= 0x20202020)
432 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
433 else
434 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
435 case META_VIDEO_BITRATE:
436 return talloc_asprintf(NULL, "%d kbps",
437 (int) (sh_video->i_bps * 8 / 1024));
438 case META_VIDEO_RESOLUTION:
439 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
440 sh_video->disp_h);
441 case META_AUDIO_CODEC:
442 if (sh_audio->codec && sh_audio->codec->name)
443 return talloc_strdup(NULL, sh_audio->codec->name);
444 return talloc_strdup(NULL, "");
445 case META_AUDIO_BITRATE:
446 return talloc_asprintf(NULL, "%d kbps",
447 (int) (sh_audio->i_bps * 8 / 1000));
448 case META_AUDIO_SAMPLES:
449 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
450 sh_audio->channels);
452 /* check for valid demuxer */
453 case META_INFO_TITLE:
454 return get_demuxer_info(mpctx, "Title");
456 case META_INFO_ARTIST:
457 return get_demuxer_info(mpctx, "Artist");
459 case META_INFO_ALBUM:
460 return get_demuxer_info(mpctx, "Album");
462 case META_INFO_YEAR:
463 return get_demuxer_info(mpctx, "Year");
465 case META_INFO_COMMENT:
466 return get_demuxer_info(mpctx, "Comment");
468 case META_INFO_TRACK:
469 return get_demuxer_info(mpctx, "Track");
471 case META_INFO_GENRE:
472 return get_demuxer_info(mpctx, "Genre");
474 default:
475 break;
478 return talloc_strdup(NULL, "");
481 static void print_file_properties(struct MPContext *mpctx, const char *filename)
483 double start_pts = MP_NOPTS_VALUE;
484 double video_start_pts = MP_NOPTS_VALUE;
485 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
486 filename_recode(filename));
487 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
488 mpctx->demuxer->desc->name);
489 if (mpctx->sh_video) {
490 /* Assume FOURCC if all bytes >= 0x20 (' ') */
491 if (mpctx->sh_video->format >= 0x20202020)
492 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
493 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
494 else
495 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
496 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
497 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
498 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
499 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
500 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
501 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
502 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
503 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
504 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
505 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
506 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
507 video_start_pts = ds_get_next_pts(mpctx->d_video);
509 if (mpctx->sh_audio) {
510 /* Assume FOURCC if all bytes >= 0x20 (' ') */
511 if (mpctx->sh_audio->format >= 0x20202020)
512 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
513 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
514 else
515 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
516 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
517 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
518 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
519 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
520 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
521 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
522 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
523 start_pts = ds_get_next_pts(mpctx->d_audio);
525 if (video_start_pts != MP_NOPTS_VALUE) {
526 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
527 (mpctx->sh_video && video_start_pts < start_pts))
528 start_pts = video_start_pts;
530 if (start_pts != MP_NOPTS_VALUE)
531 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
532 else
533 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
534 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
535 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
536 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
537 mpctx->stream->seek
538 && (!mpctx->demuxer || mpctx->demuxer->seekable));
539 if (mpctx->demuxer) {
540 int chapter_count = get_chapter_count(mpctx);
541 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
542 for (int i = 0; i < chapter_count; i++) {
543 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
544 // in milliseconds
545 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
546 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
547 char *name = chapter_name(mpctx, i);
548 if (name) {
549 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
550 name);
551 talloc_free(name);
557 /// step size of mixer changes
558 int volstep = 3;
560 #ifdef CONFIG_DVDNAV
561 static void mp_dvdnav_context_free(MPContext *ctx)
563 if (ctx->nav_smpi)
564 free_mp_image(ctx->nav_smpi);
565 ctx->nav_smpi = NULL;
566 free(ctx->nav_buffer);
567 ctx->nav_buffer = NULL;
568 ctx->nav_start = NULL;
569 ctx->nav_in_size = 0;
571 #endif
573 static void uninit_subs(struct demuxer *demuxer)
575 for (int i = 0; i < MAX_S_STREAMS; i++) {
576 struct sh_sub *sh = demuxer->s_streams[i];
577 if (sh && sh->initialized)
578 sub_uninit(sh);
582 void uninit_player(struct MPContext *mpctx, unsigned int mask)
584 mask &= mpctx->initialized_flags;
586 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
588 if (mask & INITIALIZED_ACODEC) {
589 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
590 current_module = "uninit_acodec";
591 if (mpctx->sh_audio)
592 uninit_audio(mpctx->sh_audio);
593 mpctx->sh_audio = NULL;
594 mpctx->mixer.afilter = NULL;
597 if (mask & INITIALIZED_SUB) {
598 mpctx->initialized_flags &= ~INITIALIZED_SUB;
599 if (mpctx->d_sub->sh)
600 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
603 if (mask & INITIALIZED_VCODEC) {
604 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
605 current_module = "uninit_vcodec";
606 if (mpctx->sh_video)
607 uninit_video(mpctx->sh_video);
608 mpctx->sh_video = NULL;
611 if (mask & INITIALIZED_DEMUXER) {
612 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
613 current_module = "free_demuxer";
614 if (mpctx->num_sources) {
615 mpctx->demuxer = mpctx->sources[0].demuxer;
616 for (int i = 1; i < mpctx->num_sources; i++) {
617 uninit_subs(mpctx->sources[i].demuxer);
618 free_stream(mpctx->sources[i].stream);
619 free_demuxer(mpctx->sources[i].demuxer);
622 talloc_free(mpctx->sources);
623 mpctx->sources = NULL;
624 mpctx->num_sources = 0;
625 talloc_free(mpctx->timeline);
626 mpctx->timeline = NULL;
627 mpctx->num_timeline_parts = 0;
628 talloc_free(mpctx->chapters);
629 mpctx->chapters = NULL;
630 mpctx->num_chapters = 0;
631 mpctx->video_offset = 0;
632 if (mpctx->demuxer) {
633 mpctx->stream = mpctx->demuxer->stream;
634 uninit_subs(mpctx->demuxer);
635 free_demuxer(mpctx->demuxer);
637 mpctx->demuxer = NULL;
640 // kill the cache process:
641 if (mask & INITIALIZED_STREAM) {
642 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
643 current_module = "uninit_stream";
644 if (mpctx->stream)
645 free_stream(mpctx->stream);
646 mpctx->stream = NULL;
649 if (mask & INITIALIZED_VO) {
650 mpctx->initialized_flags &= ~INITIALIZED_VO;
651 current_module = "uninit_vo";
652 vo_destroy(mpctx->video_out);
653 mpctx->video_out = NULL;
654 #ifdef CONFIG_DVDNAV
655 mp_dvdnav_context_free(mpctx);
656 #endif
659 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
660 if (mask & INITIALIZED_GETCH2) {
661 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
662 current_module = "uninit_getch2";
663 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
664 // restore terminal:
665 getch2_disable();
668 if (mask & INITIALIZED_VOBSUB) {
669 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
670 current_module = "uninit_vobsub";
671 if (vo_vobsub)
672 vobsub_close(vo_vobsub);
673 vo_vobsub = NULL;
676 if (mask & INITIALIZED_SPUDEC) {
677 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
678 current_module = "uninit_spudec";
679 spudec_free(vo_spudec);
680 vo_spudec = NULL;
683 if (mask & INITIALIZED_AO) {
684 mpctx->initialized_flags &= ~INITIALIZED_AO;
685 current_module = "uninit_ao";
686 if (mpctx->edl_muted)
687 mixer_mute(&mpctx->mixer);
688 if (mpctx->ao)
689 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
690 mpctx->ao = NULL;
693 current_module = NULL;
696 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
698 if (mpctx->user_muted && !mpctx->edl_muted)
699 mixer_mute(&mpctx->mixer);
700 uninit_player(mpctx, INITIALIZED_ALL);
701 #if defined(__MINGW32__) || defined(__CYGWIN__)
702 timeEndPeriod(1);
703 #endif
704 #ifdef CONFIG_X11
705 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
706 #endif
708 current_module = "uninit_input";
709 mp_input_uninit(mpctx->input);
711 #ifdef CONFIG_FREETYPE
712 current_module = "uninit_font";
713 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
714 free_font_desc(mpctx->osd->sub_font);
715 free_font_desc(vo_font);
716 vo_font = NULL;
717 done_freetype();
718 #endif
719 osd_free(mpctx->osd);
721 #ifdef CONFIG_ASS
722 ass_library_done(mpctx->ass_library);
723 mpctx->ass_library = NULL;
724 #endif
726 current_module = "exit_player";
728 if (mpctx->playtree_iter)
729 play_tree_iter_free(mpctx->playtree_iter);
730 mpctx->playtree_iter = NULL;
731 if (mpctx->playtree)
732 play_tree_free(mpctx->playtree, 1);
733 mpctx->playtree = NULL;
735 talloc_free(mpctx->key_fifo);
737 free(edl_records); // free mem allocated for EDL
738 edl_records = NULL;
739 switch (how) {
740 case EXIT_QUIT:
741 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
742 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
743 break;
744 case EXIT_EOF:
745 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
746 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
747 break;
748 case EXIT_ERROR:
749 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
750 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
751 break;
752 default:
753 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
755 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
756 "max framesize was %d bytes\n", max_framesize);
758 // must be last since e.g. mp_msg uses option values
759 // that will be freed by this.
760 if (mpctx->mconfig)
761 m_config_free(mpctx->mconfig);
762 mpctx->mconfig = NULL;
764 talloc_free(mpctx);
766 exit(rc);
769 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
771 exit_player_with_rc(mpctx, how, 1);
774 #ifndef __MINGW32__
775 static void child_sighandler(int x)
777 pid_t pid;
778 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
780 #endif
782 #ifdef CONFIG_CRASH_DEBUG
783 static char *prog_path;
784 static int crash_debug = 0;
785 #endif
787 static void exit_sighandler(int x)
789 static int sig_count = 0;
790 #ifdef CONFIG_CRASH_DEBUG
791 if (!crash_debug || x != SIGTRAP)
792 #endif
793 ++sig_count;
794 if (sig_count == 5) {
795 /* We're crashing bad and can't uninit cleanly :(
796 * by popular request, we make one last (dirty)
797 * effort to restore the user's
798 * terminal. */
799 getch2_disable();
800 exit(1);
802 if (sig_count == 6)
803 exit(1);
804 if (sig_count > 6) {
805 // can't stop :(
806 #ifndef __MINGW32__
807 kill(getpid(), SIGKILL);
808 #endif
810 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
811 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
812 "\nMPlayer interrupted by signal %d in module: %s\n", x,
813 current_module ? current_module : "unknown");
814 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
815 if (sig_count <= 1)
816 switch (x) {
817 case SIGINT:
818 case SIGPIPE:
819 case SIGQUIT:
820 case SIGTERM:
821 case SIGKILL:
822 async_quit_request = 1;
823 return; // killed from keyboard (^C) or killed [-9]
824 case SIGILL:
825 #if CONFIG_RUNTIME_CPUDETECT
826 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
827 #else
828 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
829 #endif
830 case SIGFPE:
831 case SIGSEGV:
832 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
833 default:
834 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
835 #ifdef CONFIG_CRASH_DEBUG
836 if (crash_debug) {
837 int gdb_pid;
838 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
839 gdb_pid = fork();
840 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
841 if (gdb_pid == 0) { // We are the child
842 char spid[20];
843 snprintf(spid, sizeof(spid), "%i", getppid());
844 getch2_disable(); // allow terminal to work properly with gdb
845 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
846 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
847 } else if (gdb_pid < 0)
848 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
849 else
850 waitpid(gdb_pid, NULL, 0);
851 if (x == SIGTRAP)
852 return;
854 #endif
856 getch2_disable();
857 exit(1);
860 #include "cfg-mplayer.h"
862 static int cfg_include(m_option_t *conf, char *filename)
864 return m_config_parse_config_file(conf->priv, filename);
867 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
869 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
871 struct MPOpts *opts = &mpctx->opts;
872 char *conffile;
873 int conffile_fd;
874 if (!(opts->noconfig & 2) &&
875 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
876 exit_player(mpctx, EXIT_NONE);
877 if ((conffile = get_path("")) == NULL)
878 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
879 else {
880 mkdir(conffile, 0777);
881 free(conffile);
882 if ((conffile = get_path("config")) == NULL)
883 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
884 else {
885 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
886 0666)) != -1) {
887 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
888 "Creating config file: %s\n", conffile);
889 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
890 close(conffile_fd);
892 if (!(opts->noconfig & 1) &&
893 m_config_parse_config_file(conf, conffile) < 0)
894 exit_player(mpctx, EXIT_NONE);
895 free(conffile);
900 #define PROFILE_CFG_PROTOCOL "protocol."
902 static void load_per_protocol_config(m_config_t *conf, const char * const file)
904 char *str;
905 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
906 m_profile_t *p;
908 /* does filename actually uses a protocol ? */
909 str = strstr(file, "://");
910 if (!str)
911 return;
913 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
914 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
915 p = m_config_get_profile(conf, protocol);
916 if (p) {
917 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
918 "Loading protocol-related profile '%s'\n", protocol);
919 m_config_set_profile(conf, p);
923 #define PROFILE_CFG_EXTENSION "extension."
925 static void load_per_extension_config(m_config_t *conf, const char * const file)
927 char *str;
928 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
929 m_profile_t *p;
931 /* does filename actually have an extension ? */
932 str = strrchr(file, '.');
933 if (!str)
934 return;
936 sprintf(extension, PROFILE_CFG_EXTENSION);
937 strncat(extension, ++str, 7);
938 p = m_config_get_profile(conf, extension);
939 if (p) {
940 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
941 "Loading extension-related profile '%s'\n", extension);
942 m_config_set_profile(conf, p);
946 #define PROFILE_CFG_VO "vo."
947 #define PROFILE_CFG_AO "ao."
949 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
951 char profile[strlen(cfg) + strlen(out) + 1];
952 m_profile_t *p;
954 sprintf(profile, "%s%s", cfg, out);
955 p = m_config_get_profile(conf, profile);
956 if (p) {
957 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
958 "Loading extension-related profile '%s'\n", profile);
959 m_config_set_profile(conf, p);
964 * Tries to load a config file
965 * @return 0 if file was not found, 1 otherwise
967 static int try_load_config(m_config_t *conf, const char *file)
969 if (!mp_path_exists(file))
970 return 0;
971 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
972 m_config_parse_config_file(conf, file);
973 return 1;
976 static void load_per_file_config(m_config_t *conf, const char * const file)
978 char *confpath;
979 char cfg[MP_PATH_MAX];
980 const char *name;
982 if (strlen(file) > MP_PATH_MAX - 14) {
983 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
984 "can not load file or directory specific config files\n");
985 return;
987 sprintf(cfg, "%s.conf", file);
989 name = mp_basename(cfg);
990 if (use_filedir_conf) {
991 char dircfg[MP_PATH_MAX];
992 strcpy(dircfg, cfg);
993 strcpy(dircfg + (name - cfg), "mplayer.conf");
994 try_load_config(conf, dircfg);
996 if (try_load_config(conf, cfg))
997 return;
1000 if ((confpath = get_path(name)) != NULL) {
1001 try_load_config(conf, confpath);
1003 free(confpath);
1007 /* When libmpdemux performs a blocking operation (network connection or
1008 * cache filling) if the operation fails we use this function to check
1009 * if it was interrupted by the user.
1010 * The function returns a new value for eof. */
1011 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1013 mp_cmd_t *cmd;
1014 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1015 switch (cmd->id) {
1016 case MP_CMD_QUIT:
1017 exit_player_with_rc(mpctx, EXIT_QUIT,
1018 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1019 case MP_CMD_PLAY_TREE_STEP: {
1020 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1021 mpctx->play_tree_step =
1022 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1023 } break;
1024 case MP_CMD_PLAY_TREE_UP_STEP: {
1025 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1026 } break;
1027 case MP_CMD_PLAY_ALT_SRC_STEP: {
1028 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1029 } break;
1031 mp_cmd_free(cmd);
1033 return stop_play;
1036 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1038 play_tree_add_bpf(entry, bstr(mpctx->filename));
1041 if (!entry) {
1042 entry = mpctx->playtree_iter->tree;
1043 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1044 != PLAY_TREE_ITER_ENTRY)
1045 return PT_NEXT_ENTRY;
1046 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1047 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1048 != PLAY_TREE_ITER_ENTRY)
1049 return PT_NEXT_ENTRY;
1051 play_tree_remove(entry, 1, 1);
1052 return PT_NEXT_SRC;
1054 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1055 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1056 entry = mpctx->playtree_iter->tree;
1057 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1058 != PLAY_TREE_ITER_ENTRY)
1059 return PT_NEXT_ENTRY;
1060 play_tree_remove(entry, 1, 1);
1062 return PT_NEXT_SRC;
1065 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1066 int noerr)
1068 struct MPOpts *opts = &mpctx->opts;
1069 sub_data *subd = NULL;
1070 struct ass_track *asst = NULL;
1071 bool is_native_ass = false;
1073 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1074 return;
1076 #ifdef CONFIG_ASS
1077 if (opts->ass_enabled) {
1078 #ifdef CONFIG_ICONV
1079 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1080 #else
1081 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1082 #endif
1083 is_native_ass = asst;
1084 if (!asst) {
1085 subd = sub_read_file(filename, fps, &mpctx->opts);
1086 if (subd) {
1087 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1088 sub_free(subd);
1089 subd = NULL;
1092 } else
1093 #endif
1094 subd = sub_read_file(filename, fps, &mpctx->opts);
1097 if (!asst && !subd) {
1098 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1099 "Cannot load subtitles: %s\n", filename_recode(filename));
1100 return;
1103 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1104 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1105 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1106 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1107 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1108 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1109 filename_recode(filename));
1110 ++mpctx->set_of_sub_size;
1111 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1112 mpctx->set_of_sub_size, filename_recode(filename));
1115 void init_vo_spudec(struct MPContext *mpctx)
1117 unsigned width, height;
1118 spudec_free(vo_spudec);
1119 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1120 vo_spudec = NULL;
1122 // we currently can't work without video stream
1123 if (!mpctx->sh_video)
1124 return;
1126 if (spudec_ifo) {
1127 unsigned int palette[16];
1128 current_module = "spudec_init_vobsub";
1129 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1130 1, -1, NULL) >= 0)
1131 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1134 width = mpctx->sh_video->disp_w;
1135 height = mpctx->sh_video->disp_h;
1137 #ifdef CONFIG_DVDREAD
1138 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1139 current_module = "spudec_init_dvdread";
1140 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1141 cur_pgc->palette, width, height, NULL, 0);
1143 #endif
1145 #ifdef CONFIG_DVDNAV
1146 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1147 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1148 current_module = "spudec_init_dvdnav";
1149 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1151 #endif
1153 if (vo_spudec == NULL) {
1154 sh_sub_t *sh = mpctx->d_sub->sh;
1155 current_module = "spudec_init_normal";
1156 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1157 sh->extradata_len);
1158 spudec_set_font_factor(vo_spudec, font_factor);
1161 if (vo_spudec != NULL) {
1162 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1163 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1164 mpctx);
1169 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1170 * make it all work is to use the builtin SDL-bootstrap code, which
1171 * will be done automatically by replacing our main() if we include SDL.h.
1173 #if defined(__APPLE__) && defined(CONFIG_SDL)
1174 #ifdef CONFIG_SDL_SDL_H
1175 #include <SDL/SDL.h>
1176 #else
1177 #include <SDL.h>
1178 #endif
1179 #endif
1182 * \brief append a formatted string
1183 * \param buf buffer to print into
1184 * \param pos position of terminating 0 in buf
1185 * \param len maximum number of characters in buf, not including terminating 0
1186 * \param format printf format string
1188 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1190 va_list va;
1191 va_start(va, format);
1192 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1193 va_end(va);
1194 if (*pos >= len) {
1195 buf[len] = 0;
1196 *pos = len;
1201 * \brief append time in the hh:mm:ss.f format
1202 * \param buf buffer to print into
1203 * \param pos position of terminating 0 in buf
1204 * \param len maximum number of characters in buf, not including terminating 0
1205 * \param time time value to convert/append
1207 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1209 int64_t tenths = 10 * time;
1210 int f1 = tenths % 10;
1211 int ss = (tenths / 10) % 60;
1212 int mm = (tenths / 600) % 60;
1213 int hh = tenths / 36000;
1214 if (time < 0) {
1215 saddf(buf, pos, len, "unknown");
1216 return;
1218 if (hh > 0)
1219 saddf(buf, pos, len, "%2d:", hh);
1220 if (hh > 0 || mm > 0)
1221 saddf(buf, pos, len, "%02d:", mm);
1222 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1225 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1227 struct MPOpts *opts = &mpctx->opts;
1228 sh_video_t * const sh_video = mpctx->sh_video;
1230 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1231 a_pos = playing_audio_pts(mpctx);
1232 if (mpctx->sh_audio && sh_video && at_frame) {
1233 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1234 if (mpctx->time_frame > 0)
1235 mpctx->last_av_difference +=
1236 mpctx->time_frame * opts->playback_speed;
1237 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1238 && !mpctx->drop_message_shown) {
1239 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1240 mpctx->drop_message_shown = true;
1243 if (opts->quiet)
1244 return;
1246 if (a_pos == MP_NOPTS_VALUE)
1247 a_pos = -9; // don't print a huge negative number
1249 int width;
1250 char *line;
1251 unsigned pos = 0;
1252 get_screen_size();
1253 if (screen_width > 0)
1254 width = screen_width;
1255 else
1256 width = 80;
1257 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1258 /* Windows command line is broken (MinGW's rxvt works, but we
1259 * should not depend on that). */
1260 width--;
1261 #endif
1262 line = malloc(width + 1); // one additional char for the terminating null
1264 // Audio time
1265 if (mpctx->sh_audio) {
1266 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1267 if (!sh_video) {
1268 float len = get_time_length(mpctx);
1269 saddf(line, &pos, width, "(");
1270 sadd_hhmmssf(line, &pos, width, a_pos);
1271 saddf(line, &pos, width, ") of %.1f (", len);
1272 sadd_hhmmssf(line, &pos, width, len);
1273 saddf(line, &pos, width, ") ");
1277 // Video time
1278 if (sh_video)
1279 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1281 // A-V sync
1282 if (mpctx->sh_audio && sh_video)
1283 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1284 mpctx->last_av_difference, mpctx->total_avsync_change);
1286 // Video stats
1287 if (sh_video)
1288 saddf(line, &pos, width, "%3d/%3d ",
1289 (int)sh_video->num_frames,
1290 (int)sh_video->num_frames_decoded);
1292 // CPU usage
1293 if (sh_video) {
1294 if (sh_video->timer > 0.5)
1295 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1296 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1297 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1298 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1299 else
1300 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1301 } else if (mpctx->sh_audio) {
1302 if (mpctx->delay > 0.5)
1303 saddf(line, &pos, width, "%4.1f%% ",
1304 100.0 * audio_time_usage / (double)mpctx->delay);
1305 else
1306 saddf(line, &pos, width, "??,?%% ");
1309 // VO stats
1310 if (sh_video)
1311 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1313 #ifdef CONFIG_STREAM_CACHE
1314 // cache stats
1315 if (stream_cache_size > 0)
1316 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1317 #endif
1319 // other
1320 if (opts->playback_speed != 1)
1321 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1323 // end
1324 if (erase_to_end_of_line) {
1325 line[pos] = 0;
1326 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1327 "%s%s\r", line, erase_to_end_of_line);
1328 } else {
1329 memset(&line[pos], ' ', width - pos);
1330 line[width] = 0;
1331 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1333 free(line);
1335 mpctx->status_printed = true;
1338 struct stream_dump_progress {
1339 uint64_t count;
1340 unsigned start_time;
1341 unsigned last_print_time;
1344 static void stream_dump_progress_start(struct stream_dump_progress *p)
1346 p->start_time = p->last_print_time = GetTimerMS();
1347 p->count = 0;
1350 static void stream_dump_progress(struct stream_dump_progress *p,
1351 uint64_t len, stream_t *stream)
1353 p->count += len;
1354 unsigned t = GetTimerMS();
1355 if (t - p->last_print_time < 1000)
1356 return;
1358 uint64_t start = stream->start_pos;
1359 uint64_t end = stream->end_pos;
1360 uint64_t pos = stream->pos;
1362 p->last_print_time = t;
1363 /* TODO: pretty print sizes; ETA */
1364 if (end > start && pos >= start && pos <= end) {
1365 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1366 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1367 p->count, 100.0 * (pos - start) / (end - start));
1368 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1369 } else {
1370 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1371 "dump: %"PRIu64 " bytes written", p->count);
1372 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1376 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1378 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1379 p->count, name);
1383 * \brief build a chain of audio filters that converts the input format
1384 * to the ao's format, taking into account the current playback_speed.
1385 * sh_audio describes the requested input format of the chain.
1386 * ao describes the requested output format of the chain.
1388 static int build_afilter_chain(struct MPContext *mpctx)
1390 struct sh_audio *sh_audio = mpctx->sh_audio;
1391 struct ao *ao = mpctx->ao;
1392 struct MPOpts *opts = &mpctx->opts;
1393 int new_srate;
1394 int result;
1395 if (!sh_audio) {
1396 mpctx->mixer.afilter = NULL;
1397 return 0;
1399 if (af_control_any_rev(sh_audio->afilter,
1400 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1401 &opts->playback_speed))
1402 new_srate = sh_audio->samplerate;
1403 else {
1404 new_srate = sh_audio->samplerate * opts->playback_speed;
1405 if (new_srate != ao->samplerate) {
1406 // limits are taken from libaf/af_resample.c
1407 if (new_srate < 8000)
1408 new_srate = 8000;
1409 if (new_srate > 192000)
1410 new_srate = 192000;
1411 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1414 result = init_audio_filters(sh_audio, new_srate,
1415 &ao->samplerate, &ao->channels, &ao->format);
1416 mpctx->mixer.afilter = sh_audio->afilter;
1417 return result;
1421 typedef struct mp_osd_msg mp_osd_msg_t;
1422 struct mp_osd_msg {
1423 /// Previous message on the stack.
1424 mp_osd_msg_t *prev;
1425 /// Message text.
1426 char *msg;
1427 int id, level, started;
1428 /// Display duration in ms.
1429 unsigned time;
1432 /// OSD message stack.
1433 static mp_osd_msg_t *osd_msg_stack = NULL;
1436 * \brief Add a message on the OSD message stack
1438 * If a message with the same id is already present in the stack
1439 * it is pulled on top of the stack, otherwise a new message is created.
1442 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1443 va_list ap)
1445 mp_osd_msg_t *msg, *last = NULL;
1447 // look if the id is already in the stack
1448 for (msg = osd_msg_stack; msg && msg->id != id;
1449 last = msg, msg = msg->prev) ;
1450 // not found: alloc it
1451 if (!msg) {
1452 msg = talloc_zero(NULL, mp_osd_msg_t);
1453 msg->prev = osd_msg_stack;
1454 osd_msg_stack = msg;
1455 } else if (last) { // found, but it's not on top of the stack
1456 last->prev = msg->prev;
1457 msg->prev = osd_msg_stack;
1458 osd_msg_stack = msg;
1460 talloc_free(msg->msg);
1461 // write the msg
1462 msg->msg = talloc_vasprintf(msg, fmt, ap);
1463 // set id and time
1464 msg->id = id;
1465 msg->level = level;
1466 msg->time = time;
1470 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1472 va_list ap;
1473 va_start(ap, fmt);
1474 set_osd_msg_va(id, level, time, fmt, ap);
1475 va_end(ap);
1478 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1480 va_list ap;
1481 va_start(ap, fmt);
1482 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1483 va_end(ap);
1487 * \brief Remove a message from the OSD stack
1489 * This function can be used to get rid of a message right away.
1493 void rm_osd_msg(int id)
1495 mp_osd_msg_t *msg, *last = NULL;
1497 // Search for the msg
1498 for (msg = osd_msg_stack; msg && msg->id != id;
1499 last = msg, msg = msg->prev) ;
1500 if (!msg)
1501 return;
1503 // Detach it from the stack and free it
1504 if (last)
1505 last->prev = msg->prev;
1506 else
1507 osd_msg_stack = msg->prev;
1508 talloc_free(msg);
1512 * \brief Remove all messages from the OSD stack
1516 static void clear_osd_msgs(void)
1518 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1519 while (msg) {
1520 prev = msg->prev;
1521 talloc_free(msg);
1522 msg = prev;
1524 osd_msg_stack = NULL;
1528 * \brief Get the current message from the OSD stack.
1530 * This function decrements the message timer and destroys the old ones.
1531 * The message that should be displayed is returned (if any).
1535 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1537 struct MPOpts *opts = &mpctx->opts;
1538 mp_osd_msg_t *msg, *prev, *last = NULL;
1539 static unsigned last_update = 0;
1540 unsigned now = GetTimerMS();
1541 unsigned diff;
1542 char hidden_dec_done = 0;
1544 if (mpctx->osd_visible) {
1545 // 36000000 means max timed visibility is 1 hour into the future, if
1546 // the difference is greater assume it's wrapped around from below 0
1547 if (mpctx->osd_visible - now > 36000000) {
1548 mpctx->osd_visible = 0;
1549 vo_osd_progbar_type = -1; // disable
1550 vo_osd_changed(OSDTYPE_PROGBAR);
1551 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1554 if (mpctx->osd_show_percentage_until - now > 36000000)
1555 mpctx->osd_show_percentage_until = 0;
1557 if (!last_update)
1558 last_update = now;
1559 diff = now >= last_update ? now - last_update : 0;
1561 last_update = now;
1563 // Look for the first message in the stack with high enough level.
1564 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1565 prev = msg->prev;
1566 if (msg->level > opts->osd_level && hidden_dec_done)
1567 continue;
1568 // The message has a high enough level or it is the first hidden one
1569 // in both cases we decrement the timer or kill it.
1570 if (!msg->started || msg->time > diff) {
1571 if (msg->started)
1572 msg->time -= diff;
1573 else
1574 msg->started = 1;
1575 // display it
1576 if (msg->level <= opts->osd_level)
1577 return msg;
1578 hidden_dec_done = 1;
1579 continue;
1581 // kill the message
1582 talloc_free(msg);
1583 if (last) {
1584 last->prev = prev;
1585 msg = last;
1586 } else {
1587 osd_msg_stack = prev;
1588 msg = NULL;
1591 // Nothing found
1592 return NULL;
1596 * \brief Display the OSD bar.
1598 * Display the OSD bar or fall back on a simple message.
1602 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1603 double min, double max, double val)
1605 struct MPOpts *opts = &mpctx->opts;
1606 if (opts->osd_level < 1)
1607 return;
1609 if (mpctx->sh_video) {
1610 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1611 vo_osd_progbar_type = type;
1612 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1613 vo_osd_changed(OSDTYPE_PROGBAR);
1614 return;
1617 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1618 name, ROUND(100 * (val - min) / (max - min)));
1622 * \brief Display text subtitles on the OSD
1624 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1626 int i;
1627 vo_sub = subs;
1628 vo_osd_changed(OSDTYPE_SUBTITLE);
1629 if (!mpctx->sh_video) {
1630 // reverse order, since newest set_osd_msg is displayed first
1631 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1632 if (!subs || i >= subs->lines || !subs->text[i])
1633 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1634 else {
1635 // HACK: currently display time for each sub line
1636 // except the last is set to 2 seconds.
1637 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1638 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1639 "%s", subs->text[i]);
1646 * \brief Update the OSD message line.
1648 * This function displays the current message on the vo OSD or on the term.
1649 * If the stack is empty and the OSD level is high enough the timer
1650 * is displayed (only on the vo OSD).
1654 static void update_osd_msg(struct MPContext *mpctx)
1656 struct MPOpts *opts = &mpctx->opts;
1657 mp_osd_msg_t *msg;
1658 struct osd_state *osd = mpctx->osd;
1659 char osd_text_timer[128];
1661 if (mpctx->add_osd_seek_info) {
1662 double percentage = get_percent_pos(mpctx);
1663 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1664 if (mpctx->sh_video)
1665 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1666 mpctx->add_osd_seek_info = false;
1669 // Look if we have a msg
1670 if ((msg = get_osd_msg(mpctx))) {
1671 if (strcmp(osd->osd_text, msg->msg)) {
1672 osd_set_text(osd, msg->msg);
1673 if (mpctx->sh_video)
1674 vo_osd_changed(OSDTYPE_OSD);
1675 else if (opts->term_osd)
1676 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1677 msg->msg);
1679 return;
1682 if (mpctx->sh_video) {
1683 // fallback on the timer
1684 if (opts->osd_level >= 2) {
1685 int len = get_time_length(mpctx);
1686 int percentage = -1;
1687 char percentage_text[10];
1688 char fractions_text[4];
1689 double fpts = get_current_time(mpctx);
1690 int pts = fpts;
1692 if (mpctx->osd_show_percentage_until)
1693 percentage = get_percent_pos(mpctx);
1695 if (percentage >= 0)
1696 snprintf(percentage_text, 9, " (%d%%)", percentage);
1697 else
1698 percentage_text[0] = 0;
1700 if (opts->osd_fractions == 1) {
1701 //print fractions as sub-second timestamp
1702 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1703 (int)((fpts - pts) * 100));
1704 } else if (opts->osd_fractions == 2) {
1705 /* Print fractions by estimating the frame count within the
1706 * second.
1708 * Rounding or cutting off numbers after the decimal point
1709 * causes problems because of float's precision and movies
1710 * whose first frame is not exactly at timestamp 0. Therefore,
1711 * we add 0.2 and cut off at the decimal point, which proved
1712 * to be good heuristic.
1714 double fps = mpctx->sh_video->fps;
1715 if (fps <= 1 || fps > 99)
1716 strcpy(fractions_text, ".??");
1717 else
1718 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1719 (int) ((fpts - pts) * fps + 0.2));
1720 } else {
1721 //do not print fractions
1722 fractions_text[0] = 0;
1725 if (opts->osd_level == 3)
1726 snprintf(osd_text_timer, sizeof(osd_text_timer),
1727 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1728 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1729 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1730 percentage_text);
1731 else
1732 snprintf(osd_text_timer, sizeof(osd_text_timer),
1733 "%c %02d:%02d:%02d%s%s",
1734 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1735 pts % 60, fractions_text, percentage_text);
1736 } else
1737 osd_text_timer[0] = 0;
1739 if (strcmp(osd->osd_text, osd_text_timer)) {
1740 osd_set_text(osd, osd_text_timer);
1741 vo_osd_changed(OSDTYPE_OSD);
1743 return;
1746 // Clear the term osd line
1747 if (opts->term_osd && osd->osd_text[0]) {
1748 osd->osd_text[0] = 0;
1749 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1754 void reinit_audio_chain(struct MPContext *mpctx)
1756 struct MPOpts *opts = &mpctx->opts;
1757 struct ao *ao;
1758 if (!mpctx->sh_audio)
1759 return;
1760 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1761 current_module = "init_audio_codec";
1762 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1763 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1764 goto init_error;
1765 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1766 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1770 current_module = "af_preinit";
1771 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1772 mpctx->initialized_flags |= INITIALIZED_AO;
1773 mpctx->ao = ao_create();
1774 mpctx->ao->samplerate = force_srate;
1775 mpctx->ao->format = opts->audio_output_format;
1777 ao = mpctx->ao;
1779 // first init to detect best values
1780 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1781 // input:
1782 mpctx->sh_audio->samplerate,
1783 // output:
1784 &ao->samplerate, &ao->channels, &ao->format)) {
1785 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1786 "pre-init!\n");
1787 exit_player(mpctx, EXIT_ERROR);
1789 if (!ao->initialized) {
1790 current_module = "ao2_init";
1791 ao->buffersize = opts->ao_buffersize;
1792 ao_init(ao, opts->audio_driver_list);
1793 if (!ao->initialized) {
1794 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1795 "Could not open/initialize audio device -> no sound.\n");
1796 goto init_error;
1798 ao->buffer.start = talloc_new(ao);
1799 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1800 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1801 ao->driver->info->short_name,
1802 ao->samplerate, ao->channels,
1803 af_fmt2str_short(ao->format),
1804 af_fmt2bits(ao->format) / 8);
1805 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1806 ao->driver->info->name, ao->driver->info->author);
1807 if (strlen(ao->driver->info->comment) > 0)
1808 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1809 ao->driver->info->comment);
1812 // init audio filters:
1813 current_module = "af_init";
1814 if (!build_afilter_chain(mpctx)) {
1815 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1816 "Couldn't find matching filter/ao format!\n");
1817 goto init_error;
1819 mpctx->mixer.ao = ao;
1820 mpctx->mixer.volstep = volstep;
1821 mpctx->syncing_audio = true;
1822 return;
1824 init_error:
1825 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1826 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1827 mpctx->d_audio->id = -2;
1831 // Return pts value corresponding to the end point of audio written to the
1832 // ao so far.
1833 static double written_audio_pts(struct MPContext *mpctx)
1835 sh_audio_t *sh_audio = mpctx->sh_audio;
1836 demux_stream_t *d_audio = mpctx->d_audio;
1837 // first calculate the end pts of audio that has been output by decoder
1838 double a_pts = sh_audio->pts;
1839 if (a_pts != MP_NOPTS_VALUE)
1840 // Good, decoder supports new way of calculating audio pts.
1841 // sh_audio->pts is the timestamp of the latest input packet with
1842 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1843 // the amount of bytes the decoder has written after that timestamp.
1844 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1845 else {
1846 // Decoder doesn't support new way of calculating pts (or we're
1847 // being called before it has decoded anything with known timestamp).
1848 // Use the old method of audio pts calculation: take the timestamp
1849 // of last packet with known pts the decoder has read data from,
1850 // and add amount of bytes read after the beginning of that packet
1851 // divided by input bps. This will be inaccurate if the input/output
1852 // ratio is not constant for every audio packet or if it is constant
1853 // but not accurately known in sh_audio->i_bps.
1855 a_pts = d_audio->pts;
1856 if (a_pts == MP_NOPTS_VALUE)
1857 return a_pts;
1859 // ds_tell_pts returns bytes read after last timestamp from
1860 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1861 // it has read but not decoded
1862 if (sh_audio->i_bps)
1863 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1864 (double)sh_audio->i_bps;
1866 // Now a_pts hopefully holds the pts for end of audio from decoder.
1867 // Substract data in buffers between decoder and audio out.
1869 // Decoded but not filtered
1870 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1872 // Data buffered in audio filters, measured in bytes of "missing" output
1873 double buffered_output = af_calc_delay(sh_audio->afilter);
1875 // Data that was ready for ao but was buffered because ao didn't fully
1876 // accept everything to internal buffers yet
1877 buffered_output += mpctx->ao->buffer.len;
1879 // Filters divide audio length by playback_speed, so multiply by it
1880 // to get the length in original units without speedup or slowdown
1881 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1883 return a_pts + mpctx->video_offset;
1886 // Return pts value corresponding to currently playing audio.
1887 double playing_audio_pts(struct MPContext *mpctx)
1889 double pts = written_audio_pts(mpctx);
1890 if (pts == MP_NOPTS_VALUE)
1891 return pts;
1892 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1895 static bool is_av_sub(int type)
1897 return type == 'b' || type == 'p' || type == 'x';
1900 void update_subtitles(struct MPContext *mpctx, double refpts,
1901 double sub_offset, bool reset)
1903 struct MPOpts *opts = &mpctx->opts;
1904 struct sh_video *sh_video = mpctx->sh_video;
1905 struct demux_stream *d_sub = mpctx->d_sub;
1906 double curpts = refpts + sub_delay;
1907 unsigned char *packet = NULL;
1908 int len;
1909 struct sh_sub *sh_sub = d_sub->sh;
1910 int type = sh_sub ? sh_sub->type : 'v';
1911 static subtitle subs;
1912 if (reset) {
1913 if (sh_sub)
1914 sub_reset(sh_sub, mpctx->osd);
1915 sub_clear_text(&subs, MP_NOPTS_VALUE);
1916 if (vo_sub)
1917 set_osd_subtitle(mpctx, NULL);
1918 if (vo_spudec) {
1919 spudec_reset(vo_spudec);
1920 vo_osd_changed(OSDTYPE_SPU);
1922 if (is_av_sub(type))
1923 reset_avsub(sh_sub);
1924 return;
1926 // find sub
1927 if (mpctx->subdata) {
1928 if (sub_fps == 0)
1929 sub_fps = sh_video ? sh_video->fps : 25;
1930 current_module = "find_sub";
1931 find_sub(mpctx, mpctx->subdata, curpts *
1932 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1933 if (vo_sub)
1934 mpctx->vo_sub_last = vo_sub;
1937 // DVD sub:
1938 if (vobsub_id >= 0 || type == 'v') {
1939 int timestamp;
1940 current_module = "spudec";
1941 /* Get a sub packet from the DVD or a vobsub */
1942 while (1) {
1943 // Vobsub
1944 len = 0;
1945 if (vo_vobsub) {
1946 if (curpts >= 0) {
1947 len = vobsub_get_packet(vo_vobsub, curpts,
1948 (void **)&packet, &timestamp);
1949 if (len > 0)
1950 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1951 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1952 len, refpts, sh_video->timer,
1953 timestamp / 90000.0, timestamp);
1955 } else {
1956 // DVD sub
1957 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1958 if (len > 0) {
1959 // XXX This is wrong, sh_video->pts can be arbitrarily
1960 // much behind demuxing position. Unfortunately using
1961 // d_video->pts which would have been the simplest
1962 // improvement doesn't work because mpeg specific hacks
1963 // in video.c set d_video->pts to 0.
1964 float x = d_sub->pts - refpts;
1965 if (x > -20 && x < 20) // prevent missing subs on pts reset
1966 timestamp = 90000 * d_sub->pts;
1967 else
1968 timestamp = 90000 * curpts;
1969 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1970 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1971 refpts, d_sub->pts, timestamp);
1974 if (len <= 0 || !packet)
1975 break;
1976 // create it only here, since with some broken demuxers we might
1977 // type = v but no DVD sub and we currently do not change the
1978 // "original frame size" ever after init, leading to wrong-sized
1979 // PGS subtitles.
1980 if (!vo_spudec)
1981 vo_spudec = spudec_new(NULL);
1982 if (vo_vobsub || timestamp >= 0)
1983 spudec_assemble(vo_spudec, packet, len, timestamp);
1985 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1986 if (type == 'd' && !d_sub->demuxer->teletext) {
1987 tt_stream_props tsp = { 0 };
1988 void *ptr = &tsp;
1989 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
1990 VBI_CONTROL_TRUE)
1991 d_sub->demuxer->teletext = ptr;
1993 if (d_sub->non_interleaved)
1994 ds_get_next_pts(d_sub);
1996 while (d_sub->first) {
1997 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1998 if (subpts > curpts) {
1999 // Libass handled subs can be fed to it in advance
2000 if (!opts->ass_enabled || !is_text_sub(type))
2001 break;
2002 // Try to avoid demuxing whole file at once
2003 if (d_sub->non_interleaved && subpts > curpts + 1)
2004 break;
2006 double duration = d_sub->first->duration;
2007 len = ds_get_packet_sub(d_sub, &packet);
2008 if (is_av_sub(type)) {
2009 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2010 if (ret < 0)
2011 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2012 "subtitle\n");
2013 continue;
2015 if (type == 'm') {
2016 if (len < 2)
2017 continue;
2018 len = FFMIN(len - 2, AV_RB16(packet));
2019 packet += 2;
2021 if (type == 'd') {
2022 if (d_sub->demuxer->teletext) {
2023 uint8_t *p = packet;
2024 p++;
2025 len--;
2026 while (len >= 46) {
2027 int sublen = p[1];
2028 if (p[0] == 2 || p[0] == 3)
2029 teletext_control(d_sub->demuxer->teletext,
2030 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2031 p += sublen + 2;
2032 len -= sublen + 2;
2035 continue;
2037 if (sh_sub && sh_sub->active) {
2038 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2039 continue;
2041 if (subpts != MP_NOPTS_VALUE) {
2042 if (duration < 0)
2043 sub_clear_text(&subs, MP_NOPTS_VALUE);
2044 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2045 int i;
2046 unsigned char *p = packet;
2047 for (i = 0; i < 8 && *p != '\0'; p++)
2048 if (*p == ',')
2049 i++;
2050 if (*p == '\0') /* Broken line? */
2051 continue;
2052 len -= p - packet;
2053 packet = p;
2055 double endpts = MP_NOPTS_VALUE;
2056 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2057 endpts = subpts + duration;
2058 sub_add_text(&subs, packet, len, endpts);
2059 set_osd_subtitle(mpctx, &subs);
2061 if (d_sub->non_interleaved)
2062 ds_get_next_pts(d_sub);
2064 if (!opts->ass_enabled)
2065 if (sub_clear_text(&subs, curpts))
2066 set_osd_subtitle(mpctx, &subs);
2068 if (vo_spudec) {
2069 spudec_heartbeat(vo_spudec, 90000 * curpts);
2070 if (spudec_changed(vo_spudec))
2071 vo_osd_changed(OSDTYPE_SPU);
2074 current_module = NULL;
2077 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2079 int page_changed;
2081 if (!demuxer->teletext)
2082 return;
2084 //Also forcing page update when such ioctl is not supported or call error occured
2085 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2086 &page_changed) != VBI_CONTROL_TRUE)
2087 page_changed = 1;
2089 if (!page_changed)
2090 return;
2092 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2093 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2094 vo_osd_teletext_page = NULL;
2095 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2096 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2097 vo_osd_teletext_half = 0;
2098 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2099 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2100 vo_osd_teletext_mode = 0;
2101 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2102 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2103 vo_osd_teletext_format = 0;
2104 vo_osd_changed(OSDTYPE_TELETEXT);
2106 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2109 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2111 struct MPOpts *opts = &mpctx->opts;
2112 // check for frame-drop:
2113 current_module = "check_framedrop";
2114 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2115 static int dropped_frames;
2116 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2117 float d = delay - mpctx->delay;
2118 ++total_frame_cnt;
2119 // we should avoid dropping too many frames in sequence unless we
2120 // are too late. and we allow 100ms A-V delay here:
2121 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2122 && !mpctx->restart_playback) {
2123 ++drop_frame_cnt;
2124 ++dropped_frames;
2125 return frame_dropping;
2126 } else
2127 dropped_frames = 0;
2129 return 0;
2133 #ifdef HAVE_RTC
2134 int rtc_fd = -1;
2135 #endif
2137 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2139 #ifdef HAVE_RTC
2140 if (rtc_fd >= 0) {
2141 // -------- RTC -----------
2142 current_module = "sleep_rtc";
2143 while (time_frame > 0.000) {
2144 unsigned long rtc_ts;
2145 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2146 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2147 "Linux RTC read error: %s\n", strerror(errno));
2148 time_frame -= get_relative_time(mpctx);
2150 } else
2151 #endif
2153 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2154 // unnecessarily high CPU usage
2155 struct MPOpts *opts = &mpctx->opts;
2156 float margin = opts->softsleep ? 0.011 : 0;
2157 current_module = "sleep_timer";
2158 while (time_frame > margin) {
2159 usec_sleep(1000000 * (time_frame - margin));
2160 time_frame -= get_relative_time(mpctx);
2162 if (opts->softsleep) {
2163 current_module = "sleep_soft";
2164 if (time_frame < 0)
2165 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2166 "Warning! Softsleep underflow!\n");
2167 while (time_frame > 0)
2168 time_frame -= get_relative_time(mpctx); // burn the CPU
2171 return time_frame;
2174 static int select_subtitle(MPContext *mpctx)
2176 struct MPOpts *opts = &mpctx->opts;
2177 // find the best sub to use
2178 int id;
2179 int found = 0;
2180 mpctx->global_sub_pos = -1; // no subs by default
2181 if (vobsub_id >= 0) {
2182 // if user asks for a vobsub id, use that first.
2183 id = vobsub_id;
2184 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2185 M_PROPERTY_OK;
2188 if (!found && opts->sub_id >= 0) {
2189 // if user asks for a dvd sub id, use that next.
2190 id = opts->sub_id;
2191 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2192 M_PROPERTY_OK;
2195 if (!found) {
2196 // if there are text subs to use, use those. (autosubs come last here)
2197 id = 0;
2198 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2199 M_PROPERTY_OK;
2202 if (!found && opts->sub_id == -1) {
2203 // finally select subs by language and container hints
2204 if (opts->sub_id == -1)
2205 opts->sub_id =
2206 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2207 opts->sub_lang);
2208 if (opts->sub_id >= 0) {
2209 id = opts->sub_id;
2210 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2211 M_PROPERTY_OK;
2214 return found;
2217 #ifdef CONFIG_DVDNAV
2218 #ifndef FF_B_TYPE
2219 #define FF_B_TYPE 3
2220 #endif
2221 /// store decoded video image
2222 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2223 mp_image_t *from_mpi)
2225 mp_image_t *mpi;
2227 /// Do not store B-frames
2228 if (from_mpi->pict_type == FF_B_TYPE)
2229 return to_mpi;
2231 if (to_mpi &&
2232 to_mpi->w == from_mpi->w &&
2233 to_mpi->h == from_mpi->h &&
2234 to_mpi->imgfmt == from_mpi->imgfmt)
2235 mpi = to_mpi;
2236 else {
2237 if (to_mpi)
2238 free_mp_image(to_mpi);
2239 if (from_mpi->w == 0 || from_mpi->h == 0)
2240 return NULL;
2241 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2244 copy_mpi(mpi, from_mpi);
2245 return mpi;
2248 static void mp_dvdnav_reset_stream(MPContext *ctx)
2250 struct MPOpts *opts = &ctx->opts;
2251 if (ctx->sh_video) {
2252 /// clear video pts
2253 ctx->d_video->pts = 0.0f;
2254 ctx->sh_video->pts = 0.0f;
2255 ctx->sh_video->i_pts = 0.0f;
2256 ctx->sh_video->last_pts = 0.0f;
2257 ctx->sh_video->num_buffered_pts = 0;
2258 ctx->sh_video->num_frames = 0;
2259 ctx->sh_video->num_frames_decoded = 0;
2260 ctx->sh_video->timer = 0.0f;
2261 ctx->sh_video->stream_delay = 0.0f;
2262 ctx->sh_video->timer = 0;
2263 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2266 if (ctx->sh_audio) {
2267 /// free audio packets and reset
2268 ds_free_packs(ctx->d_audio);
2269 audio_delay -= ctx->sh_audio->stream_delay;
2270 ctx->delay = -audio_delay;
2271 ao_reset(ctx->ao);
2272 resync_audio_stream(ctx->sh_audio);
2275 audio_delay = 0.0f;
2276 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2277 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2278 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2279 if (dvdsub_lang_id != opts->sub_id) {
2280 opts->sub_id = dvdsub_lang_id;
2281 select_subtitle(ctx);
2285 /// clear all EOF related flags
2286 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2289 /// Restore last decoded DVDNAV (still frame)
2290 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2291 int *in_size,
2292 unsigned char **start,
2293 mp_image_t *decoded_frame)
2295 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2296 return decoded_frame;
2298 /// a change occurred in dvdnav stream
2299 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2300 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2301 mp_dvdnav_context_free(mpctx);
2302 mp_dvdnav_reset_stream(mpctx);
2303 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2304 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2307 if (*in_size < 0) {
2308 float len;
2310 /// Display still frame, if any
2311 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2312 decoded_frame = mpctx->nav_smpi;
2314 /// increment video frame : continue playing after still frame
2315 len = get_time_length(mpctx);
2316 if (mpctx->sh_video->pts >= len &&
2317 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2318 mp_dvdnav_skip_still(mpctx->stream);
2319 mp_dvdnav_skip_wait(mpctx->stream);
2321 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2323 if (mpctx->nav_buffer) {
2324 *start = mpctx->nav_start;
2325 *in_size = mpctx->nav_in_size;
2326 if (mpctx->nav_start)
2327 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2331 return decoded_frame;
2334 /// Save last decoded DVDNAV (still frame)
2335 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2336 unsigned char *start,
2337 mp_image_t *decoded_frame)
2339 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2340 return;
2342 free(mpctx->nav_buffer);
2343 mpctx->nav_buffer = NULL;
2344 mpctx->nav_start = NULL;
2345 mpctx->nav_in_size = -1;
2347 if (in_size > 0)
2348 mpctx->nav_buffer = malloc(in_size);
2349 if (mpctx->nav_buffer) {
2350 mpctx->nav_start = start;
2351 mpctx->nav_in_size = in_size;
2352 memcpy(mpctx->nav_buffer, start, in_size);
2355 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2356 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2358 #endif /* CONFIG_DVDNAV */
2360 /* Modify video timing to match the audio timeline. There are two main
2361 * reasons this is needed. First, video and audio can start from different
2362 * positions at beginning of file or after a seek (MPlayer starts both
2363 * immediately even if they have different pts). Second, the file can have
2364 * audio timestamps that are inconsistent with the duration of the audio
2365 * packets, for example two consecutive timestamp values differing by
2366 * one second but only a packet with enough samples for half a second
2367 * of playback between them.
2369 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2371 current_module = "av_sync";
2373 if (!mpctx->sh_audio || mpctx->syncing_audio)
2374 return;
2376 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2377 double v_pts = mpctx->sh_video->pts;
2378 double av_delay = a_pts - v_pts;
2379 // Try to sync vo_flip() so it will *finish* at given time
2380 av_delay += mpctx->last_vo_flip_duration;
2381 av_delay -= audio_delay; // This much pts difference is desired
2383 double change = av_delay * 0.1;
2384 double max_change = default_max_pts_correction >= 0 ?
2385 default_max_pts_correction : frame_time * 0.1;
2386 if (change < -max_change)
2387 change = -max_change;
2388 else if (change > max_change)
2389 change = max_change;
2390 mpctx->delay += change;
2391 mpctx->total_avsync_change += change;
2394 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2395 double pts)
2397 if (mpctx->paused)
2398 return 0;
2399 struct ao *ao = mpctx->ao;
2400 double bps = ao->bps / mpctx->opts.playback_speed;
2401 ao->pts = pts;
2402 // hack used by some mpeg-writing AOs
2403 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2404 mpctx->delay) * 90000.0;
2405 int played = ao_play(mpctx->ao, data, len, flags);
2406 if (played > 0) {
2407 mpctx->delay += played / bps;
2408 // Keep correct pts for remaining data - could be used to flush
2409 // remaining buffer when closing ao.
2410 ao->pts += played / bps;
2412 return played;
2415 #define ASYNC_PLAY_DONE -3
2416 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2418 struct ao *ao = mpctx->ao;
2419 struct MPOpts *opts = &mpctx->opts;
2420 sh_audio_t * const sh_audio = mpctx->sh_audio;
2421 int res;
2423 // Timing info may not be set without
2424 res = decode_audio(sh_audio, &ao->buffer, 1);
2425 if (res < 0)
2426 return res;
2428 int bytes;
2429 bool did_retry = false;
2430 double written_pts;
2431 double bps = ao->bps / opts->playback_speed;
2432 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2433 mpctx->hrseek_active = false;
2434 while (1) {
2435 written_pts = written_audio_pts(mpctx);
2436 double ptsdiff;
2437 if (hrseek)
2438 ptsdiff = written_pts - mpctx->hrseek_pts;
2439 else
2440 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2441 - audio_delay;
2442 bytes = ptsdiff * bps;
2443 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2445 // ogg demuxers give packets without timing
2446 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2447 if (!did_retry) {
2448 // Try to read more data to see packets that have pts
2449 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2450 if (res < 0)
2451 return res;
2452 did_retry = true;
2453 continue;
2455 bytes = 0;
2458 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2459 bytes = 0;
2461 if (bytes > 0)
2462 break;
2464 mpctx->syncing_audio = false;
2465 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2466 int res = decode_audio(sh_audio, &ao->buffer, a);
2467 bytes += ao->buffer.len;
2468 if (bytes >= 0) {
2469 memmove(ao->buffer.start,
2470 ao->buffer.start + ao->buffer.len - bytes, bytes);
2471 ao->buffer.len = bytes;
2472 if (res < 0)
2473 return res;
2474 return decode_audio(sh_audio, &ao->buffer, playsize);
2476 ao->buffer.len = 0;
2477 if (res < 0)
2478 return res;
2480 if (hrseek)
2481 // Don't add silence in audio-only case even if position is too late
2482 return 0;
2483 int fillbyte = 0;
2484 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2485 fillbyte = 0x80;
2486 if (bytes >= playsize) {
2487 /* This case could fall back to the one below with
2488 * bytes = playsize, but then silence would keep accumulating
2489 * in a_out_buffer if the AO accepts less data than it asks for
2490 * in playsize. */
2491 char *p = malloc(playsize);
2492 memset(p, fillbyte, playsize);
2493 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2494 free(p);
2495 return ASYNC_PLAY_DONE;
2497 mpctx->syncing_audio = false;
2498 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2499 return decode_audio(sh_audio, &ao->buffer, playsize);
2502 static int fill_audio_out_buffers(struct MPContext *mpctx)
2504 struct MPOpts *opts = &mpctx->opts;
2505 struct ao *ao = mpctx->ao;
2506 unsigned int t;
2507 double tt;
2508 int playsize;
2509 int playflags = 0;
2510 bool audio_eof = false;
2511 bool partial_fill = false;
2512 sh_audio_t * const sh_audio = mpctx->sh_audio;
2513 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2514 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2516 current_module = "play_audio";
2518 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2519 return 0;
2521 // hack used by some mpeg-writing AOs
2522 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2523 mpctx->delay) * 90000.0;
2525 if (mpctx->paused)
2526 playsize = 1; // just initialize things (audio pts at least)
2527 else
2528 playsize = ao_get_space(ao);
2530 // Fill buffer if needed:
2531 current_module = "decode_audio";
2532 t = GetTimer();
2534 // Coming here with hrseek_active still set means audio-only
2535 if (!mpctx->sh_video)
2536 mpctx->syncing_audio = false;
2537 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2538 mpctx->syncing_audio = false;
2539 mpctx->hrseek_active = false;
2542 int res;
2543 if (mpctx->syncing_audio || mpctx->hrseek_active)
2544 res = audio_start_sync(mpctx, playsize);
2545 else
2546 res = decode_audio(sh_audio, &ao->buffer, playsize);
2547 if (res < 0) { // EOF, error or format change
2548 if (res == -2) {
2549 /* The format change isn't handled too gracefully. A more precise
2550 * implementation would require draining buffered old-format audio
2551 * while displaying video, then doing the output format switch.
2553 uninit_player(mpctx, INITIALIZED_AO);
2554 reinit_audio_chain(mpctx);
2555 return -1;
2556 } else if (res == ASYNC_PLAY_DONE)
2557 return 0;
2558 else if (mpctx->d_audio->eof)
2559 audio_eof = true;
2561 t = GetTimer() - t;
2562 tt = t * 0.000001f;
2563 audio_time_usage += tt;
2564 if (mpctx->timeline && modifiable_audio_format) {
2565 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2566 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2567 * ao->bps / opts->playback_speed;
2568 if (playsize > bytes) {
2569 playsize = FFMAX(bytes, 0);
2570 playflags |= AOPLAY_FINAL_CHUNK;
2571 audio_eof = true;
2572 partial_fill = true;
2576 assert(ao->buffer.len % unitsize == 0);
2577 if (playsize > ao->buffer.len) {
2578 partial_fill = true;
2579 playsize = ao->buffer.len;
2580 if (audio_eof)
2581 playflags |= AOPLAY_FINAL_CHUNK;
2583 playsize -= playsize % unitsize;
2584 if (!playsize)
2585 return partial_fill && audio_eof ? -2 : -partial_fill;
2587 // play audio:
2588 current_module = "play_audio";
2590 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2591 written_audio_pts(mpctx));
2592 assert(played % unitsize == 0);
2593 ao->buffer_playable_size = playsize - played;
2595 if (played > 0) {
2596 ao->buffer.len -= played;
2597 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2598 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2599 // Sanity check to avoid hanging in case current ao doesn't output
2600 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2601 return -2;
2604 return -partial_fill;
2607 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2608 bool sync_to_audio, float *aq_sleep_time)
2610 struct MPOpts *opts = &mpctx->opts;
2611 double audio_limit = 2;
2612 current_module = "calc_sleep_time";
2614 if (mpctx->restart_playback)
2615 return 0;
2617 *time_frame -= get_relative_time(mpctx); // reset timer
2619 if (sync_to_audio) {
2620 float delay = ao_get_delay(mpctx->ao);
2621 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2623 if (opts->autosync) {
2625 * Adjust this raw delay value by calculating the expected
2626 * delay for this frame and generating a new value which is
2627 * weighted between the two. The higher autosync is, the
2628 * closer to the delay value gets to that which "-nosound"
2629 * would have used, and the longer it will take for A/V
2630 * sync to settle at the right value (but it eventually will.)
2631 * This settling time is very short for values below 100.
2633 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2634 float difference = delay - predicted;
2635 delay = predicted + difference / (float)opts->autosync;
2638 *time_frame = delay - mpctx->delay / opts->playback_speed;
2640 // delay = amount of audio buffered in soundcard/driver
2641 delay = FFMIN(delay, 0.5);
2642 delay = FFMAX(delay, 0.1);
2643 audio_limit = delay;
2644 } else {
2645 // If we're lagging more than 200 ms behind the right playback rate,
2646 // don't try to "catch up".
2647 // If benchmark is set always output frames as fast as possible
2648 // without sleeping.
2649 if (*time_frame < -0.2 || opts->benchmark)
2650 *time_frame = 0;
2653 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2655 if (t <= 0.05)
2656 return 0;
2658 t -= 0.05;
2659 if (t > audio_limit * 0.6)
2660 t = audio_limit * 0.5;
2661 *aq_sleep_time += t;
2662 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2663 return 1;
2666 int reinit_video_chain(struct MPContext *mpctx)
2668 struct MPOpts *opts = &mpctx->opts;
2669 sh_video_t * const sh_video = mpctx->sh_video;
2670 if (!sh_video)
2671 return 0;
2672 double ar = -1.0;
2673 //================== Init VIDEO (codec & libvo) ==========================
2674 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2675 current_module = "preinit_libvo";
2677 //shouldn't we set dvideo->id=-2 when we fail?
2678 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2679 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2680 mpctx->key_fifo,
2681 mpctx->input))) {
2682 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2683 "the selected video_out (-vo) device.\n");
2684 goto err_out;
2686 mpctx->initialized_flags |= INITIALIZED_VO;
2689 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2690 &ar) != STREAM_UNSUPPORTED)
2691 mpctx->sh_video->stream_aspect = ar;
2692 current_module = "init_video_filters";
2694 char *vf_arg[] = {
2695 "_oldargs_", (char *)mpctx->video_out, NULL
2697 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2700 #ifdef CONFIG_ASS
2701 if (opts->ass_enabled) {
2702 int i;
2703 int insert = 1;
2704 if (opts->vf_settings)
2705 for (i = 0; opts->vf_settings[i].name; ++i)
2706 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2707 insert = 0;
2708 break;
2710 if (insert) {
2711 extern vf_info_t vf_info_ass;
2712 const vf_info_t *libass_vfs[] = {
2713 &vf_info_ass, NULL
2715 char *vf_arg[] = {
2716 "auto", "1", NULL
2718 int retcode = 0;
2719 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2720 sh_video->vfilter,
2721 "ass", vf_arg,
2722 &retcode);
2723 if (vf_ass)
2724 sh_video->vfilter = vf_ass;
2725 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2726 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2727 else
2728 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2729 "ASS: cannot add video filter\n");
2732 #endif
2734 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2736 #ifdef CONFIG_ASS
2737 if (opts->ass_enabled)
2738 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2739 mpctx->ass_library);
2740 #endif
2742 current_module = "init_video_codec";
2744 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2745 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2746 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2748 if (!sh_video->initialized) {
2749 if (!opts->fixed_vo)
2750 uninit_player(mpctx, INITIALIZED_VO);
2751 goto err_out;
2754 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2756 if (sh_video->codec)
2757 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2758 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2760 sh_video->last_pts = MP_NOPTS_VALUE;
2761 sh_video->num_buffered_pts = 0;
2762 sh_video->next_frame_time = 0;
2764 if (opts->auto_quality > 0) {
2765 // Auto quality option enabled
2766 output_quality = get_video_quality_max(sh_video);
2767 if (opts->auto_quality > output_quality)
2768 opts->auto_quality = output_quality;
2769 else
2770 output_quality = opts->auto_quality;
2771 mp_msg(MSGT_CPLAYER, MSGL_V,
2772 "AutoQ: setting quality to %d.\n", output_quality);
2773 set_video_quality(sh_video, output_quality);
2776 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2778 current_module = "init_vo";
2780 return 1;
2782 err_out:
2783 mpctx->sh_video = mpctx->d_video->sh = NULL;
2784 return 0;
2787 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2789 struct sh_video *sh_video = mpctx->sh_video;
2790 double frame_time = 0;
2791 struct vo *video_out = mpctx->video_out;
2792 while (1) {
2793 current_module = "filter_video";
2794 // In nocorrect-pts mode there is no way to properly time these frames
2795 if (vo_get_buffered_frame(video_out, 0) >= 0)
2796 break;
2797 if (vf_output_queued_frame(sh_video->vfilter))
2798 break;
2799 unsigned char *packet = NULL;
2800 frame_time = sh_video->next_frame_time;
2801 if (mpctx->restart_playback)
2802 frame_time = 0;
2803 int in_size = 0;
2804 while (!in_size)
2805 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2806 &packet, force_fps);
2807 if (in_size < 0) {
2808 #ifdef CONFIG_DVDNAV
2809 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2810 if (mp_dvdnav_is_eof(mpctx->stream))
2811 return -1;
2812 if (mpctx->d_video)
2813 mpctx->d_video->eof = 0;
2814 if (mpctx->d_audio)
2815 mpctx->d_audio->eof = 0;
2816 mpctx->stream->eof = 0;
2817 } else
2818 #endif
2819 return -1;
2821 if (in_size > max_framesize)
2822 max_framesize = in_size;
2823 sh_video->timer += frame_time;
2824 if (mpctx->sh_audio)
2825 mpctx->delay -= frame_time;
2826 // video_read_frame can change fps (e.g. for ASF video)
2827 vo_fps = sh_video->fps;
2828 int framedrop_type = check_framedrop(mpctx, frame_time);
2829 current_module = "decode video";
2831 void *decoded_frame;
2832 #ifdef CONFIG_DVDNAV
2833 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2834 if (in_size >= 0 && !decoded_frame)
2835 #endif
2836 decoded_frame = decode_video(sh_video, NULL, packet, in_size,
2837 framedrop_type, sh_video->pts);
2838 #ifdef CONFIG_DVDNAV
2839 // Save last still frame for future display
2840 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2841 #endif
2842 if (decoded_frame) {
2843 current_module = "filter video";
2844 filter_video(sh_video, decoded_frame, sh_video->pts);
2846 break;
2848 return frame_time;
2851 static void determine_frame_pts(struct MPContext *mpctx)
2853 struct sh_video *sh_video = mpctx->sh_video;
2854 struct MPOpts *opts = &mpctx->opts;
2856 if (opts->user_pts_assoc_mode)
2857 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2858 else if (sh_video->pts_assoc_mode == 0) {
2859 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2860 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2861 sh_video->pts_assoc_mode = 1;
2862 else
2863 sh_video->pts_assoc_mode = 2;
2864 } else {
2865 int probcount1 = sh_video->num_reordered_pts_problems;
2866 int probcount2 = sh_video->num_sorted_pts_problems;
2867 if (sh_video->pts_assoc_mode == 2) {
2868 int tmp = probcount1;
2869 probcount1 = probcount2;
2870 probcount2 = tmp;
2872 if (probcount1 >= probcount2 * 1.5 + 2) {
2873 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2874 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2875 "%d.\n", sh_video->pts_assoc_mode);
2878 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2879 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2882 static double update_video(struct MPContext *mpctx)
2884 struct sh_video *sh_video = mpctx->sh_video;
2885 struct vo *video_out = mpctx->video_out;
2886 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2887 mpctx->osd); // hack for vf_expand
2888 if (!mpctx->opts.correct_pts)
2889 return update_video_nocorrect_pts(mpctx);
2891 double pts;
2893 while (1) {
2894 current_module = "filter_video";
2895 if (vo_get_buffered_frame(video_out, false) >= 0)
2896 break;
2897 // XXX Time used in this call is not counted in any performance
2898 // timer now
2899 if (vf_output_queued_frame(sh_video->vfilter))
2900 break;
2901 int in_size = 0;
2902 unsigned char *buf = NULL;
2903 pts = MP_NOPTS_VALUE;
2904 struct demux_packet *pkt;
2905 while (1) {
2906 pkt = ds_get_packet2(mpctx->d_video, false);
2907 if (!pkt || pkt->len)
2908 break;
2909 /* Packets with size 0 are assumed to not correspond to frames,
2910 * but to indicate the absence of a frame in formats like AVI
2911 * that must have packets at fixed timecode intervals. */
2913 if (pkt) {
2914 in_size = pkt->len;
2915 buf = pkt->buffer;
2916 pts = pkt->pts;
2918 if (pts != MP_NOPTS_VALUE)
2919 pts += mpctx->video_offset;
2920 if (in_size > max_framesize)
2921 max_framesize = in_size;
2922 current_module = "decode video";
2923 if (pts >= mpctx->hrseek_pts - .005)
2924 mpctx->hrseek_framedrop = false;
2925 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2926 check_framedrop(mpctx, sh_video->frametime);
2927 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2928 framedrop_type, pts);
2929 if (decoded_frame) {
2930 determine_frame_pts(mpctx);
2931 current_module = "filter video";
2932 filter_video(sh_video, decoded_frame, sh_video->pts);
2933 } else if (!pkt) {
2934 if (vo_get_buffered_frame(video_out, true) < 0)
2935 return -1;
2937 break;
2940 if (!video_out->frame_loaded)
2941 return 0;
2943 pts = video_out->next_pts;
2944 if (pts == MP_NOPTS_VALUE) {
2945 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2946 // Try to use decoder pts from before filters
2947 pts = sh_video->pts;
2948 if (pts == MP_NOPTS_VALUE)
2949 pts = sh_video->last_pts;
2951 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2952 vo_skip_frame(video_out);
2953 return 0;
2955 mpctx->hrseek_active = false;
2956 sh_video->pts = pts;
2957 if (sh_video->last_pts == MP_NOPTS_VALUE)
2958 sh_video->last_pts = sh_video->pts;
2959 else if (sh_video->last_pts > sh_video->pts) {
2960 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2961 sh_video->pts, sh_video->last_pts);
2962 /* If the difference in pts is small treat it as jitter around the
2963 * right value (possibly caused by incorrect timestamp ordering) and
2964 * just show this frame immediately after the last one.
2965 * Treat bigger differences as timestamp resets and start counting
2966 * timing of later frames from the position of this one. */
2967 if (sh_video->last_pts - sh_video->pts > 0.5)
2968 sh_video->last_pts = sh_video->pts;
2969 else
2970 sh_video->pts = sh_video->last_pts;
2972 double frame_time = sh_video->pts - sh_video->last_pts;
2973 sh_video->last_pts = sh_video->pts;
2974 sh_video->timer += frame_time;
2975 if (mpctx->sh_audio)
2976 mpctx->delay -= frame_time;
2977 return frame_time;
2980 static int get_cache_fill(struct MPContext *mpctx)
2982 #ifdef CONFIG_STREAM_CACHE
2983 if (stream_cache_size > 0)
2984 return cache_fill_status(mpctx->stream);
2985 #endif
2986 return -1;
2989 static void update_pause_message(struct MPContext *mpctx)
2991 struct MPOpts *opts = &mpctx->opts;
2993 if (opts->quiet)
2994 return;
2996 int cache_fill = get_cache_fill(mpctx);
2997 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2999 if (!mpctx->status_printed && !cache_changed)
3000 return;
3002 char *msg = mp_gtext(" ===== PAUSE =====");
3003 char *tmpmem = NULL;
3004 if (cache_fill >= 0)
3005 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
3007 if (opts->term_osd && !mpctx->sh_video) {
3008 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
3009 update_osd_msg(mpctx);
3010 } else {
3011 if (mpctx->status_printed)
3012 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
3013 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
3016 mpctx->paused_cache_fill = cache_fill;
3017 mpctx->status_printed = false;
3019 talloc_free(tmpmem);
3022 void pause_player(struct MPContext *mpctx)
3024 if (mpctx->paused)
3025 return;
3026 mpctx->paused = 1;
3027 mpctx->step_frames = 0;
3028 mpctx->time_frame -= get_relative_time(mpctx);
3029 mpctx->osd_function = OSD_PAUSE;
3031 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3032 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3034 if (mpctx->ao && mpctx->sh_audio)
3035 ao_pause(mpctx->ao); // pause audio, keep data if possible
3037 mpctx->paused_cache_fill = get_cache_fill(mpctx);
3038 mpctx->status_printed = true;
3039 update_pause_message(mpctx);
3041 if (!mpctx->opts.quiet)
3042 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
3045 void unpause_player(struct MPContext *mpctx)
3047 if (!mpctx->paused)
3048 return;
3049 mpctx->paused = 0;
3050 if (!mpctx->step_frames)
3051 mpctx->osd_function = OSD_PLAY;
3053 if (mpctx->ao && mpctx->sh_audio)
3054 ao_resume(mpctx->ao);
3055 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3056 && !mpctx->step_frames)
3057 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3058 (void)get_relative_time(mpctx); // ignore time that passed during pause
3061 static int redraw_osd(struct MPContext *mpctx)
3063 struct sh_video *sh_video = mpctx->sh_video;
3064 struct vf_instance *vf = sh_video->vfilter;
3065 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3066 return -1;
3067 if (vo_redraw_frame(mpctx->video_out) < 0)
3068 return -1;
3069 mpctx->osd->pts = mpctx->video_pts;
3070 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3071 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3072 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3073 vo_flip_page(mpctx->video_out, 0, -1);
3074 return 0;
3077 void add_step_frame(struct MPContext *mpctx)
3079 mpctx->step_frames++;
3080 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3081 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3082 unpause_player(mpctx);
3085 static void pause_loop(struct MPContext *mpctx)
3087 mp_cmd_t *cmd;
3089 update_pause_message(mpctx);
3091 while ((cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
3092 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
3093 if (cmd) {
3094 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3095 run_command(mpctx, cmd);
3096 mp_cmd_free(cmd);
3097 continue;
3099 if (mpctx->sh_video && mpctx->video_out)
3100 vo_check_events(mpctx->video_out);
3101 update_osd_msg(mpctx);
3102 int hack = vo_osd_changed(0);
3103 vo_osd_changed(hack);
3104 if (hack || mpctx->sh_video && mpctx->video_out->want_redraw)
3105 break;
3106 update_pause_message(mpctx);
3111 // Find the right mute status and record position for new file position
3112 static void edl_seek_reset(MPContext *mpctx)
3114 mpctx->edl_muted = 0;
3115 next_edl_record = edl_records;
3117 while (next_edl_record) {
3118 if (next_edl_record->start_sec >= get_current_time(mpctx))
3119 break;
3121 if (next_edl_record->action == EDL_MUTE)
3122 mpctx->edl_muted = !mpctx->edl_muted;
3123 next_edl_record = next_edl_record->next;
3125 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3126 mixer_mute(&mpctx->mixer);
3130 // Execute EDL command for the current position if one exists
3131 static void edl_update(MPContext *mpctx)
3133 if (!next_edl_record)
3134 return;
3136 if (!mpctx->sh_video) {
3137 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
3138 "Cannot use EDL without video, disabling.\n");
3139 free_edl(edl_records);
3140 next_edl_record = NULL;
3141 edl_records = NULL;
3142 return;
3145 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3146 if (next_edl_record->action == EDL_SKIP) {
3147 mpctx->osd_function = OSD_FFW;
3148 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3149 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3150 "[%f], length [%f]\n", next_edl_record->start_sec,
3151 next_edl_record->stop_sec, next_edl_record->length_sec);
3152 } else if (next_edl_record->action == EDL_MUTE) {
3153 mpctx->edl_muted = !mpctx->edl_muted;
3154 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3155 mixer_mute(&mpctx->mixer);
3156 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3157 next_edl_record->start_sec);
3159 next_edl_record = next_edl_record->next;
3163 static void reinit_decoders(struct MPContext *mpctx)
3165 reinit_video_chain(mpctx);
3166 reinit_audio_chain(mpctx);
3167 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3170 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3172 if (mpctx->sh_video) {
3173 current_module = "seek_video_reset";
3174 resync_video_stream(mpctx->sh_video);
3175 mpctx->sh_video->timer = 0;
3176 vo_seek_reset(mpctx->video_out);
3177 mpctx->sh_video->timer = 0;
3178 mpctx->sh_video->num_buffered_pts = 0;
3179 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3180 mpctx->delay = 0;
3181 mpctx->time_frame = 0;
3182 mpctx->restart_playback = true;
3183 // Not all demuxers set d_video->pts during seek, so this value
3184 // (which is used by at least vobsub and edl code below) may
3185 // be completely wrong (probably 0).
3186 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3187 mpctx->video_pts = mpctx->sh_video->pts;
3188 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3189 true);
3190 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3193 if (mpctx->sh_audio) {
3194 current_module = "seek_audio_reset";
3195 resync_audio_stream(mpctx->sh_audio);
3196 if (reset_ao)
3197 ao_reset(mpctx->ao);
3198 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3199 mpctx->sh_audio->a_buffer_len = 0;
3200 if (!mpctx->sh_video)
3201 update_subtitles(mpctx, mpctx->sh_audio->pts,
3202 mpctx->video_offset, true);
3205 if (vo_vobsub && mpctx->sh_video) {
3206 current_module = "seek_vobsub_reset";
3207 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3210 edl_seek_reset(mpctx);
3212 mpctx->hrseek_active = false;
3213 mpctx->hrseek_framedrop = false;
3214 mpctx->total_avsync_change = 0;
3215 audio_time_usage = 0;
3216 video_time_usage = 0;
3217 vout_time_usage = 0;
3218 drop_frame_cnt = 0;
3220 current_module = NULL;
3223 static bool timeline_set_part(struct MPContext *mpctx, int i)
3225 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3226 struct timeline_part *n = mpctx->timeline + i;
3227 mpctx->timeline_part = i;
3228 mpctx->video_offset = n->start - n->source_start;
3229 if (n->source == p->source)
3230 return false;
3231 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3232 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3233 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3234 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3235 mpctx->stop_play = orig_stop_play;
3236 mpctx->demuxer = n->source->demuxer;
3237 mpctx->d_video = mpctx->demuxer->video;
3238 mpctx->d_audio = mpctx->demuxer->audio;
3239 mpctx->d_sub = mpctx->demuxer->sub;
3240 mpctx->sh_video = mpctx->d_video->sh;
3241 mpctx->sh_audio = mpctx->d_audio->sh;
3242 return true;
3245 // Given pts, switch playback to the corresponding part.
3246 // Return offset within that part.
3247 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3248 bool *need_reset)
3250 if (pts < 0)
3251 pts = 0;
3252 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3253 struct timeline_part *p = mpctx->timeline + i;
3254 if (pts < (p + 1)->start) {
3255 *need_reset = timeline_set_part(mpctx, i);
3256 return pts - p->start + p->source_start;
3259 return -1;
3263 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3264 static int seek(MPContext *mpctx, struct seek_params seek,
3265 bool timeline_fallthrough)
3267 struct MPOpts *opts = &mpctx->opts;
3269 current_module = "seek";
3270 if (mpctx->stop_play == AT_END_OF_FILE)
3271 mpctx->stop_play = KEEP_PLAYING;
3272 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3273 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3274 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3275 || opts->hr_seek > 0 || seek.exact > 0;
3276 if (seek.type == MPSEEK_FACTOR
3277 || seek.type == MPSEEK_ABSOLUTE
3278 && seek.amount < mpctx->last_chapter_pts
3279 || seek.amount < 0)
3280 mpctx->last_chapter_seek = -2;
3281 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3282 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3283 seek.type = MPSEEK_ABSOLUTE;
3285 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3286 && seek.type == MPSEEK_RELATIVE) {
3287 seek.type = MPSEEK_ABSOLUTE;
3288 seek.direction = seek.amount > 0 ? 1 : -1;
3289 seek.amount += get_current_time(mpctx);
3292 /* At least the liba52 decoder wants to read from the input stream
3293 * during initialization, so reinit must be done after the demux_seek()
3294 * call that clears possible stream EOF. */
3295 bool need_reset = false;
3296 double demuxer_amount = seek.amount;
3297 if (mpctx->timeline) {
3298 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3299 &need_reset);
3300 if (demuxer_amount == -1) {
3301 mpctx->stop_play = AT_END_OF_FILE;
3302 // Clear audio from current position
3303 if (mpctx->sh_audio) {
3304 ao_reset(mpctx->ao);
3305 mpctx->sh_audio->a_buffer_len = 0;
3307 return -1;
3310 int demuxer_style = 0;
3311 switch (seek.type) {
3312 case MPSEEK_FACTOR:
3313 demuxer_style |= SEEK_FACTOR; // fallthrough
3314 case MPSEEK_ABSOLUTE:
3315 demuxer_style |= SEEK_ABSOLUTE;
3317 if (hr_seek || seek.direction < 0)
3318 demuxer_style |= SEEK_BACKWARD;
3319 else if (seek.direction > 0)
3320 demuxer_style |= SEEK_FORWARD;
3322 if (hr_seek)
3323 demuxer_amount -= opts->hr_seek_demuxer_offset;
3324 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3325 demuxer_style);
3326 if (need_reset)
3327 reinit_decoders(mpctx);
3328 if (seekresult == 0)
3329 return -1;
3331 seek_reset(mpctx, !timeline_fallthrough);
3333 /* Use the target time as "current position" for further relative
3334 * seeks etc until a new video frame has been decoded */
3335 if (seek.type == MPSEEK_ABSOLUTE) {
3336 mpctx->video_pts = seek.amount;
3337 mpctx->last_seek_pts = seek.amount;
3338 } else
3339 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3341 if (hr_seek) {
3342 mpctx->hrseek_active = true;
3343 mpctx->hrseek_framedrop = true;
3344 mpctx->hrseek_pts = seek.amount;
3347 mpctx->start_timestamp = GetTimerMS();
3349 return 0;
3352 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3353 int exact)
3355 struct seek_params *seek = &mpctx->seek;
3356 switch (type) {
3357 case MPSEEK_RELATIVE:
3358 if (seek->type == MPSEEK_FACTOR)
3359 return; // Well... not common enough to bother doing better
3360 seek->amount += amount;
3361 seek->exact = FFMAX(seek->exact, exact);
3362 if (seek->type == MPSEEK_NONE)
3363 seek->exact = exact;
3364 if (seek->type == MPSEEK_ABSOLUTE)
3365 return;
3366 if (seek->amount == 0) {
3367 *seek = (struct seek_params){ 0 };
3368 return;
3370 seek->type = MPSEEK_RELATIVE;
3371 return;
3372 case MPSEEK_ABSOLUTE:
3373 case MPSEEK_FACTOR:
3374 *seek = (struct seek_params) {
3375 .type = type,
3376 .amount = amount,
3377 .exact = exact,
3379 return;
3380 case MPSEEK_NONE:
3381 *seek = (struct seek_params){ 0 };
3382 return;
3384 abort();
3388 double get_time_length(struct MPContext *mpctx)
3390 if (mpctx->timeline)
3391 return mpctx->timeline[mpctx->num_timeline_parts].start;
3393 struct demuxer *demuxer = mpctx->demuxer;
3394 double get_time_ans;
3395 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3396 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3397 (void *) &get_time_ans) > 0)
3398 return get_time_ans;
3400 struct sh_video *sh_video = mpctx->d_video->sh;
3401 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3402 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3403 return (double) (demuxer->movi_end - demuxer->movi_start) /
3404 (sh_video->i_bps + sh_audio->i_bps);
3405 if (sh_video && sh_video->i_bps)
3406 return (double) (demuxer->movi_end - demuxer->movi_start) /
3407 sh_video->i_bps;
3408 if (sh_audio && sh_audio->i_bps)
3409 return (double) (demuxer->movi_end - demuxer->movi_start) /
3410 sh_audio->i_bps;
3411 return 0;
3414 /* If there are timestamps from stream level then use those (for example
3415 * DVDs can have consistent times there while the MPEG-level timestamps
3416 * reset). */
3417 double get_current_time(struct MPContext *mpctx)
3419 struct demuxer *demuxer = mpctx->demuxer;
3420 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3421 return demuxer->stream_pts;
3422 struct sh_video *sh_video = demuxer->video->sh;
3423 if (sh_video)
3424 return mpctx->video_pts;
3425 double apts = playing_audio_pts(mpctx);
3426 if (apts != MP_NOPTS_VALUE)
3427 return apts;
3428 return mpctx->last_seek_pts;
3431 int get_percent_pos(struct MPContext *mpctx)
3433 struct demuxer *demuxer = mpctx->demuxer;
3434 int ans = 0;
3435 if (mpctx->timeline)
3436 ans = get_current_time(mpctx) * 100 /
3437 mpctx->timeline[mpctx->num_timeline_parts].start;
3438 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3440 else {
3441 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3442 off_t pos = demuxer->filepos > 0 ?
3443 demuxer->filepos : stream_tell(demuxer->stream);
3444 if (len > 0)
3445 ans = (pos - demuxer->movi_start) / len;
3446 else
3447 ans = 0;
3449 if (ans < 0)
3450 ans = 0;
3451 if (ans > 100)
3452 ans = 100;
3453 return ans;
3456 // -2 is no chapters, -1 is before first chapter
3457 int get_current_chapter(struct MPContext *mpctx)
3459 double current_pts = get_current_time(mpctx);
3460 if (!mpctx->chapters)
3461 return FFMAX(mpctx->last_chapter_seek,
3462 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3464 int i;
3465 for (i = 1; i < mpctx->num_chapters; i++)
3466 if (current_pts < mpctx->chapters[i].start)
3467 break;
3468 return FFMAX(mpctx->last_chapter_seek, i - 1);
3471 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3473 char *name = chapter_name(mpctx, chapter);
3474 if (name) {
3475 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3476 } else {
3477 int chapter_count = get_chapter_count(mpctx);
3478 if (chapter_count <= 0)
3479 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3480 else
3481 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3482 chapter_count);
3484 return name;
3487 // returns NULL if chapter name unavailable
3488 char *chapter_name(struct MPContext *mpctx, int chapter)
3490 if (!mpctx->chapters)
3491 return demuxer_chapter_name(mpctx->demuxer, chapter);
3492 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3495 // returns the start of the chapter in seconds
3496 double chapter_start_time(struct MPContext *mpctx, int chapter)
3498 if (!mpctx->chapters)
3499 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3500 return mpctx->chapters[chapter].start;
3503 int get_chapter_count(struct MPContext *mpctx)
3505 if (!mpctx->chapters)
3506 return demuxer_chapter_count(mpctx->demuxer);
3507 return mpctx->num_chapters;
3510 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3512 mpctx->last_chapter_seek = -2;
3513 if (!mpctx->chapters) {
3514 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3515 if (res >= 0) {
3516 if (*seek_pts == -1)
3517 seek_reset(mpctx, true);
3518 else {
3519 mpctx->last_chapter_seek = res;
3520 mpctx->last_chapter_pts = *seek_pts;
3523 return res;
3526 if (chapter >= mpctx->num_chapters)
3527 return -1;
3528 if (chapter < 0)
3529 chapter = 0;
3530 *seek_pts = mpctx->chapters[chapter].start;
3531 mpctx->last_chapter_seek = chapter;
3532 mpctx->last_chapter_pts = *seek_pts;
3533 return chapter;
3537 static void run_playloop(struct MPContext *mpctx)
3539 struct MPOpts *opts = &mpctx->opts;
3540 float aq_sleep_time = 0;
3541 bool full_audio_buffers = false;
3543 if (opts->chapterrange[1] > 0) {
3544 int cur_chapter = get_current_chapter(mpctx);
3545 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3546 mpctx->stop_play = PT_NEXT_ENTRY;
3549 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3550 mpctx->sh_audio = mpctx->d_audio->sh;
3551 mpctx->sh_audio->ds = mpctx->d_audio;
3552 reinit_audio_chain(mpctx);
3555 /*========================== PLAY AUDIO ============================*/
3557 if (!mpctx->sh_video)
3558 mpctx->restart_playback = false;
3560 if (mpctx->sh_audio && !mpctx->restart_playback) {
3561 int status = fill_audio_out_buffers(mpctx);
3562 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3563 if (status == -2)
3564 // at eof, all audio at least written to ao
3565 if (!mpctx->sh_video)
3566 mpctx->stop_play = AT_END_OF_FILE;
3570 if (!mpctx->sh_video) {
3571 if (mpctx->step_frames) {
3572 mpctx->step_frames = 0;
3573 pause_player(mpctx);
3575 // handle audio-only case:
3576 double a_pos = 0, a_buf = 0;
3577 // sh_audio can be NULL due to video stream switching
3578 // TODO: handle this better
3579 if (mpctx->sh_audio) {
3580 a_buf = ao_get_delay(mpctx->ao);
3581 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3582 a_buf;
3585 print_status(mpctx, a_pos, false);
3587 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3588 update_osd_msg(mpctx);
3589 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3590 mpctx->stop_play = AT_END_OF_FILE;
3591 else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3592 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3593 && mpctx->sh_audio) {
3594 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3595 if (!opts->gapless_audio && p->source != (p + 1)->source
3596 && a_buf > 0.05) {
3597 mpctx->stop_play = KEEP_PLAYING;
3598 mp_input_get_cmd(mpctx->input, (a_buf - .05) * 1000, true);
3599 } else {
3600 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3601 .amount = (p + 1)->start },
3602 true);
3604 } else if (!mpctx->stop_play) {
3605 int sleep_time = 100;
3606 if (mpctx->sh_audio) {
3607 if (mpctx->ao->untimed)
3608 sleep_time = 0;
3609 else if (full_audio_buffers)
3610 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3611 else
3612 sleep_time = 20;
3613 sleep_time = FFMIN(sleep_time, 100);
3615 mp_input_get_cmd(mpctx->input, sleep_time, true);
3617 } else {
3619 /*========================== PLAY VIDEO ============================*/
3621 vo_pts = mpctx->sh_video->timer * 90000.0;
3622 vo_fps = mpctx->sh_video->fps;
3624 bool blit_frame = mpctx->video_out->frame_loaded;
3625 if (!blit_frame) {
3626 double frame_time = update_video(mpctx);
3627 blit_frame = mpctx->video_out->frame_loaded;
3628 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3629 if (mpctx->sh_video->vf_initialized < 0) {
3630 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3631 "\nFATAL: Could not initialize video filters (-vf) "
3632 "or video output (-vo).\n");
3633 mpctx->stop_play = PT_NEXT_ENTRY;
3634 return;
3636 if (frame_time < 0)
3637 mpctx->stop_play = AT_END_OF_FILE;
3638 else if (!mpctx->restart_playback) {
3639 mpctx->time_frame += frame_time / opts->playback_speed;
3640 adjust_sync(mpctx, frame_time);
3643 if (mpctx->timeline) {
3644 struct timeline_part *next =
3645 mpctx->timeline + mpctx->timeline_part + 1;
3646 if (mpctx->sh_video->pts >= next->start
3647 || mpctx->stop_play == AT_END_OF_FILE
3648 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3649 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3650 .amount = next->start },
3651 true);
3652 return;
3656 // ================================================================
3658 current_module = "vo_check_events";
3659 vo_check_events(mpctx->video_out);
3661 #ifdef CONFIG_X11
3662 if (stop_xscreensaver) {
3663 current_module = "stop_xscreensaver";
3664 xscreensaver_heartbeat(mpctx->x11_state);
3666 #endif
3667 if (heartbeat_cmd) {
3668 static unsigned last_heartbeat;
3669 unsigned now = GetTimerMS();
3670 if (now - last_heartbeat > 30000) {
3671 last_heartbeat = now;
3672 system(heartbeat_cmd);
3676 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3677 &mpctx->time_frame,
3678 full_audio_buffers,
3679 &aq_sleep_time);
3681 //=================== FLIP PAGE (VIDEO BLT): ======================
3683 current_module = "flip_page";
3684 if (!frame_time_remaining && blit_frame) {
3685 vo_new_frame_imminent(mpctx->video_out);
3686 struct sh_video *sh_video = mpctx->sh_video;
3687 mpctx->video_pts = sh_video->pts;
3688 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3689 update_teletext(sh_video, mpctx->demuxer, 0);
3690 update_osd_msg(mpctx);
3691 struct vf_instance *vf = sh_video->vfilter;
3692 mpctx->osd->pts = mpctx->video_pts;
3693 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3694 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3695 vo_osd_changed(0);
3697 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3698 aq_sleep_time += mpctx->time_frame;
3699 // flag 256 means: libvo driver does its timing (dvb card)
3700 if (mpctx->time_frame > 0.001
3701 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3702 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3703 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3705 unsigned int t2 = GetTimer();
3706 /* Playing with playback speed it's possible to get pathological
3707 * cases with mpctx->time_frame negative enough to cause an
3708 * overflow in pts_us calculation, thus the FFMAX. */
3709 double time_frame = FFMAX(mpctx->time_frame, -1);
3710 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3711 int duration = -1;
3712 double pts2 = mpctx->video_out->next_pts2;
3713 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3714 && !mpctx->restart_playback) {
3715 // expected A/V sync correction is ignored
3716 double diff = (pts2 - mpctx->video_pts);
3717 diff /= opts->playback_speed;
3718 if (mpctx->time_frame < 0)
3719 diff += mpctx->time_frame;
3720 if (diff < 0)
3721 diff = 0;
3722 if (diff > 10)
3723 diff = 10;
3724 duration = diff * 1e6;
3726 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3728 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3729 vout_time_usage += mpctx->last_vo_flip_duration;
3730 if (mpctx->video_out->driver->flip_page_timed) {
3731 // No need to adjust sync based on flip speed
3732 mpctx->last_vo_flip_duration = 0;
3733 // For print_status - VO call finishing early is OK for sync
3734 mpctx->time_frame -= get_relative_time(mpctx);
3736 if (mpctx->restart_playback) {
3737 mpctx->syncing_audio = true;
3738 if (mpctx->sh_audio)
3739 fill_audio_out_buffers(mpctx);
3740 mpctx->restart_playback = false;
3741 mpctx->time_frame = 0;
3742 get_relative_time(mpctx);
3744 print_status(mpctx, MP_NOPTS_VALUE, true);
3745 screenshot_flip(mpctx);
3746 } else
3747 print_status(mpctx, MP_NOPTS_VALUE, false);
3749 if (opts->auto_quality > 0) {
3750 current_module = "autoq";
3751 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3752 ++output_quality;
3753 else if (output_quality > 1 && aq_sleep_time < 0)
3754 --output_quality;
3755 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3756 output_quality = 0;
3757 set_video_quality(mpctx->sh_video, output_quality);
3760 if (!frame_time_remaining && blit_frame) {
3761 if (play_n_frames >= 0) {
3762 --play_n_frames;
3763 if (play_n_frames <= 0)
3764 mpctx->stop_play = PT_NEXT_ENTRY;
3766 if (mpctx->step_frames > 0) {
3767 mpctx->step_frames--;
3768 if (mpctx->step_frames == 0)
3769 pause_player(mpctx);
3773 // FIXME: add size based support for -endpos
3774 if (end_at.type == END_AT_TIME &&
3775 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3776 mpctx->stop_play = PT_NEXT_ENTRY;
3778 } // end if(mpctx->sh_video)
3780 #ifdef CONFIG_DVDNAV
3781 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3782 nav_highlight_t hl;
3783 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3784 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3785 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3786 vo_osd_changed(OSDTYPE_DVDNAV);
3787 } else {
3788 osd_set_nav_box(0, 0, 0, 0);
3789 vo_osd_changed(OSDTYPE_DVDNAV);
3790 vo_osd_changed(OSDTYPE_SPU);
3793 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3794 double ar = -1.0;
3795 if (mpctx->sh_video &&
3796 stream_control(mpctx->demuxer->stream,
3797 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3798 != STREAM_UNSUPPORTED)
3799 mpctx->sh_video->stream_aspect = ar;
3802 #endif
3804 //================= Keyboard events, SEEKing ====================
3806 current_module = "key_events";
3808 while (1) {
3809 mp_cmd_t *cmd;
3810 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3811 /* Allow running consecutive seek commands to combine them,
3812 * but execute the seek before running other commands.
3813 * If the user seeks continuously (keeps arrow key down)
3814 * try to finish showing a frame from one location before doing
3815 * another seek (which could lead to unchanging display). */
3816 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3817 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3818 && GetTimerMS() - mpctx->start_timestamp < 300)
3819 break;
3820 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3821 run_command(mpctx, cmd);
3822 mp_cmd_free(cmd);
3823 if (mpctx->stop_play)
3824 break;
3826 bool slow_video = mpctx->sh_video && mpctx->video_out->frame_loaded;
3827 if (!(mpctx->paused || slow_video) || mpctx->stop_play
3828 || mpctx->seek.type || mpctx->restart_playback)
3829 break;
3830 if (mpctx->sh_video) {
3831 update_osd_msg(mpctx);
3832 int hack = vo_osd_changed(0);
3833 vo_osd_changed(hack);
3834 if (hack || mpctx->video_out->want_redraw) {
3835 if (redraw_osd(mpctx) < 0) {
3836 if (mpctx->paused)
3837 add_step_frame(mpctx);
3838 break;
3839 } else
3840 vo_osd_changed(0);
3843 if (!mpctx->paused)
3844 break;
3845 pause_loop(mpctx);
3848 // handle -sstep
3849 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3850 mpctx->osd_function = OSD_FFW;
3851 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3854 edl_update(mpctx);
3856 /* Looping. */
3857 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3858 mpctx->stop_play == PT_NEXT_ENTRY)) {
3859 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3861 if (opts->loop_times > 1)
3862 opts->loop_times--;
3863 else if (opts->loop_times == 1)
3864 opts->loop_times = -1;
3865 play_n_frames = play_n_frames_mf;
3866 mpctx->stop_play = 0;
3867 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3870 if (mpctx->seek.type) {
3871 seek(mpctx, mpctx->seek, false);
3872 mpctx->seek = (struct seek_params){ 0 };
3877 static int read_keys(void *ctx, int fd)
3879 getch2(ctx);
3880 return MP_INPUT_NOTHING;
3883 static bool attachment_is_font(struct demux_attachment *att)
3885 if (!att->name || !att->type || !att->data || !att->data_size)
3886 return false;
3887 // match against MIME types
3888 if (strcmp(att->type, "application/x-truetype-font") == 0
3889 || strcmp(att->type, "application/x-font") == 0)
3890 return true;
3891 // fallback: match against file extension
3892 if (strlen(att->name) > 4) {
3893 char *ext = att->name + strlen(att->name) - 4;
3894 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3895 || strcasecmp(ext, ".otf") == 0)
3896 return true;
3898 return false;
3901 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3903 if (audio_id == -1)
3904 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3905 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3906 demuxer_switch_audio(demuxer, audio_id);
3907 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3908 demuxer->audio->id = -2;
3909 demuxer->audio->sh = NULL;
3911 return demuxer->audio->id;
3914 static void print_version(const char *name)
3916 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3918 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3919 GetCpuCaps(&gCpuCaps);
3920 #if ARCH_X86
3921 mp_msg(MSGT_CPLAYER, MSGL_V,
3922 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3923 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3924 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3925 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3926 #if CONFIG_RUNTIME_CPUDETECT
3927 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3928 #else
3929 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3930 if (HAVE_MMX)
3931 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3932 if (HAVE_MMX2)
3933 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3934 if (HAVE_AMD3DNOW)
3935 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3936 if (HAVE_AMD3DNOWEXT)
3937 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3938 if (HAVE_SSE)
3939 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3940 if (HAVE_SSE2)
3941 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3942 if (HAVE_SSSE3)
3943 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3944 if (HAVE_CMOV)
3945 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3946 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3947 #endif /* CONFIG_RUNTIME_CPUDETECT */
3948 #endif /* ARCH_X86 */
3949 print_libav_versions();
3952 #ifdef PTW32_STATIC_LIB
3953 static void detach_ptw32(void)
3955 pthread_win32_thread_detach_np();
3956 pthread_win32_process_detach_np();
3958 #endif
3960 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3961 * file for some tools to link against. */
3962 #ifndef DISABLE_MAIN
3963 int main(int argc, char *argv[])
3965 #ifdef PTW32_STATIC_LIB
3966 pthread_win32_process_attach_np();
3967 pthread_win32_thread_attach_np();
3968 atexit(detach_ptw32);
3969 #endif
3970 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3971 || !strcmp(argv[1], "--leak-report")))
3972 talloc_enable_leak_report();
3974 #ifdef __MINGW32__
3975 mp_get_converted_argv(&argc, &argv);
3976 #endif
3978 char *mem_ptr;
3980 // movie info:
3982 /* Flag indicating whether MPlayer should exit without playing anything. */
3983 int opt_exit = 0;
3984 int i;
3986 struct MPContext *mpctx = talloc(NULL, MPContext);
3987 *mpctx = (struct MPContext){
3988 .osd_function = OSD_PLAY,
3989 .begin_skip = MP_NOPTS_VALUE,
3990 .play_tree_step = 1,
3991 .global_sub_pos = -1,
3992 .set_of_sub_pos = -1,
3993 .file_format = DEMUXER_TYPE_UNKNOWN,
3994 .last_dvb_step = 1,
3995 .paused_cache_fill = -1,
3998 InitTimer();
3999 srand(GetTimerMS());
4001 mp_msg_init();
4002 init_libav();
4004 #ifdef CONFIG_X11
4005 mpctx->x11_state = vo_x11_init_state();
4006 #endif
4007 struct MPOpts *opts = &mpctx->opts;
4008 set_default_mplayer_options(opts);
4009 // Create the config context and register the options
4010 mpctx->mconfig = m_config_new(opts, cfg_include);
4011 m_config_register_options(mpctx->mconfig, mplayer_opts);
4012 m_config_register_options(mpctx->mconfig, common_opts);
4013 mp_input_register_options(mpctx->mconfig);
4015 // Preparse the command line
4016 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
4018 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
4019 set_path_env();
4020 #endif
4022 #ifdef CONFIG_TV
4023 stream_tv_defaults.immediate = 1;
4024 #endif
4026 parse_cfgfiles(mpctx, mpctx->mconfig);
4028 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
4029 if (mpctx->playtree == NULL)
4030 opt_exit = 1;
4031 else {
4032 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
4033 if (mpctx->playtree) {
4034 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4035 mpctx->mconfig);
4036 if (mpctx->playtree_iter) {
4037 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4038 PLAY_TREE_ITER_ENTRY) {
4039 play_tree_iter_free(mpctx->playtree_iter);
4040 mpctx->playtree_iter = NULL;
4042 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
4048 print_version("MPlayer2");
4050 #if defined(__MINGW32__) || defined(__CYGWIN__)
4052 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
4053 BOOL WINAPI (*setDEP)(DWORD) = NULL;
4054 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
4055 if (kernel32) {
4056 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
4057 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
4059 if (setDEP)
4060 setDEP(3);
4061 if (setDllDir)
4062 setDllDir("");
4064 // stop Windows from showing all kinds of annoying error dialogs
4065 SetErrorMode(0x8003);
4066 // request 1ms timer resolution
4067 timeBeginPeriod(1);
4068 #endif
4070 #ifdef CONFIG_PRIORITY
4071 set_priority();
4072 #endif
4074 if (opts->video_driver_list &&
4075 strcmp(opts->video_driver_list[0], "help") == 0) {
4076 list_video_out();
4077 opt_exit = 1;
4080 if (opts->audio_driver_list &&
4081 strcmp(opts->audio_driver_list[0], "help") == 0) {
4082 list_audio_out();
4083 opt_exit = 1;
4086 /* Check codecs.conf. */
4087 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4088 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4089 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4090 if (!parse_codec_cfg(NULL))
4091 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4092 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4093 "Using built-in default codecs.conf.\n");
4096 free(mem_ptr); // release the buffer created by get_path()
4099 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4100 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4101 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4102 list_codecs(1);
4103 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4104 opt_exit = 1;
4106 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4107 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4108 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4109 list_codecs(0);
4110 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4111 opt_exit = 1;
4113 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4114 vfm_help();
4115 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4116 opt_exit = 1;
4118 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4119 afm_help();
4120 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4121 opt_exit = 1;
4123 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4124 af_help();
4125 printf("\n");
4126 opt_exit = 1;
4128 #ifdef CONFIG_X11
4129 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4130 fstype_help();
4131 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4132 opt_exit = 1;
4134 #endif
4135 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4136 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4137 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4138 demuxer_help();
4139 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4140 opt_exit = 1;
4142 if (opts->list_properties) {
4143 property_print_help();
4144 opt_exit = 1;
4147 if (opt_exit)
4148 exit_player(mpctx, EXIT_NONE);
4150 if (!mpctx->filename && !opts->player_idle_mode) {
4151 // no file/vcd/dvd -> show HELP:
4152 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4153 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4156 /* Display what configure line was used */
4157 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4159 // Many users forget to include command line in bugreports...
4160 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4161 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4162 for (i = 1; i < argc; i++)
4163 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4164 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4167 //------ load global data first ------
4169 mpctx->osd = osd_create();
4171 // check font
4172 #ifdef CONFIG_FREETYPE
4173 init_freetype();
4174 #endif
4175 #ifdef CONFIG_FONTCONFIG
4176 if (font_fontconfig <= 0) {
4177 #endif
4178 #ifdef CONFIG_BITMAP_FONT
4179 if (font_name) {
4180 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4181 if (!vo_font)
4182 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4183 filename_recode(font_name));
4184 } else {
4185 // try default:
4186 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4187 font_factor, verbose > 1);
4188 free(mem_ptr); // release the buffer created by get_path()
4189 if (!vo_font)
4190 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4191 font_factor, verbose > 1);
4193 if (sub_font_name)
4194 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4195 verbose > 1);
4196 else
4197 mpctx->osd->sub_font = vo_font;
4198 #endif
4199 #ifdef CONFIG_FONTCONFIG
4201 #endif
4203 #ifdef CONFIG_ASS
4204 mpctx->ass_library = mp_ass_init(opts);
4205 mpctx->osd->ass_library = mpctx->ass_library;
4206 #endif
4208 #ifdef HAVE_RTC
4209 if (opts->rtc) {
4210 char *rtc_device = opts->rtc_device;
4211 // seteuid(0); /* Can't hurt to try to get root here */
4212 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4213 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4214 "(it should be readable by the user.)\n",
4215 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4216 else {
4217 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4219 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4220 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4221 "ioctl (rtc_irqp_set %lu): %s\n",
4222 irqp, strerror(errno));
4223 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4224 close(rtc_fd);
4225 rtc_fd = -1;
4226 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4227 /* variable only by the root */
4228 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4229 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4230 close(rtc_fd);
4231 rtc_fd = -1;
4232 } else
4233 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4234 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4237 if (rtc_fd < 0)
4238 #endif /* HAVE_RTC */
4239 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4240 opts->softsleep ? "software" : timer_name);
4242 #ifdef HAVE_TERMCAP
4243 load_termcap(NULL); // load key-codes
4244 #endif
4246 // ========== Init keyboard FIFO (connection to libvo) ============
4248 // Init input system
4249 current_module = "init_input";
4250 mpctx->input = mp_input_init(&opts->input);
4251 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4252 if (slave_mode)
4253 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4254 else if (opts->consolecontrols)
4255 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4256 // Set the libstream interrupt callback
4257 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4259 current_module = NULL;
4261 /// Catch signals
4262 #ifndef __MINGW32__
4263 signal(SIGCHLD, child_sighandler);
4264 #endif
4266 #ifdef CONFIG_CRASH_DEBUG
4267 prog_path = argv[0];
4268 #endif
4269 //========= Catch terminate signals: ================
4270 // terminate requests:
4271 signal(SIGTERM, exit_sighandler); // kill
4272 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4274 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4276 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4277 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4278 #ifdef CONFIG_SIGHANDLER
4279 // fatal errors:
4280 signal(SIGBUS, exit_sighandler); // bus error
4281 signal(SIGSEGV, exit_sighandler); // segfault
4282 signal(SIGILL, exit_sighandler); // illegal instruction
4283 signal(SIGFPE, exit_sighandler); // floating point exc.
4284 signal(SIGABRT, exit_sighandler); // abort()
4285 #ifdef CONFIG_CRASH_DEBUG
4286 if (crash_debug)
4287 signal(SIGTRAP, exit_sighandler);
4288 #endif
4289 #endif
4291 // ***************** Now, let's see the per-file stuff ******************
4293 play_next_file:
4295 // init global sub numbers
4296 mpctx->global_sub_size = 0;
4297 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4299 if (mpctx->filename) {
4300 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4301 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4302 load_per_file_config(mpctx->mconfig, mpctx->filename);
4305 if (opts->video_driver_list)
4306 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4307 opts->video_driver_list[0]);
4308 if (opts->audio_driver_list)
4309 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4310 opts->audio_driver_list[0]);
4312 // We must enable getch2 here to be able to interrupt network connection
4313 // or cache filling
4314 if (opts->consolecontrols && !slave_mode) {
4315 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4316 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4317 "WARNING: getch2_init called twice!\n");
4318 else
4319 getch2_enable(); // prepare stdin for hotkeys...
4320 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4321 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4324 // ================= GUI idle loop (STOP state) =========================
4325 while (opts->player_idle_mode && !mpctx->filename) {
4326 play_tree_t *entry = NULL;
4327 mp_cmd_t *cmd;
4328 if (mpctx->video_out && mpctx->video_out->config_ok)
4329 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4330 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4331 if (mpctx->video_out)
4332 vo_check_events(mpctx->video_out);
4333 usec_sleep(20000);
4335 switch (cmd->id) {
4336 case MP_CMD_LOADFILE:
4337 // prepare a tree entry with the new filename
4338 entry = play_tree_new();
4339 play_tree_add_file(entry, cmd->args[0].v.s);
4340 // The entry is added to the main playtree after the switch().
4341 break;
4342 case MP_CMD_LOADLIST:
4343 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4344 break;
4345 case MP_CMD_QUIT:
4346 exit_player_with_rc(mpctx, EXIT_QUIT,
4347 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4348 break;
4349 case MP_CMD_VO_FULLSCREEN:
4350 case MP_CMD_GET_PROPERTY:
4351 case MP_CMD_SET_PROPERTY:
4352 case MP_CMD_STEP_PROPERTY:
4353 run_command(mpctx, cmd);
4354 break;
4357 mp_cmd_free(cmd);
4359 if (entry) { // user entered a command that gave a valid entry
4360 if (mpctx->playtree)
4361 // the playtree is always a node with one child. let's clear it
4362 play_tree_free_list(mpctx->playtree->child, 1);
4363 else
4364 // .. or make a brand new playtree
4365 mpctx->playtree = play_tree_new();
4367 if (!mpctx->playtree)
4368 continue; // couldn't make playtree! wait for next command
4370 play_tree_set_child(mpctx->playtree, entry);
4372 /* Make iterator start at the top the of tree. */
4373 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4374 mpctx->mconfig);
4375 if (!mpctx->playtree_iter)
4376 continue;
4378 // find the first real item in the tree
4379 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4380 PLAY_TREE_ITER_ENTRY) {
4381 // no items!
4382 play_tree_iter_free(mpctx->playtree_iter);
4383 mpctx->playtree_iter = NULL;
4384 continue; // wait for next command
4386 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4390 #ifdef CONFIG_ASS
4391 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4392 #endif
4393 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4394 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4396 if (mpctx->filename) {
4397 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4398 filename_recode(mpctx->filename));
4399 if (use_filename_title && opts->vo_wintitle == NULL)
4400 opts->vo_wintitle = talloc_strdup(NULL,
4401 mp_basename(mpctx->filename));
4404 if (edl_filename) {
4405 if (edl_records)
4406 free_edl(edl_records);
4407 next_edl_record = edl_records = edl_parse_file();
4409 if (edl_output_filename) {
4410 if (edl_fd)
4411 fclose(edl_fd);
4412 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4413 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4414 "Can't open EDL file [%s] for writing.\n",
4415 filename_recode(edl_output_filename));
4419 //==================== Open VOB-Sub ============================
4421 current_module = "vobsub";
4422 if (opts->vobsub_name) {
4423 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4424 if (vo_vobsub == NULL)
4425 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4426 filename_recode(opts->vobsub_name));
4427 } else if (opts->sub_auto && mpctx->filename) {
4428 char **vob = find_vob_subtitles(opts, mpctx->filename);
4429 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4430 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4431 if (vo_vobsub)
4432 break;
4434 talloc_free(vob);
4436 if (vo_vobsub) {
4437 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4438 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4439 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4440 mpctx);
4442 // setup global sub numbering
4443 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4444 vobsub_get_indexes_count(vo_vobsub);
4447 //============ Open & Sync STREAM --- fork cache2 ====================
4449 mpctx->stream = NULL;
4450 mpctx->demuxer = NULL;
4451 mpctx->d_audio = NULL;
4452 mpctx->d_video = NULL;
4453 mpctx->d_sub = NULL;
4454 mpctx->sh_audio = NULL;
4455 mpctx->sh_video = NULL;
4457 current_module = "open_stream";
4458 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4459 if (!mpctx->stream) { // error...
4460 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4461 goto goto_next_file;
4463 mpctx->initialized_flags |= INITIALIZED_STREAM;
4465 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4466 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4467 "playlist support will not be used automatically.\n"
4468 "MPlayer's playlist code is unsafe and should only be used with "
4469 "trusted sources.\nPlayback will probably fail.\n\n");
4470 #if 0
4471 play_tree_t *entry;
4472 // Handle playlist
4473 current_module = "handle_playlist";
4474 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4475 filename_recode(mpctx->filename));
4476 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4477 mpctx->eof = playtree_add_playlist(mpctx, entry);
4478 goto goto_next_file;
4479 #endif
4481 mpctx->stream->start_pos += seek_to_byte;
4483 if (stream_dump_type == 5) {
4484 unsigned char buf[4096];
4485 int len;
4486 FILE *f;
4487 current_module = "dumpstream";
4488 stream_reset(mpctx->stream);
4489 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4490 f = fopen(opts->stream_dump_name, "wb");
4491 if (!f) {
4492 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4493 exit_player(mpctx, EXIT_ERROR);
4495 if (opts->chapterrange[0] > 1) {
4496 int chapter = opts->chapterrange[0] - 1;
4497 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4499 struct stream_dump_progress info;
4500 stream_dump_progress_start(&info);
4501 while (!mpctx->stream->eof && !async_quit_request) {
4502 len = stream_read(mpctx->stream, buf, 4096);
4503 if (len > 0) {
4504 if (fwrite(buf, len, 1, f) != 1) {
4505 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4506 exit_player(mpctx, EXIT_ERROR);
4509 stream_dump_progress(&info, len, mpctx->stream);
4510 if (opts->chapterrange[1] > 0) {
4511 int chapter = -1;
4512 if (stream_control(mpctx->stream,
4513 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4514 && chapter + 1 > opts->chapterrange[1])
4515 break;
4518 if (fclose(f)) {
4519 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4520 opts->stream_dump_name);
4521 exit_player(mpctx, EXIT_ERROR);
4523 stream_dump_progress_end(&info, opts->stream_dump_name);
4524 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4525 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4528 #ifdef CONFIG_DVDREAD
4529 if (mpctx->stream->type == STREAMTYPE_DVD) {
4530 current_module = "dvd lang->id";
4531 if (opts->audio_lang && opts->audio_id == -1)
4532 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4533 if (opts->sub_lang && opts->sub_id == -1)
4534 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4535 // setup global sub numbering
4536 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4537 current_module = NULL;
4539 #endif
4541 #ifdef CONFIG_DVDNAV
4542 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4543 current_module = "dvdnav lang->id";
4544 if (opts->audio_lang && opts->audio_id == -1)
4545 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4546 opts->audio_lang);
4547 dvdsub_lang_id = -3;
4548 if (opts->sub_lang && opts->sub_id == -1)
4549 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4550 mpctx->stream, opts->sub_lang);
4551 // setup global sub numbering
4552 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4553 mpctx->stream);
4554 current_module = NULL;
4556 #endif
4558 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4559 goto_enable_cache:
4560 if (stream_cache_size > 0) {
4561 int res;
4562 float stream_cache_min_percent = opts->stream_cache_min_percent;
4563 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4564 current_module = "enable_cache";
4565 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4566 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4567 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4568 if (res == 0)
4569 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4570 goto goto_next_file;
4573 //============ Open DEMUXERS --- DETECT file type =======================
4574 current_module = "demux_open";
4576 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4577 opts->audio_id, opts->video_id, opts->sub_id,
4578 mpctx->filename);
4580 // HACK to get MOV Reference Files working
4582 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4583 unsigned char *playlist_entry;
4584 play_tree_t *list = NULL, *entry = NULL;
4586 current_module = "handle_demux_playlist";
4587 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4588 char *temp;
4589 const char *bname;
4591 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4592 filename_recode(playlist_entry));
4594 bname = mp_basename(playlist_entry);
4595 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4596 !strncmp(bname + 3, "gateQT", 6))
4597 continue;
4599 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4600 continue;
4602 entry = play_tree_new();
4604 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4605 playlist_entry)) { // add reference path of current file
4606 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4607 mpctx->filename)) + strlen(playlist_entry) + 1));
4608 if (temp) {
4609 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4610 strlen(mp_basename(mpctx->filename)));
4611 temp[strlen(mpctx->filename) - strlen(mp_basename(
4612 mpctx->filename))] = '\0';
4613 strcat(temp, playlist_entry);
4614 if (!strcmp(temp, mpctx->filename)) {
4615 free(temp);
4616 continue;
4618 play_tree_add_file(entry, temp);
4619 mp_msg(MSGT_CPLAYER, MSGL_V,
4620 "Resolving reference to %s.\n", temp);
4621 free(temp);
4623 } else
4624 play_tree_add_file(entry, playlist_entry);
4626 if (!list)
4627 list = entry;
4628 else
4629 play_tree_append_entry(list, entry);
4631 free_demuxer(mpctx->demuxer);
4632 mpctx->demuxer = NULL;
4634 if (list) {
4635 entry = play_tree_new();
4636 play_tree_set_child(entry, list);
4637 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4638 goto goto_next_file;
4642 if (!mpctx->demuxer) {
4643 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4644 goto goto_next_file;
4647 if (mpctx->demuxer->matroska_data.ordered_chapters)
4648 build_ordered_chapter_timeline(mpctx);
4650 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4651 build_edl_timeline(mpctx);
4653 if (mpctx->timeline) {
4654 mpctx->timeline_part = 0;
4655 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4657 int part_count = mpctx->num_timeline_parts;
4658 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4659 "sources. Total length %.3f seconds.\n", part_count,
4660 mpctx->num_sources, mpctx->timeline[part_count].start);
4661 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4662 for (int i = 0; i < mpctx->num_sources; i++)
4663 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4664 filename_recode(mpctx->sources[i].demuxer->filename));
4665 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4666 "source_start, source):\n");
4667 for (int i = 0; i < part_count; i++) {
4668 struct timeline_part *p = mpctx->timeline + i;
4669 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4670 p->source_start, p->source - mpctx->sources);
4672 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4673 mpctx->timeline[part_count].start);
4676 if (!mpctx->sources) {
4677 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4678 *mpctx->sources = (struct content_source){
4679 .stream = mpctx->stream,
4680 .demuxer = mpctx->demuxer
4682 mpctx->num_sources = 1;
4685 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4687 #ifdef CONFIG_ASS
4688 if (opts->ass_enabled && mpctx->ass_library) {
4689 for (int j = 0; j < mpctx->num_sources; j++) {
4690 struct demuxer *d = mpctx->sources[j].demuxer;
4691 for (int i = 0; i < d->num_attachments; i++) {
4692 struct demux_attachment *att = d->attachments + i;
4693 if (opts->use_embedded_fonts && attachment_is_font(att))
4694 ass_add_font(mpctx->ass_library, att->name, att->data,
4695 att->data_size);
4699 #endif
4701 current_module = "demux_open2";
4703 mpctx->d_audio = mpctx->demuxer->audio;
4704 mpctx->d_video = mpctx->demuxer->video;
4705 mpctx->d_sub = mpctx->demuxer->sub;
4707 if (ts_prog) {
4708 int tmp = ts_prog;
4709 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4711 // select audio stream
4712 for (int i = 0; i < mpctx->num_sources; i++)
4713 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4714 opts->audio_lang);
4716 // DUMP STREAMS:
4717 if ((stream_dump_type) && (stream_dump_type < 4)) {
4718 FILE *f;
4719 demux_stream_t *ds = NULL;
4720 current_module = "dump";
4721 // select stream to dump
4722 switch (stream_dump_type) {
4723 case 1: ds = mpctx->d_audio;
4724 break;
4725 case 2: ds = mpctx->d_video;
4726 break;
4727 case 3: ds = mpctx->d_sub;
4728 break;
4730 if (!ds) {
4731 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4732 "dump: FATAL: Selected stream missing!\n");
4733 exit_player(mpctx, EXIT_ERROR);
4735 // disable other streams:
4736 if (mpctx->d_audio && mpctx->d_audio != ds) {
4737 ds_free_packs(mpctx->d_audio);
4738 mpctx->d_audio->id = -2;
4740 if (mpctx->d_video && mpctx->d_video != ds) {
4741 ds_free_packs(mpctx->d_video);
4742 mpctx->d_video->id = -2;
4744 if (mpctx->d_sub && mpctx->d_sub != ds) {
4745 ds_free_packs(mpctx->d_sub);
4746 mpctx->d_sub->id = -2;
4748 // let's dump it!
4749 f = fopen(opts->stream_dump_name, "wb");
4750 if (!f) {
4751 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4752 exit_player(mpctx, EXIT_ERROR);
4754 struct stream_dump_progress info;
4755 stream_dump_progress_start(&info);
4756 while (!ds->eof) {
4757 unsigned char *start;
4758 int in_size = ds_get_packet(ds, &start);
4759 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4760 && stream_dump_type == 2)
4761 fwrite(&in_size, 1, 4, f);
4762 if (in_size > 0) {
4763 fwrite(start, in_size, 1, f);
4764 stream_dump_progress(&info, in_size, mpctx->stream);
4766 if (opts->chapterrange[1] > 0) {
4767 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4768 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4769 break;
4772 fclose(f);
4773 stream_dump_progress_end(&info, opts->stream_dump_name);
4774 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4775 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4778 mpctx->sh_audio = mpctx->d_audio->sh;
4779 mpctx->sh_video = mpctx->d_video->sh;
4781 if (mpctx->sh_video) {
4782 current_module = "video_read_properties";
4783 if (!video_read_properties(mpctx->sh_video)) {
4784 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4785 mpctx->sh_video = mpctx->d_video->sh = NULL;
4786 } else {
4787 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4788 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4789 mpctx->demuxer->file_format, mpctx->sh_video->format,
4790 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4791 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4792 if (force_fps) {
4793 mpctx->sh_video->fps = force_fps;
4794 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4796 vo_fps = mpctx->sh_video->fps;
4798 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4799 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4800 "header or invalid, use the -fps option.\n");
4806 if (!mpctx->sh_video && !mpctx->sh_audio) {
4807 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4808 #ifdef CONFIG_DVBIN
4809 if (mpctx->stream->type == STREAMTYPE_DVB) {
4810 int dir;
4811 int v = mpctx->last_dvb_step;
4812 if (v > 0)
4813 dir = DVB_CHANNEL_HIGHER;
4814 else
4815 dir = DVB_CHANNEL_LOWER;
4817 if (dvb_step_channel(mpctx->stream, dir)) {
4818 mpctx->stop_play = PT_NEXT_ENTRY;
4819 mpctx->dvbin_reopen = 1;
4822 #endif
4823 goto goto_next_file; // exit_player(_("Fatal error"));
4826 /* display clip info */
4827 demux_info_print(mpctx->demuxer);
4829 //================= Read SUBTITLES (DVD & TEXT) =========================
4830 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4831 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4832 init_vo_spudec(mpctx);
4834 // after reading video params we should load subtitles because
4835 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4836 // check .sub
4837 current_module = "read_subtitles_file";
4838 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4839 if (opts->sub_name) {
4840 for (i = 0; opts->sub_name[i] != NULL; ++i)
4841 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4843 if (opts->sub_auto) { // auto load sub file ...
4844 char **tmp = find_text_subtitles(opts, mpctx->filename);
4845 int nsub = MP_TALLOC_ELEMS(tmp);
4846 for (int i = 0; i < nsub; i++)
4847 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4848 talloc_free(tmp);
4850 if (mpctx->set_of_sub_size > 0)
4851 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4853 if (select_subtitle(mpctx)) {
4854 if (mpctx->subdata)
4855 switch (stream_dump_type) {
4856 case 3: list_sub_file(mpctx->subdata);
4857 break;
4858 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4859 break;
4860 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4861 break;
4862 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4863 break;
4864 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4865 break;
4866 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4867 break;
4871 print_file_properties(mpctx, mpctx->filename);
4873 reinit_video_chain(mpctx);
4874 if (mpctx->sh_video) {
4875 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4876 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4877 #ifdef CONFIG_FREETYPE
4878 force_load_font = 1;
4879 #endif
4880 } else if (!mpctx->sh_audio)
4881 goto goto_next_file;
4883 //================== MAIN: ==========================
4884 current_module = "main";
4886 if (opts->playing_msg) {
4887 char *msg = property_expand_string(mpctx, opts->playing_msg);
4888 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4889 free(msg);
4893 // Disable the term OSD in verbose mode
4894 if (verbose)
4895 opts->term_osd = 0;
4897 // Make sure old OSD does not stay around,
4898 // e.g. with -fixed-vo and same-resolution files
4899 clear_osd_msgs();
4900 update_osd_msg(mpctx);
4902 //================ SETUP AUDIO ==========================
4904 if (mpctx->sh_audio) {
4905 reinit_audio_chain(mpctx);
4906 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4907 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4908 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4911 current_module = "av_init";
4913 if (mpctx->sh_video) {
4914 mpctx->sh_video->timer = 0;
4915 if (!ignore_start)
4916 audio_delay += mpctx->sh_video->stream_delay;
4918 if (mpctx->sh_audio) {
4919 if (start_volume >= 0)
4920 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4921 if (!ignore_start)
4922 audio_delay -= mpctx->sh_audio->stream_delay;
4923 mpctx->delay = -audio_delay;
4926 if (!mpctx->sh_audio) {
4927 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4928 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4929 mpctx->d_audio->packs);
4930 ds_free_packs(mpctx->d_audio); // free buffered chunks
4932 if (!mpctx->sh_video) {
4933 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4934 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4935 mpctx->d_video->packs);
4936 ds_free_packs(mpctx->d_video);
4937 mpctx->d_video->id = -2;
4940 if (!mpctx->sh_video && !mpctx->sh_audio)
4941 goto goto_next_file;
4943 if (force_fps && mpctx->sh_video) {
4944 vo_fps = mpctx->sh_video->fps = force_fps;
4945 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4946 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4947 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4948 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4951 mp_input_set_section(mpctx->input, NULL);
4952 //TODO: add desired (stream-based) sections here
4953 if (mpctx->stream->type == STREAMTYPE_TV)
4954 mp_input_set_section(mpctx->input, "tv");
4955 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4956 mp_input_set_section(mpctx->input, "dvdnav");
4958 //==================== START PLAYING =======================
4960 if (opts->loop_times > 1)
4961 opts->loop_times--;
4962 else if (opts->loop_times == 1)
4963 opts->loop_times = -1;
4965 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4967 total_time_usage_start = GetTimer();
4968 audio_time_usage = 0;
4969 video_time_usage = 0;
4970 vout_time_usage = 0;
4971 total_frame_cnt = 0;
4972 drop_frame_cnt = 0; // fix for multifile fps benchmark
4973 play_n_frames = play_n_frames_mf;
4975 if (play_n_frames == 0) {
4976 mpctx->stop_play = PT_NEXT_ENTRY;
4977 goto goto_next_file;
4980 mpctx->time_frame = 0;
4981 mpctx->drop_message_shown = 0;
4982 mpctx->restart_playback = true;
4983 mpctx->video_pts = 0;
4984 mpctx->last_seek_pts = 0;
4985 mpctx->hrseek_active = false;
4986 mpctx->hrseek_framedrop = false;
4987 mpctx->step_frames = 0;
4988 mpctx->total_avsync_change = 0;
4989 mpctx->last_chapter_seek = -2;
4991 // If there's a timeline force an absolute seek to initialize state
4992 if (opts->seek_to_sec || mpctx->timeline) {
4993 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4994 seek(mpctx, mpctx->seek, false);
4995 end_at.pos += opts->seek_to_sec;
4997 if (opts->chapterrange[0] > 0) {
4998 double pts;
4999 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
5000 && pts > -1.0) {
5001 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
5002 seek(mpctx, mpctx->seek, false);
5006 if (end_at.type == END_AT_SIZE) {
5007 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
5008 "Option -endpos in MPlayer does not yet support size units.\n");
5009 end_at.type = END_AT_NONE;
5012 #ifdef CONFIG_DVDNAV
5013 mp_dvdnav_context_free(mpctx);
5014 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
5015 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
5016 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
5018 #endif
5020 mpctx->seek = (struct seek_params){ 0 };
5021 get_relative_time(mpctx); // reset current delta
5022 // Make sure VO knows current pause state
5023 if (mpctx->sh_video)
5024 vo_control(mpctx->video_out,
5025 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
5027 while (!mpctx->stop_play)
5028 run_playloop(mpctx);
5030 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
5032 #ifdef CONFIG_DVBIN
5033 if (mpctx->dvbin_reopen) {
5034 mpctx->stop_play = 0;
5035 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
5036 cache_uninit(mpctx->stream);
5037 mpctx->dvbin_reopen = 0;
5038 goto goto_enable_cache;
5040 #endif
5042 goto_next_file: // don't jump here after ao/vo/getch initialization!
5044 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
5046 if (opts->benchmark) {
5047 double tot = video_time_usage + vout_time_usage + audio_time_usage;
5048 double total_time_usage;
5049 total_time_usage_start = GetTimer() - total_time_usage_start;
5050 total_time_usage = (float)total_time_usage_start * 0.000001;
5051 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
5052 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
5053 video_time_usage, vout_time_usage, audio_time_usage,
5054 total_time_usage - tot, total_time_usage);
5055 if (total_time_usage > 0.0)
5056 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
5057 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
5058 100.0 * video_time_usage / total_time_usage,
5059 100.0 * vout_time_usage / total_time_usage,
5060 100.0 * audio_time_usage / total_time_usage,
5061 100.0 * (total_time_usage - tot) / total_time_usage,
5062 100.0);
5063 if (total_frame_cnt && frame_dropping)
5064 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
5065 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
5066 total_frame_cnt - drop_frame_cnt,
5067 (total_time_usage > 0.5) ? ((total_frame_cnt -
5068 drop_frame_cnt) / total_time_usage) : 0,
5069 drop_frame_cnt,
5070 100 * drop_frame_cnt / total_frame_cnt,
5071 total_frame_cnt,
5072 (total_time_usage > 0.5) ?
5073 (total_frame_cnt / total_time_usage) : 0);
5076 // time to uninit all, except global stuff:
5077 int uninitialize_parts = INITIALIZED_ALL;
5078 if (opts->fixed_vo)
5079 uninitialize_parts -= INITIALIZED_VO;
5080 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
5081 uninitialize_parts -= INITIALIZED_AO;
5082 uninit_player(mpctx, uninitialize_parts);
5084 if (mpctx->set_of_sub_size > 0) {
5085 current_module = "sub_free";
5086 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5087 sub_free(mpctx->set_of_subtitles[i]);
5088 #ifdef CONFIG_ASS
5089 if (mpctx->set_of_ass_tracks[i])
5090 ass_free_track(mpctx->set_of_ass_tracks[i]);
5091 #endif
5093 mpctx->set_of_sub_size = 0;
5095 mpctx->vo_sub_last = vo_sub = NULL;
5096 mpctx->subdata = NULL;
5097 #ifdef CONFIG_ASS
5098 mpctx->osd->ass_track = NULL;
5099 if (mpctx->ass_library)
5100 ass_clear_fonts(mpctx->ass_library);
5101 #endif
5103 if (!mpctx->stop_play) // In case some goto jumped here...
5104 mpctx->stop_play = PT_NEXT_ENTRY;
5106 int playtree_direction = 1;
5108 if (mpctx->stop_play == PT_NEXT_ENTRY
5109 || mpctx->stop_play == PT_PREV_ENTRY) {
5110 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5111 != PLAY_TREE_ITER_ENTRY) {
5112 play_tree_iter_free(mpctx->playtree_iter);
5113 mpctx->playtree_iter = NULL;
5115 mpctx->play_tree_step = 1;
5116 } else if (mpctx->stop_play == PT_UP_NEXT ||
5117 mpctx->stop_play == PT_UP_PREV) {
5118 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5119 if (mpctx->playtree_iter) {
5120 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5121 PLAY_TREE_ITER_ENTRY) {
5122 play_tree_iter_free(mpctx->playtree_iter);
5123 mpctx->playtree_iter = NULL;
5126 } else if (mpctx->stop_play == PT_STOP) {
5127 play_tree_iter_free(mpctx->playtree_iter);
5128 mpctx->playtree_iter = NULL;
5129 } else // NEXT PREV SRC
5130 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5132 while (mpctx->playtree_iter != NULL) {
5133 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5134 playtree_direction);
5135 if (mpctx->filename == NULL) {
5136 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5137 0) != PLAY_TREE_ITER_ENTRY) {
5138 play_tree_iter_free(mpctx->playtree_iter);
5139 mpctx->playtree_iter = NULL;
5142 } else
5143 break;
5146 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5147 if (!mpctx->playtree_iter)
5148 mpctx->filename = NULL;
5149 mpctx->stop_play = 0;
5150 goto play_next_file;
5153 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5155 return 1;
5157 #endif /* DISABLE_MAIN */