options, x11+cocoa: add option --cursor-autohide-delay
[mplayer.git] / mplayer.c
blob4f7027ec7946a08767e7404ac2f1876e4faa408a
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stdbool.h>
22 #include <math.h>
23 #include <assert.h>
25 #include <libavutil/intreadwrite.h>
27 #include "config.h"
28 #include "talloc.h"
30 #include "osdep/io.h"
32 #if defined(__MINGW32__) || defined(__CYGWIN__)
33 #include <windows.h>
34 #endif
35 #include <string.h>
36 #include <unistd.h>
38 // #include <sys/mman.h>
39 #include <sys/types.h>
40 #ifndef __MINGW32__
41 #include <sys/ioctl.h>
42 #include <sys/wait.h>
43 #else
44 #define SIGHUP 1 /* hangup */
45 #define SIGQUIT 3 /* quit */
46 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
47 #define SIGBUS 10 /* bus error */
48 #define SIGPIPE 13 /* broken pipe */
49 #endif
51 #include <sys/time.h>
52 #include <sys/stat.h>
54 #include <signal.h>
55 #include <time.h>
56 #include <fcntl.h>
57 #include <limits.h>
59 #include <errno.h>
61 #include "mp_msg.h"
62 #include "av_log.h"
65 #include "m_option.h"
66 #include "m_config.h"
67 #include "mplayer.h"
68 #include "m_property.h"
70 #include "sub/subreader.h"
71 #include "sub/find_subfiles.h"
72 #include "sub/dec_sub.h"
74 #include "mp_osd.h"
75 #include "libvo/video_out.h"
76 #include "screenshot.h"
78 #include "sub/font_load.h"
79 #include "sub/sub.h"
80 #include "sub/av_sub.h"
81 #include "libmpcodecs/dec_teletext.h"
82 #include "cpudetect.h"
83 #include "version.h"
85 #ifdef CONFIG_X11
86 #include "libvo/x11_common.h"
87 #endif
89 #include "libao2/audio_out.h"
91 #include "codec-cfg.h"
93 #include "sub/spudec.h"
94 #include "sub/vobsub.h"
96 #include "osdep/getch2.h"
97 #include "osdep/timer.h"
99 #include "input/input.h"
101 int slave_mode = 0;
102 int enable_mouse_movements = 0;
103 float start_volume = -1;
105 #include "osdep/priority.h"
107 char *heartbeat_cmd;
109 #ifdef HAVE_RTC
110 #ifdef __linux__
111 #include <linux/rtc.h>
112 #else
113 #include <rtc.h>
114 #define RTC_IRQP_SET RTCIO_IRQP_SET
115 #define RTC_PIE_ON RTCIO_PIE_ON
116 #endif /* __linux__ */
117 #endif /* HAVE_RTC */
119 #include "stream/tv.h"
120 #include "stream/stream_radio.h"
121 #ifdef CONFIG_DVBIN
122 #include "stream/dvbin.h"
123 #endif
124 #include "stream/cache2.h"
126 //**************************************************************************//
127 // Playtree
128 //**************************************************************************//
129 #include "playtree.h"
130 #include "playtreeparser.h"
132 //**************************************************************************//
133 // Config
134 //**************************************************************************//
135 #include "parser-cfg.h"
136 #include "parser-mpcmd.h"
138 //**************************************************************************//
139 // Config file
140 //**************************************************************************//
142 static int cfg_inc_verbose(m_option_t *conf)
144 ++verbose;
145 return 0;
148 #include "path.h"
150 //**************************************************************************//
151 //**************************************************************************//
152 // Input media streaming & demultiplexer:
153 //**************************************************************************//
155 static int max_framesize = 0;
157 #include "stream/stream.h"
158 #include "libmpdemux/demuxer.h"
159 #include "libmpdemux/stheader.h"
161 #ifdef CONFIG_DVDREAD
162 #include "stream/stream_dvd.h"
163 #endif
164 #include "stream/stream_dvdnav.h"
166 #include "libmpcodecs/dec_audio.h"
167 #include "libmpcodecs/dec_video.h"
168 #include "libmpcodecs/mp_image.h"
169 #include "libmpcodecs/vf.h"
170 #include "libmpcodecs/vd.h"
172 #include "mixer.h"
174 #include "mp_core.h"
175 #include "options.h"
176 #include "defaultopts.h"
178 static const char help_text[] = _(
179 "Usage: mplayer [options] [url|path/]filename\n"
180 "\n"
181 "Basic options: (complete list in the man page)\n"
182 " -vo <drv> select video output driver ('-vo help' for a list)\n"
183 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
184 #ifdef CONFIG_VCD
185 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
186 #endif
187 #ifdef CONFIG_DVDREAD
188 " dvd://<titleno> play DVD title from device instead of plain file\n"
189 #endif
190 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
191 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
192 " -nosound do not play sound\n"
193 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
194 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
195 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
196 " -playlist <file> specify playlist file\n"
197 " -vid x -aid y select video (x) and audio (y) stream to play\n"
198 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
199 " -pp <quality> enable postprocessing filter (details in the man page)\n"
200 " -framedrop enable frame dropping (for slow machines)\n"
201 "\n"
202 "Basic keys: (complete list in the man page, also check input.conf)\n"
203 " <- or -> seek backward/forward 10 seconds\n"
204 " down or up seek backward/forward 1 minute\n"
205 " pgdown or pgup seek backward/forward 10 minutes\n"
206 " < or > step backward/forward in playlist\n"
207 " p or SPACE pause movie (press any key to continue)\n"
208 " q or ESC stop playing and quit program\n"
209 " + or - adjust audio delay by +/- 0.1 second\n"
210 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
211 " * or / increase or decrease PCM volume\n"
212 " x or z adjust subtitle delay by +/- 0.1 second\n"
213 " r or t adjust subtitle position up/down, also see -vf expand\n"
214 " double click toggle fullscreen\n"
215 " right click pause (press again to continue)\n"
216 "\n"
217 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
218 "\n");
221 #define Exit_SIGILL_RTCpuSel _(\
222 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
223 " It may be a bug in our new runtime CPU-detection code...\n"\
224 " Please read DOCS/HTML/en/bugreports.html.\n")
226 #define Exit_SIGILL _(\
227 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
228 " It usually happens when you run it on a CPU different than the one it was\n"\
229 " compiled/optimized for.\n"\
230 " Verify this!\n")
232 #define Exit_SIGSEGV_SIGFPE _(\
233 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
234 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
235 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
237 #define Exit_SIGCRASH _(\
238 "- MPlayer crashed. This shouldn't happen.\n"\
239 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
240 " gcc version. If you think it's MPlayer's fault, please read\n"\
241 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
242 " won't help unless you provide this information when reporting a possible bug.\n")
244 #define SystemTooSlow _("\n\n"\
245 " ************************************************\n"\
246 " **** Your system is too SLOW to play this! ****\n"\
247 " ************************************************\n\n"\
248 "Possible reasons, problems, workarounds:\n"\
249 "- Most common: broken/buggy _audio_ driver\n"\
250 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
251 " - Experiment with different values for -autosync, 30 is a good start.\n"\
252 "- Slow video output\n"\
253 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
254 "- Slow CPU\n"\
255 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
256 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
257 "- Broken file\n"\
258 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
259 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
260 " - Try -cache 8192.\n"\
261 "- Are you using -cache to play a non-interleaved AVI file?\n"\
262 " - Try -nocache.\n"\
263 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
264 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
267 //**************************************************************************//
268 //**************************************************************************//
270 #include "mp_fifo.h"
272 // benchmark:
273 double video_time_usage;
274 double vout_time_usage;
275 static double audio_time_usage;
276 static int total_time_usage_start;
277 static int total_frame_cnt;
278 static int drop_frame_cnt; // total number of dropped frames
280 // options:
281 static int output_quality;
283 // seek:
284 static off_t seek_to_byte;
285 static off_t step_sec;
287 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
289 // codecs:
290 char **audio_codec_list; // override audio codec
291 char **video_codec_list; // override video codec
292 char **audio_fm_list; // override audio codec family
293 char **video_fm_list; // override video codec family
295 // this dvdsub_id was selected via slang
296 // use this to allow dvdnav to follow -slang across stream resets,
297 // in particular the subtitle ID for a language changes
298 int dvdsub_lang_id;
299 int vobsub_id = -1;
300 static char *spudec_ifo = NULL;
301 int forced_subs_only = 0;
303 // cache2:
304 int stream_cache_size = -1;
306 // dump:
307 int stream_dump_type = 0;
309 // A-V sync:
310 static float default_max_pts_correction = -1;
311 float audio_delay = 0;
312 static int ignore_start = 0;
314 double force_fps = 0;
315 static int force_srate = 0;
316 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
317 static int play_n_frames = -1;
318 static int play_n_frames_mf = -1;
320 // sub:
321 char *font_name = NULL;
322 char *sub_font_name = NULL;
323 extern int font_fontconfig;
324 float font_factor = 0.75;
325 float sub_delay = 0;
326 float sub_fps = 0;
327 int subcc_enabled = 0;
328 int suboverlap_enabled = 1;
330 #include "sub/ass_mp.h"
332 char *current_module; // for debugging
335 // ---
337 FILE *edl_fd; // file to write to when in -edlout mode.
338 char *edl_output_filename; // file to put EDL entries in (-edlout)
340 int use_filedir_conf;
341 int use_filename_title;
343 #include "mpcommon.h"
344 #include "command.h"
346 #include "metadata.h"
348 static float get_relative_time(struct MPContext *mpctx)
350 unsigned int new_time = GetTimer();
351 unsigned int delta = new_time - mpctx->last_time;
352 mpctx->last_time = new_time;
353 return delta * 0.000001;
356 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
358 switch (type) {
359 /* check for valid video stream */
360 case META_VIDEO_CODEC:
361 case META_VIDEO_BITRATE:
362 case META_VIDEO_RESOLUTION:
363 if (!mpctx->sh_video)
364 return 0;
365 break;
367 /* check for valid audio stream */
368 case META_AUDIO_CODEC:
369 case META_AUDIO_BITRATE:
370 case META_AUDIO_SAMPLES:
371 if (!mpctx->sh_audio)
372 return 0;
373 break;
375 /* check for valid demuxer */
376 case META_INFO_TITLE:
377 case META_INFO_ARTIST:
378 case META_INFO_ALBUM:
379 case META_INFO_YEAR:
380 case META_INFO_COMMENT:
381 case META_INFO_TRACK:
382 case META_INFO_GENRE:
383 if (!mpctx->demuxer)
384 return 0;
385 break;
387 default:
388 break;
391 return 1;
394 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
396 char **info = mpctx->demuxer->info;
397 int n;
399 if (!info || !tag)
400 return talloc_strdup(NULL, "");
402 for (n = 0; info[2 * n] != NULL; n++)
403 if (!strcasecmp(info[2 * n], tag))
404 break;
406 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
409 char *get_metadata(struct MPContext *mpctx, metadata_t type)
411 sh_audio_t * const sh_audio = mpctx->sh_audio;
412 sh_video_t * const sh_video = mpctx->sh_video;
414 if (!is_valid_metadata_type(mpctx, type))
415 return NULL;
417 switch (type) {
418 case META_NAME:
419 return talloc_strdup(NULL, mp_basename(mpctx->filename));
420 case META_VIDEO_CODEC:
421 if (sh_video->format == 0x10000001)
422 return talloc_strdup(NULL, "mpeg1");
423 else if (sh_video->format == 0x10000002)
424 return talloc_strdup(NULL, "mpeg2");
425 else if (sh_video->format == 0x10000004)
426 return talloc_strdup(NULL, "mpeg4");
427 else if (sh_video->format == 0x10000005)
428 return talloc_strdup(NULL, "h264");
429 else if (sh_video->format >= 0x20202020)
430 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
431 else
432 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
433 case META_VIDEO_BITRATE:
434 return talloc_asprintf(NULL, "%d kbps",
435 (int) (sh_video->i_bps * 8 / 1024));
436 case META_VIDEO_RESOLUTION:
437 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
438 sh_video->disp_h);
439 case META_AUDIO_CODEC:
440 if (sh_audio->codec && sh_audio->codec->name)
441 return talloc_strdup(NULL, sh_audio->codec->name);
442 return talloc_strdup(NULL, "");
443 case META_AUDIO_BITRATE:
444 return talloc_asprintf(NULL, "%d kbps",
445 (int) (sh_audio->i_bps * 8 / 1000));
446 case META_AUDIO_SAMPLES:
447 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
448 sh_audio->channels);
450 /* check for valid demuxer */
451 case META_INFO_TITLE:
452 return get_demuxer_info(mpctx, "Title");
454 case META_INFO_ARTIST:
455 return get_demuxer_info(mpctx, "Artist");
457 case META_INFO_ALBUM:
458 return get_demuxer_info(mpctx, "Album");
460 case META_INFO_YEAR:
461 return get_demuxer_info(mpctx, "Year");
463 case META_INFO_COMMENT:
464 return get_demuxer_info(mpctx, "Comment");
466 case META_INFO_TRACK:
467 return get_demuxer_info(mpctx, "Track");
469 case META_INFO_GENRE:
470 return get_demuxer_info(mpctx, "Genre");
472 default:
473 break;
476 return talloc_strdup(NULL, "");
479 static void print_file_properties(struct MPContext *mpctx, const char *filename)
481 double start_pts = MP_NOPTS_VALUE;
482 double video_start_pts = MP_NOPTS_VALUE;
483 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
484 filename_recode(filename));
485 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
486 mpctx->demuxer->desc->name);
487 if (mpctx->sh_video) {
488 /* Assume FOURCC if all bytes >= 0x20 (' ') */
489 if (mpctx->sh_video->format >= 0x20202020)
490 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
491 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
492 else
493 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
494 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
495 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
496 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
497 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
498 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
499 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
500 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
501 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
502 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
503 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
504 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
505 video_start_pts = ds_get_next_pts(mpctx->d_video);
507 if (mpctx->sh_audio) {
508 /* Assume FOURCC if all bytes >= 0x20 (' ') */
509 if (mpctx->sh_audio->format >= 0x20202020)
510 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
511 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
512 else
513 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
514 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
515 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
516 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
517 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
518 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
519 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
520 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
521 start_pts = ds_get_next_pts(mpctx->d_audio);
523 if (video_start_pts != MP_NOPTS_VALUE) {
524 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
525 (mpctx->sh_video && video_start_pts < start_pts))
526 start_pts = video_start_pts;
528 if (start_pts != MP_NOPTS_VALUE)
529 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
530 else
531 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
532 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
533 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
534 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
535 mpctx->stream->seek
536 && (!mpctx->demuxer || mpctx->demuxer->seekable));
537 if (mpctx->demuxer) {
538 int chapter_count = get_chapter_count(mpctx);
539 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
540 for (int i = 0; i < chapter_count; i++) {
541 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
542 // in milliseconds
543 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
544 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
545 char *name = chapter_name(mpctx, i);
546 if (name) {
547 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
548 name);
549 talloc_free(name);
555 /// step size of mixer changes
556 int volstep = 3;
558 #ifdef CONFIG_DVDNAV
559 static void mp_dvdnav_context_free(MPContext *ctx)
561 if (ctx->nav_smpi)
562 free_mp_image(ctx->nav_smpi);
563 ctx->nav_smpi = NULL;
564 free(ctx->nav_buffer);
565 ctx->nav_buffer = NULL;
566 ctx->nav_start = NULL;
567 ctx->nav_in_size = 0;
569 #endif
571 static void uninit_subs(struct demuxer *demuxer)
573 for (int i = 0; i < MAX_S_STREAMS; i++) {
574 struct sh_sub *sh = demuxer->s_streams[i];
575 if (sh && sh->initialized)
576 sub_uninit(sh);
580 void uninit_player(struct MPContext *mpctx, unsigned int mask)
582 mask &= mpctx->initialized_flags;
584 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
586 if (mask & INITIALIZED_ACODEC) {
587 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
588 current_module = "uninit_acodec";
589 if (mpctx->sh_audio)
590 uninit_audio(mpctx->sh_audio);
591 mpctx->sh_audio = NULL;
592 mpctx->mixer.afilter = NULL;
595 if (mask & INITIALIZED_SUB) {
596 mpctx->initialized_flags &= ~INITIALIZED_SUB;
597 if (mpctx->d_sub->sh)
598 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
601 if (mask & INITIALIZED_VCODEC) {
602 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
603 current_module = "uninit_vcodec";
604 if (mpctx->sh_video)
605 uninit_video(mpctx->sh_video);
606 mpctx->sh_video = NULL;
609 if (mask & INITIALIZED_DEMUXER) {
610 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
611 current_module = "free_demuxer";
612 if (mpctx->num_sources) {
613 mpctx->demuxer = mpctx->sources[0].demuxer;
614 for (int i = 1; i < mpctx->num_sources; i++) {
615 uninit_subs(mpctx->sources[i].demuxer);
616 free_stream(mpctx->sources[i].stream);
617 free_demuxer(mpctx->sources[i].demuxer);
620 talloc_free(mpctx->sources);
621 mpctx->sources = NULL;
622 mpctx->num_sources = 0;
623 talloc_free(mpctx->timeline);
624 mpctx->timeline = NULL;
625 mpctx->num_timeline_parts = 0;
626 talloc_free(mpctx->chapters);
627 mpctx->chapters = NULL;
628 mpctx->num_chapters = 0;
629 mpctx->video_offset = 0;
630 if (mpctx->demuxer) {
631 mpctx->stream = mpctx->demuxer->stream;
632 uninit_subs(mpctx->demuxer);
633 free_demuxer(mpctx->demuxer);
635 mpctx->demuxer = NULL;
638 // kill the cache process:
639 if (mask & INITIALIZED_STREAM) {
640 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
641 current_module = "uninit_stream";
642 if (mpctx->stream)
643 free_stream(mpctx->stream);
644 mpctx->stream = NULL;
647 if (mask & INITIALIZED_VO) {
648 mpctx->initialized_flags &= ~INITIALIZED_VO;
649 current_module = "uninit_vo";
650 vo_destroy(mpctx->video_out);
651 mpctx->video_out = NULL;
652 #ifdef CONFIG_DVDNAV
653 mp_dvdnav_context_free(mpctx);
654 #endif
657 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
658 if (mask & INITIALIZED_GETCH2) {
659 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
660 current_module = "uninit_getch2";
661 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
662 // restore terminal:
663 getch2_disable();
666 if (mask & INITIALIZED_VOBSUB) {
667 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
668 current_module = "uninit_vobsub";
669 if (vo_vobsub)
670 vobsub_close(vo_vobsub);
671 vo_vobsub = NULL;
674 if (mask & INITIALIZED_SPUDEC) {
675 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
676 current_module = "uninit_spudec";
677 spudec_free(vo_spudec);
678 vo_spudec = NULL;
681 if (mask & INITIALIZED_AO) {
682 mpctx->initialized_flags &= ~INITIALIZED_AO;
683 current_module = "uninit_ao";
684 if (mpctx->ao)
685 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
686 mpctx->ao = NULL;
689 current_module = NULL;
692 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
694 if (mpctx->user_muted)
695 mixer_mute(&mpctx->mixer);
696 uninit_player(mpctx, INITIALIZED_ALL);
697 #if defined(__MINGW32__) || defined(__CYGWIN__)
698 timeEndPeriod(1);
699 #endif
700 #ifdef CONFIG_X11
701 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
702 #endif
704 current_module = "uninit_input";
705 mp_input_uninit(mpctx->input);
707 #ifdef CONFIG_FREETYPE
708 current_module = "uninit_font";
709 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
710 free_font_desc(mpctx->osd->sub_font);
711 free_font_desc(vo_font);
712 vo_font = NULL;
713 done_freetype();
714 #endif
715 osd_free(mpctx->osd);
717 #ifdef CONFIG_ASS
718 ass_library_done(mpctx->ass_library);
719 mpctx->ass_library = NULL;
720 #endif
722 current_module = "exit_player";
724 if (mpctx->playtree_iter)
725 play_tree_iter_free(mpctx->playtree_iter);
726 mpctx->playtree_iter = NULL;
727 if (mpctx->playtree)
728 play_tree_free(mpctx->playtree, 1);
729 mpctx->playtree = NULL;
731 talloc_free(mpctx->key_fifo);
733 switch (how) {
734 case EXIT_QUIT:
735 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
736 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
737 break;
738 case EXIT_EOF:
739 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
740 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
741 break;
742 case EXIT_ERROR:
743 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
744 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
745 break;
746 default:
747 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
749 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
750 "max framesize was %d bytes\n", max_framesize);
752 // must be last since e.g. mp_msg uses option values
753 // that will be freed by this.
754 if (mpctx->mconfig)
755 m_config_free(mpctx->mconfig);
756 mpctx->mconfig = NULL;
758 talloc_free(mpctx);
760 exit(rc);
763 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
765 exit_player_with_rc(mpctx, how, 1);
768 #ifndef __MINGW32__
769 static void child_sighandler(int x)
771 pid_t pid;
772 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
774 #endif
776 #ifdef CONFIG_CRASH_DEBUG
777 static char *prog_path;
778 static int crash_debug = 0;
779 #endif
781 static void exit_sighandler(int x)
783 static int sig_count = 0;
784 #ifdef CONFIG_CRASH_DEBUG
785 if (!crash_debug || x != SIGTRAP)
786 #endif
787 ++sig_count;
788 if (sig_count == 5) {
789 /* We're crashing bad and can't uninit cleanly :(
790 * by popular request, we make one last (dirty)
791 * effort to restore the user's
792 * terminal. */
793 getch2_disable();
794 exit(1);
796 if (sig_count == 6)
797 exit(1);
798 if (sig_count > 6) {
799 // can't stop :(
800 #ifndef __MINGW32__
801 kill(getpid(), SIGKILL);
802 #endif
804 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
805 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
806 "\nMPlayer interrupted by signal %d in module: %s\n", x,
807 current_module ? current_module : "unknown");
808 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
809 if (sig_count <= 1)
810 switch (x) {
811 case SIGINT:
812 case SIGPIPE:
813 case SIGQUIT:
814 case SIGTERM:
815 case SIGKILL:
816 async_quit_request = 1;
817 return; // killed from keyboard (^C) or killed [-9]
818 case SIGILL:
819 #if CONFIG_RUNTIME_CPUDETECT
820 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
821 #else
822 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
823 #endif
824 case SIGFPE:
825 case SIGSEGV:
826 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
827 default:
828 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
829 #ifdef CONFIG_CRASH_DEBUG
830 if (crash_debug) {
831 int gdb_pid;
832 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
833 gdb_pid = fork();
834 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
835 if (gdb_pid == 0) { // We are the child
836 char spid[20];
837 snprintf(spid, sizeof(spid), "%i", getppid());
838 getch2_disable(); // allow terminal to work properly with gdb
839 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
840 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
841 } else if (gdb_pid < 0)
842 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
843 else
844 waitpid(gdb_pid, NULL, 0);
845 if (x == SIGTRAP)
846 return;
848 #endif
850 getch2_disable();
851 exit(1);
854 #include "cfg-mplayer.h"
856 static int cfg_include(m_option_t *conf, char *filename)
858 return m_config_parse_config_file(conf->priv, filename);
861 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
863 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
865 struct MPOpts *opts = &mpctx->opts;
866 char *conffile;
867 int conffile_fd;
868 if (!(opts->noconfig & 2) &&
869 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
870 exit_player(mpctx, EXIT_NONE);
871 if ((conffile = get_path("")) == NULL)
872 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
873 else {
874 mkdir(conffile, 0777);
875 free(conffile);
876 if ((conffile = get_path("config")) == NULL)
877 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
878 else {
879 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
880 0666)) != -1) {
881 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
882 "Creating config file: %s\n", conffile);
883 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
884 close(conffile_fd);
886 if (!(opts->noconfig & 1) &&
887 m_config_parse_config_file(conf, conffile) < 0)
888 exit_player(mpctx, EXIT_NONE);
889 free(conffile);
894 #define PROFILE_CFG_PROTOCOL "protocol."
896 static void load_per_protocol_config(m_config_t *conf, const char * const file)
898 char *str;
899 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
900 m_profile_t *p;
902 /* does filename actually uses a protocol ? */
903 str = strstr(file, "://");
904 if (!str)
905 return;
907 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
908 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
909 p = m_config_get_profile(conf, protocol);
910 if (p) {
911 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
912 "Loading protocol-related profile '%s'\n", protocol);
913 m_config_set_profile(conf, p);
917 #define PROFILE_CFG_EXTENSION "extension."
919 static void load_per_extension_config(m_config_t *conf, const char * const file)
921 char *str;
922 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
923 m_profile_t *p;
925 /* does filename actually have an extension ? */
926 str = strrchr(file, '.');
927 if (!str)
928 return;
930 sprintf(extension, PROFILE_CFG_EXTENSION);
931 strncat(extension, ++str, 7);
932 p = m_config_get_profile(conf, extension);
933 if (p) {
934 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
935 "Loading extension-related profile '%s'\n", extension);
936 m_config_set_profile(conf, p);
940 #define PROFILE_CFG_VO "vo."
941 #define PROFILE_CFG_AO "ao."
943 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
945 char profile[strlen(cfg) + strlen(out) + 1];
946 m_profile_t *p;
948 sprintf(profile, "%s%s", cfg, out);
949 p = m_config_get_profile(conf, profile);
950 if (p) {
951 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
952 "Loading extension-related profile '%s'\n", profile);
953 m_config_set_profile(conf, p);
958 * Tries to load a config file
959 * @return 0 if file was not found, 1 otherwise
961 static int try_load_config(m_config_t *conf, const char *file)
963 if (!mp_path_exists(file))
964 return 0;
965 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
966 m_config_parse_config_file(conf, file);
967 return 1;
970 static void load_per_file_config(m_config_t *conf, const char * const file)
972 char *confpath;
973 char cfg[MP_PATH_MAX];
974 const char *name;
976 if (strlen(file) > MP_PATH_MAX - 14) {
977 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
978 "can not load file or directory specific config files\n");
979 return;
981 sprintf(cfg, "%s.conf", file);
983 name = mp_basename(cfg);
984 if (use_filedir_conf) {
985 char dircfg[MP_PATH_MAX];
986 strcpy(dircfg, cfg);
987 strcpy(dircfg + (name - cfg), "mplayer.conf");
988 try_load_config(conf, dircfg);
990 if (try_load_config(conf, cfg))
991 return;
994 if ((confpath = get_path(name)) != NULL) {
995 try_load_config(conf, confpath);
997 free(confpath);
1001 /* When libmpdemux performs a blocking operation (network connection or
1002 * cache filling) if the operation fails we use this function to check
1003 * if it was interrupted by the user.
1004 * The function returns a new value for eof. */
1005 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1007 mp_cmd_t *cmd;
1008 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1009 switch (cmd->id) {
1010 case MP_CMD_QUIT:
1011 exit_player_with_rc(mpctx, EXIT_QUIT,
1012 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1013 case MP_CMD_PLAY_TREE_STEP: {
1014 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1015 mpctx->play_tree_step =
1016 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1017 } break;
1018 case MP_CMD_PLAY_TREE_UP_STEP: {
1019 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1020 } break;
1021 case MP_CMD_PLAY_ALT_SRC_STEP: {
1022 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1023 } break;
1025 mp_cmd_free(cmd);
1027 return stop_play;
1030 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1032 play_tree_add_bpf(entry, bstr(mpctx->filename));
1035 if (!entry) {
1036 entry = mpctx->playtree_iter->tree;
1037 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1038 != PLAY_TREE_ITER_ENTRY)
1039 return PT_NEXT_ENTRY;
1040 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1041 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1042 != PLAY_TREE_ITER_ENTRY)
1043 return PT_NEXT_ENTRY;
1045 play_tree_remove(entry, 1, 1);
1046 return PT_NEXT_SRC;
1048 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1049 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1050 entry = mpctx->playtree_iter->tree;
1051 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1052 != PLAY_TREE_ITER_ENTRY)
1053 return PT_NEXT_ENTRY;
1054 play_tree_remove(entry, 1, 1);
1056 return PT_NEXT_SRC;
1059 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1060 int noerr)
1062 struct MPOpts *opts = &mpctx->opts;
1063 sub_data *subd = NULL;
1064 struct ass_track *asst = NULL;
1065 bool is_native_ass = false;
1067 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1068 return;
1070 #ifdef CONFIG_ASS
1071 if (opts->ass_enabled) {
1072 #ifdef CONFIG_ICONV
1073 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1074 #else
1075 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1076 #endif
1077 is_native_ass = asst;
1078 if (!asst) {
1079 subd = sub_read_file(filename, fps, &mpctx->opts);
1080 if (subd) {
1081 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1082 sub_free(subd);
1083 subd = NULL;
1086 } else
1087 #endif
1088 subd = sub_read_file(filename, fps, &mpctx->opts);
1091 if (!asst && !subd) {
1092 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1093 "Cannot load subtitles: %s\n", filename_recode(filename));
1094 return;
1097 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1098 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1099 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1100 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1101 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1102 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1103 filename_recode(filename));
1104 ++mpctx->set_of_sub_size;
1105 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1106 mpctx->set_of_sub_size, filename_recode(filename));
1109 void init_vo_spudec(struct MPContext *mpctx)
1111 unsigned width, height;
1112 spudec_free(vo_spudec);
1113 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1114 vo_spudec = NULL;
1116 // we currently can't work without video stream
1117 if (!mpctx->sh_video)
1118 return;
1120 if (spudec_ifo) {
1121 unsigned int palette[16];
1122 current_module = "spudec_init_vobsub";
1123 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1124 1, -1, NULL) >= 0)
1125 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1128 width = mpctx->sh_video->disp_w;
1129 height = mpctx->sh_video->disp_h;
1131 #ifdef CONFIG_DVDREAD
1132 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1133 current_module = "spudec_init_dvdread";
1134 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1135 cur_pgc->palette, width, height, NULL, 0);
1137 #endif
1139 #ifdef CONFIG_DVDNAV
1140 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1141 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1142 current_module = "spudec_init_dvdnav";
1143 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1145 #endif
1147 if (vo_spudec == NULL) {
1148 sh_sub_t *sh = mpctx->d_sub->sh;
1149 current_module = "spudec_init_normal";
1150 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1151 sh->extradata_len);
1152 spudec_set_font_factor(vo_spudec, font_factor);
1155 if (vo_spudec != NULL) {
1156 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1157 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1158 mpctx);
1163 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1164 * make it all work is to use the builtin SDL-bootstrap code, which
1165 * will be done automatically by replacing our main() if we include SDL.h.
1167 #if defined(__APPLE__) && defined(CONFIG_SDL)
1168 #ifdef CONFIG_SDL_SDL_H
1169 #include <SDL/SDL.h>
1170 #else
1171 #include <SDL.h>
1172 #endif
1173 #endif
1176 * \brief append a formatted string
1177 * \param buf buffer to print into
1178 * \param pos position of terminating 0 in buf
1179 * \param len maximum number of characters in buf, not including terminating 0
1180 * \param format printf format string
1182 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1184 va_list va;
1185 va_start(va, format);
1186 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1187 va_end(va);
1188 if (*pos >= len) {
1189 buf[len] = 0;
1190 *pos = len;
1195 * \brief append time in the hh:mm:ss.f format
1196 * \param buf buffer to print into
1197 * \param pos position of terminating 0 in buf
1198 * \param len maximum number of characters in buf, not including terminating 0
1199 * \param time time value to convert/append
1201 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1203 int64_t tenths = 10 * time;
1204 int f1 = tenths % 10;
1205 int ss = (tenths / 10) % 60;
1206 int mm = (tenths / 600) % 60;
1207 int hh = tenths / 36000;
1208 if (time < 0) {
1209 saddf(buf, pos, len, "unknown");
1210 return;
1212 if (hh > 0)
1213 saddf(buf, pos, len, "%2d:", hh);
1214 if (hh > 0 || mm > 0)
1215 saddf(buf, pos, len, "%02d:", mm);
1216 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1219 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1221 struct MPOpts *opts = &mpctx->opts;
1222 sh_video_t * const sh_video = mpctx->sh_video;
1224 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1225 a_pos = playing_audio_pts(mpctx);
1226 if (mpctx->sh_audio && sh_video && at_frame) {
1227 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1228 if (mpctx->time_frame > 0)
1229 mpctx->last_av_difference +=
1230 mpctx->time_frame * opts->playback_speed;
1231 if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
1232 mpctx->last_av_difference = MP_NOPTS_VALUE;
1233 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1234 && !mpctx->drop_message_shown) {
1235 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1236 mpctx->drop_message_shown = true;
1239 if (opts->quiet)
1240 return;
1242 int width;
1243 char *line;
1244 unsigned pos = 0;
1245 get_screen_size();
1246 if (screen_width > 0)
1247 width = screen_width;
1248 else
1249 width = 80;
1250 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1251 /* Windows command line is broken (MinGW's rxvt works, but we
1252 * should not depend on that). */
1253 width--;
1254 #endif
1255 line = malloc(width + 1); // one additional char for the terminating null
1257 // Audio time
1258 if (mpctx->sh_audio) {
1259 if (a_pos != MP_NOPTS_VALUE)
1260 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1261 else
1262 saddf(line, &pos, width, "A: ??? ");
1263 if (!sh_video && a_pos != MP_NOPTS_VALUE) {
1264 float len = get_time_length(mpctx);
1265 saddf(line, &pos, width, "(");
1266 sadd_hhmmssf(line, &pos, width, a_pos);
1267 saddf(line, &pos, width, ") of %.1f (", len);
1268 sadd_hhmmssf(line, &pos, width, len);
1269 saddf(line, &pos, width, ") ");
1273 // Video time
1274 if (sh_video) {
1275 if (mpctx->video_pts != MP_NOPTS_VALUE)
1276 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1277 else
1278 saddf(line, &pos, width, "V: ??? ", mpctx->video_pts);
1281 // A-V sync
1282 if (mpctx->sh_audio && sh_video) {
1283 if (mpctx->last_av_difference != MP_NOPTS_VALUE)
1284 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1285 mpctx->last_av_difference, mpctx->total_avsync_change);
1286 else
1287 saddf(line, &pos, width, "A-V: ??? ct:%7.3f ",
1288 mpctx->total_avsync_change);
1291 // Video stats
1292 if (sh_video)
1293 saddf(line, &pos, width, "%3d/%3d ",
1294 (int)sh_video->num_frames,
1295 (int)sh_video->num_frames_decoded);
1297 // CPU usage
1298 if (sh_video) {
1299 if (sh_video->timer > 0.5)
1300 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1301 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1302 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1303 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1304 else
1305 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1306 } else if (mpctx->sh_audio) {
1307 if (mpctx->delay > 0.5)
1308 saddf(line, &pos, width, "%4.1f%% ",
1309 100.0 * audio_time_usage / (double)mpctx->delay);
1310 else
1311 saddf(line, &pos, width, "??,?%% ");
1314 // VO stats
1315 if (sh_video)
1316 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1318 #ifdef CONFIG_STREAM_CACHE
1319 // cache stats
1320 if (stream_cache_size > 0)
1321 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1322 #endif
1324 // other
1325 if (opts->playback_speed != 1)
1326 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1328 // end
1329 if (erase_to_end_of_line) {
1330 line[pos] = 0;
1331 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1332 "%s%s\r", line, erase_to_end_of_line);
1333 } else {
1334 memset(&line[pos], ' ', width - pos);
1335 line[width] = 0;
1336 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1338 free(line);
1340 mpctx->status_printed = true;
1343 struct stream_dump_progress {
1344 uint64_t count;
1345 unsigned start_time;
1346 unsigned last_print_time;
1349 static void stream_dump_progress_start(struct stream_dump_progress *p)
1351 p->start_time = p->last_print_time = GetTimerMS();
1352 p->count = 0;
1355 static void stream_dump_progress(struct stream_dump_progress *p,
1356 uint64_t len, stream_t *stream)
1358 p->count += len;
1359 unsigned t = GetTimerMS();
1360 if (t - p->last_print_time < 1000)
1361 return;
1363 uint64_t start = stream->start_pos;
1364 uint64_t end = stream->end_pos;
1365 uint64_t pos = stream->pos;
1367 p->last_print_time = t;
1368 /* TODO: pretty print sizes; ETA */
1369 if (end > start && pos >= start && pos <= end) {
1370 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1371 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1372 p->count, 100.0 * (pos - start) / (end - start));
1373 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1374 } else {
1375 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1376 "dump: %"PRIu64 " bytes written", p->count);
1377 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1381 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1383 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1384 p->count, name);
1388 * \brief build a chain of audio filters that converts the input format
1389 * to the ao's format, taking into account the current playback_speed.
1390 * sh_audio describes the requested input format of the chain.
1391 * ao describes the requested output format of the chain.
1393 static int build_afilter_chain(struct MPContext *mpctx)
1395 struct sh_audio *sh_audio = mpctx->sh_audio;
1396 struct ao *ao = mpctx->ao;
1397 struct MPOpts *opts = &mpctx->opts;
1398 int new_srate;
1399 int result;
1400 if (!sh_audio) {
1401 mpctx->mixer.afilter = NULL;
1402 return 0;
1404 if (af_control_any_rev(sh_audio->afilter,
1405 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1406 &opts->playback_speed))
1407 new_srate = sh_audio->samplerate;
1408 else {
1409 new_srate = sh_audio->samplerate * opts->playback_speed;
1410 if (new_srate != ao->samplerate) {
1411 // limits are taken from libaf/af_resample.c
1412 if (new_srate < 8000)
1413 new_srate = 8000;
1414 if (new_srate > 192000)
1415 new_srate = 192000;
1416 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1419 result = init_audio_filters(sh_audio, new_srate,
1420 &ao->samplerate, &ao->channels, &ao->format);
1421 mpctx->mixer.afilter = sh_audio->afilter;
1422 return result;
1426 typedef struct mp_osd_msg mp_osd_msg_t;
1427 struct mp_osd_msg {
1428 /// Previous message on the stack.
1429 mp_osd_msg_t *prev;
1430 /// Message text.
1431 char *msg;
1432 int id, level, started;
1433 /// Display duration in ms.
1434 unsigned time;
1437 /// OSD message stack.
1438 static mp_osd_msg_t *osd_msg_stack = NULL;
1441 * \brief Add a message on the OSD message stack
1443 * If a message with the same id is already present in the stack
1444 * it is pulled on top of the stack, otherwise a new message is created.
1447 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1448 va_list ap)
1450 mp_osd_msg_t *msg, *last = NULL;
1452 // look if the id is already in the stack
1453 for (msg = osd_msg_stack; msg && msg->id != id;
1454 last = msg, msg = msg->prev) ;
1455 // not found: alloc it
1456 if (!msg) {
1457 msg = talloc_zero(NULL, mp_osd_msg_t);
1458 msg->prev = osd_msg_stack;
1459 osd_msg_stack = msg;
1460 } else if (last) { // found, but it's not on top of the stack
1461 last->prev = msg->prev;
1462 msg->prev = osd_msg_stack;
1463 osd_msg_stack = msg;
1465 talloc_free(msg->msg);
1466 // write the msg
1467 msg->msg = talloc_vasprintf(msg, fmt, ap);
1468 // set id and time
1469 msg->id = id;
1470 msg->level = level;
1471 msg->time = time;
1475 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1477 va_list ap;
1478 va_start(ap, fmt);
1479 set_osd_msg_va(id, level, time, fmt, ap);
1480 va_end(ap);
1483 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1485 va_list ap;
1486 va_start(ap, fmt);
1487 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1488 va_end(ap);
1492 * \brief Remove a message from the OSD stack
1494 * This function can be used to get rid of a message right away.
1498 void rm_osd_msg(int id)
1500 mp_osd_msg_t *msg, *last = NULL;
1502 // Search for the msg
1503 for (msg = osd_msg_stack; msg && msg->id != id;
1504 last = msg, msg = msg->prev) ;
1505 if (!msg)
1506 return;
1508 // Detach it from the stack and free it
1509 if (last)
1510 last->prev = msg->prev;
1511 else
1512 osd_msg_stack = msg->prev;
1513 talloc_free(msg);
1517 * \brief Remove all messages from the OSD stack
1521 static void clear_osd_msgs(void)
1523 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1524 while (msg) {
1525 prev = msg->prev;
1526 talloc_free(msg);
1527 msg = prev;
1529 osd_msg_stack = NULL;
1533 * \brief Get the current message from the OSD stack.
1535 * This function decrements the message timer and destroys the old ones.
1536 * The message that should be displayed is returned (if any).
1540 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1542 struct MPOpts *opts = &mpctx->opts;
1543 mp_osd_msg_t *msg, *prev, *last = NULL;
1544 static unsigned last_update = 0;
1545 unsigned now = GetTimerMS();
1546 unsigned diff;
1547 char hidden_dec_done = 0;
1549 if (mpctx->osd_visible) {
1550 // 36000000 means max timed visibility is 1 hour into the future, if
1551 // the difference is greater assume it's wrapped around from below 0
1552 if (mpctx->osd_visible - now > 36000000) {
1553 mpctx->osd_visible = 0;
1554 vo_osd_progbar_type = -1; // disable
1555 vo_osd_changed(OSDTYPE_PROGBAR);
1556 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1559 if (mpctx->osd_show_percentage_until - now > 36000000)
1560 mpctx->osd_show_percentage_until = 0;
1562 if (!last_update)
1563 last_update = now;
1564 diff = now >= last_update ? now - last_update : 0;
1566 last_update = now;
1568 // Look for the first message in the stack with high enough level.
1569 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1570 prev = msg->prev;
1571 if (msg->level > opts->osd_level && hidden_dec_done)
1572 continue;
1573 // The message has a high enough level or it is the first hidden one
1574 // in both cases we decrement the timer or kill it.
1575 if (!msg->started || msg->time > diff) {
1576 if (msg->started)
1577 msg->time -= diff;
1578 else
1579 msg->started = 1;
1580 // display it
1581 if (msg->level <= opts->osd_level)
1582 return msg;
1583 hidden_dec_done = 1;
1584 continue;
1586 // kill the message
1587 talloc_free(msg);
1588 if (last) {
1589 last->prev = prev;
1590 msg = last;
1591 } else {
1592 osd_msg_stack = prev;
1593 msg = NULL;
1596 // Nothing found
1597 return NULL;
1601 * \brief Display the OSD bar.
1603 * Display the OSD bar or fall back on a simple message.
1607 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1608 double min, double max, double val)
1610 struct MPOpts *opts = &mpctx->opts;
1611 if (opts->osd_level < 1)
1612 return;
1614 if (mpctx->sh_video) {
1615 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1616 vo_osd_progbar_type = type;
1617 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1618 vo_osd_changed(OSDTYPE_PROGBAR);
1619 return;
1622 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1623 name, ROUND(100 * (val - min) / (max - min)));
1627 * \brief Display text subtitles on the OSD
1629 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1631 int i;
1632 vo_sub = subs;
1633 vo_osd_changed(OSDTYPE_SUBTITLE);
1634 if (!mpctx->sh_video) {
1635 // reverse order, since newest set_osd_msg is displayed first
1636 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1637 if (!subs || i >= subs->lines || !subs->text[i])
1638 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1639 else {
1640 // HACK: currently display time for each sub line
1641 // except the last is set to 2 seconds.
1642 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1643 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1644 "%s", subs->text[i]);
1651 * \brief Update the OSD message line.
1653 * This function displays the current message on the vo OSD or on the term.
1654 * If the stack is empty and the OSD level is high enough the timer
1655 * is displayed (only on the vo OSD).
1659 static void update_osd_msg(struct MPContext *mpctx)
1661 struct MPOpts *opts = &mpctx->opts;
1662 mp_osd_msg_t *msg;
1663 struct osd_state *osd = mpctx->osd;
1664 char osd_text_timer[128];
1666 if (mpctx->add_osd_seek_info) {
1667 double percentage = get_percent_pos(mpctx);
1668 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1669 if (mpctx->sh_video)
1670 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1671 mpctx->add_osd_seek_info = false;
1674 // Look if we have a msg
1675 if ((msg = get_osd_msg(mpctx))) {
1676 if (strcmp(osd->osd_text, msg->msg)) {
1677 osd_set_text(osd, msg->msg);
1678 if (mpctx->sh_video)
1679 vo_osd_changed(OSDTYPE_OSD);
1680 else if (opts->term_osd)
1681 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1682 msg->msg);
1684 return;
1687 if (mpctx->sh_video) {
1688 // fallback on the timer
1689 if (opts->osd_level >= 2) {
1690 int len = get_time_length(mpctx);
1691 int percentage = -1;
1692 char percentage_text[10];
1693 char fractions_text[4];
1694 double fpts = get_current_time(mpctx);
1695 int pts = fpts;
1697 if (mpctx->osd_show_percentage_until)
1698 percentage = get_percent_pos(mpctx);
1700 if (percentage >= 0)
1701 snprintf(percentage_text, 9, " (%d%%)", percentage);
1702 else
1703 percentage_text[0] = 0;
1705 if (opts->osd_fractions == 1) {
1706 //print fractions as sub-second timestamp
1707 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1708 (int)((fpts - pts) * 100));
1709 } else if (opts->osd_fractions == 2) {
1710 /* Print fractions by estimating the frame count within the
1711 * second.
1713 * Rounding or cutting off numbers after the decimal point
1714 * causes problems because of float's precision and movies
1715 * whose first frame is not exactly at timestamp 0. Therefore,
1716 * we add 0.2 and cut off at the decimal point, which proved
1717 * to be good heuristic.
1719 double fps = mpctx->sh_video->fps;
1720 if (fps <= 1 || fps > 99)
1721 strcpy(fractions_text, ".??");
1722 else
1723 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1724 (int) ((fpts - pts) * fps + 0.2));
1725 } else {
1726 //do not print fractions
1727 fractions_text[0] = 0;
1730 if (opts->osd_level == 3)
1731 snprintf(osd_text_timer, sizeof(osd_text_timer),
1732 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1733 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1734 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1735 percentage_text);
1736 else
1737 snprintf(osd_text_timer, sizeof(osd_text_timer),
1738 "%c %02d:%02d:%02d%s%s",
1739 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1740 pts % 60, fractions_text, percentage_text);
1741 } else
1742 osd_text_timer[0] = 0;
1744 if (strcmp(osd->osd_text, osd_text_timer)) {
1745 osd_set_text(osd, osd_text_timer);
1746 vo_osd_changed(OSDTYPE_OSD);
1748 return;
1751 // Clear the term osd line
1752 if (opts->term_osd && osd->osd_text[0]) {
1753 osd->osd_text[0] = 0;
1754 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1759 void reinit_audio_chain(struct MPContext *mpctx)
1761 struct MPOpts *opts = &mpctx->opts;
1762 struct ao *ao;
1763 if (!mpctx->sh_audio)
1764 return;
1765 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1766 current_module = "init_audio_codec";
1767 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1768 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1769 goto init_error;
1770 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1771 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1775 current_module = "af_preinit";
1776 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1777 mpctx->initialized_flags |= INITIALIZED_AO;
1778 mpctx->ao = ao_create();
1779 mpctx->ao->opts = opts;
1780 mpctx->ao->samplerate = force_srate;
1781 mpctx->ao->format = opts->audio_output_format;
1783 ao = mpctx->ao;
1785 // first init to detect best values
1786 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1787 // input:
1788 mpctx->sh_audio->samplerate,
1789 // output:
1790 &ao->samplerate, &ao->channels, &ao->format)) {
1791 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1792 "pre-init!\n");
1793 exit_player(mpctx, EXIT_ERROR);
1795 if (!ao->initialized) {
1796 current_module = "ao2_init";
1797 ao->buffersize = opts->ao_buffersize;
1798 ao_init(ao, opts->audio_driver_list);
1799 if (!ao->initialized) {
1800 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1801 "Could not open/initialize audio device -> no sound.\n");
1802 goto init_error;
1804 ao->buffer.start = talloc_new(ao);
1805 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1806 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1807 ao->driver->info->short_name,
1808 ao->samplerate, ao->channels,
1809 af_fmt2str_short(ao->format),
1810 af_fmt2bits(ao->format) / 8);
1811 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1812 ao->driver->info->name, ao->driver->info->author);
1813 if (strlen(ao->driver->info->comment) > 0)
1814 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1815 ao->driver->info->comment);
1818 // init audio filters:
1819 current_module = "af_init";
1820 if (!build_afilter_chain(mpctx)) {
1821 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1822 "Couldn't find matching filter/ao format!\n");
1823 goto init_error;
1825 mpctx->mixer.ao = ao;
1826 mpctx->mixer.volstep = volstep;
1827 mpctx->mixer.softvol = opts->softvol;
1828 mpctx->mixer.softvol_max = opts->softvol_max;
1829 mpctx->syncing_audio = true;
1830 return;
1832 init_error:
1833 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1834 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1835 mpctx->d_audio->id = -2;
1839 // Return pts value corresponding to the end point of audio written to the
1840 // ao so far.
1841 static double written_audio_pts(struct MPContext *mpctx)
1843 sh_audio_t *sh_audio = mpctx->sh_audio;
1844 demux_stream_t *d_audio = mpctx->d_audio;
1845 // first calculate the end pts of audio that has been output by decoder
1846 double a_pts = sh_audio->pts;
1847 if (a_pts != MP_NOPTS_VALUE)
1848 // Good, decoder supports new way of calculating audio pts.
1849 // sh_audio->pts is the timestamp of the latest input packet with
1850 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1851 // the amount of bytes the decoder has written after that timestamp.
1852 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1853 else {
1854 // Decoder doesn't support new way of calculating pts (or we're
1855 // being called before it has decoded anything with known timestamp).
1856 // Use the old method of audio pts calculation: take the timestamp
1857 // of last packet with known pts the decoder has read data from,
1858 // and add amount of bytes read after the beginning of that packet
1859 // divided by input bps. This will be inaccurate if the input/output
1860 // ratio is not constant for every audio packet or if it is constant
1861 // but not accurately known in sh_audio->i_bps.
1863 a_pts = d_audio->pts;
1864 if (a_pts == MP_NOPTS_VALUE)
1865 return a_pts;
1867 // ds_tell_pts returns bytes read after last timestamp from
1868 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1869 // it has read but not decoded
1870 if (sh_audio->i_bps)
1871 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1872 (double)sh_audio->i_bps;
1874 // Now a_pts hopefully holds the pts for end of audio from decoder.
1875 // Substract data in buffers between decoder and audio out.
1877 // Decoded but not filtered
1878 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1880 // Data buffered in audio filters, measured in bytes of "missing" output
1881 double buffered_output = af_calc_delay(sh_audio->afilter);
1883 // Data that was ready for ao but was buffered because ao didn't fully
1884 // accept everything to internal buffers yet
1885 buffered_output += mpctx->ao->buffer.len;
1887 // Filters divide audio length by playback_speed, so multiply by it
1888 // to get the length in original units without speedup or slowdown
1889 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1891 return a_pts + mpctx->video_offset;
1894 // Return pts value corresponding to currently playing audio.
1895 double playing_audio_pts(struct MPContext *mpctx)
1897 double pts = written_audio_pts(mpctx);
1898 if (pts == MP_NOPTS_VALUE)
1899 return pts;
1900 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1903 static bool is_av_sub(int type)
1905 return type == 'b' || type == 'p' || type == 'x';
1908 void update_subtitles(struct MPContext *mpctx, double refpts_tl, bool reset)
1910 mpctx->osd->sub_offset = mpctx->video_offset;
1911 struct MPOpts *opts = &mpctx->opts;
1912 struct sh_video *sh_video = mpctx->sh_video;
1913 struct demux_stream *d_sub = mpctx->d_sub;
1914 double refpts_s = refpts_tl - mpctx->osd->sub_offset;
1915 double curpts_s = refpts_s + sub_delay;
1916 unsigned char *packet = NULL;
1917 int len;
1918 struct sh_sub *sh_sub = d_sub->sh;
1919 int type = sh_sub ? sh_sub->type : 'v';
1920 static subtitle subs;
1921 if (reset) {
1922 if (sh_sub)
1923 sub_reset(sh_sub, mpctx->osd);
1924 sub_clear_text(&subs, MP_NOPTS_VALUE);
1925 if (vo_sub)
1926 set_osd_subtitle(mpctx, NULL);
1927 if (vo_spudec) {
1928 spudec_reset(vo_spudec);
1929 vo_osd_changed(OSDTYPE_SPU);
1931 if (is_av_sub(type))
1932 reset_avsub(sh_sub);
1933 return;
1935 // find sub
1936 if (mpctx->subdata) {
1937 if (sub_fps == 0)
1938 sub_fps = sh_video ? sh_video->fps : 25;
1939 current_module = "find_sub";
1940 find_sub(mpctx, mpctx->subdata, curpts_s *
1941 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1942 if (vo_sub)
1943 mpctx->vo_sub_last = vo_sub;
1946 // DVD sub:
1947 if (vobsub_id >= 0 || type == 'v') {
1948 int timestamp;
1949 current_module = "spudec";
1950 /* Get a sub packet from the DVD or a vobsub */
1951 while (1) {
1952 // Vobsub
1953 len = 0;
1954 if (vo_vobsub) {
1955 if (curpts_s >= 0) {
1956 len = vobsub_get_packet(vo_vobsub, curpts_s,
1957 (void **)&packet, &timestamp);
1958 if (len > 0)
1959 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1960 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1961 len, refpts_s, sh_video->timer,
1962 timestamp / 90000.0, timestamp);
1964 } else {
1965 // DVD sub
1966 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1967 if (len > 0) {
1968 // XXX This is wrong, sh_video->pts can be arbitrarily
1969 // much behind demuxing position. Unfortunately using
1970 // d_video->pts which would have been the simplest
1971 // improvement doesn't work because mpeg specific hacks
1972 // in video.c set d_video->pts to 0.
1973 float x = d_sub->pts - refpts_s;
1974 if (x > -20 && x < 20) // prevent missing subs on pts reset
1975 timestamp = 90000 * d_sub->pts;
1976 else
1977 timestamp = 90000 * curpts_s;
1978 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1979 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1980 refpts_s, d_sub->pts, timestamp);
1983 if (len <= 0 || !packet)
1984 break;
1985 // create it only here, since with some broken demuxers we might
1986 // type = v but no DVD sub and we currently do not change the
1987 // "original frame size" ever after init, leading to wrong-sized
1988 // PGS subtitles.
1989 if (!vo_spudec)
1990 vo_spudec = spudec_new(NULL);
1991 if (vo_vobsub || timestamp >= 0)
1992 spudec_assemble(vo_spudec, packet, len, timestamp);
1994 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1995 if (type == 'd' && !d_sub->demuxer->teletext) {
1996 tt_stream_props tsp = { 0 };
1997 void *ptr = &tsp;
1998 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
1999 VBI_CONTROL_TRUE)
2000 d_sub->demuxer->teletext = ptr;
2002 if (d_sub->non_interleaved)
2003 ds_get_next_pts(d_sub);
2005 while (d_sub->first) {
2006 double subpts_s = ds_get_next_pts(d_sub);
2007 if (subpts_s > curpts_s) {
2008 // Libass handled subs can be fed to it in advance
2009 if (!opts->ass_enabled || !is_text_sub(type))
2010 break;
2011 // Try to avoid demuxing whole file at once
2012 if (d_sub->non_interleaved && subpts_s > curpts_s + 1)
2013 break;
2015 double duration = d_sub->first->duration;
2016 len = ds_get_packet_sub(d_sub, &packet);
2017 if (is_av_sub(type)) {
2018 int ret = decode_avsub(sh_sub, packet, len, subpts_s, duration);
2019 if (ret < 0)
2020 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2021 "subtitle\n");
2022 continue;
2024 if (type == 'm') {
2025 if (len < 2)
2026 continue;
2027 len = FFMIN(len - 2, AV_RB16(packet));
2028 packet += 2;
2030 if (type == 'd') {
2031 if (d_sub->demuxer->teletext) {
2032 uint8_t *p = packet;
2033 p++;
2034 len--;
2035 while (len >= 46) {
2036 int sublen = p[1];
2037 if (p[0] == 2 || p[0] == 3)
2038 teletext_control(d_sub->demuxer->teletext,
2039 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2040 p += sublen + 2;
2041 len -= sublen + 2;
2044 continue;
2046 if (sh_sub && sh_sub->active) {
2047 sub_decode(sh_sub, mpctx->osd, packet, len, subpts_s, duration);
2048 continue;
2050 if (subpts_s != MP_NOPTS_VALUE) {
2051 if (duration < 0)
2052 sub_clear_text(&subs, MP_NOPTS_VALUE);
2053 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2054 int i;
2055 unsigned char *p = packet;
2056 for (i = 0; i < 8 && *p != '\0'; p++)
2057 if (*p == ',')
2058 i++;
2059 if (*p == '\0') /* Broken line? */
2060 continue;
2061 len -= p - packet;
2062 packet = p;
2064 double endpts_s = MP_NOPTS_VALUE;
2065 if (subpts_s != MP_NOPTS_VALUE && duration >= 0)
2066 endpts_s = subpts_s + duration;
2067 sub_add_text(&subs, packet, len, endpts_s);
2068 set_osd_subtitle(mpctx, &subs);
2070 if (d_sub->non_interleaved)
2071 ds_get_next_pts(d_sub);
2073 if (!opts->ass_enabled)
2074 if (sub_clear_text(&subs, curpts_s))
2075 set_osd_subtitle(mpctx, &subs);
2077 if (vo_spudec) {
2078 spudec_heartbeat(vo_spudec, 90000 * curpts_s);
2079 if (spudec_changed(vo_spudec))
2080 vo_osd_changed(OSDTYPE_SPU);
2083 current_module = NULL;
2086 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2088 int page_changed;
2090 if (!demuxer->teletext)
2091 return;
2093 //Also forcing page update when such ioctl is not supported or call error occured
2094 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2095 &page_changed) != VBI_CONTROL_TRUE)
2096 page_changed = 1;
2098 if (!page_changed)
2099 return;
2101 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2102 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2103 vo_osd_teletext_page = NULL;
2104 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2105 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2106 vo_osd_teletext_half = 0;
2107 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2108 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2109 vo_osd_teletext_mode = 0;
2110 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2111 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2112 vo_osd_teletext_format = 0;
2113 vo_osd_changed(OSDTYPE_TELETEXT);
2115 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2118 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2120 struct MPOpts *opts = &mpctx->opts;
2121 // check for frame-drop:
2122 current_module = "check_framedrop";
2123 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2124 static int dropped_frames;
2125 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2126 float d = delay - mpctx->delay;
2127 ++total_frame_cnt;
2128 // we should avoid dropping too many frames in sequence unless we
2129 // are too late. and we allow 100ms A-V delay here:
2130 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2131 && !mpctx->restart_playback) {
2132 ++drop_frame_cnt;
2133 ++dropped_frames;
2134 return frame_dropping;
2135 } else
2136 dropped_frames = 0;
2138 return 0;
2142 #ifdef HAVE_RTC
2143 int rtc_fd = -1;
2144 #endif
2146 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2148 #ifdef HAVE_RTC
2149 if (rtc_fd >= 0) {
2150 // -------- RTC -----------
2151 current_module = "sleep_rtc";
2152 while (time_frame > 0.000) {
2153 unsigned long rtc_ts;
2154 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2155 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2156 "Linux RTC read error: %s\n", strerror(errno));
2157 time_frame -= get_relative_time(mpctx);
2159 } else
2160 #endif
2162 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2163 // unnecessarily high CPU usage
2164 struct MPOpts *opts = &mpctx->opts;
2165 float margin = opts->softsleep ? 0.011 : 0;
2166 current_module = "sleep_timer";
2167 while (time_frame > margin) {
2168 usec_sleep(1000000 * (time_frame - margin));
2169 time_frame -= get_relative_time(mpctx);
2171 if (opts->softsleep) {
2172 current_module = "sleep_soft";
2173 if (time_frame < 0)
2174 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2175 "Warning! Softsleep underflow!\n");
2176 while (time_frame > 0)
2177 time_frame -= get_relative_time(mpctx); // burn the CPU
2180 return time_frame;
2183 static int select_subtitle(MPContext *mpctx)
2185 struct MPOpts *opts = &mpctx->opts;
2186 // find the best sub to use
2187 int id;
2188 int found = 0;
2189 mpctx->global_sub_pos = -1; // no subs by default
2190 if (vobsub_id >= 0) {
2191 // if user asks for a vobsub id, use that first.
2192 id = vobsub_id;
2193 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2194 M_PROPERTY_OK;
2197 if (!found && opts->sub_id >= 0) {
2198 // if user asks for a dvd sub id, use that next.
2199 id = opts->sub_id;
2200 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2201 M_PROPERTY_OK;
2204 if (!found) {
2205 // if there are text subs to use, use those. (autosubs come last here)
2206 id = 0;
2207 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2208 M_PROPERTY_OK;
2211 if (!found && opts->sub_id == -1) {
2212 // finally select subs by language and container hints
2213 if (opts->sub_id == -1)
2214 opts->sub_id =
2215 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2216 opts->sub_lang);
2217 if (opts->sub_id >= 0) {
2218 id = opts->sub_id;
2219 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2220 M_PROPERTY_OK;
2223 return found;
2226 #ifdef CONFIG_DVDNAV
2227 #ifndef FF_B_TYPE
2228 #define FF_B_TYPE 3
2229 #endif
2230 /// store decoded video image
2231 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2232 mp_image_t *from_mpi)
2234 mp_image_t *mpi;
2236 /// Do not store B-frames
2237 if (from_mpi->pict_type == FF_B_TYPE)
2238 return to_mpi;
2240 if (to_mpi &&
2241 to_mpi->w == from_mpi->w &&
2242 to_mpi->h == from_mpi->h &&
2243 to_mpi->imgfmt == from_mpi->imgfmt)
2244 mpi = to_mpi;
2245 else {
2246 if (to_mpi)
2247 free_mp_image(to_mpi);
2248 if (from_mpi->w == 0 || from_mpi->h == 0)
2249 return NULL;
2250 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2253 copy_mpi(mpi, from_mpi);
2254 return mpi;
2257 static void mp_dvdnav_reset_stream(MPContext *ctx)
2259 struct MPOpts *opts = &ctx->opts;
2260 if (ctx->sh_video) {
2261 /// clear video pts
2262 ctx->d_video->pts = 0.0f;
2263 ctx->sh_video->pts = 0.0f;
2264 ctx->sh_video->i_pts = 0.0f;
2265 ctx->sh_video->last_pts = 0.0f;
2266 ctx->sh_video->num_buffered_pts = 0;
2267 ctx->sh_video->num_frames = 0;
2268 ctx->sh_video->num_frames_decoded = 0;
2269 ctx->sh_video->timer = 0.0f;
2270 ctx->sh_video->stream_delay = 0.0f;
2271 ctx->sh_video->timer = 0;
2272 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2275 if (ctx->sh_audio) {
2276 /// free audio packets and reset
2277 ds_free_packs(ctx->d_audio);
2278 audio_delay -= ctx->sh_audio->stream_delay;
2279 ctx->delay = -audio_delay;
2280 ao_reset(ctx->ao);
2281 resync_audio_stream(ctx->sh_audio);
2284 audio_delay = 0.0f;
2285 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2286 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2287 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2288 if (dvdsub_lang_id != opts->sub_id) {
2289 opts->sub_id = dvdsub_lang_id;
2290 select_subtitle(ctx);
2294 /// clear all EOF related flags
2295 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2298 /// Restore last decoded DVDNAV (still frame)
2299 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2300 int *in_size,
2301 unsigned char **start,
2302 mp_image_t *decoded_frame)
2304 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2305 return decoded_frame;
2307 /// a change occurred in dvdnav stream
2308 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2309 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2310 mp_dvdnav_context_free(mpctx);
2311 mp_dvdnav_reset_stream(mpctx);
2312 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2313 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2316 if (*in_size < 0) {
2317 float len;
2319 /// Display still frame, if any
2320 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2321 decoded_frame = mpctx->nav_smpi;
2323 /// increment video frame : continue playing after still frame
2324 len = get_time_length(mpctx);
2325 if (mpctx->sh_video->pts >= len &&
2326 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2327 mp_dvdnav_skip_still(mpctx->stream);
2328 mp_dvdnav_skip_wait(mpctx->stream);
2330 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2332 if (mpctx->nav_buffer) {
2333 *start = mpctx->nav_start;
2334 *in_size = mpctx->nav_in_size;
2335 if (mpctx->nav_start)
2336 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2340 return decoded_frame;
2343 /// Save last decoded DVDNAV (still frame)
2344 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2345 unsigned char *start,
2346 mp_image_t *decoded_frame)
2348 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2349 return;
2351 free(mpctx->nav_buffer);
2352 mpctx->nav_buffer = NULL;
2353 mpctx->nav_start = NULL;
2354 mpctx->nav_in_size = -1;
2356 if (in_size > 0)
2357 mpctx->nav_buffer = malloc(in_size);
2358 if (mpctx->nav_buffer) {
2359 mpctx->nav_start = start;
2360 mpctx->nav_in_size = in_size;
2361 memcpy(mpctx->nav_buffer, start, in_size);
2364 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2365 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2367 #endif /* CONFIG_DVDNAV */
2369 /* Modify video timing to match the audio timeline. There are two main
2370 * reasons this is needed. First, video and audio can start from different
2371 * positions at beginning of file or after a seek (MPlayer starts both
2372 * immediately even if they have different pts). Second, the file can have
2373 * audio timestamps that are inconsistent with the duration of the audio
2374 * packets, for example two consecutive timestamp values differing by
2375 * one second but only a packet with enough samples for half a second
2376 * of playback between them.
2378 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2380 current_module = "av_sync";
2382 if (!mpctx->sh_audio || mpctx->syncing_audio)
2383 return;
2385 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2386 double v_pts = mpctx->sh_video->pts;
2387 double av_delay = a_pts - v_pts;
2388 // Try to sync vo_flip() so it will *finish* at given time
2389 av_delay += mpctx->last_vo_flip_duration;
2390 av_delay -= audio_delay; // This much pts difference is desired
2392 double change = av_delay * 0.1;
2393 double max_change = default_max_pts_correction >= 0 ?
2394 default_max_pts_correction : frame_time * 0.1;
2395 if (change < -max_change)
2396 change = -max_change;
2397 else if (change > max_change)
2398 change = max_change;
2399 mpctx->delay += change;
2400 mpctx->total_avsync_change += change;
2403 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2404 double pts)
2406 if (mpctx->paused)
2407 return 0;
2408 struct ao *ao = mpctx->ao;
2409 double bps = ao->bps / mpctx->opts.playback_speed;
2410 ao->pts = pts;
2411 // hack used by some mpeg-writing AOs
2412 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2413 mpctx->delay) * 90000.0;
2414 int played = ao_play(mpctx->ao, data, len, flags);
2415 if (played > 0) {
2416 mpctx->delay += played / bps;
2417 // Keep correct pts for remaining data - could be used to flush
2418 // remaining buffer when closing ao.
2419 ao->pts += played / bps;
2421 return played;
2424 #define ASYNC_PLAY_DONE -3
2425 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2427 struct ao *ao = mpctx->ao;
2428 struct MPOpts *opts = &mpctx->opts;
2429 sh_audio_t * const sh_audio = mpctx->sh_audio;
2430 int res;
2432 // Timing info may not be set without
2433 res = decode_audio(sh_audio, &ao->buffer, 1);
2434 if (res < 0)
2435 return res;
2437 int bytes;
2438 bool did_retry = false;
2439 double written_pts;
2440 double bps = ao->bps / opts->playback_speed;
2441 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2442 mpctx->hrseek_active = false;
2443 while (1) {
2444 written_pts = written_audio_pts(mpctx);
2445 double ptsdiff;
2446 if (hrseek)
2447 ptsdiff = written_pts - mpctx->hrseek_pts;
2448 else
2449 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2450 - audio_delay;
2451 bytes = ptsdiff * bps;
2452 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2454 // ogg demuxers give packets without timing
2455 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2456 if (!did_retry) {
2457 // Try to read more data to see packets that have pts
2458 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2459 if (res < 0)
2460 return res;
2461 did_retry = true;
2462 continue;
2464 bytes = 0;
2467 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2468 bytes = 0;
2470 if (bytes > 0)
2471 break;
2473 mpctx->syncing_audio = false;
2474 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2475 int res = decode_audio(sh_audio, &ao->buffer, a);
2476 bytes += ao->buffer.len;
2477 if (bytes >= 0) {
2478 memmove(ao->buffer.start,
2479 ao->buffer.start + ao->buffer.len - bytes, bytes);
2480 ao->buffer.len = bytes;
2481 if (res < 0)
2482 return res;
2483 return decode_audio(sh_audio, &ao->buffer, playsize);
2485 ao->buffer.len = 0;
2486 if (res < 0)
2487 return res;
2489 if (hrseek)
2490 // Don't add silence in audio-only case even if position is too late
2491 return 0;
2492 int fillbyte = 0;
2493 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2494 fillbyte = 0x80;
2495 if (bytes >= playsize) {
2496 /* This case could fall back to the one below with
2497 * bytes = playsize, but then silence would keep accumulating
2498 * in a_out_buffer if the AO accepts less data than it asks for
2499 * in playsize. */
2500 char *p = malloc(playsize);
2501 memset(p, fillbyte, playsize);
2502 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2503 free(p);
2504 return ASYNC_PLAY_DONE;
2506 mpctx->syncing_audio = false;
2507 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2508 return decode_audio(sh_audio, &ao->buffer, playsize);
2511 static int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
2513 struct MPOpts *opts = &mpctx->opts;
2514 struct ao *ao = mpctx->ao;
2515 unsigned int t;
2516 double tt;
2517 int playsize;
2518 int playflags = 0;
2519 bool audio_eof = false;
2520 bool partial_fill = false;
2521 sh_audio_t * const sh_audio = mpctx->sh_audio;
2522 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2523 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2525 current_module = "play_audio";
2527 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2528 return 0;
2530 // hack used by some mpeg-writing AOs
2531 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2532 mpctx->delay) * 90000.0;
2534 if (mpctx->paused)
2535 playsize = 1; // just initialize things (audio pts at least)
2536 else
2537 playsize = ao_get_space(ao);
2539 // Fill buffer if needed:
2540 current_module = "decode_audio";
2541 t = GetTimer();
2543 // Coming here with hrseek_active still set means audio-only
2544 if (!mpctx->sh_video)
2545 mpctx->syncing_audio = false;
2546 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2547 mpctx->syncing_audio = false;
2548 mpctx->hrseek_active = false;
2551 int res;
2552 if (mpctx->syncing_audio || mpctx->hrseek_active)
2553 res = audio_start_sync(mpctx, playsize);
2554 else
2555 res = decode_audio(sh_audio, &ao->buffer, playsize);
2556 if (res < 0) { // EOF, error or format change
2557 if (res == -2) {
2558 /* The format change isn't handled too gracefully. A more precise
2559 * implementation would require draining buffered old-format audio
2560 * while displaying video, then doing the output format switch.
2562 uninit_player(mpctx, INITIALIZED_AO);
2563 reinit_audio_chain(mpctx);
2564 return -1;
2565 } else if (res == ASYNC_PLAY_DONE)
2566 return 0;
2567 else if (mpctx->d_audio->eof)
2568 audio_eof = true;
2570 t = GetTimer() - t;
2571 tt = t * 0.000001f;
2572 audio_time_usage += tt;
2573 if (endpts != MP_NOPTS_VALUE && modifiable_audio_format) {
2574 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2575 * ao->bps / opts->playback_speed;
2576 if (playsize > bytes) {
2577 playsize = FFMAX(bytes, 0);
2578 playflags |= AOPLAY_FINAL_CHUNK;
2579 audio_eof = true;
2580 partial_fill = true;
2584 assert(ao->buffer.len % unitsize == 0);
2585 if (playsize > ao->buffer.len) {
2586 partial_fill = true;
2587 playsize = ao->buffer.len;
2588 if (audio_eof)
2589 playflags |= AOPLAY_FINAL_CHUNK;
2591 playsize -= playsize % unitsize;
2592 if (!playsize)
2593 return partial_fill && audio_eof ? -2 : -partial_fill;
2595 // play audio:
2596 current_module = "play_audio";
2598 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2599 written_audio_pts(mpctx));
2600 assert(played % unitsize == 0);
2601 ao->buffer_playable_size = playsize - played;
2603 if (played > 0) {
2604 ao->buffer.len -= played;
2605 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2606 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2607 // Sanity check to avoid hanging in case current ao doesn't output
2608 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2609 return -2;
2612 return -partial_fill;
2615 int reinit_video_chain(struct MPContext *mpctx)
2617 struct MPOpts *opts = &mpctx->opts;
2618 sh_video_t * const sh_video = mpctx->sh_video;
2619 if (!sh_video)
2620 return 0;
2621 double ar = -1.0;
2622 //================== Init VIDEO (codec & libvo) ==========================
2623 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2624 current_module = "preinit_libvo";
2626 //shouldn't we set dvideo->id=-2 when we fail?
2627 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2628 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2629 mpctx->key_fifo,
2630 mpctx->input))) {
2631 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2632 "the selected video_out (-vo) device.\n");
2633 goto err_out;
2635 mpctx->initialized_flags |= INITIALIZED_VO;
2638 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2639 &ar) != STREAM_UNSUPPORTED)
2640 mpctx->sh_video->stream_aspect = ar;
2641 current_module = "init_video_filters";
2643 char *vf_arg[] = {
2644 "_oldargs_", (char *)mpctx->video_out, NULL
2646 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2649 #ifdef CONFIG_ASS
2650 if (opts->ass_enabled) {
2651 int i;
2652 int insert = 1;
2653 if (opts->vf_settings)
2654 for (i = 0; opts->vf_settings[i].name; ++i)
2655 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2656 insert = 0;
2657 break;
2659 if (insert) {
2660 extern vf_info_t vf_info_ass;
2661 const vf_info_t *libass_vfs[] = {
2662 &vf_info_ass, NULL
2664 char *vf_arg[] = {
2665 "auto", "1", NULL
2667 int retcode = 0;
2668 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2669 sh_video->vfilter,
2670 "ass", vf_arg,
2671 &retcode);
2672 if (vf_ass)
2673 sh_video->vfilter = vf_ass;
2674 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2675 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2676 else
2677 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2678 "ASS: cannot add video filter\n");
2681 #endif
2683 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2685 #ifdef CONFIG_ASS
2686 if (opts->ass_enabled)
2687 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2688 mpctx->ass_library);
2689 #endif
2691 current_module = "init_video_codec";
2693 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2694 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2695 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2697 if (!sh_video->initialized) {
2698 if (!opts->fixed_vo)
2699 uninit_player(mpctx, INITIALIZED_VO);
2700 goto err_out;
2703 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2705 if (sh_video->codec)
2706 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2707 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2709 sh_video->last_pts = MP_NOPTS_VALUE;
2710 sh_video->num_buffered_pts = 0;
2711 sh_video->next_frame_time = 0;
2713 if (opts->auto_quality > 0) {
2714 // Auto quality option enabled
2715 output_quality = get_video_quality_max(sh_video);
2716 if (opts->auto_quality > output_quality)
2717 opts->auto_quality = output_quality;
2718 else
2719 output_quality = opts->auto_quality;
2720 mp_msg(MSGT_CPLAYER, MSGL_V,
2721 "AutoQ: setting quality to %d.\n", output_quality);
2722 set_video_quality(sh_video, output_quality);
2725 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2727 current_module = "init_vo";
2729 return 1;
2731 err_out:
2732 mpctx->sh_video = mpctx->d_video->sh = NULL;
2733 return 0;
2736 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2738 struct sh_video *sh_video = mpctx->sh_video;
2739 double frame_time = 0;
2740 struct vo *video_out = mpctx->video_out;
2741 while (1) {
2742 current_module = "filter_video";
2743 // In nocorrect-pts mode there is no way to properly time these frames
2744 if (vo_get_buffered_frame(video_out, 0) >= 0)
2745 break;
2746 if (vf_output_queued_frame(sh_video->vfilter))
2747 break;
2748 unsigned char *packet = NULL;
2749 frame_time = sh_video->next_frame_time;
2750 if (mpctx->restart_playback)
2751 frame_time = 0;
2752 int in_size = 0;
2753 while (!in_size)
2754 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2755 &packet, force_fps);
2756 if (in_size < 0) {
2757 #ifdef CONFIG_DVDNAV
2758 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2759 if (mp_dvdnav_is_eof(mpctx->stream))
2760 return -1;
2761 if (mpctx->d_video)
2762 mpctx->d_video->eof = 0;
2763 if (mpctx->d_audio)
2764 mpctx->d_audio->eof = 0;
2765 mpctx->stream->eof = 0;
2766 } else
2767 #endif
2768 return -1;
2770 if (in_size > max_framesize)
2771 max_framesize = in_size;
2772 sh_video->timer += frame_time;
2773 if (mpctx->sh_audio)
2774 mpctx->delay -= frame_time;
2775 // video_read_frame can change fps (e.g. for ASF video)
2776 vo_fps = sh_video->fps;
2777 int framedrop_type = check_framedrop(mpctx, frame_time);
2778 current_module = "decode video";
2780 void *decoded_frame;
2781 #ifdef CONFIG_DVDNAV
2782 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2783 if (in_size >= 0 && !decoded_frame)
2784 #endif
2785 decoded_frame = decode_video(sh_video, NULL, packet, in_size,
2786 framedrop_type, sh_video->pts);
2787 #ifdef CONFIG_DVDNAV
2788 // Save last still frame for future display
2789 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2790 #endif
2791 if (decoded_frame) {
2792 current_module = "filter video";
2793 filter_video(sh_video, decoded_frame, sh_video->pts);
2795 break;
2797 return frame_time;
2800 static void determine_frame_pts(struct MPContext *mpctx)
2802 struct sh_video *sh_video = mpctx->sh_video;
2803 struct MPOpts *opts = &mpctx->opts;
2805 if (opts->user_pts_assoc_mode)
2806 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2807 else if (sh_video->pts_assoc_mode == 0) {
2808 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2809 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2810 sh_video->pts_assoc_mode = 1;
2811 else
2812 sh_video->pts_assoc_mode = 2;
2813 } else {
2814 int probcount1 = sh_video->num_reordered_pts_problems;
2815 int probcount2 = sh_video->num_sorted_pts_problems;
2816 if (sh_video->pts_assoc_mode == 2) {
2817 int tmp = probcount1;
2818 probcount1 = probcount2;
2819 probcount2 = tmp;
2821 if (probcount1 >= probcount2 * 1.5 + 2) {
2822 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2823 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2824 "%d.\n", sh_video->pts_assoc_mode);
2827 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2828 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2831 static double update_video(struct MPContext *mpctx)
2833 struct sh_video *sh_video = mpctx->sh_video;
2834 struct vo *video_out = mpctx->video_out;
2835 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2836 mpctx->osd); // hack for vf_expand
2837 if (!mpctx->opts.correct_pts)
2838 return update_video_nocorrect_pts(mpctx);
2840 double pts;
2842 while (1) {
2843 current_module = "filter_video";
2844 if (vo_get_buffered_frame(video_out, false) >= 0)
2845 break;
2846 // XXX Time used in this call is not counted in any performance
2847 // timer now
2848 if (vf_output_queued_frame(sh_video->vfilter))
2849 break;
2850 int in_size = 0;
2851 unsigned char *buf = NULL;
2852 pts = MP_NOPTS_VALUE;
2853 struct demux_packet *pkt;
2854 while (1) {
2855 pkt = ds_get_packet2(mpctx->d_video, false);
2856 if (!pkt || pkt->len)
2857 break;
2858 /* Packets with size 0 are assumed to not correspond to frames,
2859 * but to indicate the absence of a frame in formats like AVI
2860 * that must have packets at fixed timecode intervals. */
2862 if (pkt) {
2863 in_size = pkt->len;
2864 buf = pkt->buffer;
2865 pts = pkt->pts;
2867 if (pts != MP_NOPTS_VALUE)
2868 pts += mpctx->video_offset;
2869 if (in_size > max_framesize)
2870 max_framesize = in_size;
2871 current_module = "decode video";
2872 if (pts >= mpctx->hrseek_pts - .005)
2873 mpctx->hrseek_framedrop = false;
2874 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2875 check_framedrop(mpctx, sh_video->frametime);
2876 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2877 framedrop_type, pts);
2878 if (decoded_frame) {
2879 determine_frame_pts(mpctx);
2880 current_module = "filter video";
2881 filter_video(sh_video, decoded_frame, sh_video->pts);
2882 } else if (!pkt) {
2883 if (vo_get_buffered_frame(video_out, true) < 0)
2884 return -1;
2886 break;
2889 if (!video_out->frame_loaded)
2890 return 0;
2892 pts = video_out->next_pts;
2893 if (pts == MP_NOPTS_VALUE) {
2894 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2895 // Try to use decoder pts from before filters
2896 pts = sh_video->pts;
2897 if (pts == MP_NOPTS_VALUE)
2898 pts = sh_video->last_pts;
2900 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2901 vo_skip_frame(video_out);
2902 return 0;
2904 mpctx->hrseek_active = false;
2905 sh_video->pts = pts;
2906 if (sh_video->last_pts == MP_NOPTS_VALUE)
2907 sh_video->last_pts = sh_video->pts;
2908 else if (sh_video->last_pts > sh_video->pts) {
2909 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2910 sh_video->pts, sh_video->last_pts);
2911 /* If the difference in pts is small treat it as jitter around the
2912 * right value (possibly caused by incorrect timestamp ordering) and
2913 * just show this frame immediately after the last one.
2914 * Treat bigger differences as timestamp resets and start counting
2915 * timing of later frames from the position of this one. */
2916 if (sh_video->last_pts - sh_video->pts > 0.5)
2917 sh_video->last_pts = sh_video->pts;
2918 else
2919 sh_video->pts = sh_video->last_pts;
2921 double frame_time = sh_video->pts - sh_video->last_pts;
2922 sh_video->last_pts = sh_video->pts;
2923 sh_video->timer += frame_time;
2924 if (mpctx->sh_audio)
2925 mpctx->delay -= frame_time;
2926 return frame_time;
2929 static int get_cache_fill(struct MPContext *mpctx)
2931 #ifdef CONFIG_STREAM_CACHE
2932 if (stream_cache_size > 0)
2933 return cache_fill_status(mpctx->stream);
2934 #endif
2935 return -1;
2938 static void update_pause_message(struct MPContext *mpctx)
2940 struct MPOpts *opts = &mpctx->opts;
2942 if (opts->quiet)
2943 return;
2945 int cache_fill = get_cache_fill(mpctx);
2946 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2948 if (!mpctx->status_printed && !cache_changed)
2949 return;
2951 char *msg = mp_gtext(" ===== PAUSE =====");
2952 char *tmpmem = NULL;
2953 if (cache_fill >= 0)
2954 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
2956 if (opts->term_osd && !mpctx->sh_video) {
2957 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
2958 update_osd_msg(mpctx);
2959 } else {
2960 if (mpctx->status_printed)
2961 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
2962 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
2965 mpctx->paused_cache_fill = cache_fill;
2966 mpctx->status_printed = false;
2968 talloc_free(tmpmem);
2971 void pause_player(struct MPContext *mpctx)
2973 if (mpctx->paused)
2974 return;
2975 mpctx->paused = 1;
2976 mpctx->step_frames = 0;
2977 mpctx->time_frame -= get_relative_time(mpctx);
2978 mpctx->osd_function = OSD_PAUSE;
2980 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2981 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2983 if (mpctx->ao && mpctx->sh_audio)
2984 ao_pause(mpctx->ao); // pause audio, keep data if possible
2986 mpctx->paused_cache_fill = get_cache_fill(mpctx);
2987 mpctx->status_printed = true;
2988 update_pause_message(mpctx);
2990 if (!mpctx->opts.quiet)
2991 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2994 void unpause_player(struct MPContext *mpctx)
2996 if (!mpctx->paused)
2997 return;
2998 mpctx->paused = 0;
2999 if (!mpctx->step_frames)
3000 mpctx->osd_function = OSD_PLAY;
3002 if (mpctx->ao && mpctx->sh_audio)
3003 ao_resume(mpctx->ao);
3004 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3005 && !mpctx->step_frames)
3006 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3007 (void)get_relative_time(mpctx); // ignore time that passed during pause
3010 static int redraw_osd(struct MPContext *mpctx)
3012 struct sh_video *sh_video = mpctx->sh_video;
3013 struct vf_instance *vf = sh_video->vfilter;
3014 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3015 return -1;
3016 if (vo_redraw_frame(mpctx->video_out) < 0)
3017 return -1;
3018 mpctx->osd->pts = mpctx->video_pts - mpctx->osd->sub_offset;
3019 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3020 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3021 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3022 vo_flip_page(mpctx->video_out, 0, -1);
3023 return 0;
3026 void add_step_frame(struct MPContext *mpctx)
3028 mpctx->step_frames++;
3029 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3030 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3031 unpause_player(mpctx);
3034 static void seek_reset(struct MPContext *mpctx, bool reset_ao, bool reset_ac)
3036 if (mpctx->sh_video) {
3037 current_module = "seek_video_reset";
3038 resync_video_stream(mpctx->sh_video);
3039 mpctx->sh_video->timer = 0;
3040 vo_seek_reset(mpctx->video_out);
3041 mpctx->sh_video->timer = 0;
3042 mpctx->sh_video->num_buffered_pts = 0;
3043 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3044 mpctx->delay = 0;
3045 mpctx->time_frame = 0;
3046 // Not all demuxers set d_video->pts during seek, so this value
3047 // (which is used by at least vobsub code below) may be completely
3048 // wrong (probably 0).
3049 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3050 mpctx->video_pts = mpctx->sh_video->pts;
3051 update_subtitles(mpctx, mpctx->sh_video->pts, true);
3052 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3055 if (mpctx->sh_audio && reset_ac) {
3056 current_module = "seek_audio_reset";
3057 resync_audio_stream(mpctx->sh_audio);
3058 if (reset_ao)
3059 ao_reset(mpctx->ao);
3060 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3061 mpctx->sh_audio->a_buffer_len = 0;
3062 if (!mpctx->sh_video)
3063 update_subtitles(mpctx, mpctx->sh_audio->pts, true);
3066 if (vo_vobsub && mpctx->sh_video) {
3067 current_module = "seek_vobsub_reset";
3068 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3071 mpctx->restart_playback = true;
3072 mpctx->hrseek_active = false;
3073 mpctx->hrseek_framedrop = false;
3074 mpctx->total_avsync_change = 0;
3075 audio_time_usage = 0;
3076 video_time_usage = 0;
3077 vout_time_usage = 0;
3078 drop_frame_cnt = 0;
3080 current_module = NULL;
3083 static bool timeline_set_part(struct MPContext *mpctx, int i)
3085 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3086 struct timeline_part *n = mpctx->timeline + i;
3087 mpctx->timeline_part = i;
3088 mpctx->video_offset = n->start - n->source_start;
3089 if (n->source == p->source)
3090 return false;
3091 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3092 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3093 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3094 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3095 mpctx->stop_play = orig_stop_play;
3096 mpctx->demuxer = n->source->demuxer;
3097 mpctx->d_video = mpctx->demuxer->video;
3098 mpctx->d_audio = mpctx->demuxer->audio;
3099 mpctx->d_sub = mpctx->demuxer->sub;
3100 mpctx->sh_video = mpctx->d_video->sh;
3101 mpctx->sh_audio = mpctx->d_audio->sh;
3102 return true;
3105 // Given pts, switch playback to the corresponding part.
3106 // Return offset within that part.
3107 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3108 bool *need_reset)
3110 if (pts < 0)
3111 pts = 0;
3112 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3113 struct timeline_part *p = mpctx->timeline + i;
3114 if (pts < (p + 1)->start) {
3115 *need_reset = timeline_set_part(mpctx, i);
3116 return pts - p->start + p->source_start;
3119 return -1;
3123 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3124 static int seek(MPContext *mpctx, struct seek_params seek,
3125 bool timeline_fallthrough)
3127 struct MPOpts *opts = &mpctx->opts;
3129 current_module = "seek";
3130 if (mpctx->stop_play == AT_END_OF_FILE)
3131 mpctx->stop_play = KEEP_PLAYING;
3132 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3133 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3134 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3135 || opts->hr_seek > 0 || seek.exact > 0;
3136 if (seek.type == MPSEEK_FACTOR
3137 || seek.type == MPSEEK_ABSOLUTE
3138 && seek.amount < mpctx->last_chapter_pts
3139 || seek.amount < 0)
3140 mpctx->last_chapter_seek = -2;
3141 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3142 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3143 seek.type = MPSEEK_ABSOLUTE;
3145 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3146 && seek.type == MPSEEK_RELATIVE) {
3147 seek.type = MPSEEK_ABSOLUTE;
3148 seek.direction = seek.amount > 0 ? 1 : -1;
3149 seek.amount += get_current_time(mpctx);
3152 /* At least the liba52 decoder wants to read from the input stream
3153 * during initialization, so reinit must be done after the demux_seek()
3154 * call that clears possible stream EOF. */
3155 bool need_reset = false;
3156 double demuxer_amount = seek.amount;
3157 if (mpctx->timeline) {
3158 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3159 &need_reset);
3160 if (demuxer_amount == -1) {
3161 mpctx->stop_play = AT_END_OF_FILE;
3162 // Clear audio from current position
3163 if (mpctx->sh_audio && !timeline_fallthrough) {
3164 ao_reset(mpctx->ao);
3165 mpctx->sh_audio->a_buffer_len = 0;
3167 return -1;
3170 if (need_reset) {
3171 reinit_video_chain(mpctx);
3172 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos},
3173 mpctx);
3176 int demuxer_style = 0;
3177 switch (seek.type) {
3178 case MPSEEK_FACTOR:
3179 demuxer_style |= SEEK_FACTOR; // fallthrough
3180 case MPSEEK_ABSOLUTE:
3181 demuxer_style |= SEEK_ABSOLUTE;
3183 if (hr_seek || seek.direction < 0)
3184 demuxer_style |= SEEK_BACKWARD;
3185 else if (seek.direction > 0)
3186 demuxer_style |= SEEK_FORWARD;
3188 if (hr_seek)
3189 demuxer_amount -= opts->hr_seek_demuxer_offset;
3190 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3191 demuxer_style);
3192 if (seekresult == 0) {
3193 if (need_reset) {
3194 reinit_audio_chain(mpctx);
3195 seek_reset(mpctx, !timeline_fallthrough, false);
3197 return -1;
3200 if (need_reset)
3201 reinit_audio_chain(mpctx);
3202 /* If we just reinitialized audio it doesn't need to be reset,
3203 * and resetting could lose audio some decoders produce during init. */
3204 seek_reset(mpctx, !timeline_fallthrough, !need_reset);
3206 /* Use the target time as "current position" for further relative
3207 * seeks etc until a new video frame has been decoded */
3208 if (seek.type == MPSEEK_ABSOLUTE) {
3209 mpctx->video_pts = seek.amount;
3210 mpctx->last_seek_pts = seek.amount;
3211 } else
3212 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3214 if (hr_seek) {
3215 mpctx->hrseek_active = true;
3216 mpctx->hrseek_framedrop = true;
3217 mpctx->hrseek_pts = seek.amount;
3220 mpctx->start_timestamp = GetTimerMS();
3222 return 0;
3225 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3226 int exact)
3228 struct seek_params *seek = &mpctx->seek;
3229 switch (type) {
3230 case MPSEEK_RELATIVE:
3231 if (seek->type == MPSEEK_FACTOR)
3232 return; // Well... not common enough to bother doing better
3233 seek->amount += amount;
3234 seek->exact = FFMAX(seek->exact, exact);
3235 if (seek->type == MPSEEK_NONE)
3236 seek->exact = exact;
3237 if (seek->type == MPSEEK_ABSOLUTE)
3238 return;
3239 if (seek->amount == 0) {
3240 *seek = (struct seek_params){ 0 };
3241 return;
3243 seek->type = MPSEEK_RELATIVE;
3244 return;
3245 case MPSEEK_ABSOLUTE:
3246 case MPSEEK_FACTOR:
3247 *seek = (struct seek_params) {
3248 .type = type,
3249 .amount = amount,
3250 .exact = exact,
3252 return;
3253 case MPSEEK_NONE:
3254 *seek = (struct seek_params){ 0 };
3255 return;
3257 abort();
3261 double get_time_length(struct MPContext *mpctx)
3263 if (mpctx->timeline)
3264 return mpctx->timeline[mpctx->num_timeline_parts].start;
3266 struct demuxer *demuxer = mpctx->demuxer;
3267 double get_time_ans;
3268 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3269 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3270 (void *) &get_time_ans) > 0)
3271 return get_time_ans;
3273 struct sh_video *sh_video = mpctx->d_video->sh;
3274 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3275 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3276 return (double) (demuxer->movi_end - demuxer->movi_start) /
3277 (sh_video->i_bps + sh_audio->i_bps);
3278 if (sh_video && sh_video->i_bps)
3279 return (double) (demuxer->movi_end - demuxer->movi_start) /
3280 sh_video->i_bps;
3281 if (sh_audio && sh_audio->i_bps)
3282 return (double) (demuxer->movi_end - demuxer->movi_start) /
3283 sh_audio->i_bps;
3284 return 0;
3287 /* If there are timestamps from stream level then use those (for example
3288 * DVDs can have consistent times there while the MPEG-level timestamps
3289 * reset). */
3290 double get_current_time(struct MPContext *mpctx)
3292 struct demuxer *demuxer = mpctx->demuxer;
3293 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3294 return demuxer->stream_pts;
3295 if (mpctx->sh_video) {
3296 double pts = mpctx->video_pts;
3297 if (pts != MP_NOPTS_VALUE)
3298 return pts;
3300 double apts = playing_audio_pts(mpctx);
3301 if (apts != MP_NOPTS_VALUE)
3302 return apts;
3303 return mpctx->last_seek_pts;
3306 int get_percent_pos(struct MPContext *mpctx)
3308 struct demuxer *demuxer = mpctx->demuxer;
3309 int ans = 0;
3310 if (mpctx->timeline)
3311 ans = get_current_time(mpctx) * 100 /
3312 mpctx->timeline[mpctx->num_timeline_parts].start;
3313 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3315 else {
3316 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3317 off_t pos = demuxer->filepos > 0 ?
3318 demuxer->filepos : stream_tell(demuxer->stream);
3319 if (len > 0)
3320 ans = (pos - demuxer->movi_start) / len;
3321 else
3322 ans = 0;
3324 if (ans < 0)
3325 ans = 0;
3326 if (ans > 100)
3327 ans = 100;
3328 return ans;
3331 // -2 is no chapters, -1 is before first chapter
3332 int get_current_chapter(struct MPContext *mpctx)
3334 double current_pts = get_current_time(mpctx);
3335 if (!mpctx->chapters)
3336 return FFMAX(mpctx->last_chapter_seek,
3337 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3339 int i;
3340 for (i = 1; i < mpctx->num_chapters; i++)
3341 if (current_pts < mpctx->chapters[i].start)
3342 break;
3343 return FFMAX(mpctx->last_chapter_seek, i - 1);
3346 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3348 char *name = chapter_name(mpctx, chapter);
3349 if (name) {
3350 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3351 } else {
3352 int chapter_count = get_chapter_count(mpctx);
3353 if (chapter_count <= 0)
3354 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3355 else
3356 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3357 chapter_count);
3359 return name;
3362 // returns NULL if chapter name unavailable
3363 char *chapter_name(struct MPContext *mpctx, int chapter)
3365 if (!mpctx->chapters)
3366 return demuxer_chapter_name(mpctx->demuxer, chapter);
3367 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3370 // returns the start of the chapter in seconds
3371 double chapter_start_time(struct MPContext *mpctx, int chapter)
3373 if (!mpctx->chapters)
3374 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3375 return mpctx->chapters[chapter].start;
3378 int get_chapter_count(struct MPContext *mpctx)
3380 if (!mpctx->chapters)
3381 return demuxer_chapter_count(mpctx->demuxer);
3382 return mpctx->num_chapters;
3385 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3387 mpctx->last_chapter_seek = -2;
3388 if (!mpctx->chapters) {
3389 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3390 if (res >= 0) {
3391 if (*seek_pts == -1)
3392 seek_reset(mpctx, true, true);
3393 else {
3394 mpctx->last_chapter_seek = res;
3395 mpctx->last_chapter_pts = *seek_pts;
3398 return res;
3401 if (chapter >= mpctx->num_chapters)
3402 return -1;
3403 if (chapter < 0)
3404 chapter = 0;
3405 *seek_pts = mpctx->chapters[chapter].start;
3406 mpctx->last_chapter_seek = chapter;
3407 mpctx->last_chapter_pts = *seek_pts;
3408 return chapter;
3412 static void run_playloop(struct MPContext *mpctx)
3414 struct MPOpts *opts = &mpctx->opts;
3415 bool full_audio_buffers = false;
3416 bool audio_left = false, video_left = false;
3417 double endpts = end_at.type == END_AT_TIME ? end_at.pos : MP_NOPTS_VALUE;
3418 bool end_is_chapter = false;
3419 double sleeptime = 0.5;
3420 bool was_restart = mpctx->restart_playback;
3422 if (mpctx->timeline) {
3423 double end = mpctx->timeline[mpctx->timeline_part + 1].start;
3424 if (endpts == MP_NOPTS_VALUE || end < endpts) {
3425 endpts = end;
3426 end_is_chapter = true;
3430 if (opts->chapterrange[1] > 0) {
3431 int cur_chapter = get_current_chapter(mpctx);
3432 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3433 mpctx->stop_play = PT_NEXT_ENTRY;
3436 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3437 mpctx->sh_audio = mpctx->d_audio->sh;
3438 mpctx->sh_audio->ds = mpctx->d_audio;
3439 reinit_audio_chain(mpctx);
3442 if (mpctx->step_frames && !mpctx->sh_video) {
3443 mpctx->step_frames = 0;
3444 pause_player(mpctx);
3447 if (mpctx->sh_audio && !mpctx->restart_playback) {
3448 int status = fill_audio_out_buffers(mpctx, endpts);
3449 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3450 // Not at audio stream EOF yet
3451 audio_left = status > -2;
3454 double buffered_audio = -1;
3455 while (mpctx->sh_video) { // never loops, for "break;" only
3456 vo_pts = mpctx->sh_video->timer * 90000.0;
3457 vo_fps = mpctx->sh_video->fps;
3459 video_left = mpctx->video_out->hasframe;
3460 if (!mpctx->video_out->frame_loaded
3461 && (!mpctx->paused || mpctx->restart_playback)) {
3462 double frame_time = update_video(mpctx);
3463 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3464 if (mpctx->sh_video->vf_initialized < 0) {
3465 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3466 "\nFATAL: Could not initialize video filters (-vf) "
3467 "or video output (-vo).\n");
3468 mpctx->stop_play = PT_NEXT_ENTRY;
3469 return;
3471 video_left = frame_time >= 0;
3472 if (endpts != MP_NOPTS_VALUE)
3473 video_left &= mpctx->sh_video->pts < endpts;
3474 if (video_left && !mpctx->restart_playback) {
3475 mpctx->time_frame += frame_time / opts->playback_speed;
3476 adjust_sync(mpctx, frame_time);
3480 // ================================================================
3482 current_module = "vo_check_events";
3483 vo_check_events(mpctx->video_out);
3485 #ifdef CONFIG_X11
3486 if (stop_xscreensaver) {
3487 current_module = "stop_xscreensaver";
3488 xscreensaver_heartbeat(mpctx->x11_state);
3490 #endif
3491 if (heartbeat_cmd) {
3492 static unsigned last_heartbeat;
3493 unsigned now = GetTimerMS();
3494 if (now - last_heartbeat > 30000) {
3495 last_heartbeat = now;
3496 system(heartbeat_cmd);
3500 if (!video_left || (mpctx->paused && !mpctx->restart_playback))
3501 break;
3502 if (!mpctx->video_out->frame_loaded) {
3503 sleeptime = 0;
3504 break;
3507 mpctx->time_frame -= get_relative_time(mpctx);
3508 if (full_audio_buffers && !mpctx->restart_playback) {
3509 buffered_audio = ao_get_delay(mpctx->ao);
3510 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", buffered_audio);
3512 if (opts->autosync) {
3513 /* Smooth reported playback position from AO by averaging
3514 * it with the value expected based on previus value and
3515 * time elapsed since then. May help smooth video timing
3516 * with audio output that have inaccurate position reporting.
3517 * This is badly implemented; the behavior of the smoothing
3518 * now undesirably depends on how often this code runs
3519 * (mainly depends on video frame rate). */
3520 float predicted = (mpctx->delay / opts->playback_speed +
3521 mpctx->time_frame);
3522 float difference = buffered_audio - predicted;
3523 buffered_audio = predicted + difference / opts->autosync;
3526 mpctx->time_frame = (buffered_audio -
3527 mpctx->delay / opts->playback_speed);
3528 } else {
3529 /* If we're more than 200 ms behind the right playback
3530 * position, don't try to speed up display of following
3531 * frames to catch up; continue with default speed from
3532 * the current frame instead.
3533 * If benchmark is set always output frames immediately
3534 * without sleeping.
3536 if (mpctx->time_frame < -0.2 || opts->benchmark)
3537 mpctx->time_frame = 0;
3540 double vsleep = mpctx->time_frame - mpctx->video_out->flip_queue_offset;
3541 if (vsleep > 0.050) {
3542 sleeptime = FFMIN(sleeptime, vsleep - 0.040);
3543 break;
3545 sleeptime = 0;
3547 //=================== FLIP PAGE (VIDEO BLT): ======================
3549 current_module = "flip_page";
3550 vo_new_frame_imminent(mpctx->video_out);
3551 struct sh_video *sh_video = mpctx->sh_video;
3552 mpctx->video_pts = sh_video->pts;
3553 update_subtitles(mpctx, sh_video->pts, false);
3554 update_teletext(sh_video, mpctx->demuxer, 0);
3555 update_osd_msg(mpctx);
3556 struct vf_instance *vf = sh_video->vfilter;
3557 mpctx->osd->pts = mpctx->video_pts - mpctx->osd->sub_offset;
3558 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3559 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3560 vo_osd_changed(0);
3562 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3563 float aq_sleep_time = mpctx->time_frame;
3564 if (mpctx->time_frame > 0.001
3565 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3566 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3567 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3569 unsigned int t2 = GetTimer();
3570 /* Playing with playback speed it's possible to get pathological
3571 * cases with mpctx->time_frame negative enough to cause an
3572 * overflow in pts_us calculation, thus the FFMAX. */
3573 double time_frame = FFMAX(mpctx->time_frame, -1);
3574 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3575 int duration = -1;
3576 double pts2 = mpctx->video_out->next_pts2;
3577 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts &&
3578 !mpctx->restart_playback) {
3579 // expected A/V sync correction is ignored
3580 double diff = (pts2 - mpctx->video_pts);
3581 diff /= opts->playback_speed;
3582 if (mpctx->time_frame < 0)
3583 diff += mpctx->time_frame;
3584 if (diff < 0)
3585 diff = 0;
3586 if (diff > 10)
3587 diff = 10;
3588 duration = diff * 1e6;
3590 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3592 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3593 vout_time_usage += mpctx->last_vo_flip_duration;
3594 if (mpctx->video_out->driver->flip_page_timed) {
3595 // No need to adjust sync based on flip speed
3596 mpctx->last_vo_flip_duration = 0;
3597 // For print_status - VO call finishing early is OK for sync
3598 mpctx->time_frame -= get_relative_time(mpctx);
3600 if (mpctx->restart_playback) {
3601 mpctx->syncing_audio = true;
3602 if (mpctx->sh_audio)
3603 fill_audio_out_buffers(mpctx, endpts);
3604 mpctx->restart_playback = false;
3605 mpctx->time_frame = 0;
3606 get_relative_time(mpctx);
3608 print_status(mpctx, MP_NOPTS_VALUE, true);
3609 screenshot_flip(mpctx);
3611 if (opts->auto_quality > 0) {
3612 current_module = "autoq";
3613 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3614 ++output_quality;
3615 else if (output_quality > 1 && aq_sleep_time < 0)
3616 --output_quality;
3617 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3618 output_quality = 0;
3619 set_video_quality(mpctx->sh_video, output_quality);
3622 if (play_n_frames >= 0) {
3623 --play_n_frames;
3624 if (play_n_frames <= 0)
3625 mpctx->stop_play = PT_NEXT_ENTRY;
3627 if (mpctx->step_frames > 0) {
3628 mpctx->step_frames--;
3629 if (mpctx->step_frames == 0)
3630 pause_player(mpctx);
3632 break;
3633 } // video
3635 #ifdef CONFIG_DVDNAV
3636 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3637 nav_highlight_t hl;
3638 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3639 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3640 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3641 vo_osd_changed(OSDTYPE_DVDNAV);
3642 } else {
3643 osd_set_nav_box(0, 0, 0, 0);
3644 vo_osd_changed(OSDTYPE_DVDNAV);
3645 vo_osd_changed(OSDTYPE_SPU);
3648 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3649 double ar = -1.0;
3650 if (mpctx->sh_video &&
3651 stream_control(mpctx->demuxer->stream,
3652 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3653 != STREAM_UNSUPPORTED)
3654 mpctx->sh_video->stream_aspect = ar;
3657 #endif
3659 if (mpctx->restart_playback && !video_left) {
3660 if (mpctx->sh_audio) {
3661 int status = fill_audio_out_buffers(mpctx, endpts);
3662 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3663 // Not at audio stream EOF yet
3664 audio_left = status > -2;
3666 mpctx->restart_playback = false;
3668 if (mpctx->sh_audio && buffered_audio == -1)
3669 buffered_audio = mpctx->paused ? 0 : ao_get_delay(mpctx->ao);
3671 update_osd_msg(mpctx);
3672 if (mpctx->paused)
3673 update_pause_message(mpctx);
3674 if (!video_left && (!mpctx->paused || was_restart)) {
3675 double a_pos = 0;
3676 if (mpctx->sh_audio) {
3677 a_pos = (written_audio_pts(mpctx) -
3678 mpctx->opts.playback_speed * buffered_audio);
3680 print_status(mpctx, a_pos, false);
3682 if (!mpctx->sh_video)
3683 update_subtitles(mpctx, a_pos, false);
3686 /* It's possible for the user to simultaneously switch both audio
3687 * and video streams to "disabled" at runtime. Handle this by waiting
3688 * rather than immediately stopping playback due to EOF.
3690 * When all audio has been written to output driver, stay in the
3691 * main loop handling commands until it has been mostly consumed,
3692 * except in the gapless case, where the next file will be started
3693 * while audio from the current one still remains to be played.
3695 * We want this check to trigger if we seeked to this position,
3696 * but not if we paused at it with audio possibly still buffered in
3697 * the AO. There's currently no working way to check buffered audio
3698 * inside AO while paused. Thus the "was_restart" check below, which
3699 * should trigger after seek only, when we know there's no audio
3700 * buffered.
3702 if ((mpctx->sh_audio || mpctx->sh_video) && !audio_left && !video_left
3703 && (opts->gapless_audio || buffered_audio < 0.05)
3704 && (!mpctx->paused || was_restart)) {
3705 if (end_is_chapter) {
3706 seek(mpctx, (struct seek_params){
3707 .type = MPSEEK_ABSOLUTE,
3708 .amount = mpctx->timeline[mpctx->timeline_part+1].start
3709 }, true);
3710 } else
3711 mpctx->stop_play = AT_END_OF_FILE;
3712 } else if (!mpctx->stop_play) {
3713 double audio_sleep = 9;
3714 if (mpctx->sh_audio && !mpctx->paused) {
3715 if (mpctx->ao->untimed) {
3716 if (!mpctx->sh_video)
3717 audio_sleep = 0;
3718 } else if (full_audio_buffers) {
3719 audio_sleep = buffered_audio - 0.050;
3720 // Keep extra safety margin if the buffers are large
3721 if (audio_sleep > 0.100)
3722 audio_sleep = FFMAX(audio_sleep - 0.200, 0.100);
3723 else
3724 audio_sleep = FFMAX(audio_sleep, 0.020);
3725 } else
3726 audio_sleep = 0.020;
3728 sleeptime = FFMIN(sleeptime, audio_sleep);
3729 if (sleeptime > 0) {
3730 if (!mpctx->sh_video)
3731 goto novideo;
3732 int hack = vo_osd_changed(0);
3733 vo_osd_changed(hack);
3734 if (hack || mpctx->video_out->want_redraw) {
3735 if (redraw_osd(mpctx) < 0) {
3736 if (mpctx->paused && video_left)
3737 add_step_frame(mpctx);
3738 else
3739 goto novideo;
3740 } else
3741 vo_osd_changed(0);
3742 } else {
3743 novideo:
3744 mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
3749 //================= Keyboard events, SEEKing ====================
3751 current_module = "key_events";
3753 mp_cmd_t *cmd;
3754 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3755 /* Allow running consecutive seek commands to combine them,
3756 * but execute the seek before running other commands.
3757 * If the user seeks continuously (keeps arrow key down)
3758 * try to finish showing a frame from one location before doing
3759 * another seek (which could lead to unchanging display). */
3760 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3761 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3762 && GetTimerMS() - mpctx->start_timestamp < 300)
3763 break;
3764 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3765 run_command(mpctx, cmd);
3766 mp_cmd_free(cmd);
3767 if (mpctx->stop_play)
3768 break;
3771 // handle -sstep
3772 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3773 mpctx->osd_function = OSD_FFW;
3774 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3777 /* Looping. */
3778 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3779 mpctx->stop_play == PT_NEXT_ENTRY)) {
3780 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3782 if (opts->loop_times > 1)
3783 opts->loop_times--;
3784 else if (opts->loop_times == 1)
3785 opts->loop_times = -1;
3786 play_n_frames = play_n_frames_mf;
3787 mpctx->stop_play = 0;
3788 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3791 if (mpctx->seek.type) {
3792 seek(mpctx, mpctx->seek, false);
3793 mpctx->seek = (struct seek_params){ 0 };
3798 static int read_keys(void *ctx, int fd)
3800 getch2(ctx);
3801 return MP_INPUT_NOTHING;
3804 static bool attachment_is_font(struct demux_attachment *att)
3806 if (!att->name || !att->type || !att->data || !att->data_size)
3807 return false;
3808 // match against MIME types
3809 if (strcmp(att->type, "application/x-truetype-font") == 0
3810 || strcmp(att->type, "application/x-font") == 0)
3811 return true;
3812 // fallback: match against file extension
3813 if (strlen(att->name) > 4) {
3814 char *ext = att->name + strlen(att->name) - 4;
3815 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3816 || strcasecmp(ext, ".otf") == 0)
3817 return true;
3819 return false;
3822 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3824 if (audio_id == -1)
3825 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3826 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3827 demuxer_switch_audio(demuxer, audio_id);
3828 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3829 demuxer->audio->id = -2;
3830 demuxer->audio->sh = NULL;
3832 return demuxer->audio->id;
3835 static void print_version(const char *name)
3837 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3839 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3840 GetCpuCaps(&gCpuCaps);
3841 #if ARCH_X86
3842 mp_msg(MSGT_CPLAYER, MSGL_V,
3843 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3844 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3845 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3846 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3847 #if CONFIG_RUNTIME_CPUDETECT
3848 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3849 #else
3850 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3851 if (HAVE_MMX)
3852 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3853 if (HAVE_MMX2)
3854 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3855 if (HAVE_AMD3DNOW)
3856 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3857 if (HAVE_AMD3DNOWEXT)
3858 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3859 if (HAVE_SSE)
3860 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3861 if (HAVE_SSE2)
3862 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3863 if (HAVE_SSSE3)
3864 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3865 if (HAVE_CMOV)
3866 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3867 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3868 #endif /* CONFIG_RUNTIME_CPUDETECT */
3869 #endif /* ARCH_X86 */
3870 print_libav_versions();
3873 #ifdef PTW32_STATIC_LIB
3874 static void detach_ptw32(void)
3876 pthread_win32_thread_detach_np();
3877 pthread_win32_process_detach_np();
3879 #endif
3881 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3882 * file for some tools to link against. */
3883 #ifndef DISABLE_MAIN
3884 int main(int argc, char *argv[])
3886 #ifdef PTW32_STATIC_LIB
3887 pthread_win32_process_attach_np();
3888 pthread_win32_thread_attach_np();
3889 atexit(detach_ptw32);
3890 #endif
3891 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3892 || !strcmp(argv[1], "--leak-report")))
3893 talloc_enable_leak_report();
3895 #ifdef __MINGW32__
3896 mp_get_converted_argv(&argc, &argv);
3897 #endif
3899 char *mem_ptr;
3901 // movie info:
3903 /* Flag indicating whether MPlayer should exit without playing anything. */
3904 int opt_exit = 0;
3905 int i;
3907 struct MPContext *mpctx = talloc(NULL, MPContext);
3908 *mpctx = (struct MPContext){
3909 .osd_function = OSD_PLAY,
3910 .begin_skip = MP_NOPTS_VALUE,
3911 .play_tree_step = 1,
3912 .global_sub_pos = -1,
3913 .set_of_sub_pos = -1,
3914 .file_format = DEMUXER_TYPE_UNKNOWN,
3915 .last_dvb_step = 1,
3916 .paused_cache_fill = -1,
3919 InitTimer();
3920 srand(GetTimerMS());
3922 mp_msg_init();
3923 init_libav();
3925 #ifdef CONFIG_X11
3926 mpctx->x11_state = vo_x11_init_state();
3927 #endif
3928 struct MPOpts *opts = &mpctx->opts;
3929 set_default_mplayer_options(opts);
3930 // Create the config context and register the options
3931 mpctx->mconfig = m_config_new(opts, cfg_include);
3932 m_config_register_options(mpctx->mconfig, mplayer_opts);
3933 m_config_register_options(mpctx->mconfig, common_opts);
3934 mp_input_register_options(mpctx->mconfig);
3936 // Preparse the command line
3937 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
3939 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3940 set_path_env();
3941 #endif
3943 #ifdef CONFIG_TV
3944 stream_tv_defaults.immediate = 1;
3945 #endif
3947 parse_cfgfiles(mpctx, mpctx->mconfig);
3949 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3950 if (mpctx->playtree == NULL)
3951 opt_exit = 1;
3952 else {
3953 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3954 if (mpctx->playtree) {
3955 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3956 mpctx->mconfig);
3957 if (mpctx->playtree_iter) {
3958 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3959 PLAY_TREE_ITER_ENTRY) {
3960 play_tree_iter_free(mpctx->playtree_iter);
3961 mpctx->playtree_iter = NULL;
3963 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3969 print_version("MPlayer2");
3971 #if defined(__MINGW32__) || defined(__CYGWIN__)
3973 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3974 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3975 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3976 if (kernel32) {
3977 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3978 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3980 if (setDEP)
3981 setDEP(3);
3982 if (setDllDir)
3983 setDllDir("");
3985 // stop Windows from showing all kinds of annoying error dialogs
3986 SetErrorMode(0x8003);
3987 // request 1ms timer resolution
3988 timeBeginPeriod(1);
3989 #endif
3991 #ifdef CONFIG_PRIORITY
3992 set_priority();
3993 #endif
3995 if (opts->video_driver_list &&
3996 strcmp(opts->video_driver_list[0], "help") == 0) {
3997 list_video_out();
3998 opt_exit = 1;
4001 if (opts->audio_driver_list &&
4002 strcmp(opts->audio_driver_list[0], "help") == 0) {
4003 list_audio_out();
4004 opt_exit = 1;
4007 /* Check codecs.conf. */
4008 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4009 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4010 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4011 if (!parse_codec_cfg(NULL))
4012 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4013 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4014 "Using built-in default codecs.conf.\n");
4017 free(mem_ptr); // release the buffer created by get_path()
4020 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4021 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4022 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4023 list_codecs(1);
4024 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4025 opt_exit = 1;
4027 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4028 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4029 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4030 list_codecs(0);
4031 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4032 opt_exit = 1;
4034 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4035 vfm_help();
4036 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4037 opt_exit = 1;
4039 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4040 afm_help();
4041 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4042 opt_exit = 1;
4044 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4045 af_help();
4046 printf("\n");
4047 opt_exit = 1;
4049 #ifdef CONFIG_X11
4050 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4051 fstype_help();
4052 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4053 opt_exit = 1;
4055 #endif
4056 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4057 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4058 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4059 demuxer_help();
4060 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4061 opt_exit = 1;
4063 if (opts->list_properties) {
4064 property_print_help();
4065 opt_exit = 1;
4068 if (opt_exit)
4069 exit_player(mpctx, EXIT_NONE);
4071 if (!mpctx->filename && !opts->player_idle_mode) {
4072 // no file/vcd/dvd -> show HELP:
4073 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4074 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4077 /* Display what configure line was used */
4078 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4080 // Many users forget to include command line in bugreports...
4081 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4082 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4083 for (i = 1; i < argc; i++)
4084 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4085 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4088 //------ load global data first ------
4090 mpctx->osd = osd_create();
4092 // check font
4093 #ifdef CONFIG_FREETYPE
4094 init_freetype();
4095 #endif
4096 #ifdef CONFIG_FONTCONFIG
4097 if (font_fontconfig <= 0) {
4098 #endif
4099 #ifdef CONFIG_BITMAP_FONT
4100 if (font_name) {
4101 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4102 if (!vo_font)
4103 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4104 filename_recode(font_name));
4105 } else {
4106 // try default:
4107 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4108 font_factor, verbose > 1);
4109 free(mem_ptr); // release the buffer created by get_path()
4110 if (!vo_font)
4111 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4112 font_factor, verbose > 1);
4114 if (sub_font_name)
4115 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4116 verbose > 1);
4117 else
4118 mpctx->osd->sub_font = vo_font;
4119 #endif
4120 #ifdef CONFIG_FONTCONFIG
4122 #endif
4124 #ifdef CONFIG_ASS
4125 mpctx->ass_library = mp_ass_init(opts);
4126 mpctx->osd->ass_library = mpctx->ass_library;
4127 #endif
4129 #ifdef HAVE_RTC
4130 if (opts->rtc) {
4131 char *rtc_device = opts->rtc_device;
4132 // seteuid(0); /* Can't hurt to try to get root here */
4133 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4134 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4135 "(it should be readable by the user.)\n",
4136 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4137 else {
4138 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4140 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4141 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4142 "ioctl (rtc_irqp_set %lu): %s\n",
4143 irqp, strerror(errno));
4144 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4145 close(rtc_fd);
4146 rtc_fd = -1;
4147 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4148 /* variable only by the root */
4149 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4150 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4151 close(rtc_fd);
4152 rtc_fd = -1;
4153 } else
4154 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4155 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4158 if (rtc_fd < 0)
4159 #endif /* HAVE_RTC */
4160 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4161 opts->softsleep ? "software" : timer_name);
4163 #ifdef HAVE_TERMCAP
4164 load_termcap(NULL); // load key-codes
4165 #endif
4167 // ========== Init keyboard FIFO (connection to libvo) ============
4169 // Init input system
4170 current_module = "init_input";
4171 mpctx->input = mp_input_init(&opts->input);
4172 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4173 if (slave_mode)
4174 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4175 else if (opts->consolecontrols)
4176 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4177 // Set the libstream interrupt callback
4178 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4180 current_module = NULL;
4182 /// Catch signals
4183 #ifndef __MINGW32__
4184 signal(SIGCHLD, child_sighandler);
4185 #endif
4187 #ifdef CONFIG_CRASH_DEBUG
4188 prog_path = argv[0];
4189 #endif
4190 //========= Catch terminate signals: ================
4191 // terminate requests:
4192 signal(SIGTERM, exit_sighandler); // kill
4193 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4195 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4197 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4198 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4199 #ifdef CONFIG_SIGHANDLER
4200 // fatal errors:
4201 signal(SIGBUS, exit_sighandler); // bus error
4202 signal(SIGSEGV, exit_sighandler); // segfault
4203 signal(SIGILL, exit_sighandler); // illegal instruction
4204 signal(SIGFPE, exit_sighandler); // floating point exc.
4205 signal(SIGABRT, exit_sighandler); // abort()
4206 #ifdef CONFIG_CRASH_DEBUG
4207 if (crash_debug)
4208 signal(SIGTRAP, exit_sighandler);
4209 #endif
4210 #endif
4212 // ***************** Now, let's see the per-file stuff ******************
4214 play_next_file:
4216 // init global sub numbers
4217 mpctx->global_sub_size = 0;
4218 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4220 if (mpctx->filename) {
4221 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4222 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4223 load_per_file_config(mpctx->mconfig, mpctx->filename);
4226 if (opts->video_driver_list)
4227 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4228 opts->video_driver_list[0]);
4229 if (opts->audio_driver_list)
4230 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4231 opts->audio_driver_list[0]);
4233 // We must enable getch2 here to be able to interrupt network connection
4234 // or cache filling
4235 if (opts->consolecontrols && !slave_mode) {
4236 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4237 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4238 "WARNING: getch2_init called twice!\n");
4239 else
4240 getch2_enable(); // prepare stdin for hotkeys...
4241 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4242 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4245 // ================= GUI idle loop (STOP state) =========================
4246 while (opts->player_idle_mode && !mpctx->filename) {
4247 play_tree_t *entry = NULL;
4248 mp_cmd_t *cmd;
4249 if (mpctx->video_out && mpctx->video_out->config_ok)
4250 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4251 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4252 if (mpctx->video_out)
4253 vo_check_events(mpctx->video_out);
4254 usec_sleep(20000);
4256 switch (cmd->id) {
4257 case MP_CMD_LOADFILE:
4258 // prepare a tree entry with the new filename
4259 entry = play_tree_new();
4260 play_tree_add_file(entry, cmd->args[0].v.s);
4261 // The entry is added to the main playtree after the switch().
4262 break;
4263 case MP_CMD_LOADLIST:
4264 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4265 break;
4266 case MP_CMD_QUIT:
4267 exit_player_with_rc(mpctx, EXIT_QUIT,
4268 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4269 break;
4270 case MP_CMD_VO_FULLSCREEN:
4271 case MP_CMD_GET_PROPERTY:
4272 case MP_CMD_SET_PROPERTY:
4273 case MP_CMD_STEP_PROPERTY:
4274 run_command(mpctx, cmd);
4275 break;
4278 mp_cmd_free(cmd);
4280 if (entry) { // user entered a command that gave a valid entry
4281 if (mpctx->playtree)
4282 // the playtree is always a node with one child. let's clear it
4283 play_tree_free_list(mpctx->playtree->child, 1);
4284 else
4285 // .. or make a brand new playtree
4286 mpctx->playtree = play_tree_new();
4288 if (!mpctx->playtree)
4289 continue; // couldn't make playtree! wait for next command
4291 play_tree_set_child(mpctx->playtree, entry);
4293 /* Make iterator start at the top the of tree. */
4294 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4295 mpctx->mconfig);
4296 if (!mpctx->playtree_iter)
4297 continue;
4299 // find the first real item in the tree
4300 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4301 PLAY_TREE_ITER_ENTRY) {
4302 // no items!
4303 play_tree_iter_free(mpctx->playtree_iter);
4304 mpctx->playtree_iter = NULL;
4305 continue; // wait for next command
4307 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4311 #ifdef CONFIG_ASS
4312 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4313 #endif
4314 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4315 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4317 if (mpctx->filename) {
4318 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4319 filename_recode(mpctx->filename));
4320 if (use_filename_title && opts->vo_wintitle == NULL)
4321 opts->vo_wintitle = talloc_strdup(NULL,
4322 mp_basename(mpctx->filename));
4325 if (edl_output_filename) {
4326 if (edl_fd)
4327 fclose(edl_fd);
4328 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4329 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4330 "Can't open EDL file [%s] for writing.\n",
4331 filename_recode(edl_output_filename));
4335 //==================== Open VOB-Sub ============================
4337 current_module = "vobsub";
4338 if (opts->vobsub_name) {
4339 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4340 if (vo_vobsub == NULL)
4341 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4342 filename_recode(opts->vobsub_name));
4343 } else if (opts->sub_auto && mpctx->filename) {
4344 char **vob = find_vob_subtitles(opts, mpctx->filename);
4345 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4346 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4347 if (vo_vobsub)
4348 break;
4350 talloc_free(vob);
4352 if (vo_vobsub) {
4353 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4354 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4355 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4356 mpctx);
4358 // setup global sub numbering
4359 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4360 vobsub_get_indexes_count(vo_vobsub);
4363 //============ Open & Sync STREAM --- fork cache2 ====================
4365 mpctx->stream = NULL;
4366 mpctx->demuxer = NULL;
4367 mpctx->d_audio = NULL;
4368 mpctx->d_video = NULL;
4369 mpctx->d_sub = NULL;
4370 mpctx->sh_audio = NULL;
4371 mpctx->sh_video = NULL;
4373 current_module = "open_stream";
4374 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4375 if (!mpctx->stream) { // error...
4376 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4377 goto goto_next_file;
4379 mpctx->initialized_flags |= INITIALIZED_STREAM;
4381 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4382 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4383 "playlist support will not be used automatically.\n"
4384 "MPlayer's playlist code is unsafe and should only be used with "
4385 "trusted sources.\nPlayback will probably fail.\n\n");
4386 #if 0
4387 play_tree_t *entry;
4388 // Handle playlist
4389 current_module = "handle_playlist";
4390 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4391 filename_recode(mpctx->filename));
4392 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4393 mpctx->eof = playtree_add_playlist(mpctx, entry);
4394 goto goto_next_file;
4395 #endif
4397 mpctx->stream->start_pos += seek_to_byte;
4399 if (stream_dump_type == 5) {
4400 unsigned char buf[4096];
4401 int len;
4402 FILE *f;
4403 current_module = "dumpstream";
4404 stream_reset(mpctx->stream);
4405 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4406 f = fopen(opts->stream_dump_name, "wb");
4407 if (!f) {
4408 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4409 exit_player(mpctx, EXIT_ERROR);
4411 if (opts->chapterrange[0] > 1) {
4412 int chapter = opts->chapterrange[0] - 1;
4413 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4415 struct stream_dump_progress info;
4416 stream_dump_progress_start(&info);
4417 while (!mpctx->stream->eof && !async_quit_request) {
4418 len = stream_read(mpctx->stream, buf, 4096);
4419 if (len > 0) {
4420 if (fwrite(buf, len, 1, f) != 1) {
4421 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4422 exit_player(mpctx, EXIT_ERROR);
4425 stream_dump_progress(&info, len, mpctx->stream);
4426 if (opts->chapterrange[1] > 0) {
4427 int chapter = -1;
4428 if (stream_control(mpctx->stream,
4429 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4430 && chapter + 1 > opts->chapterrange[1])
4431 break;
4434 if (fclose(f)) {
4435 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4436 opts->stream_dump_name);
4437 exit_player(mpctx, EXIT_ERROR);
4439 stream_dump_progress_end(&info, opts->stream_dump_name);
4440 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4441 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4444 #ifdef CONFIG_DVDREAD
4445 if (mpctx->stream->type == STREAMTYPE_DVD) {
4446 current_module = "dvd lang->id";
4447 if (opts->audio_lang && opts->audio_id == -1)
4448 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4449 if (opts->sub_lang && opts->sub_id == -1)
4450 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4451 // setup global sub numbering
4452 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4453 current_module = NULL;
4455 #endif
4457 #ifdef CONFIG_DVDNAV
4458 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4459 current_module = "dvdnav lang->id";
4460 if (opts->audio_lang && opts->audio_id == -1)
4461 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4462 opts->audio_lang);
4463 dvdsub_lang_id = -3;
4464 if (opts->sub_lang && opts->sub_id == -1)
4465 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4466 mpctx->stream, opts->sub_lang);
4467 // setup global sub numbering
4468 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4469 mpctx->stream);
4470 current_module = NULL;
4472 #endif
4474 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4475 goto_enable_cache:
4476 if (stream_cache_size > 0) {
4477 int res;
4478 float stream_cache_min_percent = opts->stream_cache_min_percent;
4479 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4480 current_module = "enable_cache";
4481 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4482 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4483 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4484 if (res == 0)
4485 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4486 goto goto_next_file;
4489 //============ Open DEMUXERS --- DETECT file type =======================
4490 current_module = "demux_open";
4492 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4493 opts->audio_id, opts->video_id, opts->sub_id,
4494 mpctx->filename);
4496 // HACK to get MOV Reference Files working
4498 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4499 unsigned char *playlist_entry;
4500 play_tree_t *list = NULL, *entry = NULL;
4502 current_module = "handle_demux_playlist";
4503 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4504 char *temp;
4505 const char *bname;
4507 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4508 filename_recode(playlist_entry));
4510 bname = mp_basename(playlist_entry);
4511 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4512 !strncmp(bname + 3, "gateQT", 6))
4513 continue;
4515 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4516 continue;
4518 entry = play_tree_new();
4520 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4521 playlist_entry)) { // add reference path of current file
4522 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4523 mpctx->filename)) + strlen(playlist_entry) + 1));
4524 if (temp) {
4525 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4526 strlen(mp_basename(mpctx->filename)));
4527 temp[strlen(mpctx->filename) - strlen(mp_basename(
4528 mpctx->filename))] = '\0';
4529 strcat(temp, playlist_entry);
4530 if (!strcmp(temp, mpctx->filename)) {
4531 free(temp);
4532 continue;
4534 play_tree_add_file(entry, temp);
4535 mp_msg(MSGT_CPLAYER, MSGL_V,
4536 "Resolving reference to %s.\n", temp);
4537 free(temp);
4539 } else
4540 play_tree_add_file(entry, playlist_entry);
4542 if (!list)
4543 list = entry;
4544 else
4545 play_tree_append_entry(list, entry);
4547 free_demuxer(mpctx->demuxer);
4548 mpctx->demuxer = NULL;
4550 if (list) {
4551 entry = play_tree_new();
4552 play_tree_set_child(entry, list);
4553 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4554 goto goto_next_file;
4558 if (!mpctx->demuxer) {
4559 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4560 goto goto_next_file;
4563 if (mpctx->demuxer->matroska_data.ordered_chapters)
4564 build_ordered_chapter_timeline(mpctx);
4566 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4567 build_edl_timeline(mpctx);
4569 if (mpctx->timeline) {
4570 mpctx->timeline_part = 0;
4571 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4573 int part_count = mpctx->num_timeline_parts;
4574 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4575 "sources. Total length %.3f seconds.\n", part_count,
4576 mpctx->num_sources, mpctx->timeline[part_count].start);
4577 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4578 for (int i = 0; i < mpctx->num_sources; i++)
4579 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4580 filename_recode(mpctx->sources[i].demuxer->filename));
4581 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4582 "source_start, source):\n");
4583 for (int i = 0; i < part_count; i++) {
4584 struct timeline_part *p = mpctx->timeline + i;
4585 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4586 p->source_start, p->source - mpctx->sources);
4588 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4589 mpctx->timeline[part_count].start);
4592 if (!mpctx->sources) {
4593 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4594 *mpctx->sources = (struct content_source){
4595 .stream = mpctx->stream,
4596 .demuxer = mpctx->demuxer
4598 mpctx->num_sources = 1;
4601 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4603 #ifdef CONFIG_ASS
4604 if (opts->ass_enabled && mpctx->ass_library) {
4605 for (int j = 0; j < mpctx->num_sources; j++) {
4606 struct demuxer *d = mpctx->sources[j].demuxer;
4607 for (int i = 0; i < d->num_attachments; i++) {
4608 struct demux_attachment *att = d->attachments + i;
4609 if (opts->use_embedded_fonts && attachment_is_font(att))
4610 ass_add_font(mpctx->ass_library, att->name, att->data,
4611 att->data_size);
4615 #endif
4617 current_module = "demux_open2";
4619 mpctx->d_audio = mpctx->demuxer->audio;
4620 mpctx->d_video = mpctx->demuxer->video;
4621 mpctx->d_sub = mpctx->demuxer->sub;
4623 if (ts_prog) {
4624 int tmp = ts_prog;
4625 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4627 // select audio stream
4628 for (int i = 0; i < mpctx->num_sources; i++)
4629 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4630 opts->audio_lang);
4632 // DUMP STREAMS:
4633 if ((stream_dump_type) && (stream_dump_type < 4)) {
4634 FILE *f;
4635 demux_stream_t *ds = NULL;
4636 current_module = "dump";
4637 // select stream to dump
4638 switch (stream_dump_type) {
4639 case 1: ds = mpctx->d_audio;
4640 break;
4641 case 2: ds = mpctx->d_video;
4642 break;
4643 case 3: ds = mpctx->d_sub;
4644 break;
4646 if (!ds) {
4647 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4648 "dump: FATAL: Selected stream missing!\n");
4649 exit_player(mpctx, EXIT_ERROR);
4651 // disable other streams:
4652 if (mpctx->d_audio && mpctx->d_audio != ds) {
4653 ds_free_packs(mpctx->d_audio);
4654 mpctx->d_audio->id = -2;
4656 if (mpctx->d_video && mpctx->d_video != ds) {
4657 ds_free_packs(mpctx->d_video);
4658 mpctx->d_video->id = -2;
4660 if (mpctx->d_sub && mpctx->d_sub != ds) {
4661 ds_free_packs(mpctx->d_sub);
4662 mpctx->d_sub->id = -2;
4664 // let's dump it!
4665 f = fopen(opts->stream_dump_name, "wb");
4666 if (!f) {
4667 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4668 exit_player(mpctx, EXIT_ERROR);
4670 struct stream_dump_progress info;
4671 stream_dump_progress_start(&info);
4672 while (!ds->eof) {
4673 unsigned char *start;
4674 int in_size = ds_get_packet(ds, &start);
4675 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4676 && stream_dump_type == 2)
4677 fwrite(&in_size, 1, 4, f);
4678 if (in_size > 0) {
4679 fwrite(start, in_size, 1, f);
4680 stream_dump_progress(&info, in_size, mpctx->stream);
4682 if (opts->chapterrange[1] > 0) {
4683 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4684 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4685 break;
4688 fclose(f);
4689 stream_dump_progress_end(&info, opts->stream_dump_name);
4690 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4691 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4694 mpctx->sh_audio = mpctx->d_audio->sh;
4695 mpctx->sh_video = mpctx->d_video->sh;
4697 if (mpctx->sh_video) {
4698 current_module = "video_read_properties";
4699 if (!video_read_properties(mpctx->sh_video)) {
4700 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4701 mpctx->sh_video = mpctx->d_video->sh = NULL;
4702 } else {
4703 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4704 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4705 mpctx->demuxer->file_format, mpctx->sh_video->format,
4706 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4707 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4708 if (force_fps) {
4709 mpctx->sh_video->fps = force_fps;
4710 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4712 vo_fps = mpctx->sh_video->fps;
4714 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4715 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4716 "header or invalid, use the -fps option.\n");
4722 if (!mpctx->sh_video && !mpctx->sh_audio) {
4723 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4724 #ifdef CONFIG_DVBIN
4725 if (mpctx->stream->type == STREAMTYPE_DVB) {
4726 int dir;
4727 int v = mpctx->last_dvb_step;
4728 if (v > 0)
4729 dir = DVB_CHANNEL_HIGHER;
4730 else
4731 dir = DVB_CHANNEL_LOWER;
4733 if (dvb_step_channel(mpctx->stream, dir)) {
4734 mpctx->stop_play = PT_NEXT_ENTRY;
4735 mpctx->dvbin_reopen = 1;
4738 #endif
4739 goto goto_next_file; // exit_player(_("Fatal error"));
4742 /* display clip info */
4743 demux_info_print(mpctx->demuxer);
4745 //================= Read SUBTITLES (DVD & TEXT) =========================
4746 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4747 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4748 init_vo_spudec(mpctx);
4750 // after reading video params we should load subtitles because
4751 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4752 // check .sub
4753 current_module = "read_subtitles_file";
4754 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4755 if (opts->sub_name) {
4756 for (i = 0; opts->sub_name[i] != NULL; ++i)
4757 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4759 if (opts->sub_auto) { // auto load sub file ...
4760 char **tmp = find_text_subtitles(opts, mpctx->filename);
4761 int nsub = MP_TALLOC_ELEMS(tmp);
4762 for (int i = 0; i < nsub; i++)
4763 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4764 talloc_free(tmp);
4766 if (mpctx->set_of_sub_size > 0)
4767 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4769 if (select_subtitle(mpctx)) {
4770 if (mpctx->subdata)
4771 switch (stream_dump_type) {
4772 case 3: list_sub_file(mpctx->subdata);
4773 break;
4774 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4775 break;
4776 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4777 break;
4778 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4779 break;
4780 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4781 break;
4782 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4783 break;
4787 print_file_properties(mpctx, mpctx->filename);
4789 reinit_video_chain(mpctx);
4790 if (mpctx->sh_video) {
4791 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4792 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4793 #ifdef CONFIG_FREETYPE
4794 force_load_font = 1;
4795 #endif
4796 } else if (!mpctx->sh_audio)
4797 goto goto_next_file;
4799 //================== MAIN: ==========================
4800 current_module = "main";
4802 if (opts->playing_msg) {
4803 char *msg = property_expand_string(mpctx, opts->playing_msg);
4804 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4805 free(msg);
4809 // Disable the term OSD in verbose mode
4810 if (verbose)
4811 opts->term_osd = 0;
4813 // Make sure old OSD does not stay around,
4814 // e.g. with -fixed-vo and same-resolution files
4815 clear_osd_msgs();
4816 update_osd_msg(mpctx);
4818 //================ SETUP AUDIO ==========================
4820 if (mpctx->sh_audio) {
4821 reinit_audio_chain(mpctx);
4822 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4823 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4824 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4827 current_module = "av_init";
4829 if (mpctx->sh_video) {
4830 mpctx->sh_video->timer = 0;
4831 if (!ignore_start)
4832 audio_delay += mpctx->sh_video->stream_delay;
4834 if (mpctx->sh_audio) {
4835 if (start_volume >= 0)
4836 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4837 if (!ignore_start)
4838 audio_delay -= mpctx->sh_audio->stream_delay;
4839 mpctx->delay = -audio_delay;
4842 if (!mpctx->sh_audio) {
4843 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4844 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4845 mpctx->d_audio->packs);
4846 ds_free_packs(mpctx->d_audio); // free buffered chunks
4848 if (!mpctx->sh_video) {
4849 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4850 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4851 mpctx->d_video->packs);
4852 ds_free_packs(mpctx->d_video);
4853 mpctx->d_video->id = -2;
4856 if (!mpctx->sh_video && !mpctx->sh_audio)
4857 goto goto_next_file;
4859 if (force_fps && mpctx->sh_video) {
4860 vo_fps = mpctx->sh_video->fps = force_fps;
4861 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4862 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4863 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4864 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4867 mp_input_set_section(mpctx->input, NULL);
4868 //TODO: add desired (stream-based) sections here
4869 if (mpctx->stream->type == STREAMTYPE_TV)
4870 mp_input_set_section(mpctx->input, "tv");
4871 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4872 mp_input_set_section(mpctx->input, "dvdnav");
4874 //==================== START PLAYING =======================
4876 if (opts->loop_times > 1)
4877 opts->loop_times--;
4878 else if (opts->loop_times == 1)
4879 opts->loop_times = -1;
4881 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4883 total_time_usage_start = GetTimer();
4884 audio_time_usage = 0;
4885 video_time_usage = 0;
4886 vout_time_usage = 0;
4887 total_frame_cnt = 0;
4888 drop_frame_cnt = 0; // fix for multifile fps benchmark
4889 play_n_frames = play_n_frames_mf;
4891 if (play_n_frames == 0) {
4892 mpctx->stop_play = PT_NEXT_ENTRY;
4893 goto goto_next_file;
4896 mpctx->time_frame = 0;
4897 mpctx->drop_message_shown = 0;
4898 mpctx->restart_playback = true;
4899 mpctx->video_pts = 0;
4900 mpctx->last_seek_pts = 0;
4901 mpctx->hrseek_active = false;
4902 mpctx->hrseek_framedrop = false;
4903 mpctx->step_frames = 0;
4904 mpctx->total_avsync_change = 0;
4905 mpctx->last_chapter_seek = -2;
4907 // If there's a timeline force an absolute seek to initialize state
4908 if (opts->seek_to_sec || mpctx->timeline) {
4909 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4910 seek(mpctx, mpctx->seek, false);
4911 end_at.pos += opts->seek_to_sec;
4913 if (opts->chapterrange[0] > 0) {
4914 double pts;
4915 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4916 && pts > -1.0) {
4917 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4918 seek(mpctx, mpctx->seek, false);
4922 if (end_at.type == END_AT_SIZE) {
4923 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4924 "Option -endpos in MPlayer does not yet support size units.\n");
4925 end_at.type = END_AT_NONE;
4928 #ifdef CONFIG_DVDNAV
4929 mp_dvdnav_context_free(mpctx);
4930 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4931 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4932 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4934 #endif
4936 mpctx->seek = (struct seek_params){ 0 };
4937 get_relative_time(mpctx); // reset current delta
4938 // Make sure VO knows current pause state
4939 if (mpctx->sh_video)
4940 vo_control(mpctx->video_out,
4941 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4943 while (!mpctx->stop_play)
4944 run_playloop(mpctx);
4946 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4948 #ifdef CONFIG_DVBIN
4949 if (mpctx->dvbin_reopen) {
4950 mpctx->stop_play = 0;
4951 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4952 cache_uninit(mpctx->stream);
4953 mpctx->dvbin_reopen = 0;
4954 goto goto_enable_cache;
4956 #endif
4958 goto_next_file: // don't jump here after ao/vo/getch initialization!
4960 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4962 if (opts->benchmark) {
4963 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4964 double total_time_usage;
4965 total_time_usage_start = GetTimer() - total_time_usage_start;
4966 total_time_usage = (float)total_time_usage_start * 0.000001;
4967 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4968 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4969 video_time_usage, vout_time_usage, audio_time_usage,
4970 total_time_usage - tot, total_time_usage);
4971 if (total_time_usage > 0.0)
4972 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4973 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4974 100.0 * video_time_usage / total_time_usage,
4975 100.0 * vout_time_usage / total_time_usage,
4976 100.0 * audio_time_usage / total_time_usage,
4977 100.0 * (total_time_usage - tot) / total_time_usage,
4978 100.0);
4979 if (total_frame_cnt && frame_dropping)
4980 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4981 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4982 total_frame_cnt - drop_frame_cnt,
4983 (total_time_usage > 0.5) ? ((total_frame_cnt -
4984 drop_frame_cnt) / total_time_usage) : 0,
4985 drop_frame_cnt,
4986 100 * drop_frame_cnt / total_frame_cnt,
4987 total_frame_cnt,
4988 (total_time_usage > 0.5) ?
4989 (total_frame_cnt / total_time_usage) : 0);
4992 // time to uninit all, except global stuff:
4993 int uninitialize_parts = INITIALIZED_ALL;
4994 if (opts->fixed_vo)
4995 uninitialize_parts -= INITIALIZED_VO;
4996 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4997 uninitialize_parts -= INITIALIZED_AO;
4998 uninit_player(mpctx, uninitialize_parts);
5000 if (mpctx->set_of_sub_size > 0) {
5001 current_module = "sub_free";
5002 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5003 sub_free(mpctx->set_of_subtitles[i]);
5004 #ifdef CONFIG_ASS
5005 if (mpctx->set_of_ass_tracks[i])
5006 ass_free_track(mpctx->set_of_ass_tracks[i]);
5007 #endif
5009 mpctx->set_of_sub_size = 0;
5011 mpctx->vo_sub_last = vo_sub = NULL;
5012 mpctx->subdata = NULL;
5013 #ifdef CONFIG_ASS
5014 mpctx->osd->ass_track = NULL;
5015 if (mpctx->ass_library)
5016 ass_clear_fonts(mpctx->ass_library);
5017 #endif
5019 if (!mpctx->stop_play) // In case some goto jumped here...
5020 mpctx->stop_play = PT_NEXT_ENTRY;
5022 int playtree_direction = 1;
5024 if (mpctx->stop_play == PT_NEXT_ENTRY
5025 || mpctx->stop_play == PT_PREV_ENTRY) {
5026 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5027 != PLAY_TREE_ITER_ENTRY) {
5028 play_tree_iter_free(mpctx->playtree_iter);
5029 mpctx->playtree_iter = NULL;
5031 mpctx->play_tree_step = 1;
5032 } else if (mpctx->stop_play == PT_UP_NEXT ||
5033 mpctx->stop_play == PT_UP_PREV) {
5034 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5035 if (mpctx->playtree_iter) {
5036 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5037 PLAY_TREE_ITER_ENTRY) {
5038 play_tree_iter_free(mpctx->playtree_iter);
5039 mpctx->playtree_iter = NULL;
5042 } else if (mpctx->stop_play == PT_STOP) {
5043 play_tree_iter_free(mpctx->playtree_iter);
5044 mpctx->playtree_iter = NULL;
5045 } else // NEXT PREV SRC
5046 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5048 while (mpctx->playtree_iter != NULL) {
5049 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5050 playtree_direction);
5051 if (mpctx->filename == NULL) {
5052 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5053 0) != PLAY_TREE_ITER_ENTRY) {
5054 play_tree_iter_free(mpctx->playtree_iter);
5055 mpctx->playtree_iter = NULL;
5058 } else
5059 break;
5062 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5063 if (!mpctx->playtree_iter)
5064 mpctx->filename = NULL;
5065 mpctx->stop_play = 0;
5066 goto play_next_file;
5069 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5071 return 1;
5073 #endif /* DISABLE_MAIN */