core, demux: fix --identify chapter output with ordered chapters
[mplayer.git] / mplayer.c
blob7030a50da0a67ec91fa80f568258951bf57a271c
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stdbool.h>
22 #include <math.h>
23 #include <assert.h>
25 #include "config.h"
26 #include "talloc.h"
28 #if defined(__MINGW32__) || defined(__CYGWIN__)
29 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
30 #include <windows.h>
31 #endif
32 #include <string.h>
33 #include <unistd.h>
35 // #include <sys/mman.h>
36 #include <sys/types.h>
37 #ifndef __MINGW32__
38 #include <sys/ioctl.h>
39 #include <sys/wait.h>
40 #else
41 #define SIGHUP 1 /* hangup */
42 #define SIGQUIT 3 /* quit */
43 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
44 #define SIGBUS 10 /* bus error */
45 #define SIGPIPE 13 /* broken pipe */
46 #endif
48 #include <sys/time.h>
49 #include <sys/stat.h>
51 #include <signal.h>
52 #include <time.h>
53 #include <fcntl.h>
54 #include <limits.h>
56 #include <errno.h>
58 #include "mp_msg.h"
59 #include "av_log.h"
62 #include "m_option.h"
63 #include "m_config.h"
64 #include "mplayer.h"
65 #include "access_mpcontext.h"
66 #include "m_property.h"
68 #include "libavutil/avstring.h"
70 #include "sub/subreader.h"
71 #include "sub/find_subfiles.h"
72 #include "sub/dec_sub.h"
74 #include "mp_osd.h"
75 #include "libvo/video_out.h"
77 #include "sub/font_load.h"
78 #include "sub/sub.h"
79 #include "ffmpeg_files/intreadwrite.h"
80 #include "sub/av_sub.h"
81 #include "libmpcodecs/dec_teletext.h"
82 #include "cpudetect.h"
83 #include "version.h"
85 #ifdef CONFIG_X11
86 #include "libvo/x11_common.h"
87 #endif
89 #include "libao2/audio_out.h"
91 #include "codec-cfg.h"
93 #include "edl.h"
95 #include "sub/spudec.h"
96 #include "sub/vobsub.h"
98 #include "osdep/getch2.h"
99 #include "osdep/timer.h"
101 #include "input/input.h"
103 int slave_mode = 0;
104 int enable_mouse_movements = 0;
105 float start_volume = -1;
107 #include "osdep/priority.h"
109 char *heartbeat_cmd;
111 #ifdef HAVE_RTC
112 #ifdef __linux__
113 #include <linux/rtc.h>
114 #else
115 #include <rtc.h>
116 #define RTC_IRQP_SET RTCIO_IRQP_SET
117 #define RTC_PIE_ON RTCIO_PIE_ON
118 #endif /* __linux__ */
119 #endif /* HAVE_RTC */
121 #include "stream/tv.h"
122 #include "stream/stream_radio.h"
123 #ifdef CONFIG_DVBIN
124 #include "stream/dvbin.h"
125 #endif
126 #include "stream/cache2.h"
128 //**************************************************************************//
129 // Playtree
130 //**************************************************************************//
131 #include "playtree.h"
132 #include "playtreeparser.h"
134 //**************************************************************************//
135 // Config
136 //**************************************************************************//
137 #include "parser-cfg.h"
138 #include "parser-mpcmd.h"
140 //**************************************************************************//
141 // Config file
142 //**************************************************************************//
144 static int cfg_inc_verbose(m_option_t *conf)
146 ++verbose;
147 return 0;
150 #include "path.h"
152 //**************************************************************************//
153 //**************************************************************************//
154 // Input media streaming & demultiplexer:
155 //**************************************************************************//
157 static int max_framesize = 0;
159 #include "stream/stream.h"
160 #include "libmpdemux/demuxer.h"
161 #include "libmpdemux/stheader.h"
163 #ifdef CONFIG_DVDREAD
164 #include "stream/stream_dvd.h"
165 #endif
166 #include "stream/stream_dvdnav.h"
168 #include "libmpcodecs/dec_audio.h"
169 #include "libmpcodecs/dec_video.h"
170 #include "libmpcodecs/mp_image.h"
171 #include "libmpcodecs/vf.h"
172 #include "libmpcodecs/vd.h"
174 #include "mixer.h"
176 #include "mp_core.h"
177 #include "options.h"
178 #include "defaultopts.h"
180 static const char help_text[] = _(
181 "Usage: mplayer [options] [url|path/]filename\n"
182 "\n"
183 "Basic options: (complete list in the man page)\n"
184 " -vo <drv> select video output driver ('-vo help' for a list)\n"
185 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
186 #ifdef CONFIG_VCD
187 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
188 #endif
189 #ifdef CONFIG_DVDREAD
190 " dvd://<titleno> play DVD title from device instead of plain file\n"
191 #endif
192 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
193 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
194 " -nosound do not play sound\n"
195 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
196 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
197 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
198 " -playlist <file> specify playlist file\n"
199 " -vid x -aid y select video (x) and audio (y) stream to play\n"
200 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
201 " -pp <quality> enable postprocessing filter (details in the man page)\n"
202 " -framedrop enable frame dropping (for slow machines)\n"
203 "\n"
204 "Basic keys: (complete list in the man page, also check input.conf)\n"
205 " <- or -> seek backward/forward 10 seconds\n"
206 " down or up seek backward/forward 1 minute\n"
207 " pgdown or pgup seek backward/forward 10 minutes\n"
208 " < or > step backward/forward in playlist\n"
209 " p or SPACE pause movie (press any key to continue)\n"
210 " q or ESC stop playing and quit program\n"
211 " + or - adjust audio delay by +/- 0.1 second\n"
212 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
213 " * or / increase or decrease PCM volume\n"
214 " x or z adjust subtitle delay by +/- 0.1 second\n"
215 " r or t adjust subtitle position up/down, also see -vf expand\n"
216 " double click toggle fullscreen\n"
217 " right click pause (press again to continue)\n"
218 "\n"
219 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
220 "\n");
223 #define Exit_SIGILL_RTCpuSel _(\
224 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
225 " It may be a bug in our new runtime CPU-detection code...\n"\
226 " Please read DOCS/HTML/en/bugreports.html.\n")
228 #define Exit_SIGILL _(\
229 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
230 " It usually happens when you run it on a CPU different than the one it was\n"\
231 " compiled/optimized for.\n"\
232 " Verify this!\n")
234 #define Exit_SIGSEGV_SIGFPE _(\
235 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
236 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
237 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
239 #define Exit_SIGCRASH _(\
240 "- MPlayer crashed. This shouldn't happen.\n"\
241 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
242 " gcc version. If you think it's MPlayer's fault, please read\n"\
243 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
244 " won't help unless you provide this information when reporting a possible bug.\n")
246 #define SystemTooSlow _("\n\n"\
247 " ************************************************\n"\
248 " **** Your system is too SLOW to play this! ****\n"\
249 " ************************************************\n\n"\
250 "Possible reasons, problems, workarounds:\n"\
251 "- Most common: broken/buggy _audio_ driver\n"\
252 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
253 " - Experiment with different values for -autosync, 30 is a good start.\n"\
254 "- Slow video output\n"\
255 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
256 "- Slow CPU\n"\
257 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
258 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
259 "- Broken file\n"\
260 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
261 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
262 " - Try -cache 8192.\n"\
263 "- Are you using -cache to play a non-interleaved AVI file?\n"\
264 " - Try -nocache.\n"\
265 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
266 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
269 //**************************************************************************//
270 //**************************************************************************//
272 #include "mp_fifo.h"
274 // benchmark:
275 double video_time_usage;
276 double vout_time_usage;
277 static double audio_time_usage;
278 static int total_time_usage_start;
279 static int total_frame_cnt;
280 static int drop_frame_cnt; // total number of dropped frames
282 // options:
283 static int output_quality;
285 // seek:
286 static off_t seek_to_byte;
287 static off_t step_sec;
289 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
291 // codecs:
292 char **audio_codec_list; // override audio codec
293 char **video_codec_list; // override video codec
294 char **audio_fm_list; // override audio codec family
295 char **video_fm_list; // override video codec family
297 // this dvdsub_id was selected via slang
298 // use this to allow dvdnav to follow -slang across stream resets,
299 // in particular the subtitle ID for a language changes
300 int dvdsub_lang_id;
301 int vobsub_id = -1;
302 static char *spudec_ifo = NULL;
303 int forced_subs_only = 0;
305 // cache2:
306 int stream_cache_size = -1;
308 // dump:
309 int stream_dump_type = 0;
311 // A-V sync:
312 static float default_max_pts_correction = -1;
313 float audio_delay = 0;
314 static int ignore_start = 0;
316 double force_fps = 0;
317 static int force_srate = 0;
318 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
319 static int play_n_frames = -1;
320 static int play_n_frames_mf = -1;
322 // sub:
323 char *font_name = NULL;
324 char *sub_font_name = NULL;
325 extern int font_fontconfig;
326 float font_factor = 0.75;
327 float sub_delay = 0;
328 float sub_fps = 0;
329 int subcc_enabled = 0;
330 int suboverlap_enabled = 1;
332 #include "sub/ass_mp.h"
334 char *current_module; // for debugging
337 // ---
339 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
340 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
341 FILE *edl_fd; // file to write to when in -edlout mode.
342 int use_filedir_conf;
343 int use_filename_title;
345 #include "mpcommon.h"
346 #include "command.h"
348 #include "metadata.h"
350 void *mpctx_get_video_out(MPContext *mpctx)
352 return mpctx->video_out;
355 void *mpctx_get_demuxer(MPContext *mpctx)
357 return mpctx->demuxer;
360 void *mpctx_get_playtree_iter(MPContext *mpctx)
362 return mpctx->playtree_iter;
365 void *mpctx_get_mixer(MPContext *mpctx)
367 return &mpctx->mixer;
370 int mpctx_get_global_sub_size(MPContext *mpctx)
372 return mpctx->global_sub_size;
375 int mpctx_get_osd_function(MPContext *mpctx)
377 return mpctx->osd_function;
380 static float get_relative_time(struct MPContext *mpctx)
382 unsigned int new_time = GetTimer();
383 unsigned int delta = new_time - mpctx->last_time;
384 mpctx->last_time = new_time;
385 return delta * 0.000001;
388 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
390 switch (type) {
391 /* check for valid video stream */
392 case META_VIDEO_CODEC:
393 case META_VIDEO_BITRATE:
394 case META_VIDEO_RESOLUTION:
395 if (!mpctx->sh_video)
396 return 0;
397 break;
399 /* check for valid audio stream */
400 case META_AUDIO_CODEC:
401 case META_AUDIO_BITRATE:
402 case META_AUDIO_SAMPLES:
403 if (!mpctx->sh_audio)
404 return 0;
405 break;
407 /* check for valid demuxer */
408 case META_INFO_TITLE:
409 case META_INFO_ARTIST:
410 case META_INFO_ALBUM:
411 case META_INFO_YEAR:
412 case META_INFO_COMMENT:
413 case META_INFO_TRACK:
414 case META_INFO_GENRE:
415 if (!mpctx->demuxer)
416 return 0;
417 break;
419 default:
420 break;
423 return 1;
426 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
428 char **info = mpctx->demuxer->info;
429 int n;
431 if (!info || !tag)
432 return talloc_strdup(NULL, "");
434 for (n = 0; info[2 * n] != NULL; n++)
435 if (!strcasecmp(info[2 * n], tag))
436 break;
438 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
441 char *get_metadata(struct MPContext *mpctx, metadata_t type)
443 sh_audio_t * const sh_audio = mpctx->sh_audio;
444 sh_video_t * const sh_video = mpctx->sh_video;
446 if (!is_valid_metadata_type(mpctx, type))
447 return NULL;
449 switch (type) {
450 case META_NAME:
451 return talloc_strdup(NULL, mp_basename(mpctx->filename));
452 case META_VIDEO_CODEC:
453 if (sh_video->format == 0x10000001)
454 return talloc_strdup(NULL, "mpeg1");
455 else if (sh_video->format == 0x10000002)
456 return talloc_strdup(NULL, "mpeg2");
457 else if (sh_video->format == 0x10000004)
458 return talloc_strdup(NULL, "mpeg4");
459 else if (sh_video->format == 0x10000005)
460 return talloc_strdup(NULL, "h264");
461 else if (sh_video->format >= 0x20202020)
462 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
463 else
464 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
465 case META_VIDEO_BITRATE:
466 return talloc_asprintf(NULL, "%d kbps",
467 (int) (sh_video->i_bps * 8 / 1024));
468 case META_VIDEO_RESOLUTION:
469 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
470 sh_video->disp_h);
471 case META_AUDIO_CODEC:
472 if (sh_audio->codec && sh_audio->codec->name)
473 return talloc_strdup(NULL, sh_audio->codec->name);
474 return talloc_strdup(NULL, "");
475 case META_AUDIO_BITRATE:
476 return talloc_asprintf(NULL, "%d kbps",
477 (int) (sh_audio->i_bps * 8 / 1000));
478 case META_AUDIO_SAMPLES:
479 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
480 sh_audio->channels);
482 /* check for valid demuxer */
483 case META_INFO_TITLE:
484 return get_demuxer_info(mpctx, "Title");
486 case META_INFO_ARTIST:
487 return get_demuxer_info(mpctx, "Artist");
489 case META_INFO_ALBUM:
490 return get_demuxer_info(mpctx, "Album");
492 case META_INFO_YEAR:
493 return get_demuxer_info(mpctx, "Year");
495 case META_INFO_COMMENT:
496 return get_demuxer_info(mpctx, "Comment");
498 case META_INFO_TRACK:
499 return get_demuxer_info(mpctx, "Track");
501 case META_INFO_GENRE:
502 return get_demuxer_info(mpctx, "Genre");
504 default:
505 break;
508 return talloc_strdup(NULL, "");
511 static void print_file_properties(struct MPContext *mpctx, const char *filename)
513 double start_pts = MP_NOPTS_VALUE;
514 double video_start_pts = MP_NOPTS_VALUE;
515 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
516 filename_recode(filename));
517 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
518 mpctx->demuxer->desc->name);
519 if (mpctx->sh_video) {
520 /* Assume FOURCC if all bytes >= 0x20 (' ') */
521 if (mpctx->sh_video->format >= 0x20202020)
522 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
523 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
524 else
525 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
526 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
527 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
528 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
529 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
530 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
531 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
532 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
533 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
534 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
535 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
536 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
537 video_start_pts = ds_get_next_pts(mpctx->d_video);
539 if (mpctx->sh_audio) {
540 /* Assume FOURCC if all bytes >= 0x20 (' ') */
541 if (mpctx->sh_audio->format >= 0x20202020)
542 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
543 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
544 else
545 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
546 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
547 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
548 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
549 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
550 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
551 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
552 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
553 start_pts = ds_get_next_pts(mpctx->d_audio);
555 if (video_start_pts != MP_NOPTS_VALUE) {
556 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
557 (mpctx->sh_video && video_start_pts < start_pts))
558 start_pts = video_start_pts;
560 if (start_pts != MP_NOPTS_VALUE)
561 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
562 else
563 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
564 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
565 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
566 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
567 mpctx->stream->seek
568 && (!mpctx->demuxer || mpctx->demuxer->seekable));
569 if (mpctx->demuxer) {
570 int chapter_count = get_chapter_count(mpctx);
571 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
572 for (int i = 0; i < chapter_count; i++) {
573 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
574 // in milliseconds
575 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
576 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
577 char *name = chapter_name(mpctx, i);
578 if (name) {
579 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
580 name);
581 talloc_free(name);
587 /// step size of mixer changes
588 int volstep = 3;
590 #ifdef CONFIG_DVDNAV
591 static void mp_dvdnav_context_free(MPContext *ctx)
593 if (ctx->nav_smpi)
594 free_mp_image(ctx->nav_smpi);
595 ctx->nav_smpi = NULL;
596 free(ctx->nav_buffer);
597 ctx->nav_buffer = NULL;
598 ctx->nav_start = NULL;
599 ctx->nav_in_size = 0;
601 #endif
603 static void uninit_subs(struct demuxer *demuxer)
605 for (int i = 0; i < MAX_S_STREAMS; i++) {
606 struct sh_sub *sh = demuxer->s_streams[i];
607 if (sh && sh->initialized)
608 sub_uninit(sh);
612 void uninit_player(struct MPContext *mpctx, unsigned int mask)
614 mask &= mpctx->initialized_flags;
616 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
618 if (mask & INITIALIZED_ACODEC) {
619 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
620 current_module = "uninit_acodec";
621 if (mpctx->sh_audio)
622 uninit_audio(mpctx->sh_audio);
623 mpctx->sh_audio = NULL;
624 mpctx->mixer.afilter = NULL;
627 if (mask & INITIALIZED_SUB) {
628 mpctx->initialized_flags &= ~INITIALIZED_SUB;
629 if (mpctx->d_sub->sh)
630 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
633 if (mask & INITIALIZED_VCODEC) {
634 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
635 current_module = "uninit_vcodec";
636 if (mpctx->sh_video)
637 uninit_video(mpctx->sh_video);
638 mpctx->sh_video = NULL;
641 if (mask & INITIALIZED_DEMUXER) {
642 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
643 current_module = "free_demuxer";
644 if (mpctx->num_sources) {
645 mpctx->demuxer = mpctx->sources[0].demuxer;
646 for (int i = 1; i < mpctx->num_sources; i++) {
647 uninit_subs(mpctx->sources[i].demuxer);
648 free_stream(mpctx->sources[i].stream);
649 free_demuxer(mpctx->sources[i].demuxer);
652 talloc_free(mpctx->sources);
653 mpctx->sources = NULL;
654 mpctx->num_sources = 0;
655 talloc_free(mpctx->timeline);
656 mpctx->timeline = NULL;
657 mpctx->num_timeline_parts = 0;
658 talloc_free(mpctx->chapters);
659 mpctx->chapters = NULL;
660 mpctx->num_chapters = 0;
661 mpctx->video_offset = 0;
662 if (mpctx->demuxer) {
663 mpctx->stream = mpctx->demuxer->stream;
664 uninit_subs(mpctx->demuxer);
665 free_demuxer(mpctx->demuxer);
667 mpctx->demuxer = NULL;
670 // kill the cache process:
671 if (mask & INITIALIZED_STREAM) {
672 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
673 current_module = "uninit_stream";
674 if (mpctx->stream)
675 free_stream(mpctx->stream);
676 mpctx->stream = NULL;
679 if (mask & INITIALIZED_VO) {
680 mpctx->initialized_flags &= ~INITIALIZED_VO;
681 current_module = "uninit_vo";
682 vo_destroy(mpctx->video_out);
683 mpctx->video_out = NULL;
684 #ifdef CONFIG_DVDNAV
685 mp_dvdnav_context_free(mpctx);
686 #endif
689 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
690 if (mask & INITIALIZED_GETCH2) {
691 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
692 current_module = "uninit_getch2";
693 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
694 // restore terminal:
695 getch2_disable();
698 if (mask & INITIALIZED_VOBSUB) {
699 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
700 current_module = "uninit_vobsub";
701 if (vo_vobsub)
702 vobsub_close(vo_vobsub);
703 vo_vobsub = NULL;
706 if (mask & INITIALIZED_SPUDEC) {
707 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
708 current_module = "uninit_spudec";
709 spudec_free(vo_spudec);
710 vo_spudec = NULL;
713 if (mask & INITIALIZED_AO) {
714 mpctx->initialized_flags &= ~INITIALIZED_AO;
715 current_module = "uninit_ao";
716 if (mpctx->edl_muted)
717 mixer_mute(&mpctx->mixer);
718 if (mpctx->ao)
719 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
720 mpctx->ao = NULL;
723 current_module = NULL;
726 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
728 if (mpctx->user_muted && !mpctx->edl_muted)
729 mixer_mute(&mpctx->mixer);
730 uninit_player(mpctx, INITIALIZED_ALL);
731 #if defined(__MINGW32__) || defined(__CYGWIN__)
732 timeEndPeriod(1);
733 #endif
734 #ifdef CONFIG_X11
735 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
736 #endif
738 current_module = "uninit_input";
739 mp_input_uninit(mpctx->input);
741 #ifdef CONFIG_FREETYPE
742 current_module = "uninit_font";
743 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
744 free_font_desc(mpctx->osd->sub_font);
745 free_font_desc(vo_font);
746 vo_font = NULL;
747 done_freetype();
748 #endif
749 osd_free(mpctx->osd);
751 #ifdef CONFIG_ASS
752 ass_library_done(mpctx->ass_library);
753 mpctx->ass_library = NULL;
754 #endif
756 current_module = "exit_player";
758 if (mpctx->playtree_iter)
759 play_tree_iter_free(mpctx->playtree_iter);
760 mpctx->playtree_iter = NULL;
761 if (mpctx->playtree)
762 play_tree_free(mpctx->playtree, 1);
763 mpctx->playtree = NULL;
765 talloc_free(mpctx->key_fifo);
767 free(edl_records); // free mem allocated for EDL
768 edl_records = NULL;
769 switch (how) {
770 case EXIT_QUIT:
771 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
772 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
773 break;
774 case EXIT_EOF:
775 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
776 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
777 break;
778 case EXIT_ERROR:
779 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
780 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
781 break;
782 default:
783 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
785 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
786 "max framesize was %d bytes\n", max_framesize);
788 // must be last since e.g. mp_msg uses option values
789 // that will be freed by this.
790 if (mpctx->mconfig)
791 m_config_free(mpctx->mconfig);
792 mpctx->mconfig = NULL;
794 exit(rc);
797 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
799 exit_player_with_rc(mpctx, how, 1);
802 #ifndef __MINGW32__
803 static void child_sighandler(int x)
805 pid_t pid;
806 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
808 #endif
810 #ifdef CONFIG_CRASH_DEBUG
811 static char *prog_path;
812 static int crash_debug = 0;
813 #endif
815 static void exit_sighandler(int x)
817 static int sig_count = 0;
818 #ifdef CONFIG_CRASH_DEBUG
819 if (!crash_debug || x != SIGTRAP)
820 #endif
821 ++sig_count;
822 if (sig_count == 5) {
823 /* We're crashing bad and can't uninit cleanly :(
824 * by popular request, we make one last (dirty)
825 * effort to restore the user's
826 * terminal. */
827 getch2_disable();
828 exit(1);
830 if (sig_count == 6)
831 exit(1);
832 if (sig_count > 6) {
833 // can't stop :(
834 #ifndef __MINGW32__
835 kill(getpid(), SIGKILL);
836 #endif
838 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
839 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
840 "\nMPlayer interrupted by signal %d in module: %s\n", x,
841 current_module ? current_module : "unknown");
842 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
843 if (sig_count <= 1)
844 switch (x) {
845 case SIGINT:
846 case SIGPIPE:
847 case SIGQUIT:
848 case SIGTERM:
849 case SIGKILL:
850 async_quit_request = 1;
851 return; // killed from keyboard (^C) or killed [-9]
852 case SIGILL:
853 #if CONFIG_RUNTIME_CPUDETECT
854 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
855 #else
856 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
857 #endif
858 case SIGFPE:
859 case SIGSEGV:
860 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
861 default:
862 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
863 #ifdef CONFIG_CRASH_DEBUG
864 if (crash_debug) {
865 int gdb_pid;
866 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
867 gdb_pid = fork();
868 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
869 if (gdb_pid == 0) { // We are the child
870 char spid[20];
871 snprintf(spid, sizeof(spid), "%i", getppid());
872 getch2_disable(); // allow terminal to work properly with gdb
873 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
874 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
875 } else if (gdb_pid < 0)
876 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
877 else
878 waitpid(gdb_pid, NULL, 0);
879 if (x == SIGTRAP)
880 return;
882 #endif
884 getch2_disable();
885 exit(1);
888 #include "cfg-mplayer.h"
890 static int cfg_include(m_option_t *conf, char *filename)
892 return m_config_parse_config_file(conf->priv, filename);
895 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
897 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
899 struct MPOpts *opts = &mpctx->opts;
900 char *conffile;
901 int conffile_fd;
902 if (!(opts->noconfig & 2) &&
903 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
904 exit_player(mpctx, EXIT_NONE);
905 if ((conffile = get_path("")) == NULL)
906 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
907 else {
908 #ifdef __MINGW32__
909 mkdir(conffile);
910 #else
911 mkdir(conffile, 0777);
912 #endif
913 free(conffile);
914 if ((conffile = get_path("config")) == NULL)
915 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
916 else {
917 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
918 0666)) != -1) {
919 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
920 "Creating config file: %s\n", conffile);
921 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
922 close(conffile_fd);
924 if (!(opts->noconfig & 1) &&
925 m_config_parse_config_file(conf, conffile) < 0)
926 exit_player(mpctx, EXIT_NONE);
927 free(conffile);
932 #define PROFILE_CFG_PROTOCOL "protocol."
934 static void load_per_protocol_config(m_config_t *conf, const char * const file)
936 char *str;
937 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
938 m_profile_t *p;
940 /* does filename actually uses a protocol ? */
941 str = strstr(file, "://");
942 if (!str)
943 return;
945 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
946 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
947 p = m_config_get_profile(conf, protocol);
948 if (p) {
949 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
950 "Loading protocol-related profile '%s'\n", protocol);
951 m_config_set_profile(conf, p);
955 #define PROFILE_CFG_EXTENSION "extension."
957 static void load_per_extension_config(m_config_t *conf, const char * const file)
959 char *str;
960 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
961 m_profile_t *p;
963 /* does filename actually have an extension ? */
964 str = strrchr(file, '.');
965 if (!str)
966 return;
968 sprintf(extension, PROFILE_CFG_EXTENSION);
969 strncat(extension, ++str, 7);
970 p = m_config_get_profile(conf, extension);
971 if (p) {
972 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
973 "Loading extension-related profile '%s'\n", extension);
974 m_config_set_profile(conf, p);
978 #define PROFILE_CFG_VO "vo."
979 #define PROFILE_CFG_AO "ao."
981 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
983 char profile[strlen(cfg) + strlen(out) + 1];
984 m_profile_t *p;
986 sprintf(profile, "%s%s", cfg, out);
987 p = m_config_get_profile(conf, profile);
988 if (p) {
989 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
990 "Loading extension-related profile '%s'\n", profile);
991 m_config_set_profile(conf, p);
996 * Tries to load a config file
997 * @return 0 if file was not found, 1 otherwise
999 static int try_load_config(m_config_t *conf, const char *file)
1001 struct stat st;
1002 if (stat(file, &st))
1003 return 0;
1004 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1005 m_config_parse_config_file(conf, file);
1006 return 1;
1009 static void load_per_file_config(m_config_t *conf, const char * const file)
1011 char *confpath;
1012 char cfg[PATH_MAX];
1013 const char *name;
1015 if (strlen(file) > PATH_MAX - 14) {
1016 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
1017 "can not load file or directory specific config files\n");
1018 return;
1020 sprintf(cfg, "%s.conf", file);
1022 name = mp_basename(cfg);
1023 if (use_filedir_conf) {
1024 char dircfg[PATH_MAX];
1025 strcpy(dircfg, cfg);
1026 strcpy(dircfg + (name - cfg), "mplayer.conf");
1027 try_load_config(conf, dircfg);
1029 if (try_load_config(conf, cfg))
1030 return;
1033 if ((confpath = get_path(name)) != NULL) {
1034 try_load_config(conf, confpath);
1036 free(confpath);
1040 /* When libmpdemux performs a blocking operation (network connection or
1041 * cache filling) if the operation fails we use this function to check
1042 * if it was interrupted by the user.
1043 * The function returns a new value for eof. */
1044 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1046 mp_cmd_t *cmd;
1047 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1048 switch (cmd->id) {
1049 case MP_CMD_QUIT:
1050 exit_player_with_rc(mpctx, EXIT_QUIT,
1051 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1052 case MP_CMD_PLAY_TREE_STEP: {
1053 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1054 mpctx->play_tree_step =
1055 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1056 } break;
1057 case MP_CMD_PLAY_TREE_UP_STEP: {
1058 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1059 } break;
1060 case MP_CMD_PLAY_ALT_SRC_STEP: {
1061 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1062 } break;
1064 mp_cmd_free(cmd);
1066 return stop_play;
1069 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1071 play_tree_add_bpf(entry, bstr(mpctx->filename));
1074 if (!entry) {
1075 entry = mpctx->playtree_iter->tree;
1076 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1077 != PLAY_TREE_ITER_ENTRY)
1078 return PT_NEXT_ENTRY;
1079 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1080 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1081 != PLAY_TREE_ITER_ENTRY)
1082 return PT_NEXT_ENTRY;
1084 play_tree_remove(entry, 1, 1);
1085 return PT_NEXT_SRC;
1087 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1088 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1089 entry = mpctx->playtree_iter->tree;
1090 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1091 != PLAY_TREE_ITER_ENTRY)
1092 return PT_NEXT_ENTRY;
1093 play_tree_remove(entry, 1, 1);
1095 return PT_NEXT_SRC;
1098 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1099 int noerr)
1101 struct MPOpts *opts = &mpctx->opts;
1102 sub_data *subd = NULL;
1103 struct ass_track *asst = NULL;
1104 bool is_native_ass = false;
1106 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1107 return;
1109 #ifdef CONFIG_ASS
1110 if (opts->ass_enabled) {
1111 #ifdef CONFIG_ICONV
1112 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1113 #else
1114 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1115 #endif
1116 is_native_ass = asst;
1117 if (!asst) {
1118 subd = sub_read_file(filename, fps, &mpctx->opts);
1119 if (subd) {
1120 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1121 sub_free(subd);
1122 subd = NULL;
1125 } else
1126 #endif
1127 subd = sub_read_file(filename, fps, &mpctx->opts);
1130 if (!asst && !subd) {
1131 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1132 "Cannot load subtitles: %s\n", filename_recode(filename));
1133 return;
1136 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1137 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1138 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1139 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1140 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1141 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1142 filename_recode(filename));
1143 ++mpctx->set_of_sub_size;
1144 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1145 mpctx->set_of_sub_size, filename_recode(filename));
1148 void init_vo_spudec(struct MPContext *mpctx)
1150 unsigned width, height;
1151 spudec_free(vo_spudec);
1152 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1153 vo_spudec = NULL;
1155 // we currently can't work without video stream
1156 if (!mpctx->sh_video)
1157 return;
1159 if (spudec_ifo) {
1160 unsigned int palette[16];
1161 current_module = "spudec_init_vobsub";
1162 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1163 1, -1, NULL) >= 0)
1164 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1167 width = mpctx->sh_video->disp_w;
1168 height = mpctx->sh_video->disp_h;
1170 #ifdef CONFIG_DVDREAD
1171 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1172 current_module = "spudec_init_dvdread";
1173 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1174 cur_pgc->palette, width, height, NULL, 0);
1176 #endif
1178 #ifdef CONFIG_DVDNAV
1179 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1180 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1181 current_module = "spudec_init_dvdnav";
1182 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1184 #endif
1186 if (vo_spudec == NULL) {
1187 sh_sub_t *sh = mpctx->d_sub->sh;
1188 current_module = "spudec_init_normal";
1189 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1190 sh->extradata_len);
1191 spudec_set_font_factor(vo_spudec, font_factor);
1194 if (vo_spudec != NULL) {
1195 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1196 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1197 mpctx);
1202 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1203 * make it all work is to use the builtin SDL-bootstrap code, which
1204 * will be done automatically by replacing our main() if we include SDL.h.
1206 #if defined(__APPLE__) && defined(CONFIG_SDL)
1207 #ifdef CONFIG_SDL_SDL_H
1208 #include <SDL/SDL.h>
1209 #else
1210 #include <SDL.h>
1211 #endif
1212 #endif
1215 * \brief append a formatted string
1216 * \param buf buffer to print into
1217 * \param pos position of terminating 0 in buf
1218 * \param len maximum number of characters in buf, not including terminating 0
1219 * \param format printf format string
1221 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1223 va_list va;
1224 va_start(va, format);
1225 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1226 va_end(va);
1227 if (*pos >= len) {
1228 buf[len] = 0;
1229 *pos = len;
1234 * \brief append time in the hh:mm:ss.f format
1235 * \param buf buffer to print into
1236 * \param pos position of terminating 0 in buf
1237 * \param len maximum number of characters in buf, not including terminating 0
1238 * \param time time value to convert/append
1240 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1242 int64_t tenths = 10 * time;
1243 int f1 = tenths % 10;
1244 int ss = (tenths / 10) % 60;
1245 int mm = (tenths / 600) % 60;
1246 int hh = tenths / 36000;
1247 if (time < 0) {
1248 saddf(buf, pos, len, "unknown");
1249 return;
1251 if (hh > 0)
1252 saddf(buf, pos, len, "%2d:", hh);
1253 if (hh > 0 || mm > 0)
1254 saddf(buf, pos, len, "%02d:", mm);
1255 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1258 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1260 struct MPOpts *opts = &mpctx->opts;
1261 sh_video_t * const sh_video = mpctx->sh_video;
1263 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1264 a_pos = playing_audio_pts(mpctx);
1265 if (mpctx->sh_audio && sh_video && at_frame) {
1266 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1267 if (mpctx->time_frame > 0)
1268 mpctx->last_av_difference +=
1269 mpctx->time_frame * opts->playback_speed;
1270 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1271 && !mpctx->drop_message_shown) {
1272 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1273 mpctx->drop_message_shown = true;
1276 if (opts->quiet)
1277 return;
1279 if (a_pos == MP_NOPTS_VALUE)
1280 a_pos = -9; // don't print a huge negative number
1282 int width;
1283 char *line;
1284 unsigned pos = 0;
1285 get_screen_size();
1286 if (screen_width > 0)
1287 width = screen_width;
1288 else
1289 width = 80;
1290 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1291 /* Windows command line is broken (MinGW's rxvt works, but we
1292 * should not depend on that). */
1293 width--;
1294 #endif
1295 line = malloc(width + 1); // one additional char for the terminating null
1297 // Audio time
1298 if (mpctx->sh_audio) {
1299 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1300 if (!sh_video) {
1301 float len = get_time_length(mpctx);
1302 saddf(line, &pos, width, "(");
1303 sadd_hhmmssf(line, &pos, width, a_pos);
1304 saddf(line, &pos, width, ") of %.1f (", len);
1305 sadd_hhmmssf(line, &pos, width, len);
1306 saddf(line, &pos, width, ") ");
1310 // Video time
1311 if (sh_video)
1312 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1314 // A-V sync
1315 if (mpctx->sh_audio && sh_video)
1316 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1317 mpctx->last_av_difference, mpctx->total_avsync_change);
1319 // Video stats
1320 if (sh_video)
1321 saddf(line, &pos, width, "%3d/%3d ",
1322 (int)sh_video->num_frames,
1323 (int)sh_video->num_frames_decoded);
1325 // CPU usage
1326 if (sh_video) {
1327 if (sh_video->timer > 0.5)
1328 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1329 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1330 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1331 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1332 else
1333 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1334 } else if (mpctx->sh_audio) {
1335 if (mpctx->delay > 0.5)
1336 saddf(line, &pos, width, "%4.1f%% ",
1337 100.0 * audio_time_usage / (double)mpctx->delay);
1338 else
1339 saddf(line, &pos, width, "??,?%% ");
1342 // VO stats
1343 if (sh_video)
1344 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1346 #ifdef CONFIG_STREAM_CACHE
1347 // cache stats
1348 if (stream_cache_size > 0)
1349 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1350 #endif
1352 // other
1353 if (opts->playback_speed != 1)
1354 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1356 // end
1357 if (erase_to_end_of_line) {
1358 line[pos] = 0;
1359 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1360 "%s%s\r", line, erase_to_end_of_line);
1361 } else {
1362 memset(&line[pos], ' ', width - pos);
1363 line[width] = 0;
1364 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1366 free(line);
1369 struct stream_dump_progress {
1370 uint64_t count;
1371 unsigned start_time;
1372 unsigned last_print_time;
1375 static void stream_dump_progress_start(struct stream_dump_progress *p)
1377 p->start_time = p->last_print_time = GetTimerMS();
1378 p->count = 0;
1381 static void stream_dump_progress(struct stream_dump_progress *p,
1382 uint64_t len, stream_t *stream)
1384 p->count += len;
1385 unsigned t = GetTimerMS();
1386 if (t - p->last_print_time < 1000)
1387 return;
1389 uint64_t start = stream->start_pos;
1390 uint64_t end = stream->end_pos;
1391 uint64_t pos = stream->pos;
1393 p->last_print_time = t;
1394 /* TODO: pretty print sizes; ETA */
1395 if (end > start && pos >= start && pos <= end) {
1396 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1397 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1398 p->count, 100.0 * (pos - start) / (end - start));
1399 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1400 } else {
1401 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1402 "dump: %"PRIu64 " bytes written", p->count);
1403 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1407 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1409 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1410 p->count, name);
1414 * \brief build a chain of audio filters that converts the input format
1415 * to the ao's format, taking into account the current playback_speed.
1416 * sh_audio describes the requested input format of the chain.
1417 * ao describes the requested output format of the chain.
1419 static int build_afilter_chain(struct MPContext *mpctx)
1421 struct sh_audio *sh_audio = mpctx->sh_audio;
1422 struct ao *ao = mpctx->ao;
1423 struct MPOpts *opts = &mpctx->opts;
1424 int new_srate;
1425 int result;
1426 if (!sh_audio) {
1427 mpctx->mixer.afilter = NULL;
1428 return 0;
1430 if (af_control_any_rev(sh_audio->afilter,
1431 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1432 &opts->playback_speed))
1433 new_srate = sh_audio->samplerate;
1434 else {
1435 new_srate = sh_audio->samplerate * opts->playback_speed;
1436 if (new_srate != ao->samplerate) {
1437 // limits are taken from libaf/af_resample.c
1438 if (new_srate < 8000)
1439 new_srate = 8000;
1440 if (new_srate > 192000)
1441 new_srate = 192000;
1442 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1445 result = init_audio_filters(sh_audio, new_srate,
1446 &ao->samplerate, &ao->channels, &ao->format);
1447 mpctx->mixer.afilter = sh_audio->afilter;
1448 return result;
1452 typedef struct mp_osd_msg mp_osd_msg_t;
1453 struct mp_osd_msg {
1454 /// Previous message on the stack.
1455 mp_osd_msg_t *prev;
1456 /// Message text.
1457 char *msg;
1458 int id, level, started;
1459 /// Display duration in ms.
1460 unsigned time;
1463 /// OSD message stack.
1464 static mp_osd_msg_t *osd_msg_stack = NULL;
1467 * \brief Add a message on the OSD message stack
1469 * If a message with the same id is already present in the stack
1470 * it is pulled on top of the stack, otherwise a new message is created.
1473 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1474 va_list ap)
1476 mp_osd_msg_t *msg, *last = NULL;
1478 // look if the id is already in the stack
1479 for (msg = osd_msg_stack; msg && msg->id != id;
1480 last = msg, msg = msg->prev) ;
1481 // not found: alloc it
1482 if (!msg) {
1483 msg = talloc_zero(NULL, mp_osd_msg_t);
1484 msg->prev = osd_msg_stack;
1485 osd_msg_stack = msg;
1486 } else if (last) { // found, but it's not on top of the stack
1487 last->prev = msg->prev;
1488 msg->prev = osd_msg_stack;
1489 osd_msg_stack = msg;
1491 talloc_free(msg->msg);
1492 // write the msg
1493 msg->msg = talloc_vasprintf(msg, fmt, ap);
1494 // set id and time
1495 msg->id = id;
1496 msg->level = level;
1497 msg->time = time;
1501 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1503 va_list ap;
1504 va_start(ap, fmt);
1505 set_osd_msg_va(id, level, time, fmt, ap);
1506 va_end(ap);
1509 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1511 va_list ap;
1512 va_start(ap, fmt);
1513 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1514 va_end(ap);
1518 * \brief Remove a message from the OSD stack
1520 * This function can be used to get rid of a message right away.
1524 void rm_osd_msg(int id)
1526 mp_osd_msg_t *msg, *last = NULL;
1528 // Search for the msg
1529 for (msg = osd_msg_stack; msg && msg->id != id;
1530 last = msg, msg = msg->prev) ;
1531 if (!msg)
1532 return;
1534 // Detach it from the stack and free it
1535 if (last)
1536 last->prev = msg->prev;
1537 else
1538 osd_msg_stack = msg->prev;
1539 talloc_free(msg);
1543 * \brief Remove all messages from the OSD stack
1547 static void clear_osd_msgs(void)
1549 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1550 while (msg) {
1551 prev = msg->prev;
1552 talloc_free(msg);
1553 msg = prev;
1555 osd_msg_stack = NULL;
1559 * \brief Get the current message from the OSD stack.
1561 * This function decrements the message timer and destroys the old ones.
1562 * The message that should be displayed is returned (if any).
1566 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1568 struct MPOpts *opts = &mpctx->opts;
1569 mp_osd_msg_t *msg, *prev, *last = NULL;
1570 static unsigned last_update = 0;
1571 unsigned now = GetTimerMS();
1572 unsigned diff;
1573 char hidden_dec_done = 0;
1575 if (mpctx->osd_visible) {
1576 // 36000000 means max timed visibility is 1 hour into the future, if
1577 // the difference is greater assume it's wrapped around from below 0
1578 if (mpctx->osd_visible - now > 36000000) {
1579 mpctx->osd_visible = 0;
1580 vo_osd_progbar_type = -1; // disable
1581 vo_osd_changed(OSDTYPE_PROGBAR);
1582 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1585 if (mpctx->osd_show_percentage_until - now > 36000000)
1586 mpctx->osd_show_percentage_until = 0;
1588 if (!last_update)
1589 last_update = now;
1590 diff = now >= last_update ? now - last_update : 0;
1592 last_update = now;
1594 // Look for the first message in the stack with high enough level.
1595 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1596 prev = msg->prev;
1597 if (msg->level > opts->osd_level && hidden_dec_done)
1598 continue;
1599 // The message has a high enough level or it is the first hidden one
1600 // in both cases we decrement the timer or kill it.
1601 if (!msg->started || msg->time > diff) {
1602 if (msg->started)
1603 msg->time -= diff;
1604 else
1605 msg->started = 1;
1606 // display it
1607 if (msg->level <= opts->osd_level)
1608 return msg;
1609 hidden_dec_done = 1;
1610 continue;
1612 // kill the message
1613 talloc_free(msg);
1614 if (last) {
1615 last->prev = prev;
1616 msg = last;
1617 } else {
1618 osd_msg_stack = prev;
1619 msg = NULL;
1622 // Nothing found
1623 return NULL;
1627 * \brief Display the OSD bar.
1629 * Display the OSD bar or fall back on a simple message.
1633 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1634 double min, double max, double val)
1636 struct MPOpts *opts = &mpctx->opts;
1637 if (opts->osd_level < 1)
1638 return;
1640 if (mpctx->sh_video) {
1641 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1642 vo_osd_progbar_type = type;
1643 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1644 vo_osd_changed(OSDTYPE_PROGBAR);
1645 return;
1648 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1649 name, ROUND(100 * (val - min) / (max - min)));
1653 * \brief Display text subtitles on the OSD
1655 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1657 int i;
1658 vo_sub = subs;
1659 vo_osd_changed(OSDTYPE_SUBTITLE);
1660 if (!mpctx->sh_video) {
1661 // reverse order, since newest set_osd_msg is displayed first
1662 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1663 if (!subs || i >= subs->lines || !subs->text[i])
1664 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1665 else {
1666 // HACK: currently display time for each sub line
1667 // except the last is set to 2 seconds.
1668 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1669 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1670 "%s", subs->text[i]);
1677 * \brief Update the OSD message line.
1679 * This function displays the current message on the vo OSD or on the term.
1680 * If the stack is empty and the OSD level is high enough the timer
1681 * is displayed (only on the vo OSD).
1685 static void update_osd_msg(struct MPContext *mpctx)
1687 struct MPOpts *opts = &mpctx->opts;
1688 mp_osd_msg_t *msg;
1689 struct osd_state *osd = mpctx->osd;
1690 char osd_text_timer[128];
1692 if (mpctx->add_osd_seek_info) {
1693 double percentage = get_percent_pos(mpctx);
1694 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1695 if (mpctx->sh_video)
1696 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1697 mpctx->add_osd_seek_info = false;
1700 // Look if we have a msg
1701 if ((msg = get_osd_msg(mpctx))) {
1702 if (strcmp(osd->osd_text, msg->msg)) {
1703 osd_set_text(osd, msg->msg);
1704 if (mpctx->sh_video)
1705 vo_osd_changed(OSDTYPE_OSD);
1706 else if (opts->term_osd)
1707 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1708 msg->msg);
1710 return;
1713 if (mpctx->sh_video) {
1714 // fallback on the timer
1715 if (opts->osd_level >= 2) {
1716 int len = get_time_length(mpctx);
1717 int percentage = -1;
1718 char percentage_text[10];
1719 char fractions_text[4];
1720 double fpts = get_current_time(mpctx);
1721 int pts = fpts;
1723 if (mpctx->osd_show_percentage_until)
1724 percentage = get_percent_pos(mpctx);
1726 if (percentage >= 0)
1727 snprintf(percentage_text, 9, " (%d%%)", percentage);
1728 else
1729 percentage_text[0] = 0;
1731 if (opts->osd_fractions == 1) {
1732 //print fractions as sub-second timestamp
1733 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1734 (int)((fpts - pts) * 100));
1735 } else if (opts->osd_fractions == 2) {
1736 /* Print fractions by estimating the frame count within the
1737 * second.
1739 * Rounding or cutting off numbers after the decimal point
1740 * causes problems because of float's precision and movies
1741 * whose first frame is not exactly at timestamp 0. Therefore,
1742 * we add 0.2 and cut off at the decimal point, which proved
1743 * to be good heuristic.
1745 double fps = mpctx->sh_video->fps;
1746 if (fps <= 1 || fps > 99)
1747 strcpy(fractions_text, ".??");
1748 else
1749 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1750 (int) ((fpts - pts) * fps + 0.2));
1751 } else {
1752 //do not print fractions
1753 fractions_text[0] = 0;
1756 if (opts->osd_level == 3)
1757 snprintf(osd_text_timer, sizeof(osd_text_timer),
1758 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1759 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1760 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1761 percentage_text);
1762 else
1763 snprintf(osd_text_timer, sizeof(osd_text_timer),
1764 "%c %02d:%02d:%02d%s%s",
1765 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1766 pts % 60, fractions_text, percentage_text);
1767 } else
1768 osd_text_timer[0] = 0;
1770 if (strcmp(osd->osd_text, osd_text_timer)) {
1771 osd_set_text(osd, osd_text_timer);
1772 vo_osd_changed(OSDTYPE_OSD);
1774 return;
1777 // Clear the term osd line
1778 if (opts->term_osd && osd->osd_text[0]) {
1779 osd->osd_text[0] = 0;
1780 printf("%s\n", opts->term_osd_esc);
1785 void reinit_audio_chain(struct MPContext *mpctx)
1787 struct MPOpts *opts = &mpctx->opts;
1788 struct ao *ao;
1789 if (!mpctx->sh_audio)
1790 return;
1791 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1792 current_module = "init_audio_codec";
1793 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1794 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1795 goto init_error;
1796 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1797 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1801 current_module = "af_preinit";
1802 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1803 mpctx->initialized_flags |= INITIALIZED_AO;
1804 mpctx->ao = ao_create();
1805 mpctx->ao->samplerate = force_srate;
1806 mpctx->ao->format = opts->audio_output_format;
1808 ao = mpctx->ao;
1810 // first init to detect best values
1811 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1812 // input:
1813 mpctx->sh_audio->samplerate,
1814 // output:
1815 &ao->samplerate, &ao->channels, &ao->format)) {
1816 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1817 "pre-init!\n");
1818 exit_player(mpctx, EXIT_ERROR);
1820 if (!ao->initialized) {
1821 current_module = "ao2_init";
1822 ao->buffersize = opts->ao_buffersize;
1823 ao_init(ao, opts->audio_driver_list);
1824 if (!ao->initialized) {
1825 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1826 "Could not open/initialize audio device -> no sound.\n");
1827 goto init_error;
1829 ao->buffer.start = talloc_new(ao);
1830 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1831 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1832 ao->driver->info->short_name,
1833 ao->samplerate, ao->channels,
1834 af_fmt2str_short(ao->format),
1835 af_fmt2bits(ao->format) / 8);
1836 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1837 ao->driver->info->name, ao->driver->info->author);
1838 if (strlen(ao->driver->info->comment) > 0)
1839 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1840 ao->driver->info->comment);
1843 // init audio filters:
1844 current_module = "af_init";
1845 if (!build_afilter_chain(mpctx)) {
1846 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1847 "Couldn't find matching filter/ao format!\n");
1848 goto init_error;
1850 mpctx->mixer.ao = ao;
1851 mpctx->mixer.volstep = volstep;
1852 mpctx->syncing_audio = true;
1853 return;
1855 init_error:
1856 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1857 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1858 mpctx->d_audio->id = -2;
1862 // Return pts value corresponding to the end point of audio written to the
1863 // ao so far.
1864 static double written_audio_pts(struct MPContext *mpctx)
1866 sh_audio_t *sh_audio = mpctx->sh_audio;
1867 demux_stream_t *d_audio = mpctx->d_audio;
1868 // first calculate the end pts of audio that has been output by decoder
1869 double a_pts = sh_audio->pts;
1870 if (a_pts != MP_NOPTS_VALUE)
1871 // Good, decoder supports new way of calculating audio pts.
1872 // sh_audio->pts is the timestamp of the latest input packet with
1873 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1874 // the amount of bytes the decoder has written after that timestamp.
1875 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1876 else {
1877 // Decoder doesn't support new way of calculating pts (or we're
1878 // being called before it has decoded anything with known timestamp).
1879 // Use the old method of audio pts calculation: take the timestamp
1880 // of last packet with known pts the decoder has read data from,
1881 // and add amount of bytes read after the beginning of that packet
1882 // divided by input bps. This will be inaccurate if the input/output
1883 // ratio is not constant for every audio packet or if it is constant
1884 // but not accurately known in sh_audio->i_bps.
1886 a_pts = d_audio->pts;
1887 if (a_pts == MP_NOPTS_VALUE)
1888 return a_pts;
1890 // ds_tell_pts returns bytes read after last timestamp from
1891 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1892 // it has read but not decoded
1893 if (sh_audio->i_bps)
1894 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1895 (double)sh_audio->i_bps;
1897 // Now a_pts hopefully holds the pts for end of audio from decoder.
1898 // Substract data in buffers between decoder and audio out.
1900 // Decoded but not filtered
1901 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1903 // Data buffered in audio filters, measured in bytes of "missing" output
1904 double buffered_output = af_calc_delay(sh_audio->afilter);
1906 // Data that was ready for ao but was buffered because ao didn't fully
1907 // accept everything to internal buffers yet
1908 buffered_output += mpctx->ao->buffer.len;
1910 // Filters divide audio length by playback_speed, so multiply by it
1911 // to get the length in original units without speedup or slowdown
1912 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1914 return a_pts + mpctx->video_offset;
1917 // Return pts value corresponding to currently playing audio.
1918 double playing_audio_pts(struct MPContext *mpctx)
1920 double pts = written_audio_pts(mpctx);
1921 if (pts == MP_NOPTS_VALUE)
1922 return pts;
1923 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1926 static bool is_av_sub(int type)
1928 return type == 'b' || type == 'p' || type == 'x';
1931 void update_subtitles(struct MPContext *mpctx, double refpts,
1932 double sub_offset, bool reset)
1934 struct MPOpts *opts = &mpctx->opts;
1935 struct sh_video *sh_video = mpctx->sh_video;
1936 struct demux_stream *d_sub = mpctx->d_sub;
1937 double curpts = refpts + sub_delay;
1938 unsigned char *packet = NULL;
1939 int len;
1940 struct sh_sub *sh_sub = d_sub->sh;
1941 int type = sh_sub ? sh_sub->type : 'v';
1942 static subtitle subs;
1943 if (reset) {
1944 if (sh_sub)
1945 sub_reset(sh_sub, mpctx->osd);
1946 sub_clear_text(&subs, MP_NOPTS_VALUE);
1947 if (vo_sub)
1948 set_osd_subtitle(mpctx, NULL);
1949 if (vo_spudec) {
1950 spudec_reset(vo_spudec);
1951 vo_osd_changed(OSDTYPE_SPU);
1953 #ifdef CONFIG_FFMPEG
1954 if (is_av_sub(type))
1955 reset_avsub(sh_sub);
1956 #endif
1957 return;
1959 // find sub
1960 if (mpctx->subdata) {
1961 if (sub_fps == 0)
1962 sub_fps = sh_video ? sh_video->fps : 25;
1963 current_module = "find_sub";
1964 find_sub(mpctx, mpctx->subdata, curpts *
1965 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1966 if (vo_sub)
1967 mpctx->vo_sub_last = vo_sub;
1970 // DVD sub:
1971 if (vobsub_id >= 0 || type == 'v') {
1972 int timestamp;
1973 current_module = "spudec";
1974 /* Get a sub packet from the DVD or a vobsub */
1975 while (1) {
1976 // Vobsub
1977 len = 0;
1978 if (vo_vobsub) {
1979 if (curpts >= 0) {
1980 len = vobsub_get_packet(vo_vobsub, curpts,
1981 (void **)&packet, &timestamp);
1982 if (len > 0)
1983 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1984 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1985 len, refpts, sh_video->timer,
1986 timestamp / 90000.0, timestamp);
1988 } else {
1989 // DVD sub
1990 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1991 if (len > 0) {
1992 // XXX This is wrong, sh_video->pts can be arbitrarily
1993 // much behind demuxing position. Unfortunately using
1994 // d_video->pts which would have been the simplest
1995 // improvement doesn't work because mpeg specific hacks
1996 // in video.c set d_video->pts to 0.
1997 float x = d_sub->pts - refpts;
1998 if (x > -20 && x < 20) // prevent missing subs on pts reset
1999 timestamp = 90000 * d_sub->pts;
2000 else
2001 timestamp = 90000 * curpts;
2002 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
2003 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
2004 refpts, d_sub->pts, timestamp);
2007 if (len <= 0 || !packet)
2008 break;
2009 // create it only here, since with some broken demuxers we might
2010 // type = v but no DVD sub and we currently do not change the
2011 // "original frame size" ever after init, leading to wrong-sized
2012 // PGS subtitles.
2013 if (!vo_spudec)
2014 vo_spudec = spudec_new(NULL);
2015 if (vo_vobsub || timestamp >= 0)
2016 spudec_assemble(vo_spudec, packet, len, timestamp);
2018 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
2019 if (type == 'd' && !d_sub->demuxer->teletext) {
2020 tt_stream_props tsp = { 0 };
2021 void *ptr = &tsp;
2022 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
2023 VBI_CONTROL_TRUE)
2024 d_sub->demuxer->teletext = ptr;
2026 if (d_sub->non_interleaved)
2027 ds_get_next_pts(d_sub);
2029 while (d_sub->first) {
2030 double subpts = ds_get_next_pts(d_sub) + sub_offset;
2031 if (subpts > curpts) {
2032 // Libass handled subs can be fed to it in advance
2033 if (!opts->ass_enabled || !is_text_sub(type))
2034 break;
2035 // Try to avoid demuxing whole file at once
2036 if (d_sub->non_interleaved && subpts > curpts + 1)
2037 break;
2039 double duration = d_sub->first->duration;
2040 len = ds_get_packet_sub(d_sub, &packet);
2041 if (is_av_sub(type)) {
2042 #ifdef CONFIG_FFMPEG
2043 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2044 if (ret < 0)
2045 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2046 "subtitle\n");
2047 #endif
2048 continue;
2050 if (type == 'm') {
2051 if (len < 2)
2052 continue;
2053 len = FFMIN(len - 2, AV_RB16(packet));
2054 packet += 2;
2056 if (type == 'd') {
2057 if (d_sub->demuxer->teletext) {
2058 uint8_t *p = packet;
2059 p++;
2060 len--;
2061 while (len >= 46) {
2062 int sublen = p[1];
2063 if (p[0] == 2 || p[0] == 3)
2064 teletext_control(d_sub->demuxer->teletext,
2065 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2066 p += sublen + 2;
2067 len -= sublen + 2;
2070 continue;
2072 if (sh_sub && sh_sub->active) {
2073 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2074 continue;
2076 if (subpts != MP_NOPTS_VALUE) {
2077 if (duration < 0)
2078 sub_clear_text(&subs, MP_NOPTS_VALUE);
2079 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2080 int i;
2081 unsigned char *p = packet;
2082 for (i = 0; i < 8 && *p != '\0'; p++)
2083 if (*p == ',')
2084 i++;
2085 if (*p == '\0') /* Broken line? */
2086 continue;
2087 len -= p - packet;
2088 packet = p;
2090 double endpts = MP_NOPTS_VALUE;
2091 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2092 endpts = subpts + duration;
2093 sub_add_text(&subs, packet, len, endpts);
2094 set_osd_subtitle(mpctx, &subs);
2096 if (d_sub->non_interleaved)
2097 ds_get_next_pts(d_sub);
2099 if (!opts->ass_enabled)
2100 if (sub_clear_text(&subs, curpts))
2101 set_osd_subtitle(mpctx, &subs);
2103 if (vo_spudec) {
2104 spudec_heartbeat(vo_spudec, 90000 * curpts);
2105 if (spudec_changed(vo_spudec))
2106 vo_osd_changed(OSDTYPE_SPU);
2109 current_module = NULL;
2112 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2114 int page_changed;
2116 if (!demuxer->teletext)
2117 return;
2119 //Also forcing page update when such ioctl is not supported or call error occured
2120 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2121 &page_changed) != VBI_CONTROL_TRUE)
2122 page_changed = 1;
2124 if (!page_changed)
2125 return;
2127 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2128 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2129 vo_osd_teletext_page = NULL;
2130 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2131 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2132 vo_osd_teletext_half = 0;
2133 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2134 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2135 vo_osd_teletext_mode = 0;
2136 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2137 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2138 vo_osd_teletext_format = 0;
2139 vo_osd_changed(OSDTYPE_TELETEXT);
2141 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2144 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2146 struct MPOpts *opts = &mpctx->opts;
2147 // check for frame-drop:
2148 current_module = "check_framedrop";
2149 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2150 static int dropped_frames;
2151 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2152 float d = delay - mpctx->delay;
2153 ++total_frame_cnt;
2154 // we should avoid dropping too many frames in sequence unless we
2155 // are too late. and we allow 100ms A-V delay here:
2156 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2157 && !mpctx->restart_playback) {
2158 ++drop_frame_cnt;
2159 ++dropped_frames;
2160 return frame_dropping;
2161 } else
2162 dropped_frames = 0;
2164 return 0;
2168 #ifdef HAVE_RTC
2169 int rtc_fd = -1;
2170 #endif
2172 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2174 #ifdef HAVE_RTC
2175 if (rtc_fd >= 0) {
2176 // -------- RTC -----------
2177 current_module = "sleep_rtc";
2178 while (time_frame > 0.000) {
2179 unsigned long rtc_ts;
2180 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2181 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2182 "Linux RTC read error: %s\n", strerror(errno));
2183 time_frame -= get_relative_time(mpctx);
2185 } else
2186 #endif
2188 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2189 // unnecessarily high CPU usage
2190 struct MPOpts *opts = &mpctx->opts;
2191 float margin = opts->softsleep ? 0.011 : 0;
2192 current_module = "sleep_timer";
2193 while (time_frame > margin) {
2194 usec_sleep(1000000 * (time_frame - margin));
2195 time_frame -= get_relative_time(mpctx);
2197 if (opts->softsleep) {
2198 current_module = "sleep_soft";
2199 if (time_frame < 0)
2200 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2201 "Warning! Softsleep underflow!\n");
2202 while (time_frame > 0)
2203 time_frame -= get_relative_time(mpctx); // burn the CPU
2206 return time_frame;
2209 static int select_subtitle(MPContext *mpctx)
2211 struct MPOpts *opts = &mpctx->opts;
2212 // find the best sub to use
2213 int id;
2214 int found = 0;
2215 mpctx->global_sub_pos = -1; // no subs by default
2216 if (vobsub_id >= 0) {
2217 // if user asks for a vobsub id, use that first.
2218 id = vobsub_id;
2219 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2220 M_PROPERTY_OK;
2223 if (!found && opts->sub_id >= 0) {
2224 // if user asks for a dvd sub id, use that next.
2225 id = opts->sub_id;
2226 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2227 M_PROPERTY_OK;
2230 if (!found) {
2231 // if there are text subs to use, use those. (autosubs come last here)
2232 id = 0;
2233 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2234 M_PROPERTY_OK;
2237 if (!found && opts->sub_id == -1) {
2238 // finally select subs by language and container hints
2239 if (opts->sub_id == -1)
2240 opts->sub_id =
2241 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2242 opts->sub_lang);
2243 if (opts->sub_id >= 0) {
2244 id = opts->sub_id;
2245 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2246 M_PROPERTY_OK;
2249 return found;
2252 #ifdef CONFIG_DVDNAV
2253 #ifndef FF_B_TYPE
2254 #define FF_B_TYPE 3
2255 #endif
2256 /// store decoded video image
2257 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2258 mp_image_t *from_mpi)
2260 mp_image_t *mpi;
2262 /// Do not store B-frames
2263 if (from_mpi->pict_type == FF_B_TYPE)
2264 return to_mpi;
2266 if (to_mpi &&
2267 to_mpi->w == from_mpi->w &&
2268 to_mpi->h == from_mpi->h &&
2269 to_mpi->imgfmt == from_mpi->imgfmt)
2270 mpi = to_mpi;
2271 else {
2272 if (to_mpi)
2273 free_mp_image(to_mpi);
2274 if (from_mpi->w == 0 || from_mpi->h == 0)
2275 return NULL;
2276 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2279 copy_mpi(mpi, from_mpi);
2280 return mpi;
2283 static void mp_dvdnav_reset_stream(MPContext *ctx)
2285 struct MPOpts *opts = &ctx->opts;
2286 if (ctx->sh_video) {
2287 /// clear video pts
2288 ctx->d_video->pts = 0.0f;
2289 ctx->sh_video->pts = 0.0f;
2290 ctx->sh_video->i_pts = 0.0f;
2291 ctx->sh_video->last_pts = 0.0f;
2292 ctx->sh_video->num_buffered_pts = 0;
2293 ctx->sh_video->num_frames = 0;
2294 ctx->sh_video->num_frames_decoded = 0;
2295 ctx->sh_video->timer = 0.0f;
2296 ctx->sh_video->stream_delay = 0.0f;
2297 ctx->sh_video->timer = 0;
2298 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2301 if (ctx->sh_audio) {
2302 /// free audio packets and reset
2303 ds_free_packs(ctx->d_audio);
2304 audio_delay -= ctx->sh_audio->stream_delay;
2305 ctx->delay = -audio_delay;
2306 ao_reset(ctx->ao);
2307 resync_audio_stream(ctx->sh_audio);
2310 audio_delay = 0.0f;
2311 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2312 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2313 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2314 if (dvdsub_lang_id != opts->sub_id) {
2315 opts->sub_id = dvdsub_lang_id;
2316 select_subtitle(ctx);
2320 /// clear all EOF related flags
2321 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2324 /// Restore last decoded DVDNAV (still frame)
2325 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2326 int *in_size,
2327 unsigned char **start,
2328 mp_image_t *decoded_frame)
2330 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2331 return decoded_frame;
2333 /// a change occurred in dvdnav stream
2334 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2335 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2336 mp_dvdnav_context_free(mpctx);
2337 mp_dvdnav_reset_stream(mpctx);
2338 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2339 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2342 if (*in_size < 0) {
2343 float len;
2345 /// Display still frame, if any
2346 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2347 decoded_frame = mpctx->nav_smpi;
2349 /// increment video frame : continue playing after still frame
2350 len = get_time_length(mpctx);
2351 if (mpctx->sh_video->pts >= len &&
2352 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2353 mp_dvdnav_skip_still(mpctx->stream);
2354 mp_dvdnav_skip_wait(mpctx->stream);
2356 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2358 if (mpctx->nav_buffer) {
2359 *start = mpctx->nav_start;
2360 *in_size = mpctx->nav_in_size;
2361 if (mpctx->nav_start)
2362 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2366 return decoded_frame;
2369 /// Save last decoded DVDNAV (still frame)
2370 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2371 unsigned char *start,
2372 mp_image_t *decoded_frame)
2374 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2375 return;
2377 free(mpctx->nav_buffer);
2378 mpctx->nav_buffer = NULL;
2379 mpctx->nav_start = NULL;
2380 mpctx->nav_in_size = -1;
2382 if (in_size > 0)
2383 mpctx->nav_buffer = malloc(in_size);
2384 if (mpctx->nav_buffer) {
2385 mpctx->nav_start = start;
2386 mpctx->nav_in_size = in_size;
2387 memcpy(mpctx->nav_buffer, start, in_size);
2390 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2391 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2393 #endif /* CONFIG_DVDNAV */
2395 /* Modify video timing to match the audio timeline. There are two main
2396 * reasons this is needed. First, video and audio can start from different
2397 * positions at beginning of file or after a seek (MPlayer starts both
2398 * immediately even if they have different pts). Second, the file can have
2399 * audio timestamps that are inconsistent with the duration of the audio
2400 * packets, for example two consecutive timestamp values differing by
2401 * one second but only a packet with enough samples for half a second
2402 * of playback between them.
2404 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2406 current_module = "av_sync";
2408 if (!mpctx->sh_audio || mpctx->syncing_audio)
2409 return;
2411 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2412 double v_pts = mpctx->sh_video->pts;
2413 double av_delay = a_pts - v_pts;
2414 // Try to sync vo_flip() so it will *finish* at given time
2415 av_delay += mpctx->last_vo_flip_duration;
2416 av_delay -= audio_delay; // This much pts difference is desired
2418 double change = av_delay * 0.1;
2419 double max_change = default_max_pts_correction >= 0 ?
2420 default_max_pts_correction : frame_time * 0.1;
2421 if (change < -max_change)
2422 change = -max_change;
2423 else if (change > max_change)
2424 change = max_change;
2425 mpctx->delay += change;
2426 mpctx->total_avsync_change += change;
2429 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2430 double pts)
2432 if (mpctx->paused)
2433 return 0;
2434 struct ao *ao = mpctx->ao;
2435 double bps = ao->bps / mpctx->opts.playback_speed;
2436 ao->pts = pts;
2437 // hack used by some mpeg-writing AOs
2438 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2439 mpctx->delay) * 90000.0;
2440 int played = ao_play(mpctx->ao, data, len, flags);
2441 if (played > 0) {
2442 mpctx->delay += played / bps;
2443 // Keep correct pts for remaining data - could be used to flush
2444 // remaining buffer when closing ao.
2445 ao->pts += played / bps;
2447 return played;
2450 #define ASYNC_PLAY_DONE -3
2451 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2453 struct ao *ao = mpctx->ao;
2454 struct MPOpts *opts = &mpctx->opts;
2455 sh_audio_t * const sh_audio = mpctx->sh_audio;
2456 int res;
2458 // Timing info may not be set without
2459 res = decode_audio(sh_audio, &ao->buffer, 1);
2460 if (res < 0)
2461 return res;
2463 int bytes;
2464 bool did_retry = false;
2465 double written_pts;
2466 double bps = ao->bps / opts->playback_speed;
2467 while (1) {
2468 written_pts = written_audio_pts(mpctx);
2469 double ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2470 - audio_delay;
2471 bytes = ptsdiff * bps;
2472 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2474 // ogg demuxers give packets without timing
2475 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2476 if (!did_retry) {
2477 // Try to read more data to see packets that have pts
2478 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2479 if (res < 0)
2480 return res;
2481 did_retry = true;
2482 continue;
2484 bytes = 0;
2487 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2488 bytes = 0;
2490 if (bytes > 0)
2491 break;
2493 mpctx->syncing_audio = false;
2494 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2495 int res = decode_audio(sh_audio, &ao->buffer, a);
2496 bytes += ao->buffer.len;
2497 if (bytes >= 0) {
2498 memmove(ao->buffer.start,
2499 ao->buffer.start + ao->buffer.len - bytes, bytes);
2500 ao->buffer.len = bytes;
2501 if (res < 0)
2502 return res;
2503 return decode_audio(sh_audio, &ao->buffer, playsize);
2505 ao->buffer.len = 0;
2506 if (res < 0)
2507 return res;
2509 int fillbyte = 0;
2510 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2511 fillbyte = 0x80;
2512 if (bytes >= playsize) {
2513 /* This case could fall back to the one below with
2514 * bytes = playsize, but then silence would keep accumulating
2515 * in a_out_buffer if the AO accepts less data than it asks for
2516 * in playsize. */
2517 char *p = malloc(playsize);
2518 memset(p, fillbyte, playsize);
2519 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2520 free(p);
2521 return ASYNC_PLAY_DONE;
2523 mpctx->syncing_audio = false;
2524 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2525 return decode_audio(sh_audio, &ao->buffer, playsize);
2528 static int fill_audio_out_buffers(struct MPContext *mpctx)
2530 struct MPOpts *opts = &mpctx->opts;
2531 struct ao *ao = mpctx->ao;
2532 unsigned int t;
2533 double tt;
2534 int playsize;
2535 int playflags = 0;
2536 bool audio_eof = false;
2537 bool partial_fill = false;
2538 sh_audio_t * const sh_audio = mpctx->sh_audio;
2539 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2540 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2542 current_module = "play_audio";
2544 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2545 return 0;
2547 // hack used by some mpeg-writing AOs
2548 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2549 mpctx->delay) * 90000.0;
2551 if (mpctx->paused)
2552 playsize = 1; // just initialize things (audio pts at least)
2553 else
2554 playsize = ao_get_space(ao);
2556 // Fill buffer if needed:
2557 current_module = "decode_audio";
2558 t = GetTimer();
2560 if (!opts->initial_audio_sync || !modifiable_audio_format)
2561 mpctx->syncing_audio = false;
2563 int res;
2564 if (mpctx->syncing_audio && mpctx->sh_video)
2565 res = audio_start_sync(mpctx, playsize);
2566 else
2567 res = decode_audio(sh_audio, &ao->buffer, playsize);
2568 if (res < 0) { // EOF, error or format change
2569 if (res == -2) {
2570 /* The format change isn't handled too gracefully. A more precise
2571 * implementation would require draining buffered old-format audio
2572 * while displaying video, then doing the output format switch.
2574 uninit_player(mpctx, INITIALIZED_AO);
2575 reinit_audio_chain(mpctx);
2576 return -1;
2577 } else if (res == ASYNC_PLAY_DONE)
2578 return 0;
2579 else if (mpctx->d_audio->eof)
2580 audio_eof = true;
2582 t = GetTimer() - t;
2583 tt = t * 0.000001f;
2584 audio_time_usage += tt;
2585 if (mpctx->timeline && modifiable_audio_format) {
2586 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2587 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2588 * ao->bps / opts->playback_speed;
2589 if (playsize > bytes) {
2590 playsize = FFMAX(bytes, 0);
2591 playflags |= AOPLAY_FINAL_CHUNK;
2592 audio_eof = true;
2593 partial_fill = true;
2597 assert(ao->buffer.len % unitsize == 0);
2598 if (playsize > ao->buffer.len) {
2599 partial_fill = true;
2600 playsize = ao->buffer.len;
2601 if (audio_eof)
2602 playflags |= AOPLAY_FINAL_CHUNK;
2604 playsize -= playsize % unitsize;
2605 if (!playsize)
2606 return partial_fill && audio_eof ? -2 : -partial_fill;
2608 // play audio:
2609 current_module = "play_audio";
2611 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2612 written_audio_pts(mpctx));
2613 assert(played % unitsize == 0);
2614 ao->buffer_playable_size = playsize - played;
2616 if (played > 0) {
2617 ao->buffer.len -= played;
2618 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2619 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2620 // Sanity check to avoid hanging in case current ao doesn't output
2621 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2622 return -2;
2625 return -partial_fill;
2628 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2629 bool sync_to_audio, float *aq_sleep_time)
2631 struct MPOpts *opts = &mpctx->opts;
2632 double audio_limit = 2;
2633 current_module = "calc_sleep_time";
2635 if (mpctx->restart_playback)
2636 return 0;
2638 *time_frame -= get_relative_time(mpctx); // reset timer
2640 if (sync_to_audio) {
2641 float delay = ao_get_delay(mpctx->ao);
2642 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2644 if (opts->autosync) {
2646 * Adjust this raw delay value by calculating the expected
2647 * delay for this frame and generating a new value which is
2648 * weighted between the two. The higher autosync is, the
2649 * closer to the delay value gets to that which "-nosound"
2650 * would have used, and the longer it will take for A/V
2651 * sync to settle at the right value (but it eventually will.)
2652 * This settling time is very short for values below 100.
2654 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2655 float difference = delay - predicted;
2656 delay = predicted + difference / (float)opts->autosync;
2659 *time_frame = delay - mpctx->delay / opts->playback_speed;
2661 // delay = amount of audio buffered in soundcard/driver
2662 delay = FFMIN(delay, 0.5);
2663 delay = FFMAX(delay, 0.1);
2664 audio_limit = delay;
2665 } else {
2666 // If we're lagging more than 200 ms behind the right playback rate,
2667 // don't try to "catch up".
2668 // If benchmark is set always output frames as fast as possible
2669 // without sleeping.
2670 if (*time_frame < -0.2 || opts->benchmark)
2671 *time_frame = 0;
2674 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2676 if (t <= 0.05)
2677 return 0;
2679 t -= 0.05;
2680 if (t > audio_limit * 0.6)
2681 t = audio_limit * 0.5;
2682 *aq_sleep_time += t;
2683 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2684 return 1;
2687 int reinit_video_chain(struct MPContext *mpctx)
2689 struct MPOpts *opts = &mpctx->opts;
2690 sh_video_t * const sh_video = mpctx->sh_video;
2691 if (!sh_video)
2692 return 0;
2693 double ar = -1.0;
2694 //================== Init VIDEO (codec & libvo) ==========================
2695 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2696 current_module = "preinit_libvo";
2698 //shouldn't we set dvideo->id=-2 when we fail?
2699 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2700 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2701 mpctx->key_fifo,
2702 mpctx->input))) {
2703 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2704 "the selected video_out (-vo) device.\n");
2705 goto err_out;
2707 mpctx->initialized_flags |= INITIALIZED_VO;
2710 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2711 &ar) != STREAM_UNSUPPORTED)
2712 mpctx->sh_video->stream_aspect = ar;
2713 current_module = "init_video_filters";
2715 char *vf_arg[] = {
2716 "_oldargs_", (char *)mpctx->video_out, NULL
2718 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2721 #ifdef CONFIG_ASS
2722 if (opts->ass_enabled) {
2723 int i;
2724 int insert = 1;
2725 if (opts->vf_settings)
2726 for (i = 0; opts->vf_settings[i].name; ++i)
2727 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2728 insert = 0;
2729 break;
2731 if (insert) {
2732 extern vf_info_t vf_info_ass;
2733 const vf_info_t *libass_vfs[] = {
2734 &vf_info_ass, NULL
2736 char *vf_arg[] = {
2737 "auto", "1", NULL
2739 int retcode = 0;
2740 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2741 sh_video->vfilter,
2742 "ass", vf_arg,
2743 &retcode);
2744 if (vf_ass)
2745 sh_video->vfilter = vf_ass;
2746 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2747 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2748 else
2749 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2750 "ASS: cannot add video filter\n");
2753 #endif
2755 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2757 #ifdef CONFIG_ASS
2758 if (opts->ass_enabled)
2759 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2760 mpctx->ass_library);
2761 #endif
2763 current_module = "init_video_codec";
2765 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2766 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2767 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2769 if (!sh_video->initialized) {
2770 if (!opts->fixed_vo)
2771 uninit_player(mpctx, INITIALIZED_VO);
2772 goto err_out;
2775 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2777 if (sh_video->codec)
2778 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2779 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2781 sh_video->last_pts = MP_NOPTS_VALUE;
2782 sh_video->num_buffered_pts = 0;
2783 sh_video->next_frame_time = 0;
2785 if (opts->auto_quality > 0) {
2786 // Auto quality option enabled
2787 output_quality = get_video_quality_max(sh_video);
2788 if (opts->auto_quality > output_quality)
2789 opts->auto_quality = output_quality;
2790 else
2791 output_quality = opts->auto_quality;
2792 mp_msg(MSGT_CPLAYER, MSGL_V,
2793 "AutoQ: setting quality to %d.\n", output_quality);
2794 set_video_quality(sh_video, output_quality);
2797 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2799 current_module = "init_vo";
2801 return 1;
2803 err_out:
2804 mpctx->sh_video = mpctx->d_video->sh = NULL;
2805 return 0;
2808 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2810 struct sh_video *sh_video = mpctx->sh_video;
2811 double frame_time = 0;
2812 struct vo *video_out = mpctx->video_out;
2813 while (1) {
2814 current_module = "filter_video";
2815 // In nocorrect-pts mode there is no way to properly time these frames
2816 if (vo_get_buffered_frame(video_out, 0) >= 0)
2817 break;
2818 if (vf_output_queued_frame(sh_video->vfilter))
2819 break;
2820 unsigned char *packet = NULL;
2821 frame_time = sh_video->next_frame_time;
2822 if (mpctx->restart_playback)
2823 frame_time = 0;
2824 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2825 &packet, force_fps);
2826 if (in_size < 0) {
2827 #ifdef CONFIG_DVDNAV
2828 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2829 if (mp_dvdnav_is_eof(mpctx->stream))
2830 return -1;
2831 if (mpctx->d_video)
2832 mpctx->d_video->eof = 0;
2833 if (mpctx->d_audio)
2834 mpctx->d_audio->eof = 0;
2835 mpctx->stream->eof = 0;
2836 } else
2837 #endif
2838 return -1;
2840 if (in_size > max_framesize)
2841 max_framesize = in_size;
2842 sh_video->timer += frame_time;
2843 if (mpctx->sh_audio)
2844 mpctx->delay -= frame_time;
2845 // video_read_frame can change fps (e.g. for ASF video)
2846 vo_fps = sh_video->fps;
2847 int framedrop_type = check_framedrop(mpctx, frame_time);
2848 current_module = "decode video";
2850 void *decoded_frame;
2851 #ifdef CONFIG_DVDNAV
2852 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2853 if (in_size >= 0 && !decoded_frame)
2854 #endif
2855 decoded_frame = decode_video(sh_video, NULL, packet, in_size,
2856 framedrop_type, sh_video->pts);
2857 #ifdef CONFIG_DVDNAV
2858 // Save last still frame for future display
2859 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2860 #endif
2861 if (decoded_frame) {
2862 current_module = "filter video";
2863 filter_video(sh_video, decoded_frame, sh_video->pts);
2865 break;
2867 return frame_time;
2870 static void determine_frame_pts(struct MPContext *mpctx)
2872 struct sh_video *sh_video = mpctx->sh_video;
2873 struct MPOpts *opts = &mpctx->opts;
2875 if (opts->user_pts_assoc_mode)
2876 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2877 else if (sh_video->pts_assoc_mode == 0) {
2878 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2879 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2880 sh_video->pts_assoc_mode = 1;
2881 else
2882 sh_video->pts_assoc_mode = 2;
2883 } else {
2884 int probcount1 = sh_video->num_reordered_pts_problems;
2885 int probcount2 = sh_video->num_sorted_pts_problems;
2886 if (sh_video->pts_assoc_mode == 2) {
2887 int tmp = probcount1;
2888 probcount1 = probcount2;
2889 probcount2 = tmp;
2891 if (probcount1 >= probcount2 * 1.5 + 2) {
2892 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2893 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2894 "%d.\n", sh_video->pts_assoc_mode);
2897 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2898 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2901 static double update_video(struct MPContext *mpctx)
2903 struct sh_video *sh_video = mpctx->sh_video;
2904 struct vo *video_out = mpctx->video_out;
2905 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2906 mpctx->osd); // hack for vf_expand
2907 if (!mpctx->opts.correct_pts)
2908 return update_video_nocorrect_pts(mpctx);
2910 double pts;
2912 while (1) {
2913 current_module = "filter_video";
2914 if (!mpctx->hrseek_active
2915 && vo_get_buffered_frame(video_out, false) >= 0)
2916 break;
2917 // XXX Time used in this call is not counted in any performance
2918 // timer now
2919 if (vf_output_queued_frame(sh_video->vfilter))
2920 break;
2921 int in_size = 0;
2922 unsigned char *buf = NULL;
2923 pts = MP_NOPTS_VALUE;
2924 struct demux_packet *pkt = ds_get_packet2(mpctx->d_video);
2925 if (pkt) {
2926 in_size = pkt->len;
2927 buf = pkt->buffer;
2928 pts = pkt->pts;
2930 if (pts != MP_NOPTS_VALUE)
2931 pts += mpctx->video_offset;
2932 if (in_size > max_framesize)
2933 max_framesize = in_size;
2934 current_module = "decode video";
2935 if (pts >= mpctx->hrseek_pts - .005)
2936 mpctx->hrseek_framedrop = false;
2937 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2938 check_framedrop(mpctx, sh_video->frametime);
2939 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2940 framedrop_type, pts);
2941 if (decoded_frame) {
2942 determine_frame_pts(mpctx);
2943 current_module = "filter video";
2944 filter_video(sh_video, decoded_frame, sh_video->pts);
2945 } else if (!pkt) {
2946 if (vo_get_buffered_frame(video_out, true) < 0)
2947 return -1;
2949 break;
2952 if (!video_out->frame_loaded)
2953 return 0;
2955 pts = video_out->next_pts;
2956 if (pts == MP_NOPTS_VALUE) {
2957 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2958 // Try to use decoder pts from before filters
2959 pts = sh_video->pts;
2960 if (pts == MP_NOPTS_VALUE)
2961 pts = sh_video->last_pts;
2963 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2964 vo_skip_frame(video_out);
2965 return 0;
2967 mpctx->hrseek_active = false;
2968 sh_video->pts = pts;
2969 if (sh_video->last_pts == MP_NOPTS_VALUE)
2970 sh_video->last_pts = sh_video->pts;
2971 else if (sh_video->last_pts > sh_video->pts) {
2972 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2973 sh_video->pts, sh_video->last_pts);
2974 /* If the difference in pts is small treat it as jitter around the
2975 * right value (possibly caused by incorrect timestamp ordering) and
2976 * just show this frame immediately after the last one.
2977 * Treat bigger differences as timestamp resets and start counting
2978 * timing of later frames from the position of this one. */
2979 if (sh_video->last_pts - sh_video->pts > 0.5)
2980 sh_video->last_pts = sh_video->pts;
2981 else
2982 sh_video->pts = sh_video->last_pts;
2984 double frame_time = sh_video->pts - sh_video->last_pts;
2985 sh_video->last_pts = sh_video->pts;
2986 sh_video->timer += frame_time;
2987 if (mpctx->sh_audio)
2988 mpctx->delay -= frame_time;
2989 return frame_time;
2992 void pause_player(struct MPContext *mpctx)
2994 if (mpctx->paused)
2995 return;
2996 mpctx->paused = 1;
2997 mpctx->step_frames = 0;
2998 mpctx->time_frame -= get_relative_time(mpctx);
3000 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3001 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3003 if (mpctx->ao && mpctx->sh_audio)
3004 ao_pause(mpctx->ao); // pause audio, keep data if possible
3007 void unpause_player(struct MPContext *mpctx)
3009 if (!mpctx->paused)
3010 return;
3011 mpctx->paused = 0;
3013 if (mpctx->ao && mpctx->sh_audio)
3014 ao_resume(mpctx->ao);
3015 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3016 && !mpctx->step_frames)
3017 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3018 (void)get_relative_time(mpctx); // ignore time that passed during pause
3021 void add_step_frame(struct MPContext *mpctx)
3023 mpctx->step_frames++;
3024 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3025 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3026 unpause_player(mpctx);
3029 static void pause_loop(struct MPContext *mpctx)
3031 struct MPOpts *opts = &mpctx->opts;
3032 mp_cmd_t *cmd;
3033 #ifdef CONFIG_STREAM_CACHE
3034 int old_cache_fill = stream_cache_size > 0 ?
3035 cache_fill_status(mpctx->stream) : 0;
3036 #endif
3037 if (!opts->quiet) {
3038 if (opts->term_osd && !mpctx->sh_video) {
3039 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
3040 update_osd_msg(mpctx);
3041 } else
3042 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
3043 mp_gtext(" ===== PAUSE ====="));
3044 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
3047 while ((cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
3048 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
3049 if (cmd) {
3050 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3051 run_command(mpctx, cmd);
3052 mp_cmd_free(cmd);
3053 continue;
3055 if (mpctx->sh_video && mpctx->video_out)
3056 vo_check_events(mpctx->video_out);
3057 usec_sleep(20000);
3058 update_osd_msg(mpctx);
3059 int hack = vo_osd_changed(0);
3060 vo_osd_changed(hack);
3061 if (hack)
3062 break;
3063 #ifdef CONFIG_STREAM_CACHE
3064 if (!opts->quiet && stream_cache_size > 0) {
3065 int new_cache_fill = cache_fill_status(mpctx->stream);
3066 if (new_cache_fill != old_cache_fill) {
3067 if (opts->term_osd && !mpctx->sh_video) {
3068 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
3069 mp_gtext(" ===== PAUSE ====="),
3070 new_cache_fill);
3071 update_osd_msg(mpctx);
3072 } else
3073 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
3074 mp_gtext(" ===== PAUSE ====="),
3075 new_cache_fill);
3076 old_cache_fill = new_cache_fill;
3079 #endif
3084 // Find the right mute status and record position for new file position
3085 static void edl_seek_reset(MPContext *mpctx)
3087 mpctx->edl_muted = 0;
3088 next_edl_record = edl_records;
3090 while (next_edl_record) {
3091 if (next_edl_record->start_sec >= get_current_time(mpctx))
3092 break;
3094 if (next_edl_record->action == EDL_MUTE)
3095 mpctx->edl_muted = !mpctx->edl_muted;
3096 next_edl_record = next_edl_record->next;
3098 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3099 mixer_mute(&mpctx->mixer);
3103 // Execute EDL command for the current position if one exists
3104 static void edl_update(MPContext *mpctx)
3106 if (!next_edl_record)
3107 return;
3109 if (!mpctx->sh_video) {
3110 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
3111 "Cannot use EDL without video, disabling.\n");
3112 free_edl(edl_records);
3113 next_edl_record = NULL;
3114 edl_records = NULL;
3115 return;
3118 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3119 if (next_edl_record->action == EDL_SKIP) {
3120 mpctx->osd_function = OSD_FFW;
3121 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3122 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3123 "[%f], length [%f]\n", next_edl_record->start_sec,
3124 next_edl_record->stop_sec, next_edl_record->length_sec);
3125 } else if (next_edl_record->action == EDL_MUTE) {
3126 mpctx->edl_muted = !mpctx->edl_muted;
3127 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3128 mixer_mute(&mpctx->mixer);
3129 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3130 next_edl_record->start_sec);
3132 next_edl_record = next_edl_record->next;
3136 static void reinit_decoders(struct MPContext *mpctx)
3138 reinit_video_chain(mpctx);
3139 reinit_audio_chain(mpctx);
3140 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3143 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3145 if (mpctx->sh_video) {
3146 current_module = "seek_video_reset";
3147 resync_video_stream(mpctx->sh_video);
3148 mpctx->sh_video->timer = 0;
3149 vo_seek_reset(mpctx->video_out);
3150 mpctx->sh_video->timer = 0;
3151 mpctx->sh_video->num_buffered_pts = 0;
3152 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3153 mpctx->delay = 0;
3154 mpctx->time_frame = 0;
3155 mpctx->restart_playback = true;
3156 // Not all demuxers set d_video->pts during seek, so this value
3157 // (which is used by at least vobsub and edl code below) may
3158 // be completely wrong (probably 0).
3159 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3160 mpctx->video_pts = mpctx->sh_video->pts;
3161 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3162 true);
3163 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3166 if (mpctx->sh_audio) {
3167 current_module = "seek_audio_reset";
3168 resync_audio_stream(mpctx->sh_audio);
3169 if (reset_ao)
3170 ao_reset(mpctx->ao);
3171 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3172 mpctx->sh_audio->a_buffer_len = 0;
3173 if (!mpctx->sh_video)
3174 update_subtitles(mpctx, mpctx->sh_audio->pts,
3175 mpctx->video_offset, true);
3178 if (vo_vobsub && mpctx->sh_video) {
3179 current_module = "seek_vobsub_reset";
3180 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3183 edl_seek_reset(mpctx);
3185 mpctx->hrseek_active = false;
3186 mpctx->hrseek_framedrop = false;
3187 mpctx->total_avsync_change = 0;
3188 audio_time_usage = 0;
3189 video_time_usage = 0;
3190 vout_time_usage = 0;
3191 drop_frame_cnt = 0;
3193 current_module = NULL;
3196 static bool timeline_set_part(struct MPContext *mpctx, int i)
3198 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3199 struct timeline_part *n = mpctx->timeline + i;
3200 mpctx->timeline_part = i;
3201 mpctx->video_offset = n->start - n->source_start;
3202 if (n->source == p->source)
3203 return false;
3204 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3205 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3206 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3207 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3208 mpctx->stop_play = orig_stop_play;
3209 mpctx->demuxer = n->source->demuxer;
3210 mpctx->d_video = mpctx->demuxer->video;
3211 mpctx->d_audio = mpctx->demuxer->audio;
3212 mpctx->d_sub = mpctx->demuxer->sub;
3213 mpctx->sh_video = mpctx->d_video->sh;
3214 mpctx->sh_audio = mpctx->d_audio->sh;
3215 return true;
3218 // Given pts, switch playback to the corresponding part.
3219 // Return offset within that part.
3220 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3221 bool *need_reset)
3223 if (pts < 0)
3224 pts = 0;
3225 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3226 struct timeline_part *p = mpctx->timeline + i;
3227 if (pts < (p + 1)->start) {
3228 *need_reset = timeline_set_part(mpctx, i);
3229 return pts - p->start + p->source_start;
3232 return -1;
3236 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3237 static int seek(MPContext *mpctx, struct seek_params seek,
3238 bool timeline_fallthrough)
3240 struct MPOpts *opts = &mpctx->opts;
3242 current_module = "seek";
3243 if (mpctx->stop_play == AT_END_OF_FILE)
3244 mpctx->stop_play = KEEP_PLAYING;
3245 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3246 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3247 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3248 || opts->hr_seek > 0 || seek.exact > 0;
3249 if (seek.type == MPSEEK_FACTOR
3250 || seek.type == MPSEEK_ABSOLUTE
3251 && seek.amount < mpctx->last_chapter_pts
3252 || seek.amount < 0)
3253 mpctx->last_chapter_seek = -2;
3254 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3255 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3256 seek.type = MPSEEK_ABSOLUTE;
3258 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3259 && seek.type == MPSEEK_RELATIVE) {
3260 seek.type = MPSEEK_ABSOLUTE;
3261 seek.direction = seek.amount > 0 ? 1 : -1;
3262 seek.amount += get_current_time(mpctx);
3265 /* At least the liba52 decoder wants to read from the input stream
3266 * during initialization, so reinit must be done after the demux_seek()
3267 * call that clears possible stream EOF. */
3268 bool need_reset = false;
3269 double demuxer_amount = seek.amount;
3270 if (mpctx->timeline) {
3271 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3272 &need_reset);
3273 if (demuxer_amount == -1) {
3274 mpctx->stop_play = AT_END_OF_FILE;
3275 // Clear audio from current position
3276 if (mpctx->sh_audio) {
3277 ao_reset(mpctx->ao);
3278 mpctx->sh_audio->a_buffer_len = 0;
3280 return -1;
3283 int demuxer_style = 0;
3284 switch (seek.type) {
3285 case MPSEEK_FACTOR:
3286 demuxer_style |= SEEK_FACTOR; // fallthrough
3287 case MPSEEK_ABSOLUTE:
3288 demuxer_style |= SEEK_ABSOLUTE;
3290 if (hr_seek || seek.direction < 0)
3291 demuxer_style |= SEEK_BACKWARD;
3292 else if (seek.direction > 0)
3293 demuxer_style |= SEEK_FORWARD;
3295 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3296 demuxer_style);
3297 if (need_reset)
3298 reinit_decoders(mpctx);
3299 if (seekresult == 0)
3300 return -1;
3302 seek_reset(mpctx, !timeline_fallthrough);
3304 /* Use the target time as "current position" for further relative
3305 * seeks etc until a new video frame has been decoded */
3306 if (seek.type == MPSEEK_ABSOLUTE) {
3307 mpctx->video_pts = seek.amount;
3308 mpctx->last_seek_pts = seek.amount;
3309 } else
3310 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3312 if (hr_seek) {
3313 mpctx->hrseek_active = true;
3314 mpctx->hrseek_framedrop = true;
3315 mpctx->hrseek_pts = seek.amount;
3318 mpctx->start_timestamp = GetTimerMS();
3320 return 0;
3323 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3324 int exact)
3326 struct seek_params *seek = &mpctx->seek;
3327 switch (type) {
3328 case MPSEEK_RELATIVE:
3329 if (seek->type == MPSEEK_FACTOR)
3330 return; // Well... not common enough to bother doing better
3331 seek->amount += amount;
3332 seek->exact = FFMAX(seek->exact, exact);
3333 if (seek->type == MPSEEK_NONE)
3334 seek->exact = exact;
3335 if (seek->type == MPSEEK_ABSOLUTE)
3336 return;
3337 if (seek->amount == 0) {
3338 *seek = (struct seek_params){ 0 };
3339 return;
3341 seek->type = MPSEEK_RELATIVE;
3342 return;
3343 case MPSEEK_ABSOLUTE:
3344 case MPSEEK_FACTOR:
3345 *seek = (struct seek_params) {
3346 .type = type,
3347 .amount = amount,
3348 .exact = exact,
3350 return;
3351 case MPSEEK_NONE:
3352 *seek = (struct seek_params){ 0 };
3353 return;
3355 abort();
3359 double get_time_length(struct MPContext *mpctx)
3361 if (mpctx->timeline)
3362 return mpctx->timeline[mpctx->num_timeline_parts].start;
3364 struct demuxer *demuxer = mpctx->demuxer;
3365 double get_time_ans;
3366 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3367 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3368 (void *) &get_time_ans) > 0)
3369 return get_time_ans;
3371 struct sh_video *sh_video = mpctx->d_video->sh;
3372 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3373 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3374 return (double) (demuxer->movi_end - demuxer->movi_start) /
3375 (sh_video->i_bps + sh_audio->i_bps);
3376 if (sh_video && sh_video->i_bps)
3377 return (double) (demuxer->movi_end - demuxer->movi_start) /
3378 sh_video->i_bps;
3379 if (sh_audio && sh_audio->i_bps)
3380 return (double) (demuxer->movi_end - demuxer->movi_start) /
3381 sh_audio->i_bps;
3382 return 0;
3385 /* If there are timestamps from stream level then use those (for example
3386 * DVDs can have consistent times there while the MPEG-level timestamps
3387 * reset). */
3388 double get_current_time(struct MPContext *mpctx)
3390 struct demuxer *demuxer = mpctx->demuxer;
3391 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3392 return demuxer->stream_pts;
3393 struct sh_video *sh_video = demuxer->video->sh;
3394 if (sh_video)
3395 return mpctx->video_pts;
3396 double apts = playing_audio_pts(mpctx);
3397 if (apts != MP_NOPTS_VALUE)
3398 return apts;
3399 return mpctx->last_seek_pts;
3402 int get_percent_pos(struct MPContext *mpctx)
3404 struct demuxer *demuxer = mpctx->demuxer;
3405 int ans = 0;
3406 if (mpctx->timeline)
3407 ans = get_current_time(mpctx) * 100 /
3408 mpctx->timeline[mpctx->num_timeline_parts].start;
3409 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3411 else {
3412 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3413 off_t pos = demuxer->filepos > 0 ?
3414 demuxer->filepos : stream_tell(demuxer->stream);
3415 if (len > 0)
3416 ans = (pos - demuxer->movi_start) / len;
3417 else
3418 ans = 0;
3420 if (ans < 0)
3421 ans = 0;
3422 if (ans > 100)
3423 ans = 100;
3424 return ans;
3427 // -2 is no chapters, -1 is before first chapter
3428 int get_current_chapter(struct MPContext *mpctx)
3430 double current_pts = get_current_time(mpctx);
3431 if (!mpctx->chapters)
3432 return FFMAX(mpctx->last_chapter_seek,
3433 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3435 int i;
3436 for (i = 1; i < mpctx->num_chapters; i++)
3437 if (current_pts < mpctx->chapters[i].start)
3438 break;
3439 return FFMAX(mpctx->last_chapter_seek, i - 1);
3442 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3444 char *name = chapter_name(mpctx, chapter);
3445 if (name) {
3446 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3447 } else {
3448 int chapter_count = get_chapter_count(mpctx);
3449 if (chapter_count <= 0)
3450 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3451 else
3452 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3453 chapter_count);
3455 return name;
3458 // returns NULL if chapter name unavailable
3459 char *chapter_name(struct MPContext *mpctx, int chapter)
3461 if (!mpctx->chapters)
3462 return demuxer_chapter_name(mpctx->demuxer, chapter);
3463 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3466 // returns the start of the chapter in seconds
3467 double chapter_start_time(struct MPContext *mpctx, int chapter)
3469 if (!mpctx->chapters)
3470 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3471 return mpctx->chapters[chapter].start;
3474 int get_chapter_count(struct MPContext *mpctx)
3476 if (!mpctx->chapters)
3477 return demuxer_chapter_count(mpctx->demuxer);
3478 return mpctx->num_chapters;
3481 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3483 mpctx->last_chapter_seek = -2;
3484 if (!mpctx->chapters) {
3485 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3486 if (res >= 0) {
3487 if (*seek_pts == -1)
3488 seek_reset(mpctx, true);
3489 else {
3490 mpctx->last_chapter_seek = res;
3491 mpctx->last_chapter_pts = *seek_pts;
3494 return res;
3497 if (chapter >= mpctx->num_chapters)
3498 return -1;
3499 if (chapter < 0)
3500 chapter = 0;
3501 *seek_pts = mpctx->chapters[chapter].start;
3502 mpctx->last_chapter_seek = chapter;
3503 mpctx->last_chapter_pts = *seek_pts;
3504 return chapter;
3508 static void run_playloop(struct MPContext *mpctx)
3510 struct MPOpts *opts = &mpctx->opts;
3511 float aq_sleep_time = 0;
3512 bool full_audio_buffers = false;
3514 if (opts->chapterrange[1] > 0) {
3515 int cur_chapter = get_current_chapter(mpctx);
3516 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3517 mpctx->stop_play = PT_NEXT_ENTRY;
3520 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3521 mpctx->sh_audio = mpctx->d_audio->sh;
3522 mpctx->sh_audio->ds = mpctx->d_audio;
3523 reinit_audio_chain(mpctx);
3526 /*========================== PLAY AUDIO ============================*/
3528 if (!mpctx->sh_video)
3529 mpctx->restart_playback = false;
3531 if (mpctx->sh_audio && !mpctx->restart_playback) {
3532 int status = fill_audio_out_buffers(mpctx);
3533 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3534 if (status == -2)
3535 // at eof, all audio at least written to ao
3536 if (!mpctx->sh_video)
3537 mpctx->stop_play = AT_END_OF_FILE;
3541 if (!mpctx->sh_video) {
3542 if (mpctx->step_frames) {
3543 mpctx->step_frames = 0;
3544 pause_player(mpctx);
3546 // handle audio-only case:
3547 double a_pos = 0, a_buf = 0;
3548 // sh_audio can be NULL due to video stream switching
3549 // TODO: handle this better
3550 if (mpctx->sh_audio) {
3551 a_buf = ao_get_delay(mpctx->ao);
3552 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3553 a_buf;
3556 print_status(mpctx, a_pos, false);
3558 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3559 update_osd_msg(mpctx);
3560 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3561 mpctx->stop_play = AT_END_OF_FILE;
3562 else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3563 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3564 && mpctx->sh_audio) {
3565 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3566 if (!opts->gapless_audio && p->source != (p + 1)->source
3567 && a_buf > 0.05) {
3568 mpctx->stop_play = KEEP_PLAYING;
3569 mp_input_get_cmd(mpctx->input, (a_buf - .05) * 1000, true);
3570 } else {
3571 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3572 .amount = (p + 1)->start },
3573 true);
3575 } else if (!mpctx->stop_play) {
3576 int sleep_time = 100;
3577 if (mpctx->sh_audio) {
3578 if (mpctx->ao->untimed)
3579 sleep_time = 0;
3580 else if (full_audio_buffers)
3581 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3582 else
3583 sleep_time = 20;
3584 sleep_time = FFMIN(sleep_time, 100);
3586 mp_input_get_cmd(mpctx->input, sleep_time, true);
3588 } else {
3590 /*========================== PLAY VIDEO ============================*/
3592 vo_pts = mpctx->sh_video->timer * 90000.0;
3593 vo_fps = mpctx->sh_video->fps;
3595 bool blit_frame = mpctx->video_out->frame_loaded;
3596 if (!blit_frame || mpctx->hrseek_active) {
3597 double frame_time = update_video(mpctx);
3598 blit_frame = mpctx->video_out->frame_loaded;
3599 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3600 if (mpctx->sh_video->vf_initialized < 0) {
3601 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3602 "\nFATAL: Could not initialize video filters (-vf) "
3603 "or video output (-vo).\n");
3604 mpctx->stop_play = PT_NEXT_ENTRY;
3605 return;
3607 if (frame_time < 0)
3608 mpctx->stop_play = AT_END_OF_FILE;
3609 else if (!mpctx->restart_playback) {
3610 mpctx->time_frame += frame_time / opts->playback_speed;
3611 adjust_sync(mpctx, frame_time);
3614 if (mpctx->timeline) {
3615 struct timeline_part *next =
3616 mpctx->timeline + mpctx->timeline_part + 1;
3617 if (mpctx->sh_video->pts >= next->start
3618 || mpctx->stop_play == AT_END_OF_FILE
3619 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3620 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3621 .amount = next->start },
3622 true);
3623 return;
3627 // ================================================================
3629 current_module = "vo_check_events";
3630 vo_check_events(mpctx->video_out);
3632 #ifdef CONFIG_X11
3633 if (stop_xscreensaver) {
3634 current_module = "stop_xscreensaver";
3635 xscreensaver_heartbeat(mpctx->x11_state);
3637 #endif
3638 if (heartbeat_cmd) {
3639 static unsigned last_heartbeat;
3640 unsigned now = GetTimerMS();
3641 if (now - last_heartbeat > 30000) {
3642 last_heartbeat = now;
3643 system(heartbeat_cmd);
3647 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3648 &mpctx->time_frame,
3649 full_audio_buffers,
3650 &aq_sleep_time);
3652 //=================== FLIP PAGE (VIDEO BLT): ======================
3654 current_module = "flip_page";
3655 if (!frame_time_remaining && blit_frame) {
3656 struct sh_video *sh_video = mpctx->sh_video;
3657 mpctx->video_pts = sh_video->pts;
3658 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3659 update_teletext(sh_video, mpctx->demuxer, 0);
3660 update_osd_msg(mpctx);
3661 struct vf_instance *vf = sh_video->vfilter;
3662 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3663 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3664 vo_osd_changed(0);
3666 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3667 aq_sleep_time += mpctx->time_frame;
3668 // flag 256 means: libvo driver does its timing (dvb card)
3669 if (mpctx->time_frame > 0.001
3670 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3671 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3672 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3674 unsigned int t2 = GetTimer();
3675 /* Playing with playback speed it's possible to get pathological
3676 * cases with mpctx->time_frame negative enough to cause an
3677 * overflow in pts_us calculation, thus the FFMAX. */
3678 double time_frame = FFMAX(mpctx->time_frame, -1);
3679 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3680 int duration = -1;
3681 double pts2 = mpctx->video_out->next_pts2;
3682 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3683 && !mpctx->restart_playback) {
3684 // expected A/V sync correction is ignored
3685 double diff = (pts2 - mpctx->video_pts);
3686 diff /= opts->playback_speed;
3687 if (mpctx->time_frame < 0)
3688 diff += mpctx->time_frame;
3689 if (diff < 0)
3690 diff = 0;
3691 if (diff > 10)
3692 diff = 10;
3693 duration = diff * 1e6;
3695 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3697 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3698 vout_time_usage += mpctx->last_vo_flip_duration;
3699 if (mpctx->video_out->driver->flip_page_timed) {
3700 // No need to adjust sync based on flip speed
3701 mpctx->last_vo_flip_duration = 0;
3702 // For print_status - VO call finishing early is OK for sync
3703 mpctx->time_frame -= get_relative_time(mpctx);
3705 if (mpctx->restart_playback) {
3706 mpctx->syncing_audio = true;
3707 if (mpctx->sh_audio)
3708 fill_audio_out_buffers(mpctx);
3709 mpctx->restart_playback = false;
3710 mpctx->time_frame = 0;
3711 get_relative_time(mpctx);
3713 print_status(mpctx, MP_NOPTS_VALUE, true);
3714 } else
3715 print_status(mpctx, MP_NOPTS_VALUE, false);
3717 if (opts->auto_quality > 0) {
3718 current_module = "autoq";
3719 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3720 ++output_quality;
3721 else if (output_quality > 1 && aq_sleep_time < 0)
3722 --output_quality;
3723 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3724 output_quality = 0;
3725 set_video_quality(mpctx->sh_video, output_quality);
3728 if (!frame_time_remaining && blit_frame) {
3729 if (play_n_frames >= 0) {
3730 --play_n_frames;
3731 if (play_n_frames <= 0)
3732 mpctx->stop_play = PT_NEXT_ENTRY;
3734 if (mpctx->step_frames > 0) {
3735 mpctx->step_frames--;
3736 if (mpctx->step_frames == 0)
3737 pause_player(mpctx);
3741 // FIXME: add size based support for -endpos
3742 if (end_at.type == END_AT_TIME &&
3743 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3744 mpctx->stop_play = PT_NEXT_ENTRY;
3746 } // end if(mpctx->sh_video)
3748 #ifdef CONFIG_DVDNAV
3749 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3750 nav_highlight_t hl;
3751 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3752 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3753 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3754 vo_osd_changed(OSDTYPE_DVDNAV);
3755 } else {
3756 osd_set_nav_box(0, 0, 0, 0);
3757 vo_osd_changed(OSDTYPE_DVDNAV);
3758 vo_osd_changed(OSDTYPE_SPU);
3761 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3762 double ar = -1.0;
3763 if (mpctx->sh_video &&
3764 stream_control(mpctx->demuxer->stream,
3765 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3766 != STREAM_UNSUPPORTED)
3767 mpctx->sh_video->stream_aspect = ar;
3770 #endif
3772 //================= Keyboard events, SEEKing ====================
3774 current_module = "key_events";
3776 while (1) {
3777 mp_cmd_t *cmd;
3778 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3779 /* Allow running consecutive seek commands to combine them,
3780 * but execute the seek before running other commands.
3781 * If the user seeks continuously (keeps arrow key down)
3782 * try to finish showing a frame from one location before doing
3783 * another seek (which could lead to unchanging display). */
3784 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3785 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3786 && GetTimerMS() - mpctx->start_timestamp < 300)
3787 break;
3788 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3789 run_command(mpctx, cmd);
3790 mp_cmd_free(cmd);
3791 if (mpctx->stop_play)
3792 break;
3794 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3795 || mpctx->restart_playback)
3796 break;
3797 if (mpctx->sh_video) {
3798 update_osd_msg(mpctx);
3799 int hack = vo_osd_changed(0);
3800 vo_osd_changed(hack);
3801 if (hack) {
3802 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3803 add_step_frame(mpctx);
3804 break;
3805 } else
3806 vo_osd_changed(0);
3809 pause_loop(mpctx);
3812 // handle -sstep
3813 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3814 mpctx->osd_function = OSD_FFW;
3815 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3818 edl_update(mpctx);
3820 /* Looping. */
3821 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3822 mpctx->stop_play == PT_NEXT_ENTRY)) {
3823 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3825 if (opts->loop_times > 1)
3826 opts->loop_times--;
3827 else if (opts->loop_times == 1)
3828 opts->loop_times = -1;
3829 play_n_frames = play_n_frames_mf;
3830 mpctx->stop_play = 0;
3831 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3834 if (mpctx->seek.type) {
3835 seek(mpctx, mpctx->seek, false);
3836 mpctx->seek = (struct seek_params){ 0 };
3841 static int read_keys(void *ctx, int fd)
3843 getch2(ctx);
3844 return MP_INPUT_NOTHING;
3847 static bool attachment_is_font(struct demux_attachment *att)
3849 if (!att->name || !att->type || !att->data || !att->data_size)
3850 return false;
3851 // match against MIME types
3852 if (strcmp(att->type, "application/x-truetype-font") == 0
3853 || strcmp(att->type, "application/x-font") == 0)
3854 return true;
3855 // fallback: match against file extension
3856 if (strlen(att->name) > 4) {
3857 char *ext = att->name + strlen(att->name) - 4;
3858 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3859 || strcasecmp(ext, ".otf") == 0)
3860 return true;
3862 return false;
3865 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3867 if (audio_id == -1)
3868 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3869 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3870 demuxer_switch_audio(demuxer, audio_id);
3871 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3872 demuxer->audio->id = -2;
3873 demuxer->audio->sh = NULL;
3875 return demuxer->audio->id;
3878 static void print_version(const char *name)
3880 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3882 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3883 GetCpuCaps(&gCpuCaps);
3884 #if ARCH_X86
3885 mp_msg(MSGT_CPLAYER, MSGL_V,
3886 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3887 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3888 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3889 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3890 #if CONFIG_RUNTIME_CPUDETECT
3891 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3892 #else
3893 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3894 if (HAVE_MMX)
3895 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3896 if (HAVE_MMX2)
3897 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3898 if (HAVE_AMD3DNOW)
3899 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3900 if (HAVE_AMD3DNOWEXT)
3901 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3902 if (HAVE_SSE)
3903 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3904 if (HAVE_SSE2)
3905 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3906 if (HAVE_SSSE3)
3907 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3908 if (HAVE_CMOV)
3909 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3910 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3911 #endif /* CONFIG_RUNTIME_CPUDETECT */
3912 #endif /* ARCH_X86 */
3913 print_libav_versions();
3916 #ifdef PTW32_STATIC_LIB
3917 static void detach_ptw32(void)
3919 pthread_win32_thread_detach_np();
3920 pthread_win32_process_detach_np();
3922 #endif
3924 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3925 * file for some tools to link against. */
3926 #ifndef DISABLE_MAIN
3927 int main(int argc, char *argv[])
3929 #ifdef PTW32_STATIC_LIB
3930 pthread_win32_process_attach_np();
3931 pthread_win32_thread_attach_np();
3932 atexit(detach_ptw32);
3933 #endif
3934 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3935 || !strcmp(argv[1], "--leak-report")))
3936 talloc_enable_leak_report();
3938 char *mem_ptr;
3940 // movie info:
3942 /* Flag indicating whether MPlayer should exit without playing anything. */
3943 int opt_exit = 0;
3944 int i;
3946 struct MPContext *mpctx = &(struct MPContext){
3947 .osd_function = OSD_PLAY,
3948 .begin_skip = MP_NOPTS_VALUE,
3949 .play_tree_step = 1,
3950 .global_sub_pos = -1,
3951 .set_of_sub_pos = -1,
3952 .file_format = DEMUXER_TYPE_UNKNOWN,
3953 .last_dvb_step = 1,
3956 InitTimer();
3957 srand(GetTimerMS());
3959 mp_msg_init();
3960 init_libav();
3962 #ifdef CONFIG_X11
3963 mpctx->x11_state = vo_x11_init_state();
3964 #endif
3965 struct MPOpts *opts = &mpctx->opts;
3966 set_default_mplayer_options(opts);
3967 // Create the config context and register the options
3968 mpctx->mconfig = m_config_new(opts, cfg_include);
3969 m_config_register_options(mpctx->mconfig, mplayer_opts);
3970 m_config_register_options(mpctx->mconfig, common_opts);
3971 mp_input_register_options(mpctx->mconfig);
3973 // Preparse the command line
3974 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
3976 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3977 set_path_env();
3978 #endif
3980 #ifdef CONFIG_TV
3981 stream_tv_defaults.immediate = 1;
3982 #endif
3984 parse_cfgfiles(mpctx, mpctx->mconfig);
3986 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3987 if (mpctx->playtree == NULL)
3988 opt_exit = 1;
3989 else {
3990 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3991 if (mpctx->playtree) {
3992 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3993 mpctx->mconfig);
3994 if (mpctx->playtree_iter) {
3995 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3996 PLAY_TREE_ITER_ENTRY) {
3997 play_tree_iter_free(mpctx->playtree_iter);
3998 mpctx->playtree_iter = NULL;
4000 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
4006 print_version("MPlayer2");
4008 #if defined(__MINGW32__) || defined(__CYGWIN__)
4010 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
4011 BOOL WINAPI (*setDEP)(DWORD) = NULL;
4012 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
4013 if (kernel32) {
4014 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
4015 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
4017 if (setDEP)
4018 setDEP(3);
4019 if (setDllDir)
4020 setDllDir("");
4022 // stop Windows from showing all kinds of annoying error dialogs
4023 SetErrorMode(0x8003);
4024 // request 1ms timer resolution
4025 timeBeginPeriod(1);
4026 #endif
4028 #ifdef CONFIG_PRIORITY
4029 set_priority();
4030 #endif
4032 if (opts->video_driver_list &&
4033 strcmp(opts->video_driver_list[0], "help") == 0) {
4034 list_video_out();
4035 opt_exit = 1;
4038 if (opts->audio_driver_list &&
4039 strcmp(opts->audio_driver_list[0], "help") == 0) {
4040 list_audio_out();
4041 opt_exit = 1;
4044 /* Check codecs.conf. */
4045 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4046 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4047 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4048 if (!parse_codec_cfg(NULL))
4049 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4050 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4051 "Using built-in default codecs.conf.\n");
4054 free(mem_ptr); // release the buffer created by get_path()
4057 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4058 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4059 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4060 list_codecs(1);
4061 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4062 opt_exit = 1;
4064 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4065 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4066 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4067 list_codecs(0);
4068 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4069 opt_exit = 1;
4071 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4072 vfm_help();
4073 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4074 opt_exit = 1;
4076 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4077 afm_help();
4078 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4079 opt_exit = 1;
4081 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4082 af_help();
4083 printf("\n");
4084 opt_exit = 1;
4086 #ifdef CONFIG_X11
4087 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4088 fstype_help();
4089 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4090 opt_exit = 1;
4092 #endif
4093 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4094 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4095 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4096 demuxer_help();
4097 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4098 opt_exit = 1;
4100 if (opts->list_properties) {
4101 property_print_help();
4102 opt_exit = 1;
4105 if (opt_exit)
4106 exit_player(mpctx, EXIT_NONE);
4108 if (!mpctx->filename && !opts->player_idle_mode) {
4109 // no file/vcd/dvd -> show HELP:
4110 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4111 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4114 /* Display what configure line was used */
4115 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4117 // Many users forget to include command line in bugreports...
4118 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4119 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4120 for (i = 1; i < argc; i++)
4121 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4122 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4125 //------ load global data first ------
4127 mpctx->osd = osd_create();
4129 // check font
4130 #ifdef CONFIG_FREETYPE
4131 init_freetype();
4132 #endif
4133 #ifdef CONFIG_FONTCONFIG
4134 if (font_fontconfig <= 0) {
4135 #endif
4136 #ifdef CONFIG_BITMAP_FONT
4137 if (font_name) {
4138 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4139 if (!vo_font)
4140 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4141 filename_recode(font_name));
4142 } else {
4143 // try default:
4144 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4145 font_factor, verbose > 1);
4146 free(mem_ptr); // release the buffer created by get_path()
4147 if (!vo_font)
4148 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4149 font_factor, verbose > 1);
4151 if (sub_font_name)
4152 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4153 verbose > 1);
4154 else
4155 mpctx->osd->sub_font = vo_font;
4156 #endif
4157 #ifdef CONFIG_FONTCONFIG
4159 #endif
4161 #ifdef CONFIG_ASS
4162 mpctx->ass_library = mp_ass_init(opts);
4163 mpctx->osd->ass_library = mpctx->ass_library;
4164 #endif
4166 #ifdef HAVE_RTC
4167 if (opts->rtc) {
4168 char *rtc_device = opts->rtc_device;
4169 // seteuid(0); /* Can't hurt to try to get root here */
4170 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4171 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4172 "(it should be readable by the user.)\n",
4173 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4174 else {
4175 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4177 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4178 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4179 "ioctl (rtc_irqp_set %lu): %s\n",
4180 irqp, strerror(errno));
4181 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4182 close(rtc_fd);
4183 rtc_fd = -1;
4184 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4185 /* variable only by the root */
4186 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4187 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4188 close(rtc_fd);
4189 rtc_fd = -1;
4190 } else
4191 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4192 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4195 if (rtc_fd < 0)
4196 #endif /* HAVE_RTC */
4197 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4198 opts->softsleep ? "software" : timer_name);
4200 #ifdef HAVE_TERMCAP
4201 load_termcap(NULL); // load key-codes
4202 #endif
4204 // ========== Init keyboard FIFO (connection to libvo) ============
4206 // Init input system
4207 current_module = "init_input";
4208 mpctx->input = mp_input_init(&opts->input);
4209 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4210 if (slave_mode)
4211 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4212 else if (opts->consolecontrols)
4213 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4214 // Set the libstream interrupt callback
4215 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4217 current_module = NULL;
4219 /// Catch signals
4220 #ifndef __MINGW32__
4221 signal(SIGCHLD, child_sighandler);
4222 #endif
4224 #ifdef CONFIG_CRASH_DEBUG
4225 prog_path = argv[0];
4226 #endif
4227 //========= Catch terminate signals: ================
4228 // terminate requests:
4229 signal(SIGTERM, exit_sighandler); // kill
4230 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4232 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4234 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4235 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4236 #ifdef CONFIG_SIGHANDLER
4237 // fatal errors:
4238 signal(SIGBUS, exit_sighandler); // bus error
4239 signal(SIGSEGV, exit_sighandler); // segfault
4240 signal(SIGILL, exit_sighandler); // illegal instruction
4241 signal(SIGFPE, exit_sighandler); // floating point exc.
4242 signal(SIGABRT, exit_sighandler); // abort()
4243 #ifdef CONFIG_CRASH_DEBUG
4244 if (crash_debug)
4245 signal(SIGTRAP, exit_sighandler);
4246 #endif
4247 #endif
4249 // ***************** Now, let's see the per-file stuff ******************
4251 play_next_file:
4253 // init global sub numbers
4254 mpctx->global_sub_size = 0;
4255 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4257 if (mpctx->filename) {
4258 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4259 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4260 load_per_file_config(mpctx->mconfig, mpctx->filename);
4263 if (opts->video_driver_list)
4264 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4265 opts->video_driver_list[0]);
4266 if (opts->audio_driver_list)
4267 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4268 opts->audio_driver_list[0]);
4270 // We must enable getch2 here to be able to interrupt network connection
4271 // or cache filling
4272 if (opts->consolecontrols && !slave_mode) {
4273 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4274 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4275 "WARNING: getch2_init called twice!\n");
4276 else
4277 getch2_enable(); // prepare stdin for hotkeys...
4278 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4279 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4282 // ================= GUI idle loop (STOP state) =========================
4283 while (opts->player_idle_mode && !mpctx->filename) {
4284 play_tree_t *entry = NULL;
4285 mp_cmd_t *cmd;
4286 if (mpctx->video_out && mpctx->video_out->config_ok)
4287 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4288 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4289 if (mpctx->video_out)
4290 vo_check_events(mpctx->video_out);
4291 usec_sleep(20000);
4293 switch (cmd->id) {
4294 case MP_CMD_LOADFILE:
4295 // prepare a tree entry with the new filename
4296 entry = play_tree_new();
4297 play_tree_add_file(entry, cmd->args[0].v.s);
4298 // The entry is added to the main playtree after the switch().
4299 break;
4300 case MP_CMD_LOADLIST:
4301 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4302 break;
4303 case MP_CMD_QUIT:
4304 exit_player_with_rc(mpctx, EXIT_QUIT,
4305 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4306 break;
4307 case MP_CMD_VO_FULLSCREEN:
4308 case MP_CMD_GET_PROPERTY:
4309 case MP_CMD_SET_PROPERTY:
4310 case MP_CMD_STEP_PROPERTY:
4311 run_command(mpctx, cmd);
4312 break;
4315 mp_cmd_free(cmd);
4317 if (entry) { // user entered a command that gave a valid entry
4318 if (mpctx->playtree)
4319 // the playtree is always a node with one child. let's clear it
4320 play_tree_free_list(mpctx->playtree->child, 1);
4321 else
4322 // .. or make a brand new playtree
4323 mpctx->playtree = play_tree_new();
4325 if (!mpctx->playtree)
4326 continue; // couldn't make playtree! wait for next command
4328 play_tree_set_child(mpctx->playtree, entry);
4330 /* Make iterator start at the top the of tree. */
4331 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4332 mpctx->mconfig);
4333 if (!mpctx->playtree_iter)
4334 continue;
4336 // find the first real item in the tree
4337 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4338 PLAY_TREE_ITER_ENTRY) {
4339 // no items!
4340 play_tree_iter_free(mpctx->playtree_iter);
4341 mpctx->playtree_iter = NULL;
4342 continue; // wait for next command
4344 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4348 #ifdef CONFIG_ASS
4349 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4350 #endif
4351 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4352 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4354 if (mpctx->filename) {
4355 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4356 filename_recode(mpctx->filename));
4357 if (use_filename_title && opts->vo_wintitle == NULL)
4358 opts->vo_wintitle = talloc_strdup(NULL,
4359 mp_basename(mpctx->filename));
4362 if (edl_filename) {
4363 if (edl_records)
4364 free_edl(edl_records);
4365 next_edl_record = edl_records = edl_parse_file();
4367 if (edl_output_filename) {
4368 if (edl_fd)
4369 fclose(edl_fd);
4370 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4371 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4372 "Can't open EDL file [%s] for writing.\n",
4373 filename_recode(edl_output_filename));
4377 //==================== Open VOB-Sub ============================
4379 current_module = "vobsub";
4380 if (opts->vobsub_name) {
4381 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4382 if (vo_vobsub == NULL)
4383 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4384 filename_recode(opts->vobsub_name));
4385 } else if (opts->sub_auto && mpctx->filename) {
4386 char **vob = find_vob_subtitles(opts, mpctx->filename);
4387 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4388 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4389 if (vo_vobsub)
4390 break;
4392 talloc_free(vob);
4394 if (vo_vobsub) {
4395 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4396 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4397 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4398 mpctx);
4400 // setup global sub numbering
4401 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4402 vobsub_get_indexes_count(vo_vobsub);
4405 //============ Open & Sync STREAM --- fork cache2 ====================
4407 mpctx->stream = NULL;
4408 mpctx->demuxer = NULL;
4409 mpctx->d_audio = NULL;
4410 mpctx->d_video = NULL;
4411 mpctx->d_sub = NULL;
4412 mpctx->sh_audio = NULL;
4413 mpctx->sh_video = NULL;
4415 current_module = "open_stream";
4416 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4417 if (!mpctx->stream) { // error...
4418 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4419 goto goto_next_file;
4421 mpctx->initialized_flags |= INITIALIZED_STREAM;
4423 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4424 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4425 "playlist support will not be used automatically.\n"
4426 "MPlayer's playlist code is unsafe and should only be used with "
4427 "trusted sources.\nPlayback will probably fail.\n\n");
4428 #if 0
4429 play_tree_t *entry;
4430 // Handle playlist
4431 current_module = "handle_playlist";
4432 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4433 filename_recode(mpctx->filename));
4434 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4435 mpctx->eof = playtree_add_playlist(mpctx, entry);
4436 goto goto_next_file;
4437 #endif
4439 mpctx->stream->start_pos += seek_to_byte;
4441 if (stream_dump_type == 5) {
4442 unsigned char buf[4096];
4443 int len;
4444 FILE *f;
4445 current_module = "dumpstream";
4446 stream_reset(mpctx->stream);
4447 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4448 f = fopen(opts->stream_dump_name, "wb");
4449 if (!f) {
4450 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4451 exit_player(mpctx, EXIT_ERROR);
4453 if (opts->chapterrange[0] > 1) {
4454 int chapter = opts->chapterrange[0] - 1;
4455 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4457 struct stream_dump_progress info;
4458 stream_dump_progress_start(&info);
4459 while (!mpctx->stream->eof && !async_quit_request) {
4460 len = stream_read(mpctx->stream, buf, 4096);
4461 if (len > 0) {
4462 if (fwrite(buf, len, 1, f) != 1) {
4463 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4464 exit_player(mpctx, EXIT_ERROR);
4467 stream_dump_progress(&info, len, mpctx->stream);
4468 if (opts->chapterrange[1] > 0) {
4469 int chapter = -1;
4470 if (stream_control(mpctx->stream,
4471 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4472 && chapter + 1 > opts->chapterrange[1])
4473 break;
4476 if (fclose(f)) {
4477 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4478 opts->stream_dump_name);
4479 exit_player(mpctx, EXIT_ERROR);
4481 stream_dump_progress_end(&info, opts->stream_dump_name);
4482 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4483 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4486 #ifdef CONFIG_DVDREAD
4487 if (mpctx->stream->type == STREAMTYPE_DVD) {
4488 current_module = "dvd lang->id";
4489 if (opts->audio_lang && opts->audio_id == -1)
4490 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4491 if (opts->sub_lang && opts->sub_id == -1)
4492 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4493 // setup global sub numbering
4494 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4495 current_module = NULL;
4497 #endif
4499 #ifdef CONFIG_DVDNAV
4500 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4501 current_module = "dvdnav lang->id";
4502 if (opts->audio_lang && opts->audio_id == -1)
4503 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4504 opts->audio_lang);
4505 dvdsub_lang_id = -3;
4506 if (opts->sub_lang && opts->sub_id == -1)
4507 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4508 mpctx->stream, opts->sub_lang);
4509 // setup global sub numbering
4510 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4511 mpctx->stream);
4512 current_module = NULL;
4514 #endif
4516 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4517 goto_enable_cache:
4518 if (stream_cache_size > 0) {
4519 int res;
4520 float stream_cache_min_percent = opts->stream_cache_min_percent;
4521 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4522 current_module = "enable_cache";
4523 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4524 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4525 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4526 if (res == 0)
4527 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4528 goto goto_next_file;
4531 //============ Open DEMUXERS --- DETECT file type =======================
4532 current_module = "demux_open";
4534 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4535 opts->audio_id, opts->video_id, opts->sub_id,
4536 mpctx->filename);
4538 // HACK to get MOV Reference Files working
4540 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4541 unsigned char *playlist_entry;
4542 play_tree_t *list = NULL, *entry = NULL;
4544 current_module = "handle_demux_playlist";
4545 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4546 char *temp;
4547 const char *bname;
4549 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4550 filename_recode(playlist_entry));
4552 bname = mp_basename(playlist_entry);
4553 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4554 !strncmp(bname + 3, "gateQT", 6))
4555 continue;
4557 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4558 continue;
4560 entry = play_tree_new();
4562 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4563 playlist_entry)) { // add reference path of current file
4564 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4565 mpctx->filename)) + strlen(playlist_entry) + 1));
4566 if (temp) {
4567 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4568 strlen(mp_basename(mpctx->filename)));
4569 temp[strlen(mpctx->filename) - strlen(mp_basename(
4570 mpctx->filename))] = '\0';
4571 strcat(temp, playlist_entry);
4572 if (!strcmp(temp, mpctx->filename)) {
4573 free(temp);
4574 continue;
4576 play_tree_add_file(entry, temp);
4577 mp_msg(MSGT_CPLAYER, MSGL_V,
4578 "Resolving reference to %s.\n", temp);
4579 free(temp);
4581 } else
4582 play_tree_add_file(entry, playlist_entry);
4584 if (!list)
4585 list = entry;
4586 else
4587 play_tree_append_entry(list, entry);
4589 free_demuxer(mpctx->demuxer);
4590 mpctx->demuxer = NULL;
4592 if (list) {
4593 entry = play_tree_new();
4594 play_tree_set_child(entry, list);
4595 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4596 goto goto_next_file;
4600 if (!mpctx->demuxer) {
4601 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4602 goto goto_next_file;
4605 if (mpctx->demuxer->matroska_data.ordered_chapters)
4606 build_ordered_chapter_timeline(mpctx);
4608 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4609 build_edl_timeline(mpctx);
4611 if (mpctx->timeline) {
4612 mpctx->timeline_part = 0;
4613 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4615 int part_count = mpctx->num_timeline_parts;
4616 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4617 "sources. Total length %.3f seconds.\n", part_count,
4618 mpctx->num_sources, mpctx->timeline[part_count].start);
4619 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4620 for (int i = 0; i < mpctx->num_sources; i++)
4621 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4622 filename_recode(mpctx->sources[i].demuxer->filename));
4623 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4624 "source_start, source):\n");
4625 for (int i = 0; i < part_count; i++) {
4626 struct timeline_part *p = mpctx->timeline + i;
4627 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4628 p->source_start, p->source - mpctx->sources);
4630 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4631 mpctx->timeline[part_count].start);
4634 if (!mpctx->sources) {
4635 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4636 *mpctx->sources = (struct content_source){
4637 .stream = mpctx->stream,
4638 .demuxer = mpctx->demuxer
4640 mpctx->num_sources = 1;
4643 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4645 #ifdef CONFIG_ASS
4646 if (opts->ass_enabled && mpctx->ass_library) {
4647 for (int j = 0; j < mpctx->num_sources; j++) {
4648 struct demuxer *d = mpctx->sources[j].demuxer;
4649 for (int i = 0; i < d->num_attachments; i++) {
4650 struct demux_attachment *att = d->attachments + i;
4651 if (opts->use_embedded_fonts && attachment_is_font(att))
4652 ass_add_font(mpctx->ass_library, att->name, att->data,
4653 att->data_size);
4657 #endif
4659 current_module = "demux_open2";
4661 mpctx->d_audio = mpctx->demuxer->audio;
4662 mpctx->d_video = mpctx->demuxer->video;
4663 mpctx->d_sub = mpctx->demuxer->sub;
4665 if (ts_prog) {
4666 int tmp = ts_prog;
4667 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4669 // select audio stream
4670 for (int i = 0; i < mpctx->num_sources; i++)
4671 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4672 opts->audio_lang);
4674 // DUMP STREAMS:
4675 if ((stream_dump_type) && (stream_dump_type < 4)) {
4676 FILE *f;
4677 demux_stream_t *ds = NULL;
4678 current_module = "dump";
4679 // select stream to dump
4680 switch (stream_dump_type) {
4681 case 1: ds = mpctx->d_audio;
4682 break;
4683 case 2: ds = mpctx->d_video;
4684 break;
4685 case 3: ds = mpctx->d_sub;
4686 break;
4688 if (!ds) {
4689 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4690 "dump: FATAL: Selected stream missing!\n");
4691 exit_player(mpctx, EXIT_ERROR);
4693 // disable other streams:
4694 if (mpctx->d_audio && mpctx->d_audio != ds) {
4695 ds_free_packs(mpctx->d_audio);
4696 mpctx->d_audio->id = -2;
4698 if (mpctx->d_video && mpctx->d_video != ds) {
4699 ds_free_packs(mpctx->d_video);
4700 mpctx->d_video->id = -2;
4702 if (mpctx->d_sub && mpctx->d_sub != ds) {
4703 ds_free_packs(mpctx->d_sub);
4704 mpctx->d_sub->id = -2;
4706 // let's dump it!
4707 f = fopen(opts->stream_dump_name, "wb");
4708 if (!f) {
4709 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4710 exit_player(mpctx, EXIT_ERROR);
4712 struct stream_dump_progress info;
4713 stream_dump_progress_start(&info);
4714 while (!ds->eof) {
4715 unsigned char *start;
4716 int in_size = ds_get_packet(ds, &start);
4717 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4718 && stream_dump_type == 2)
4719 fwrite(&in_size, 1, 4, f);
4720 if (in_size > 0) {
4721 fwrite(start, in_size, 1, f);
4722 stream_dump_progress(&info, in_size, mpctx->stream);
4724 if (opts->chapterrange[1] > 0) {
4725 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4726 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4727 break;
4730 fclose(f);
4731 stream_dump_progress_end(&info, opts->stream_dump_name);
4732 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4733 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4736 mpctx->sh_audio = mpctx->d_audio->sh;
4737 mpctx->sh_video = mpctx->d_video->sh;
4739 if (mpctx->sh_video) {
4740 current_module = "video_read_properties";
4741 if (!video_read_properties(mpctx->sh_video)) {
4742 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4743 mpctx->sh_video = mpctx->d_video->sh = NULL;
4744 } else {
4745 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4746 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4747 mpctx->demuxer->file_format, mpctx->sh_video->format,
4748 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4749 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4750 if (force_fps) {
4751 mpctx->sh_video->fps = force_fps;
4752 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4754 vo_fps = mpctx->sh_video->fps;
4756 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4757 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4758 "header or invalid, use the -fps option.\n");
4764 if (!mpctx->sh_video && !mpctx->sh_audio) {
4765 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4766 #ifdef CONFIG_DVBIN
4767 if (mpctx->stream->type == STREAMTYPE_DVB) {
4768 int dir;
4769 int v = mpctx->last_dvb_step;
4770 if (v > 0)
4771 dir = DVB_CHANNEL_HIGHER;
4772 else
4773 dir = DVB_CHANNEL_LOWER;
4775 if (dvb_step_channel(mpctx->stream, dir)) {
4776 mpctx->stop_play = PT_NEXT_ENTRY;
4777 mpctx->dvbin_reopen = 1;
4780 #endif
4781 goto goto_next_file; // exit_player(_("Fatal error"));
4784 /* display clip info */
4785 demux_info_print(mpctx->demuxer);
4787 //================= Read SUBTITLES (DVD & TEXT) =========================
4788 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4789 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4790 init_vo_spudec(mpctx);
4792 // after reading video params we should load subtitles because
4793 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4794 // check .sub
4795 current_module = "read_subtitles_file";
4796 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4797 if (opts->sub_name) {
4798 for (i = 0; opts->sub_name[i] != NULL; ++i)
4799 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4801 if (opts->sub_auto) { // auto load sub file ...
4802 char **tmp = find_text_subtitles(opts, mpctx->filename);
4803 int nsub = MP_TALLOC_ELEMS(tmp);
4804 for (int i = 0; i < nsub; i++)
4805 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4806 talloc_free(tmp);
4808 if (mpctx->set_of_sub_size > 0)
4809 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4811 if (select_subtitle(mpctx)) {
4812 if (mpctx->subdata)
4813 switch (stream_dump_type) {
4814 case 3: list_sub_file(mpctx->subdata);
4815 break;
4816 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4817 break;
4818 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4819 break;
4820 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4821 break;
4822 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4823 break;
4824 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4825 break;
4829 print_file_properties(mpctx, mpctx->filename);
4831 reinit_video_chain(mpctx);
4832 if (mpctx->sh_video) {
4833 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4834 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4835 #ifdef CONFIG_FREETYPE
4836 force_load_font = 1;
4837 #endif
4838 } else if (!mpctx->sh_audio)
4839 goto goto_next_file;
4841 //================== MAIN: ==========================
4842 current_module = "main";
4844 if (opts->playing_msg) {
4845 char *msg = property_expand_string(mpctx, opts->playing_msg);
4846 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4847 free(msg);
4851 // Disable the term OSD in verbose mode
4852 if (verbose)
4853 opts->term_osd = 0;
4855 // Make sure old OSD does not stay around,
4856 // e.g. with -fixed-vo and same-resolution files
4857 clear_osd_msgs();
4858 update_osd_msg(mpctx);
4860 //================ SETUP AUDIO ==========================
4862 if (mpctx->sh_audio) {
4863 reinit_audio_chain(mpctx);
4864 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4865 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4866 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4869 current_module = "av_init";
4871 if (mpctx->sh_video) {
4872 mpctx->sh_video->timer = 0;
4873 if (!ignore_start)
4874 audio_delay += mpctx->sh_video->stream_delay;
4876 if (mpctx->sh_audio) {
4877 if (start_volume >= 0)
4878 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4879 if (!ignore_start)
4880 audio_delay -= mpctx->sh_audio->stream_delay;
4881 mpctx->delay = -audio_delay;
4884 if (!mpctx->sh_audio) {
4885 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4886 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4887 mpctx->d_audio->packs);
4888 ds_free_packs(mpctx->d_audio); // free buffered chunks
4890 if (!mpctx->sh_video) {
4891 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4892 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4893 mpctx->d_video->packs);
4894 ds_free_packs(mpctx->d_video);
4895 mpctx->d_video->id = -2;
4898 if (!mpctx->sh_video && !mpctx->sh_audio)
4899 goto goto_next_file;
4901 if (force_fps && mpctx->sh_video) {
4902 vo_fps = mpctx->sh_video->fps = force_fps;
4903 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4904 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4905 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4906 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4909 mp_input_set_section(mpctx->input, NULL);
4910 //TODO: add desired (stream-based) sections here
4911 if (mpctx->stream->type == STREAMTYPE_TV)
4912 mp_input_set_section(mpctx->input, "tv");
4913 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4914 mp_input_set_section(mpctx->input, "dvdnav");
4916 //==================== START PLAYING =======================
4918 if (opts->loop_times > 1)
4919 opts->loop_times--;
4920 else if (opts->loop_times == 1)
4921 opts->loop_times = -1;
4923 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4925 total_time_usage_start = GetTimer();
4926 audio_time_usage = 0;
4927 video_time_usage = 0;
4928 vout_time_usage = 0;
4929 total_frame_cnt = 0;
4930 drop_frame_cnt = 0; // fix for multifile fps benchmark
4931 play_n_frames = play_n_frames_mf;
4933 if (play_n_frames == 0) {
4934 mpctx->stop_play = PT_NEXT_ENTRY;
4935 goto goto_next_file;
4938 mpctx->time_frame = 0;
4939 mpctx->drop_message_shown = 0;
4940 mpctx->restart_playback = true;
4941 mpctx->video_pts = 0;
4942 mpctx->last_seek_pts = 0;
4943 mpctx->hrseek_active = false;
4944 mpctx->hrseek_framedrop = false;
4945 mpctx->step_frames = 0;
4946 mpctx->total_avsync_change = 0;
4947 mpctx->last_chapter_seek = -2;
4949 // If there's a timeline force an absolute seek to initialize state
4950 if (opts->seek_to_sec || mpctx->timeline) {
4951 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4952 seek(mpctx, mpctx->seek, false);
4953 end_at.pos += opts->seek_to_sec;
4955 if (opts->chapterrange[0] > 0) {
4956 double pts;
4957 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4958 && pts > -1.0) {
4959 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4960 seek(mpctx, mpctx->seek, false);
4964 if (end_at.type == END_AT_SIZE) {
4965 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4966 "Option -endpos in MPlayer does not yet support size units.\n");
4967 end_at.type = END_AT_NONE;
4970 #ifdef CONFIG_DVDNAV
4971 mp_dvdnav_context_free(mpctx);
4972 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4973 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4974 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4976 #endif
4978 mpctx->seek = (struct seek_params){ 0 };
4979 get_relative_time(mpctx); // reset current delta
4980 // Make sure VO knows current pause state
4981 if (mpctx->sh_video)
4982 vo_control(mpctx->video_out,
4983 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4985 while (!mpctx->stop_play)
4986 run_playloop(mpctx);
4988 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4990 #ifdef CONFIG_DVBIN
4991 if (mpctx->dvbin_reopen) {
4992 mpctx->stop_play = 0;
4993 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4994 cache_uninit(mpctx->stream);
4995 mpctx->dvbin_reopen = 0;
4996 goto goto_enable_cache;
4998 #endif
5000 goto_next_file: // don't jump here after ao/vo/getch initialization!
5002 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
5004 if (opts->benchmark) {
5005 double tot = video_time_usage + vout_time_usage + audio_time_usage;
5006 double total_time_usage;
5007 total_time_usage_start = GetTimer() - total_time_usage_start;
5008 total_time_usage = (float)total_time_usage_start * 0.000001;
5009 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
5010 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
5011 video_time_usage, vout_time_usage, audio_time_usage,
5012 total_time_usage - tot, total_time_usage);
5013 if (total_time_usage > 0.0)
5014 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
5015 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
5016 100.0 * video_time_usage / total_time_usage,
5017 100.0 * vout_time_usage / total_time_usage,
5018 100.0 * audio_time_usage / total_time_usage,
5019 100.0 * (total_time_usage - tot) / total_time_usage,
5020 100.0);
5021 if (total_frame_cnt && frame_dropping)
5022 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
5023 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
5024 total_frame_cnt - drop_frame_cnt,
5025 (total_time_usage > 0.5) ? ((total_frame_cnt -
5026 drop_frame_cnt) / total_time_usage) : 0,
5027 drop_frame_cnt,
5028 100 * drop_frame_cnt / total_frame_cnt,
5029 total_frame_cnt,
5030 (total_time_usage > 0.5) ?
5031 (total_frame_cnt / total_time_usage) : 0);
5034 // time to uninit all, except global stuff:
5035 int uninitialize_parts = INITIALIZED_ALL;
5036 if (opts->fixed_vo)
5037 uninitialize_parts -= INITIALIZED_VO;
5038 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
5039 uninitialize_parts -= INITIALIZED_AO;
5040 uninit_player(mpctx, uninitialize_parts);
5042 if (mpctx->set_of_sub_size > 0) {
5043 current_module = "sub_free";
5044 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5045 sub_free(mpctx->set_of_subtitles[i]);
5046 #ifdef CONFIG_ASS
5047 if (mpctx->set_of_ass_tracks[i])
5048 ass_free_track(mpctx->set_of_ass_tracks[i]);
5049 #endif
5051 mpctx->set_of_sub_size = 0;
5053 mpctx->vo_sub_last = vo_sub = NULL;
5054 mpctx->subdata = NULL;
5055 #ifdef CONFIG_ASS
5056 mpctx->osd->ass_track = NULL;
5057 if (mpctx->ass_library)
5058 ass_clear_fonts(mpctx->ass_library);
5059 #endif
5061 if (!mpctx->stop_play) // In case some goto jumped here...
5062 mpctx->stop_play = PT_NEXT_ENTRY;
5064 int playtree_direction = 1;
5066 if (mpctx->stop_play == PT_NEXT_ENTRY
5067 || mpctx->stop_play == PT_PREV_ENTRY) {
5068 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5069 != PLAY_TREE_ITER_ENTRY) {
5070 play_tree_iter_free(mpctx->playtree_iter);
5071 mpctx->playtree_iter = NULL;
5073 mpctx->play_tree_step = 1;
5074 } else if (mpctx->stop_play == PT_UP_NEXT ||
5075 mpctx->stop_play == PT_UP_PREV) {
5076 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5077 if (mpctx->playtree_iter) {
5078 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5079 PLAY_TREE_ITER_ENTRY) {
5080 play_tree_iter_free(mpctx->playtree_iter);
5081 mpctx->playtree_iter = NULL;
5084 } else if (mpctx->stop_play == PT_STOP) {
5085 play_tree_iter_free(mpctx->playtree_iter);
5086 mpctx->playtree_iter = NULL;
5087 } else // NEXT PREV SRC
5088 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5090 while (mpctx->playtree_iter != NULL) {
5091 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5092 playtree_direction);
5093 if (mpctx->filename == NULL) {
5094 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5095 0) != PLAY_TREE_ITER_ENTRY) {
5096 play_tree_iter_free(mpctx->playtree_iter);
5097 mpctx->playtree_iter = NULL;
5100 } else
5101 break;
5104 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5105 if (!mpctx->playtree_iter)
5106 mpctx->filename = NULL;
5107 mpctx->stop_play = 0;
5108 goto play_next_file;
5111 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5113 return 1;
5115 #endif /* DISABLE_MAIN */