options, subs: add --ass-vsfilter-aspect-compat
[mplayer.git] / mplayer.c
blob5433fe41c84687aeee416da23f3679b32e454cf3
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 /// \file
20 /// \ingroup Properties Command2Property OSDMsgStack
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdbool.h>
25 #include <math.h>
26 #include <assert.h>
28 #include "config.h"
29 #include "talloc.h"
31 #if defined(__MINGW32__) || defined(__CYGWIN__)
32 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
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 "access_mpcontext.h"
69 #include "m_property.h"
71 #include "libavutil/avstring.h"
73 #include "sub/subreader.h"
74 #include "sub/find_subfiles.h"
75 #include "sub/dec_sub.h"
77 #include "mp_osd.h"
78 #include "libvo/video_out.h"
80 #include "sub/font_load.h"
81 #include "sub/sub.h"
82 #include "ffmpeg_files/intreadwrite.h"
83 #include "sub/av_sub.h"
84 #include "libmpcodecs/dec_teletext.h"
85 #include "cpudetect.h"
86 #include "version.h"
88 #ifdef CONFIG_X11
89 #include "libvo/x11_common.h"
90 #endif
92 #include "libao2/audio_out.h"
94 #include "codec-cfg.h"
96 #include "edl.h"
98 #include "sub/spudec.h"
99 #include "sub/vobsub.h"
101 #include "osdep/getch2.h"
102 #include "osdep/timer.h"
104 #include "input/input.h"
106 int slave_mode = 0;
107 int enable_mouse_movements = 0;
108 float start_volume = -1;
110 #include "osdep/priority.h"
112 char *heartbeat_cmd;
114 #ifdef HAVE_RTC
115 #ifdef __linux__
116 #include <linux/rtc.h>
117 #else
118 #include <rtc.h>
119 #define RTC_IRQP_SET RTCIO_IRQP_SET
120 #define RTC_PIE_ON RTCIO_PIE_ON
121 #endif /* __linux__ */
122 #endif /* HAVE_RTC */
124 #include "stream/tv.h"
125 #include "stream/stream_radio.h"
126 #ifdef CONFIG_DVBIN
127 #include "stream/dvbin.h"
128 #endif
129 #include "stream/cache2.h"
131 //**************************************************************************//
132 // Playtree
133 //**************************************************************************//
134 #include "playtree.h"
135 #include "playtreeparser.h"
137 //**************************************************************************//
138 // Config
139 //**************************************************************************//
140 #include "parser-cfg.h"
141 #include "parser-mpcmd.h"
143 //**************************************************************************//
144 // Config file
145 //**************************************************************************//
147 static int cfg_inc_verbose(m_option_t *conf)
149 ++verbose;
150 return 0;
153 #include "path.h"
155 //**************************************************************************//
156 //**************************************************************************//
157 // Input media streaming & demultiplexer:
158 //**************************************************************************//
160 static int max_framesize = 0;
162 #include "stream/stream.h"
163 #include "libmpdemux/demuxer.h"
164 #include "libmpdemux/stheader.h"
166 #ifdef CONFIG_DVDREAD
167 #include "stream/stream_dvd.h"
168 #endif
169 #include "stream/stream_dvdnav.h"
171 #include "libmpcodecs/dec_audio.h"
172 #include "libmpcodecs/dec_video.h"
173 #include "libmpcodecs/mp_image.h"
174 #include "libmpcodecs/vf.h"
175 #include "libmpcodecs/vd.h"
177 #include "mixer.h"
179 #include "mp_core.h"
180 #include "options.h"
181 #include "defaultopts.h"
183 static const char help_text[] = _(
184 "Usage: mplayer [options] [url|path/]filename\n"
185 "\n"
186 "Basic options: (complete list in the man page)\n"
187 " -vo <drv> select video output driver ('-vo help' for a list)\n"
188 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
189 #ifdef CONFIG_VCD
190 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
191 #endif
192 #ifdef CONFIG_DVDREAD
193 " dvd://<titleno> play DVD title from device instead of plain file\n"
194 #endif
195 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
196 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
197 " -nosound do not play sound\n"
198 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
199 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
200 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
201 " -playlist <file> specify playlist file\n"
202 " -vid x -aid y select video (x) and audio (y) stream to play\n"
203 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
204 " -pp <quality> enable postprocessing filter (details in the man page)\n"
205 " -framedrop enable frame dropping (for slow machines)\n"
206 "\n"
207 "Basic keys: (complete list in the man page, also check input.conf)\n"
208 " <- or -> seek backward/forward 10 seconds\n"
209 " down or up seek backward/forward 1 minute\n"
210 " pgdown or pgup seek backward/forward 10 minutes\n"
211 " < or > step backward/forward in playlist\n"
212 " p or SPACE pause movie (press any key to continue)\n"
213 " q or ESC stop playing and quit program\n"
214 " + or - adjust audio delay by +/- 0.1 second\n"
215 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
216 " * or / increase or decrease PCM volume\n"
217 " x or z adjust subtitle delay by +/- 0.1 second\n"
218 " r or t adjust subtitle position up/down, also see -vf expand\n"
219 " double click toggle fullscreen\n"
220 " right click pause (press again to continue)\n"
221 "\n"
222 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
223 "\n");
226 #define Exit_SIGILL_RTCpuSel _(\
227 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
228 " It may be a bug in our new runtime CPU-detection code...\n"\
229 " Please read DOCS/HTML/en/bugreports.html.\n")
231 #define Exit_SIGILL _(\
232 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
233 " It usually happens when you run it on a CPU different than the one it was\n"\
234 " compiled/optimized for.\n"\
235 " Verify this!\n")
237 #define Exit_SIGSEGV_SIGFPE _(\
238 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
239 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
240 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
242 #define Exit_SIGCRASH _(\
243 "- MPlayer crashed. This shouldn't happen.\n"\
244 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
245 " gcc version. If you think it's MPlayer's fault, please read\n"\
246 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
247 " won't help unless you provide this information when reporting a possible bug.\n")
249 #define SystemTooSlow _("\n\n"\
250 " ************************************************\n"\
251 " **** Your system is too SLOW to play this! ****\n"\
252 " ************************************************\n\n"\
253 "Possible reasons, problems, workarounds:\n"\
254 "- Most common: broken/buggy _audio_ driver\n"\
255 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
256 " - Experiment with different values for -autosync, 30 is a good start.\n"\
257 "- Slow video output\n"\
258 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
259 "- Slow CPU\n"\
260 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
261 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
262 "- Broken file\n"\
263 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
264 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
265 " - Try -cache 8192.\n"\
266 "- Are you using -cache to play a non-interleaved AVI file?\n"\
267 " - Try -nocache.\n"\
268 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
269 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
272 //**************************************************************************//
273 //**************************************************************************//
275 #include "mp_fifo.h"
277 // benchmark:
278 double video_time_usage;
279 double vout_time_usage;
280 static double audio_time_usage;
281 static int total_time_usage_start;
282 static int total_frame_cnt;
283 static int drop_frame_cnt; // total number of dropped frames
285 // options:
286 static int output_quality;
288 // seek:
289 static off_t seek_to_byte;
290 static off_t step_sec;
292 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
294 // codecs:
295 char **audio_codec_list; // override audio codec
296 char **video_codec_list; // override video codec
297 char **audio_fm_list; // override audio codec family
298 char **video_fm_list; // override video codec family
300 // this dvdsub_id was selected via slang
301 // use this to allow dvdnav to follow -slang across stream resets,
302 // in particular the subtitle ID for a language changes
303 int dvdsub_lang_id;
304 int vobsub_id = -1;
305 static char *spudec_ifo = NULL;
306 int forced_subs_only = 0;
307 int file_filter = 1;
309 // cache2:
310 int stream_cache_size = -1;
312 // dump:
313 int stream_dump_type = 0;
315 // A-V sync:
316 static float default_max_pts_correction = -1;
317 float audio_delay = 0;
318 static int ignore_start = 0;
320 double force_fps = 0;
321 static int force_srate = 0;
322 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
323 static int play_n_frames = -1;
324 static int play_n_frames_mf = -1;
326 // sub:
327 char *font_name = NULL;
328 char *sub_font_name = NULL;
329 extern int font_fontconfig;
330 float font_factor = 0.75;
331 float sub_delay = 0;
332 float sub_fps = 0;
333 int subcc_enabled = 0;
334 int suboverlap_enabled = 1;
336 #include "sub/ass_mp.h"
338 char *current_module; // for debugging
341 // ---
343 #ifdef CONFIG_MENU
344 #include "m_struct.h"
345 #include "libmenu/menu.h"
346 static const vf_info_t * const libmenu_vfs[] = {
347 &vf_info_menu,
348 NULL
350 static vf_instance_t *vf_menu;
351 int use_menu;
352 static char *menu_cfg;
353 static char *menu_root = "main";
354 #endif
357 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
358 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
359 FILE *edl_fd; // file to write to when in -edlout mode.
360 int use_filedir_conf;
361 int use_filename_title;
363 #include "mpcommon.h"
364 #include "command.h"
366 #include "metadata.h"
368 void *mpctx_get_video_out(MPContext *mpctx)
370 return mpctx->video_out;
373 void *mpctx_get_demuxer(MPContext *mpctx)
375 return mpctx->demuxer;
378 void *mpctx_get_playtree_iter(MPContext *mpctx)
380 return mpctx->playtree_iter;
383 void *mpctx_get_mixer(MPContext *mpctx)
385 return &mpctx->mixer;
388 int mpctx_get_global_sub_size(MPContext *mpctx)
390 return mpctx->global_sub_size;
393 int mpctx_get_osd_function(MPContext *mpctx)
395 return mpctx->osd_function;
398 static float get_relative_time(struct MPContext *mpctx)
400 unsigned int new_time = GetTimer();
401 unsigned int delta = new_time - mpctx->last_time;
402 mpctx->last_time = new_time;
403 return delta * 0.000001;
406 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
408 switch (type) {
409 /* check for valid video stream */
410 case META_VIDEO_CODEC:
411 case META_VIDEO_BITRATE:
412 case META_VIDEO_RESOLUTION:
413 if (!mpctx->sh_video)
414 return 0;
415 break;
417 /* check for valid audio stream */
418 case META_AUDIO_CODEC:
419 case META_AUDIO_BITRATE:
420 case META_AUDIO_SAMPLES:
421 if (!mpctx->sh_audio)
422 return 0;
423 break;
425 /* check for valid demuxer */
426 case META_INFO_TITLE:
427 case META_INFO_ARTIST:
428 case META_INFO_ALBUM:
429 case META_INFO_YEAR:
430 case META_INFO_COMMENT:
431 case META_INFO_TRACK:
432 case META_INFO_GENRE:
433 if (!mpctx->demuxer)
434 return 0;
435 break;
437 default:
438 break;
441 return 1;
444 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
446 char **info = mpctx->demuxer->info;
447 int n;
449 if (!info || !tag)
450 return talloc_strdup(NULL, "");
452 for (n = 0; info[2 * n] != NULL; n++)
453 if (!strcasecmp(info[2 * n], tag))
454 break;
456 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
459 char *get_metadata(struct MPContext *mpctx, metadata_t type)
461 sh_audio_t * const sh_audio = mpctx->sh_audio;
462 sh_video_t * const sh_video = mpctx->sh_video;
464 if (!is_valid_metadata_type(mpctx, type))
465 return NULL;
467 switch (type) {
468 case META_NAME:
469 return talloc_strdup(NULL, mp_basename(mpctx->filename));
470 case META_VIDEO_CODEC:
471 if (sh_video->format == 0x10000001)
472 return talloc_strdup(NULL, "mpeg1");
473 else if (sh_video->format == 0x10000002)
474 return talloc_strdup(NULL, "mpeg2");
475 else if (sh_video->format == 0x10000004)
476 return talloc_strdup(NULL, "mpeg4");
477 else if (sh_video->format == 0x10000005)
478 return talloc_strdup(NULL, "h264");
479 else if (sh_video->format >= 0x20202020)
480 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
481 else
482 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
483 case META_VIDEO_BITRATE:
484 return talloc_asprintf(NULL, "%d kbps",
485 (int) (sh_video->i_bps * 8 / 1024));
486 case META_VIDEO_RESOLUTION:
487 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
488 sh_video->disp_h);
489 case META_AUDIO_CODEC:
490 if (sh_audio->codec && sh_audio->codec->name)
491 return talloc_strdup(NULL, sh_audio->codec->name);
492 return talloc_strdup(NULL, "");
493 case META_AUDIO_BITRATE:
494 return talloc_asprintf(NULL, "%d kbps",
495 (int) (sh_audio->i_bps * 8 / 1000));
496 case META_AUDIO_SAMPLES:
497 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
498 sh_audio->channels);
500 /* check for valid demuxer */
501 case META_INFO_TITLE:
502 return get_demuxer_info(mpctx, "Title");
504 case META_INFO_ARTIST:
505 return get_demuxer_info(mpctx, "Artist");
507 case META_INFO_ALBUM:
508 return get_demuxer_info(mpctx, "Album");
510 case META_INFO_YEAR:
511 return get_demuxer_info(mpctx, "Year");
513 case META_INFO_COMMENT:
514 return get_demuxer_info(mpctx, "Comment");
516 case META_INFO_TRACK:
517 return get_demuxer_info(mpctx, "Track");
519 case META_INFO_GENRE:
520 return get_demuxer_info(mpctx, "Genre");
522 default:
523 break;
526 return talloc_strdup(NULL, "");
529 static void print_file_properties(struct MPContext *mpctx, const char *filename)
531 double start_pts = MP_NOPTS_VALUE;
532 double video_start_pts = MP_NOPTS_VALUE;
533 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
534 filename_recode(filename));
535 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
536 mpctx->demuxer->desc->name);
537 if (mpctx->sh_video) {
538 /* Assume FOURCC if all bytes >= 0x20 (' ') */
539 if (mpctx->sh_video->format >= 0x20202020)
540 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
541 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
542 else
543 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
544 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
545 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
546 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
547 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
548 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
549 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
550 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
551 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
552 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
553 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
554 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
555 video_start_pts = ds_get_next_pts(mpctx->d_video);
557 if (mpctx->sh_audio) {
558 /* Assume FOURCC if all bytes >= 0x20 (' ') */
559 if (mpctx->sh_audio->format >= 0x20202020)
560 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
561 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
562 else
563 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
564 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
565 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
566 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
567 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
568 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
569 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
570 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
571 start_pts = ds_get_next_pts(mpctx->d_audio);
573 if (video_start_pts != MP_NOPTS_VALUE) {
574 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
575 (mpctx->sh_video && video_start_pts < start_pts))
576 start_pts = video_start_pts;
578 if (start_pts != MP_NOPTS_VALUE)
579 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
580 else
581 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
582 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
583 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
584 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
585 mpctx->stream->seek
586 && (!mpctx->demuxer || mpctx->demuxer->seekable));
587 if (mpctx->demuxer) {
588 if (mpctx->demuxer->num_chapters == 0)
589 stream_control(mpctx->demuxer->stream,
590 STREAM_CTRL_GET_NUM_CHAPTERS,
591 &mpctx->demuxer->num_chapters);
592 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
593 "ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
597 /// step size of mixer changes
598 int volstep = 3;
600 #ifdef CONFIG_DVDNAV
601 static void mp_dvdnav_context_free(MPContext *ctx)
603 if (ctx->nav_smpi)
604 free_mp_image(ctx->nav_smpi);
605 ctx->nav_smpi = NULL;
606 free(ctx->nav_buffer);
607 ctx->nav_buffer = NULL;
608 ctx->nav_start = NULL;
609 ctx->nav_in_size = 0;
611 #endif
613 static void uninit_subs(struct demuxer *demuxer)
615 for (int i = 0; i < MAX_S_STREAMS; i++) {
616 struct sh_sub *sh = demuxer->s_streams[i];
617 if (sh && sh->initialized)
618 sub_uninit(sh);
622 void uninit_player(struct MPContext *mpctx, unsigned int mask)
624 mask &= mpctx->initialized_flags;
626 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
628 if (mask & INITIALIZED_ACODEC) {
629 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
630 current_module = "uninit_acodec";
631 if (mpctx->sh_audio)
632 uninit_audio(mpctx->sh_audio);
633 mpctx->sh_audio = NULL;
634 mpctx->mixer.afilter = NULL;
637 if (mask & INITIALIZED_SUB) {
638 mpctx->initialized_flags &= ~INITIALIZED_SUB;
639 if (mpctx->d_sub->sh)
640 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
643 if (mask & INITIALIZED_VCODEC) {
644 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
645 current_module = "uninit_vcodec";
646 if (mpctx->sh_video)
647 uninit_video(mpctx->sh_video);
648 mpctx->sh_video = NULL;
649 #ifdef CONFIG_MENU
650 vf_menu = NULL;
651 #endif
654 if (mask & INITIALIZED_DEMUXER) {
655 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
656 current_module = "free_demuxer";
657 if (mpctx->num_sources) {
658 mpctx->demuxer = mpctx->sources[0].demuxer;
659 for (int i = 1; i < mpctx->num_sources; i++) {
660 uninit_subs(mpctx->sources[i].demuxer);
661 free_stream(mpctx->sources[i].stream);
662 free_demuxer(mpctx->sources[i].demuxer);
665 talloc_free(mpctx->sources);
666 mpctx->sources = NULL;
667 mpctx->num_sources = 0;
668 talloc_free(mpctx->timeline);
669 mpctx->timeline = NULL;
670 mpctx->num_timeline_parts = 0;
671 talloc_free(mpctx->chapters);
672 mpctx->chapters = NULL;
673 mpctx->num_chapters = 0;
674 mpctx->video_offset = 0;
675 if (mpctx->demuxer) {
676 mpctx->stream = mpctx->demuxer->stream;
677 uninit_subs(mpctx->demuxer);
678 free_demuxer(mpctx->demuxer);
680 mpctx->demuxer = NULL;
683 // kill the cache process:
684 if (mask & INITIALIZED_STREAM) {
685 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
686 current_module = "uninit_stream";
687 if (mpctx->stream)
688 free_stream(mpctx->stream);
689 mpctx->stream = NULL;
692 if (mask & INITIALIZED_VO) {
693 mpctx->initialized_flags &= ~INITIALIZED_VO;
694 current_module = "uninit_vo";
695 vo_destroy(mpctx->video_out);
696 mpctx->video_out = NULL;
697 #ifdef CONFIG_DVDNAV
698 mp_dvdnav_context_free(mpctx);
699 #endif
702 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
703 if (mask & INITIALIZED_GETCH2) {
704 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
705 current_module = "uninit_getch2";
706 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
707 // restore terminal:
708 getch2_disable();
711 if (mask & INITIALIZED_VOBSUB) {
712 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
713 current_module = "uninit_vobsub";
714 if (vo_vobsub)
715 vobsub_close(vo_vobsub);
716 vo_vobsub = NULL;
719 if (mask & INITIALIZED_SPUDEC) {
720 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
721 current_module = "uninit_spudec";
722 spudec_free(vo_spudec);
723 vo_spudec = NULL;
726 if (mask & INITIALIZED_AO) {
727 mpctx->initialized_flags &= ~INITIALIZED_AO;
728 current_module = "uninit_ao";
729 if (mpctx->edl_muted)
730 mixer_mute(&mpctx->mixer);
731 if (mpctx->ao)
732 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
733 mpctx->ao = NULL;
736 current_module = NULL;
739 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
741 if (mpctx->user_muted && !mpctx->edl_muted)
742 mixer_mute(&mpctx->mixer);
743 uninit_player(mpctx, INITIALIZED_ALL);
744 #if defined(__MINGW32__) || defined(__CYGWIN__)
745 timeEndPeriod(1);
746 #endif
747 #ifdef CONFIG_X11
748 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
749 #endif
751 current_module = "uninit_input";
752 mp_input_uninit(mpctx->input);
753 #ifdef CONFIG_MENU
754 if (use_menu)
755 menu_uninit();
756 #endif
758 #ifdef CONFIG_FREETYPE
759 current_module = "uninit_font";
760 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
761 free_font_desc(mpctx->osd->sub_font);
762 free_font_desc(vo_font);
763 vo_font = NULL;
764 done_freetype();
765 #endif
766 osd_free(mpctx->osd);
768 #ifdef CONFIG_ASS
769 ass_library_done(mpctx->ass_library);
770 mpctx->ass_library = NULL;
771 #endif
773 current_module = "exit_player";
775 if (mpctx->playtree_iter)
776 play_tree_iter_free(mpctx->playtree_iter);
777 mpctx->playtree_iter = NULL;
778 if (mpctx->playtree)
779 play_tree_free(mpctx->playtree, 1);
780 mpctx->playtree = NULL;
782 talloc_free(mpctx->key_fifo);
784 free(edl_records); // free mem allocated for EDL
785 edl_records = NULL;
786 switch (how) {
787 case EXIT_QUIT:
788 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
789 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
790 break;
791 case EXIT_EOF:
792 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
793 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
794 break;
795 case EXIT_ERROR:
796 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
797 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
798 break;
799 default:
800 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
802 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
803 "max framesize was %d bytes\n", max_framesize);
805 // must be last since e.g. mp_msg uses option values
806 // that will be freed by this.
807 if (mpctx->mconfig)
808 m_config_free(mpctx->mconfig);
809 mpctx->mconfig = NULL;
811 exit(rc);
814 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
816 exit_player_with_rc(mpctx, how, 1);
819 #ifndef __MINGW32__
820 static void child_sighandler(int x)
822 pid_t pid;
823 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
825 #endif
827 #ifdef CONFIG_CRASH_DEBUG
828 static char *prog_path;
829 static int crash_debug = 0;
830 #endif
832 static void exit_sighandler(int x)
834 static int sig_count = 0;
835 #ifdef CONFIG_CRASH_DEBUG
836 if (!crash_debug || x != SIGTRAP)
837 #endif
838 ++sig_count;
839 if (sig_count == 5) {
840 /* We're crashing bad and can't uninit cleanly :(
841 * by popular request, we make one last (dirty)
842 * effort to restore the user's
843 * terminal. */
844 getch2_disable();
845 exit(1);
847 if (sig_count == 6)
848 exit(1);
849 if (sig_count > 6) {
850 // can't stop :(
851 #ifndef __MINGW32__
852 kill(getpid(), SIGKILL);
853 #endif
855 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
856 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
857 "\nMPlayer interrupted by signal %d in module: %s\n", x,
858 current_module ? current_module : "unknown");
859 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
860 if (sig_count <= 1)
861 switch (x) {
862 case SIGINT:
863 case SIGPIPE:
864 case SIGQUIT:
865 case SIGTERM:
866 case SIGKILL:
867 async_quit_request = 1;
868 return; // killed from keyboard (^C) or killed [-9]
869 case SIGILL:
870 #if CONFIG_RUNTIME_CPUDETECT
871 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
872 #else
873 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
874 #endif
875 case SIGFPE:
876 case SIGSEGV:
877 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
878 default:
879 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
880 #ifdef CONFIG_CRASH_DEBUG
881 if (crash_debug) {
882 int gdb_pid;
883 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
884 gdb_pid = fork();
885 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
886 if (gdb_pid == 0) { // We are the child
887 char spid[20];
888 snprintf(spid, sizeof(spid), "%i", getppid());
889 getch2_disable(); // allow terminal to work properly with gdb
890 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
891 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
892 } else if (gdb_pid < 0)
893 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
894 else
895 waitpid(gdb_pid, NULL, 0);
896 if (x == SIGTRAP)
897 return;
899 #endif
901 getch2_disable();
902 exit(1);
905 #include "cfg-mplayer.h"
907 static int cfg_include(m_option_t *conf, char *filename)
909 return m_config_parse_config_file(conf->priv, filename);
912 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
914 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
916 struct MPOpts *opts = &mpctx->opts;
917 char *conffile;
918 int conffile_fd;
919 if (!(opts->noconfig & 2) &&
920 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
921 exit_player(mpctx, EXIT_NONE);
922 if ((conffile = get_path("")) == NULL)
923 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
924 else {
925 #ifdef __MINGW32__
926 mkdir(conffile);
927 #else
928 mkdir(conffile, 0777);
929 #endif
930 free(conffile);
931 if ((conffile = get_path("config")) == NULL)
932 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
933 else {
934 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
935 0666)) != -1) {
936 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
937 "Creating config file: %s\n", conffile);
938 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
939 close(conffile_fd);
941 if (!(opts->noconfig & 1) &&
942 m_config_parse_config_file(conf, conffile) < 0)
943 exit_player(mpctx, EXIT_NONE);
944 free(conffile);
949 #define PROFILE_CFG_PROTOCOL "protocol."
951 static void load_per_protocol_config(m_config_t *conf, const char * const file)
953 char *str;
954 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
955 m_profile_t *p;
957 /* does filename actually uses a protocol ? */
958 str = strstr(file, "://");
959 if (!str)
960 return;
962 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
963 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
964 p = m_config_get_profile(conf, protocol);
965 if (p) {
966 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
967 "Loading protocol-related profile '%s'\n", protocol);
968 m_config_set_profile(conf, p);
972 #define PROFILE_CFG_EXTENSION "extension."
974 static void load_per_extension_config(m_config_t *conf, const char * const file)
976 char *str;
977 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
978 m_profile_t *p;
980 /* does filename actually have an extension ? */
981 str = strrchr(file, '.');
982 if (!str)
983 return;
985 sprintf(extension, PROFILE_CFG_EXTENSION);
986 strncat(extension, ++str, 7);
987 p = m_config_get_profile(conf, extension);
988 if (p) {
989 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
990 "Loading extension-related profile '%s'\n", extension);
991 m_config_set_profile(conf, p);
995 #define PROFILE_CFG_VO "vo."
996 #define PROFILE_CFG_AO "ao."
998 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
1000 char profile[strlen(cfg) + strlen(out) + 1];
1001 m_profile_t *p;
1003 sprintf(profile, "%s%s", cfg, out);
1004 p = m_config_get_profile(conf, profile);
1005 if (p) {
1006 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
1007 "Loading extension-related profile '%s'\n", profile);
1008 m_config_set_profile(conf, p);
1013 * Tries to load a config file
1014 * @return 0 if file was not found, 1 otherwise
1016 static int try_load_config(m_config_t *conf, const char *file)
1018 struct stat st;
1019 if (stat(file, &st))
1020 return 0;
1021 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1022 m_config_parse_config_file(conf, file);
1023 return 1;
1026 static void load_per_file_config(m_config_t *conf, const char * const file)
1028 char *confpath;
1029 char cfg[PATH_MAX];
1030 const char *name;
1032 if (strlen(file) > PATH_MAX - 14) {
1033 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
1034 "can not load file or directory specific config files\n");
1035 return;
1037 sprintf(cfg, "%s.conf", file);
1039 name = mp_basename(cfg);
1040 if (use_filedir_conf) {
1041 char dircfg[PATH_MAX];
1042 strcpy(dircfg, cfg);
1043 strcpy(dircfg + (name - cfg), "mplayer.conf");
1044 try_load_config(conf, dircfg);
1046 if (try_load_config(conf, cfg))
1047 return;
1050 if ((confpath = get_path(name)) != NULL) {
1051 try_load_config(conf, confpath);
1053 free(confpath);
1057 /* When libmpdemux performs a blocking operation (network connection or
1058 * cache filling) if the operation fails we use this function to check
1059 * if it was interrupted by the user.
1060 * The function returns a new value for eof. */
1061 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1063 mp_cmd_t *cmd;
1064 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1065 switch (cmd->id) {
1066 case MP_CMD_QUIT:
1067 exit_player_with_rc(mpctx, EXIT_QUIT,
1068 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1069 case MP_CMD_PLAY_TREE_STEP: {
1070 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1071 mpctx->play_tree_step =
1072 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1073 } break;
1074 case MP_CMD_PLAY_TREE_UP_STEP: {
1075 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1076 } break;
1077 case MP_CMD_PLAY_ALT_SRC_STEP: {
1078 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1079 } break;
1081 mp_cmd_free(cmd);
1083 return stop_play;
1086 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1088 play_tree_add_bpf(entry, bstr(mpctx->filename));
1091 if (!entry) {
1092 entry = mpctx->playtree_iter->tree;
1093 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1094 != PLAY_TREE_ITER_ENTRY)
1095 return PT_NEXT_ENTRY;
1096 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1097 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1098 != PLAY_TREE_ITER_ENTRY)
1099 return PT_NEXT_ENTRY;
1101 play_tree_remove(entry, 1, 1);
1102 return PT_NEXT_SRC;
1104 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1105 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1106 entry = mpctx->playtree_iter->tree;
1107 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1108 != PLAY_TREE_ITER_ENTRY)
1109 return PT_NEXT_ENTRY;
1110 play_tree_remove(entry, 1, 1);
1112 return PT_NEXT_SRC;
1115 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1116 int noerr)
1118 struct MPOpts *opts = &mpctx->opts;
1119 sub_data *subd = NULL;
1120 struct ass_track *asst = NULL;
1121 bool is_native_ass = false;
1123 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1124 return;
1126 #ifdef CONFIG_ASS
1127 if (opts->ass_enabled) {
1128 #ifdef CONFIG_ICONV
1129 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1130 #else
1131 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1132 #endif
1133 is_native_ass = asst;
1134 if (!asst) {
1135 subd = sub_read_file(filename, fps, &mpctx->opts);
1136 if (subd) {
1137 asst = mp_ass_read_subdata(mpctx->ass_library, subd, fps);
1138 sub_free(subd);
1139 subd = NULL;
1142 } else
1143 #endif
1144 subd = sub_read_file(filename, fps, &mpctx->opts);
1147 if (!asst && !subd) {
1148 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1149 "Cannot load subtitles: %s\n", filename_recode(filename));
1150 return;
1153 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1154 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1155 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1156 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1157 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1158 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1159 filename_recode(filename));
1160 ++mpctx->set_of_sub_size;
1161 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1162 mpctx->set_of_sub_size, filename_recode(filename));
1165 void init_vo_spudec(struct MPContext *mpctx)
1167 unsigned width, height;
1168 spudec_free(vo_spudec);
1169 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1170 vo_spudec = NULL;
1172 // we currently can't work without video stream
1173 if (!mpctx->sh_video)
1174 return;
1176 if (spudec_ifo) {
1177 unsigned int palette[16];
1178 current_module = "spudec_init_vobsub";
1179 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1180 1, -1, NULL) >= 0)
1181 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1184 width = mpctx->sh_video->disp_w;
1185 height = mpctx->sh_video->disp_h;
1187 #ifdef CONFIG_DVDREAD
1188 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1189 current_module = "spudec_init_dvdread";
1190 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1191 cur_pgc->palette, width, height, NULL, 0);
1193 #endif
1195 #ifdef CONFIG_DVDNAV
1196 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1197 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1198 current_module = "spudec_init_dvdnav";
1199 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1201 #endif
1203 if (vo_spudec == NULL) {
1204 sh_sub_t *sh = mpctx->d_sub->sh;
1205 current_module = "spudec_init_normal";
1206 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1207 sh->extradata_len);
1208 spudec_set_font_factor(vo_spudec, font_factor);
1211 if (vo_spudec != NULL) {
1212 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1213 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1214 mpctx);
1219 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1220 * make it all work is to use the builtin SDL-bootstrap code, which
1221 * will be done automatically by replacing our main() if we include SDL.h.
1223 #if defined(__APPLE__) && defined(CONFIG_SDL)
1224 #ifdef CONFIG_SDL_SDL_H
1225 #include <SDL/SDL.h>
1226 #else
1227 #include <SDL.h>
1228 #endif
1229 #endif
1232 * \brief append a formatted string
1233 * \param buf buffer to print into
1234 * \param pos position of terminating 0 in buf
1235 * \param len maximum number of characters in buf, not including terminating 0
1236 * \param format printf format string
1238 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1240 va_list va;
1241 va_start(va, format);
1242 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1243 va_end(va);
1244 if (*pos >= len) {
1245 buf[len] = 0;
1246 *pos = len;
1251 * \brief append time in the hh:mm:ss.f format
1252 * \param buf buffer to print into
1253 * \param pos position of terminating 0 in buf
1254 * \param len maximum number of characters in buf, not including terminating 0
1255 * \param time time value to convert/append
1257 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1259 int64_t tenths = 10 * time;
1260 int f1 = tenths % 10;
1261 int ss = (tenths / 10) % 60;
1262 int mm = (tenths / 600) % 60;
1263 int hh = tenths / 36000;
1264 if (time < 0) {
1265 saddf(buf, pos, len, "unknown");
1266 return;
1268 if (hh > 0)
1269 saddf(buf, pos, len, "%2d:", hh);
1270 if (hh > 0 || mm > 0)
1271 saddf(buf, pos, len, "%02d:", mm);
1272 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1275 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1277 struct MPOpts *opts = &mpctx->opts;
1278 sh_video_t * const sh_video = mpctx->sh_video;
1280 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1281 a_pos = playing_audio_pts(mpctx);
1282 if (mpctx->sh_audio && sh_video && at_frame) {
1283 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1284 if (mpctx->time_frame > 0)
1285 mpctx->last_av_difference +=
1286 mpctx->time_frame * opts->playback_speed;
1287 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1288 && !mpctx->drop_message_shown) {
1289 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1290 mpctx->drop_message_shown = true;
1293 if (opts->quiet)
1294 return;
1296 if (a_pos == MP_NOPTS_VALUE)
1297 a_pos = -9; // don't print a huge negative number
1299 int width;
1300 char *line;
1301 unsigned pos = 0;
1302 get_screen_size();
1303 if (screen_width > 0)
1304 width = screen_width;
1305 else
1306 width = 80;
1307 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1308 /* Windows command line is broken (MinGW's rxvt works, but we
1309 * should not depend on that). */
1310 width--;
1311 #endif
1312 line = malloc(width + 1); // one additional char for the terminating null
1314 // Audio time
1315 if (mpctx->sh_audio) {
1316 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1317 if (!sh_video) {
1318 float len = get_time_length(mpctx);
1319 saddf(line, &pos, width, "(");
1320 sadd_hhmmssf(line, &pos, width, a_pos);
1321 saddf(line, &pos, width, ") of %.1f (", len);
1322 sadd_hhmmssf(line, &pos, width, len);
1323 saddf(line, &pos, width, ") ");
1327 // Video time
1328 if (sh_video)
1329 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1331 // A-V sync
1332 if (mpctx->sh_audio && sh_video)
1333 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1334 mpctx->last_av_difference, mpctx->total_avsync_change);
1336 // Video stats
1337 if (sh_video)
1338 saddf(line, &pos, width, "%3d/%3d ",
1339 (int)sh_video->num_frames,
1340 (int)sh_video->num_frames_decoded);
1342 // CPU usage
1343 if (sh_video) {
1344 if (sh_video->timer > 0.5)
1345 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1346 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1347 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1348 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1349 else
1350 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1351 } else if (mpctx->sh_audio) {
1352 if (mpctx->delay > 0.5)
1353 saddf(line, &pos, width, "%4.1f%% ",
1354 100.0 * audio_time_usage / (double)mpctx->delay);
1355 else
1356 saddf(line, &pos, width, "??,?%% ");
1359 // VO stats
1360 if (sh_video)
1361 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1363 #ifdef CONFIG_STREAM_CACHE
1364 // cache stats
1365 if (stream_cache_size > 0)
1366 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1367 #endif
1369 // other
1370 if (opts->playback_speed != 1)
1371 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1373 // end
1374 if (erase_to_end_of_line) {
1375 line[pos] = 0;
1376 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1377 "%s%s\r", line, erase_to_end_of_line);
1378 } else {
1379 memset(&line[pos], ' ', width - pos);
1380 line[width] = 0;
1381 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1383 free(line);
1386 struct stream_dump_progress {
1387 uint64_t count;
1388 unsigned start_time;
1389 unsigned last_print_time;
1392 static void stream_dump_progress_start(struct stream_dump_progress *p)
1394 p->start_time = p->last_print_time = GetTimerMS();
1395 p->count = 0;
1398 static void stream_dump_progress(struct stream_dump_progress *p,
1399 uint64_t len, stream_t *stream)
1401 p->count += len;
1402 unsigned t = GetTimerMS();
1403 if (t - p->last_print_time < 1000)
1404 return;
1406 uint64_t start = stream->start_pos;
1407 uint64_t end = stream->end_pos;
1408 uint64_t pos = stream->pos;
1410 p->last_print_time = t;
1411 /* TODO: pretty print sizes; ETA */
1412 if (end > start && pos >= start && pos <= end) {
1413 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1414 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1415 p->count, 100.0 * (pos - start) / (end - start));
1416 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1417 } else {
1418 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1419 "dump: %"PRIu64 " bytes written", p->count);
1420 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1424 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1426 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1427 p->count, name);
1431 * \brief build a chain of audio filters that converts the input format
1432 * to the ao's format, taking into account the current playback_speed.
1433 * sh_audio describes the requested input format of the chain.
1434 * ao describes the requested output format of the chain.
1436 static int build_afilter_chain(struct MPContext *mpctx)
1438 struct sh_audio *sh_audio = mpctx->sh_audio;
1439 struct ao *ao = mpctx->ao;
1440 struct MPOpts *opts = &mpctx->opts;
1441 int new_srate;
1442 int result;
1443 if (!sh_audio) {
1444 mpctx->mixer.afilter = NULL;
1445 return 0;
1447 if (af_control_any_rev(sh_audio->afilter,
1448 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1449 &opts->playback_speed))
1450 new_srate = sh_audio->samplerate;
1451 else {
1452 new_srate = sh_audio->samplerate * opts->playback_speed;
1453 if (new_srate != ao->samplerate) {
1454 // limits are taken from libaf/af_resample.c
1455 if (new_srate < 8000)
1456 new_srate = 8000;
1457 if (new_srate > 192000)
1458 new_srate = 192000;
1459 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1462 result = init_audio_filters(sh_audio, new_srate,
1463 &ao->samplerate, &ao->channels, &ao->format);
1464 mpctx->mixer.afilter = sh_audio->afilter;
1465 return result;
1469 typedef struct mp_osd_msg mp_osd_msg_t;
1470 struct mp_osd_msg {
1471 /// Previous message on the stack.
1472 mp_osd_msg_t *prev;
1473 /// Message text.
1474 char *msg;
1475 int id, level, started;
1476 /// Display duration in ms.
1477 unsigned time;
1480 /// OSD message stack.
1481 static mp_osd_msg_t *osd_msg_stack = NULL;
1484 * \brief Add a message on the OSD message stack
1486 * If a message with the same id is already present in the stack
1487 * it is pulled on top of the stack, otherwise a new message is created.
1490 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1491 va_list ap)
1493 mp_osd_msg_t *msg, *last = NULL;
1495 // look if the id is already in the stack
1496 for (msg = osd_msg_stack; msg && msg->id != id;
1497 last = msg, msg = msg->prev) ;
1498 // not found: alloc it
1499 if (!msg) {
1500 msg = talloc_zero(NULL, mp_osd_msg_t);
1501 msg->prev = osd_msg_stack;
1502 osd_msg_stack = msg;
1503 } else if (last) { // found, but it's not on top of the stack
1504 last->prev = msg->prev;
1505 msg->prev = osd_msg_stack;
1506 osd_msg_stack = msg;
1508 talloc_free(msg->msg);
1509 // write the msg
1510 msg->msg = talloc_vasprintf(msg, fmt, ap);
1511 // set id and time
1512 msg->id = id;
1513 msg->level = level;
1514 msg->time = time;
1518 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1520 va_list ap;
1521 va_start(ap, fmt);
1522 set_osd_msg_va(id, level, time, fmt, ap);
1523 va_end(ap);
1526 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1528 va_list ap;
1529 va_start(ap, fmt);
1530 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1531 va_end(ap);
1535 * \brief Remove a message from the OSD stack
1537 * This function can be used to get rid of a message right away.
1541 void rm_osd_msg(int id)
1543 mp_osd_msg_t *msg, *last = NULL;
1545 // Search for the msg
1546 for (msg = osd_msg_stack; msg && msg->id != id;
1547 last = msg, msg = msg->prev) ;
1548 if (!msg)
1549 return;
1551 // Detach it from the stack and free it
1552 if (last)
1553 last->prev = msg->prev;
1554 else
1555 osd_msg_stack = msg->prev;
1556 talloc_free(msg);
1560 * \brief Remove all messages from the OSD stack
1564 static void clear_osd_msgs(void)
1566 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1567 while (msg) {
1568 prev = msg->prev;
1569 talloc_free(msg);
1570 msg = prev;
1572 osd_msg_stack = NULL;
1576 * \brief Get the current message from the OSD stack.
1578 * This function decrements the message timer and destroys the old ones.
1579 * The message that should be displayed is returned (if any).
1583 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1585 struct MPOpts *opts = &mpctx->opts;
1586 mp_osd_msg_t *msg, *prev, *last = NULL;
1587 static unsigned last_update = 0;
1588 unsigned now = GetTimerMS();
1589 unsigned diff;
1590 char hidden_dec_done = 0;
1592 if (mpctx->osd_visible) {
1593 // 36000000 means max timed visibility is 1 hour into the future, if
1594 // the difference is greater assume it's wrapped around from below 0
1595 if (mpctx->osd_visible - now > 36000000) {
1596 mpctx->osd_visible = 0;
1597 vo_osd_progbar_type = -1; // disable
1598 vo_osd_changed(OSDTYPE_PROGBAR);
1599 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1602 if (mpctx->osd_show_percentage_until - now > 36000000)
1603 mpctx->osd_show_percentage_until = 0;
1605 if (!last_update)
1606 last_update = now;
1607 diff = now >= last_update ? now - last_update : 0;
1609 last_update = now;
1611 // Look for the first message in the stack with high enough level.
1612 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1613 prev = msg->prev;
1614 if (msg->level > opts->osd_level && hidden_dec_done)
1615 continue;
1616 // The message has a high enough level or it is the first hidden one
1617 // in both cases we decrement the timer or kill it.
1618 if (!msg->started || msg->time > diff) {
1619 if (msg->started)
1620 msg->time -= diff;
1621 else
1622 msg->started = 1;
1623 // display it
1624 if (msg->level <= opts->osd_level)
1625 return msg;
1626 hidden_dec_done = 1;
1627 continue;
1629 // kill the message
1630 talloc_free(msg);
1631 if (last) {
1632 last->prev = prev;
1633 msg = last;
1634 } else {
1635 osd_msg_stack = prev;
1636 msg = NULL;
1639 // Nothing found
1640 return NULL;
1644 * \brief Display the OSD bar.
1646 * Display the OSD bar or fall back on a simple message.
1650 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1651 double min, double max, double val)
1653 struct MPOpts *opts = &mpctx->opts;
1654 if (opts->osd_level < 1)
1655 return;
1657 if (mpctx->sh_video) {
1658 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1659 vo_osd_progbar_type = type;
1660 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1661 vo_osd_changed(OSDTYPE_PROGBAR);
1662 return;
1665 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1666 name, ROUND(100 * (val - min) / (max - min)));
1670 * \brief Display text subtitles on the OSD
1672 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1674 int i;
1675 vo_sub = subs;
1676 vo_osd_changed(OSDTYPE_SUBTITLE);
1677 if (!mpctx->sh_video) {
1678 // reverse order, since newest set_osd_msg is displayed first
1679 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1680 if (!subs || i >= subs->lines || !subs->text[i])
1681 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1682 else {
1683 // HACK: currently display time for each sub line
1684 // except the last is set to 2 seconds.
1685 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1686 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1687 "%s", subs->text[i]);
1694 * \brief Update the OSD message line.
1696 * This function displays the current message on the vo OSD or on the term.
1697 * If the stack is empty and the OSD level is high enough the timer
1698 * is displayed (only on the vo OSD).
1702 static void update_osd_msg(struct MPContext *mpctx)
1704 struct MPOpts *opts = &mpctx->opts;
1705 mp_osd_msg_t *msg;
1706 struct osd_state *osd = mpctx->osd;
1707 char osd_text_timer[128];
1709 if (mpctx->add_osd_seek_info) {
1710 double percentage = get_percent_pos(mpctx);
1711 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1712 if (mpctx->sh_video)
1713 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1714 mpctx->add_osd_seek_info = false;
1717 // Look if we have a msg
1718 if ((msg = get_osd_msg(mpctx))) {
1719 if (strcmp(osd->osd_text, msg->msg)) {
1720 osd_set_text(osd, msg->msg);
1721 if (mpctx->sh_video)
1722 vo_osd_changed(OSDTYPE_OSD);
1723 else if (opts->term_osd)
1724 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1725 msg->msg);
1727 return;
1730 if (mpctx->sh_video) {
1731 // fallback on the timer
1732 if (opts->osd_level >= 2) {
1733 int len = get_time_length(mpctx);
1734 int percentage = -1;
1735 char percentage_text[10];
1736 char fractions_text[4];
1737 double fpts = get_current_time(mpctx);
1738 int pts = fpts;
1740 if (mpctx->osd_show_percentage_until)
1741 percentage = get_percent_pos(mpctx);
1743 if (percentage >= 0)
1744 snprintf(percentage_text, 9, " (%d%%)", percentage);
1745 else
1746 percentage_text[0] = 0;
1748 if (opts->osd_fractions == 1) {
1749 //print fractions as sub-second timestamp
1750 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1751 (int)((fpts - pts) * 100));
1752 } else if (opts->osd_fractions == 2) {
1753 /* Print fractions by estimating the frame count within the
1754 * second.
1756 * Rounding or cutting off numbers after the decimal point
1757 * causes problems because of float's precision and movies
1758 * whose first frame is not exactly at timestamp 0. Therefore,
1759 * we add 0.2 and cut off at the decimal point, which proved
1760 * to be good heuristic.
1762 double fps = mpctx->sh_video->fps;
1763 if (fps <= 1 || fps > 99)
1764 strcpy(fractions_text, ".??");
1765 else
1766 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1767 (int) ((fpts - pts) * fps + 0.2));
1768 } else {
1769 //do not print fractions
1770 fractions_text[0] = 0;
1773 if (opts->osd_level == 3)
1774 snprintf(osd_text_timer, sizeof(osd_text_timer),
1775 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1776 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1777 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1778 percentage_text);
1779 else
1780 snprintf(osd_text_timer, sizeof(osd_text_timer),
1781 "%c %02d:%02d:%02d%s%s",
1782 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1783 pts % 60, fractions_text, percentage_text);
1784 } else
1785 osd_text_timer[0] = 0;
1787 if (strcmp(osd->osd_text, osd_text_timer)) {
1788 osd_set_text(osd, osd_text_timer);
1789 vo_osd_changed(OSDTYPE_OSD);
1791 return;
1794 // Clear the term osd line
1795 if (opts->term_osd && osd->osd_text[0]) {
1796 osd->osd_text[0] = 0;
1797 printf("%s\n", opts->term_osd_esc);
1801 ///@}
1802 // OSDMsgStack
1805 void reinit_audio_chain(struct MPContext *mpctx)
1807 struct MPOpts *opts = &mpctx->opts;
1808 struct ao *ao;
1809 if (!mpctx->sh_audio)
1810 return;
1811 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1812 current_module = "init_audio_codec";
1813 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1814 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1815 goto init_error;
1816 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1817 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1821 current_module = "af_preinit";
1822 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1823 mpctx->initialized_flags |= INITIALIZED_AO;
1824 mpctx->ao = ao_create();
1825 mpctx->ao->samplerate = force_srate;
1826 mpctx->ao->format = opts->audio_output_format;
1828 ao = mpctx->ao;
1830 // first init to detect best values
1831 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1832 // input:
1833 mpctx->sh_audio->samplerate,
1834 // output:
1835 &ao->samplerate, &ao->channels, &ao->format)) {
1836 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1837 "pre-init!\n");
1838 exit_player(mpctx, EXIT_ERROR);
1840 if (!ao->initialized) {
1841 current_module = "ao2_init";
1842 ao->buffersize = opts->ao_buffersize;
1843 ao_init(ao, opts->audio_driver_list);
1844 if (!ao->initialized) {
1845 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1846 "Could not open/initialize audio device -> no sound.\n");
1847 goto init_error;
1849 ao->buffer.start = talloc_new(ao);
1850 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1851 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1852 ao->driver->info->short_name,
1853 ao->samplerate, ao->channels,
1854 af_fmt2str_short(ao->format),
1855 af_fmt2bits(ao->format) / 8);
1856 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1857 ao->driver->info->name, ao->driver->info->author);
1858 if (strlen(ao->driver->info->comment) > 0)
1859 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1860 ao->driver->info->comment);
1863 // init audio filters:
1864 current_module = "af_init";
1865 if (!build_afilter_chain(mpctx)) {
1866 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1867 "Couldn't find matching filter/ao format!\n");
1868 goto init_error;
1870 mpctx->mixer.ao = ao;
1871 mpctx->mixer.volstep = volstep;
1872 mpctx->syncing_audio = true;
1873 return;
1875 init_error:
1876 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1877 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1878 mpctx->d_audio->id = -2;
1882 ///@}
1883 // Command2Property
1886 // Return pts value corresponding to the end point of audio written to the
1887 // ao so far.
1888 static double written_audio_pts(struct MPContext *mpctx)
1890 sh_audio_t *sh_audio = mpctx->sh_audio;
1891 demux_stream_t *d_audio = mpctx->d_audio;
1892 // first calculate the end pts of audio that has been output by decoder
1893 double a_pts = sh_audio->pts;
1894 if (a_pts != MP_NOPTS_VALUE)
1895 // Good, decoder supports new way of calculating audio pts.
1896 // sh_audio->pts is the timestamp of the latest input packet with
1897 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1898 // the amount of bytes the decoder has written after that timestamp.
1899 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1900 else {
1901 // Decoder doesn't support new way of calculating pts (or we're
1902 // being called before it has decoded anything with known timestamp).
1903 // Use the old method of audio pts calculation: take the timestamp
1904 // of last packet with known pts the decoder has read data from,
1905 // and add amount of bytes read after the beginning of that packet
1906 // divided by input bps. This will be inaccurate if the input/output
1907 // ratio is not constant for every audio packet or if it is constant
1908 // but not accurately known in sh_audio->i_bps.
1910 a_pts = d_audio->pts;
1911 if (a_pts == MP_NOPTS_VALUE)
1912 return a_pts;
1914 // ds_tell_pts returns bytes read after last timestamp from
1915 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1916 // it has read but not decoded
1917 if (sh_audio->i_bps)
1918 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1919 (double)sh_audio->i_bps;
1921 // Now a_pts hopefully holds the pts for end of audio from decoder.
1922 // Substract data in buffers between decoder and audio out.
1924 // Decoded but not filtered
1925 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1927 // Data buffered in audio filters, measured in bytes of "missing" output
1928 double buffered_output = af_calc_delay(sh_audio->afilter);
1930 // Data that was ready for ao but was buffered because ao didn't fully
1931 // accept everything to internal buffers yet
1932 buffered_output += mpctx->ao->buffer.len;
1934 // Filters divide audio length by playback_speed, so multiply by it
1935 // to get the length in original units without speedup or slowdown
1936 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1938 return a_pts + mpctx->video_offset;
1941 // Return pts value corresponding to currently playing audio.
1942 double playing_audio_pts(struct MPContext *mpctx)
1944 double pts = written_audio_pts(mpctx);
1945 if (pts == MP_NOPTS_VALUE)
1946 return pts;
1947 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1950 static bool is_av_sub(int type)
1952 return type == 'b' || type == 'p' || type == 'x';
1955 void update_subtitles(struct MPContext *mpctx, double refpts,
1956 double sub_offset, bool reset)
1958 struct MPOpts *opts = &mpctx->opts;
1959 struct sh_video *sh_video = mpctx->sh_video;
1960 struct demux_stream *d_sub = mpctx->d_sub;
1961 double curpts = refpts + sub_delay;
1962 unsigned char *packet = NULL;
1963 int len;
1964 struct sh_sub *sh_sub = d_sub->sh;
1965 int type = sh_sub ? sh_sub->type : 'v';
1966 static subtitle subs;
1967 if (reset) {
1968 if (sh_sub)
1969 sub_reset(sh_sub, mpctx->osd);
1970 sub_clear_text(&subs, MP_NOPTS_VALUE);
1971 if (vo_sub)
1972 set_osd_subtitle(mpctx, NULL);
1973 if (vo_spudec) {
1974 spudec_reset(vo_spudec);
1975 vo_osd_changed(OSDTYPE_SPU);
1977 #ifdef CONFIG_FFMPEG
1978 if (is_av_sub(type))
1979 reset_avsub(sh_sub);
1980 #endif
1981 return;
1983 // find sub
1984 if (mpctx->subdata) {
1985 if (sub_fps == 0)
1986 sub_fps = sh_video ? sh_video->fps : 25;
1987 current_module = "find_sub";
1988 find_sub(mpctx, mpctx->subdata, curpts *
1989 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1990 if (vo_sub)
1991 mpctx->vo_sub_last = vo_sub;
1994 // DVD sub:
1995 if (vobsub_id >= 0 || type == 'v') {
1996 int timestamp;
1997 current_module = "spudec";
1998 /* Get a sub packet from the DVD or a vobsub */
1999 while (1) {
2000 // Vobsub
2001 len = 0;
2002 if (vo_vobsub) {
2003 if (curpts >= 0) {
2004 len = vobsub_get_packet(vo_vobsub, curpts,
2005 (void **)&packet, &timestamp);
2006 if (len > 0)
2007 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
2008 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
2009 len, refpts, sh_video->timer,
2010 timestamp / 90000.0, timestamp);
2012 } else {
2013 // DVD sub
2014 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
2015 if (len > 0) {
2016 // XXX This is wrong, sh_video->pts can be arbitrarily
2017 // much behind demuxing position. Unfortunately using
2018 // d_video->pts which would have been the simplest
2019 // improvement doesn't work because mpeg specific hacks
2020 // in video.c set d_video->pts to 0.
2021 float x = d_sub->pts - refpts;
2022 if (x > -20 && x < 20) // prevent missing subs on pts reset
2023 timestamp = 90000 * d_sub->pts;
2024 else
2025 timestamp = 90000 * curpts;
2026 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
2027 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
2028 refpts, d_sub->pts, timestamp);
2031 if (len <= 0 || !packet)
2032 break;
2033 // create it only here, since with some broken demuxers we might
2034 // type = v but no DVD sub and we currently do not change the
2035 // "original frame size" ever after init, leading to wrong-sized
2036 // PGS subtitles.
2037 if (!vo_spudec)
2038 vo_spudec = spudec_new(NULL);
2039 if (vo_vobsub || timestamp >= 0)
2040 spudec_assemble(vo_spudec, packet, len, timestamp);
2042 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
2043 if (type == 'd' && !d_sub->demuxer->teletext) {
2044 tt_stream_props tsp = { 0 };
2045 void *ptr = &tsp;
2046 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
2047 VBI_CONTROL_TRUE)
2048 d_sub->demuxer->teletext = ptr;
2050 if (d_sub->non_interleaved)
2051 ds_get_next_pts(d_sub);
2053 while (d_sub->first) {
2054 double subpts = ds_get_next_pts(d_sub) + sub_offset;
2055 if (subpts > curpts) {
2056 // Libass handled subs can be fed to it in advance
2057 if (!opts->ass_enabled || !is_text_sub(type))
2058 break;
2059 // Try to avoid demuxing whole file at once
2060 if (d_sub->non_interleaved && subpts > curpts + 1)
2061 break;
2063 double duration = d_sub->first->duration;
2064 len = ds_get_packet_sub(d_sub, &packet);
2065 if (is_av_sub(type)) {
2066 #ifdef CONFIG_FFMPEG
2067 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2068 if (ret < 0)
2069 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2070 "subtitle\n");
2071 #endif
2072 continue;
2074 if (type == 'm') {
2075 if (len < 2)
2076 continue;
2077 len = FFMIN(len - 2, AV_RB16(packet));
2078 packet += 2;
2080 if (type == 'd') {
2081 if (d_sub->demuxer->teletext) {
2082 uint8_t *p = packet;
2083 p++;
2084 len--;
2085 while (len >= 46) {
2086 int sublen = p[1];
2087 if (p[0] == 2 || p[0] == 3)
2088 teletext_control(d_sub->demuxer->teletext,
2089 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2090 p += sublen + 2;
2091 len -= sublen + 2;
2094 continue;
2096 if (sh_sub && sh_sub->active) {
2097 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2098 continue;
2100 if (subpts != MP_NOPTS_VALUE) {
2101 if (duration < 0)
2102 sub_clear_text(&subs, MP_NOPTS_VALUE);
2103 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2104 int i;
2105 unsigned char *p = packet;
2106 for (i = 0; i < 8 && *p != '\0'; p++)
2107 if (*p == ',')
2108 i++;
2109 if (*p == '\0') /* Broken line? */
2110 continue;
2111 len -= p - packet;
2112 packet = p;
2114 double endpts = MP_NOPTS_VALUE;
2115 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2116 endpts = subpts + duration;
2117 sub_add_text(&subs, packet, len, endpts);
2118 set_osd_subtitle(mpctx, &subs);
2120 if (d_sub->non_interleaved)
2121 ds_get_next_pts(d_sub);
2123 if (!opts->ass_enabled)
2124 if (sub_clear_text(&subs, curpts))
2125 set_osd_subtitle(mpctx, &subs);
2127 if (vo_spudec) {
2128 spudec_heartbeat(vo_spudec, 90000 * curpts);
2129 if (spudec_changed(vo_spudec))
2130 vo_osd_changed(OSDTYPE_SPU);
2133 current_module = NULL;
2136 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2138 int page_changed;
2140 if (!demuxer->teletext)
2141 return;
2143 //Also forcing page update when such ioctl is not supported or call error occured
2144 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2145 &page_changed) != VBI_CONTROL_TRUE)
2146 page_changed = 1;
2148 if (!page_changed)
2149 return;
2151 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2152 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2153 vo_osd_teletext_page = NULL;
2154 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2155 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2156 vo_osd_teletext_half = 0;
2157 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2158 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2159 vo_osd_teletext_mode = 0;
2160 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2161 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2162 vo_osd_teletext_format = 0;
2163 vo_osd_changed(OSDTYPE_TELETEXT);
2165 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2168 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2170 struct MPOpts *opts = &mpctx->opts;
2171 // check for frame-drop:
2172 current_module = "check_framedrop";
2173 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2174 static int dropped_frames;
2175 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2176 float d = delay - mpctx->delay;
2177 ++total_frame_cnt;
2178 // we should avoid dropping too many frames in sequence unless we
2179 // are too late. and we allow 100ms A-V delay here:
2180 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2181 && !mpctx->restart_playback) {
2182 ++drop_frame_cnt;
2183 ++dropped_frames;
2184 return frame_dropping;
2185 } else
2186 dropped_frames = 0;
2188 return 0;
2192 #ifdef HAVE_RTC
2193 int rtc_fd = -1;
2194 #endif
2196 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2198 #ifdef HAVE_RTC
2199 if (rtc_fd >= 0) {
2200 // -------- RTC -----------
2201 current_module = "sleep_rtc";
2202 while (time_frame > 0.000) {
2203 unsigned long rtc_ts;
2204 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2205 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2206 "Linux RTC read error: %s\n", strerror(errno));
2207 time_frame -= get_relative_time(mpctx);
2209 } else
2210 #endif
2212 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2213 // unnecessarily high CPU usage
2214 struct MPOpts *opts = &mpctx->opts;
2215 float margin = opts->softsleep ? 0.011 : 0;
2216 current_module = "sleep_timer";
2217 while (time_frame > margin) {
2218 usec_sleep(1000000 * (time_frame - margin));
2219 time_frame -= get_relative_time(mpctx);
2221 if (opts->softsleep) {
2222 current_module = "sleep_soft";
2223 if (time_frame < 0)
2224 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2225 "Warning! Softsleep underflow!\n");
2226 while (time_frame > 0)
2227 time_frame -= get_relative_time(mpctx); // burn the CPU
2230 return time_frame;
2233 static int select_subtitle(MPContext *mpctx)
2235 struct MPOpts *opts = &mpctx->opts;
2236 // find the best sub to use
2237 int id;
2238 int found = 0;
2239 mpctx->global_sub_pos = -1; // no subs by default
2240 if (vobsub_id >= 0) {
2241 // if user asks for a vobsub id, use that first.
2242 id = vobsub_id;
2243 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2244 M_PROPERTY_OK;
2247 if (!found && opts->sub_id >= 0) {
2248 // if user asks for a dvd sub id, use that next.
2249 id = opts->sub_id;
2250 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2251 M_PROPERTY_OK;
2254 if (!found) {
2255 // if there are text subs to use, use those. (autosubs come last here)
2256 id = 0;
2257 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2258 M_PROPERTY_OK;
2261 if (!found && opts->sub_id == -1) {
2262 // finally select subs by language and container hints
2263 if (opts->sub_id == -1)
2264 opts->sub_id =
2265 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2266 opts->sub_lang);
2267 if (opts->sub_id >= 0) {
2268 id = opts->sub_id;
2269 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2270 M_PROPERTY_OK;
2273 return found;
2276 #ifdef CONFIG_DVDNAV
2277 #ifndef FF_B_TYPE
2278 #define FF_B_TYPE 3
2279 #endif
2280 /// store decoded video image
2281 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2282 mp_image_t *from_mpi)
2284 mp_image_t *mpi;
2286 /// Do not store B-frames
2287 if (from_mpi->pict_type == FF_B_TYPE)
2288 return to_mpi;
2290 if (to_mpi &&
2291 to_mpi->w == from_mpi->w &&
2292 to_mpi->h == from_mpi->h &&
2293 to_mpi->imgfmt == from_mpi->imgfmt)
2294 mpi = to_mpi;
2295 else {
2296 if (to_mpi)
2297 free_mp_image(to_mpi);
2298 if (from_mpi->w == 0 || from_mpi->h == 0)
2299 return NULL;
2300 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2303 copy_mpi(mpi, from_mpi);
2304 return mpi;
2307 static void mp_dvdnav_reset_stream(MPContext *ctx)
2309 struct MPOpts *opts = &ctx->opts;
2310 if (ctx->sh_video) {
2311 /// clear video pts
2312 ctx->d_video->pts = 0.0f;
2313 ctx->sh_video->pts = 0.0f;
2314 ctx->sh_video->i_pts = 0.0f;
2315 ctx->sh_video->last_pts = 0.0f;
2316 ctx->sh_video->num_buffered_pts = 0;
2317 ctx->sh_video->num_frames = 0;
2318 ctx->sh_video->num_frames_decoded = 0;
2319 ctx->sh_video->timer = 0.0f;
2320 ctx->sh_video->stream_delay = 0.0f;
2321 ctx->sh_video->timer = 0;
2322 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2325 if (ctx->sh_audio) {
2326 /// free audio packets and reset
2327 ds_free_packs(ctx->d_audio);
2328 audio_delay -= ctx->sh_audio->stream_delay;
2329 ctx->delay = -audio_delay;
2330 ao_reset(ctx->ao);
2331 resync_audio_stream(ctx->sh_audio);
2334 audio_delay = 0.0f;
2335 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2336 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2337 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2338 if (dvdsub_lang_id != opts->sub_id) {
2339 opts->sub_id = dvdsub_lang_id;
2340 select_subtitle(ctx);
2344 /// clear all EOF related flags
2345 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2348 /// Restore last decoded DVDNAV (still frame)
2349 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2350 int *in_size,
2351 unsigned char **start,
2352 mp_image_t *decoded_frame)
2354 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2355 return decoded_frame;
2357 /// a change occurred in dvdnav stream
2358 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2359 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2360 mp_dvdnav_context_free(mpctx);
2361 mp_dvdnav_reset_stream(mpctx);
2362 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2363 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2366 if (*in_size < 0) {
2367 float len;
2369 /// Display still frame, if any
2370 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2371 decoded_frame = mpctx->nav_smpi;
2373 /// increment video frame : continue playing after still frame
2374 len = get_time_length(mpctx);
2375 if (mpctx->sh_video->pts >= len &&
2376 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2377 mp_dvdnav_skip_still(mpctx->stream);
2378 mp_dvdnav_skip_wait(mpctx->stream);
2380 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2382 if (mpctx->nav_buffer) {
2383 *start = mpctx->nav_start;
2384 *in_size = mpctx->nav_in_size;
2385 if (mpctx->nav_start)
2386 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2390 return decoded_frame;
2393 /// Save last decoded DVDNAV (still frame)
2394 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2395 unsigned char *start,
2396 mp_image_t *decoded_frame)
2398 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2399 return;
2401 free(mpctx->nav_buffer);
2402 mpctx->nav_buffer = NULL;
2403 mpctx->nav_start = NULL;
2404 mpctx->nav_in_size = -1;
2406 if (in_size > 0)
2407 mpctx->nav_buffer = malloc(in_size);
2408 if (mpctx->nav_buffer) {
2409 mpctx->nav_start = start;
2410 mpctx->nav_in_size = in_size;
2411 memcpy(mpctx->nav_buffer, start, in_size);
2414 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2415 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2417 #endif /* CONFIG_DVDNAV */
2419 /* Modify video timing to match the audio timeline. There are two main
2420 * reasons this is needed. First, video and audio can start from different
2421 * positions at beginning of file or after a seek (MPlayer starts both
2422 * immediately even if they have different pts). Second, the file can have
2423 * audio timestamps that are inconsistent with the duration of the audio
2424 * packets, for example two consecutive timestamp values differing by
2425 * one second but only a packet with enough samples for half a second
2426 * of playback between them.
2428 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2430 current_module = "av_sync";
2432 if (!mpctx->sh_audio || mpctx->syncing_audio)
2433 return;
2435 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2436 double v_pts = mpctx->sh_video->pts;
2437 double av_delay = a_pts - v_pts;
2438 // Try to sync vo_flip() so it will *finish* at given time
2439 av_delay += mpctx->last_vo_flip_duration;
2440 av_delay -= audio_delay; // This much pts difference is desired
2442 double change = av_delay * 0.1;
2443 double max_change = default_max_pts_correction >= 0 ?
2444 default_max_pts_correction : frame_time * 0.1;
2445 if (change < -max_change)
2446 change = -max_change;
2447 else if (change > max_change)
2448 change = max_change;
2449 mpctx->delay += change;
2450 mpctx->total_avsync_change += change;
2453 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2454 double pts)
2456 if (mpctx->paused)
2457 return 0;
2458 struct ao *ao = mpctx->ao;
2459 double bps = ao->bps / mpctx->opts.playback_speed;
2460 ao->pts = pts;
2461 // hack used by some mpeg-writing AOs
2462 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2463 mpctx->delay) * 90000.0;
2464 int played = ao_play(mpctx->ao, data, len, flags);
2465 if (played > 0) {
2466 mpctx->delay += played / bps;
2467 // Keep correct pts for remaining data - could be used to flush
2468 // remaining buffer when closing ao.
2469 ao->pts += played / bps;
2471 return played;
2474 #define ASYNC_PLAY_DONE -3
2475 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2477 struct ao *ao = mpctx->ao;
2478 struct MPOpts *opts = &mpctx->opts;
2479 sh_audio_t * const sh_audio = mpctx->sh_audio;
2480 int res;
2482 // Timing info may not be set without
2483 res = decode_audio(sh_audio, &ao->buffer, 1);
2484 if (res < 0)
2485 return res;
2487 int bytes;
2488 bool did_retry = false;
2489 double written_pts;
2490 double bps = ao->bps / opts->playback_speed;
2491 while (1) {
2492 written_pts = written_audio_pts(mpctx);
2493 double ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2494 - audio_delay;
2495 bytes = ptsdiff * bps;
2496 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2498 // ogg demuxers give packets without timing
2499 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2500 if (!did_retry) {
2501 // Try to read more data to see packets that have pts
2502 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2503 if (res < 0)
2504 return res;
2505 did_retry = true;
2506 continue;
2508 bytes = 0;
2511 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2512 bytes = 0;
2514 if (bytes > 0)
2515 break;
2517 mpctx->syncing_audio = false;
2518 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2519 int res = decode_audio(sh_audio, &ao->buffer, a);
2520 bytes += ao->buffer.len;
2521 if (bytes >= 0) {
2522 memmove(ao->buffer.start,
2523 ao->buffer.start + ao->buffer.len - bytes, bytes);
2524 ao->buffer.len = bytes;
2525 if (res < 0)
2526 return res;
2527 return decode_audio(sh_audio, &ao->buffer, playsize);
2529 ao->buffer.len = 0;
2530 if (res < 0)
2531 return res;
2533 int fillbyte = 0;
2534 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2535 fillbyte = 0x80;
2536 if (bytes >= playsize) {
2537 /* This case could fall back to the one below with
2538 * bytes = playsize, but then silence would keep accumulating
2539 * in a_out_buffer if the AO accepts less data than it asks for
2540 * in playsize. */
2541 char *p = malloc(playsize);
2542 memset(p, fillbyte, playsize);
2543 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2544 free(p);
2545 return ASYNC_PLAY_DONE;
2547 mpctx->syncing_audio = false;
2548 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2549 return decode_audio(sh_audio, &ao->buffer, playsize);
2552 static int fill_audio_out_buffers(struct MPContext *mpctx)
2554 struct MPOpts *opts = &mpctx->opts;
2555 struct ao *ao = mpctx->ao;
2556 unsigned int t;
2557 double tt;
2558 int playsize;
2559 int playflags = 0;
2560 bool audio_eof = false;
2561 bool partial_fill = false;
2562 sh_audio_t * const sh_audio = mpctx->sh_audio;
2563 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2564 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2566 current_module = "play_audio";
2568 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2569 return 0;
2571 // hack used by some mpeg-writing AOs
2572 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2573 mpctx->delay) * 90000.0;
2575 if (mpctx->paused)
2576 playsize = 1; // just initialize things (audio pts at least)
2577 else
2578 playsize = ao_get_space(ao);
2580 // Fill buffer if needed:
2581 current_module = "decode_audio";
2582 t = GetTimer();
2584 if (!opts->initial_audio_sync || !modifiable_audio_format)
2585 mpctx->syncing_audio = false;
2587 int res;
2588 if (mpctx->syncing_audio && mpctx->sh_video)
2589 res = audio_start_sync(mpctx, playsize);
2590 else
2591 res = decode_audio(sh_audio, &ao->buffer, playsize);
2592 if (res < 0) { // EOF, error or format change
2593 if (res == -2) {
2594 /* The format change isn't handled too gracefully. A more precise
2595 * implementation would require draining buffered old-format audio
2596 * while displaying video, then doing the output format switch.
2598 uninit_player(mpctx, INITIALIZED_AO);
2599 reinit_audio_chain(mpctx);
2600 return -1;
2601 } else if (res == ASYNC_PLAY_DONE)
2602 return 0;
2603 else if (mpctx->d_audio->eof)
2604 audio_eof = true;
2606 t = GetTimer() - t;
2607 tt = t * 0.000001f;
2608 audio_time_usage += tt;
2609 if (mpctx->timeline && modifiable_audio_format) {
2610 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2611 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2612 * ao->bps / opts->playback_speed;
2613 if (playsize > bytes) {
2614 playsize = FFMAX(bytes, 0);
2615 playflags |= AOPLAY_FINAL_CHUNK;
2616 audio_eof = true;
2617 partial_fill = true;
2621 assert(ao->buffer.len % unitsize == 0);
2622 if (playsize > ao->buffer.len) {
2623 partial_fill = true;
2624 playsize = ao->buffer.len;
2625 if (audio_eof)
2626 playflags |= AOPLAY_FINAL_CHUNK;
2628 playsize -= playsize % unitsize;
2629 if (!playsize)
2630 return partial_fill && audio_eof ? -2 : -partial_fill;
2632 // play audio:
2633 current_module = "play_audio";
2635 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2636 written_audio_pts(mpctx));
2637 assert(played % unitsize == 0);
2638 ao->buffer_playable_size = playsize - played;
2640 if (played > 0) {
2641 ao->buffer.len -= played;
2642 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2643 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2644 // Sanity check to avoid hanging in case current ao doesn't output
2645 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2646 return -2;
2649 return -partial_fill;
2652 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2653 bool sync_to_audio, float *aq_sleep_time)
2655 struct MPOpts *opts = &mpctx->opts;
2656 double audio_limit = 2;
2657 current_module = "calc_sleep_time";
2659 if (mpctx->restart_playback)
2660 return 0;
2662 *time_frame -= get_relative_time(mpctx); // reset timer
2664 if (sync_to_audio) {
2665 float delay = ao_get_delay(mpctx->ao);
2666 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2668 if (opts->autosync) {
2670 * Adjust this raw delay value by calculating the expected
2671 * delay for this frame and generating a new value which is
2672 * weighted between the two. The higher autosync is, the
2673 * closer to the delay value gets to that which "-nosound"
2674 * would have used, and the longer it will take for A/V
2675 * sync to settle at the right value (but it eventually will.)
2676 * This settling time is very short for values below 100.
2678 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2679 float difference = delay - predicted;
2680 delay = predicted + difference / (float)opts->autosync;
2683 *time_frame = delay - mpctx->delay / opts->playback_speed;
2685 // delay = amount of audio buffered in soundcard/driver
2686 delay = FFMIN(delay, 0.5);
2687 delay = FFMAX(delay, 0.1);
2688 audio_limit = delay;
2689 } else {
2690 // If we're lagging more than 200 ms behind the right playback rate,
2691 // don't try to "catch up".
2692 // If benchmark is set always output frames as fast as possible
2693 // without sleeping.
2694 if (*time_frame < -0.2 || opts->benchmark)
2695 *time_frame = 0;
2698 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2700 if (t <= 0.05)
2701 return 0;
2703 t -= 0.05;
2704 if (t > audio_limit * 0.6)
2705 t = audio_limit * 0.5;
2706 *aq_sleep_time += t;
2707 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2708 return 1;
2711 int reinit_video_chain(struct MPContext *mpctx)
2713 struct MPOpts *opts = &mpctx->opts;
2714 sh_video_t * const sh_video = mpctx->sh_video;
2715 if (!sh_video)
2716 return 0;
2717 double ar = -1.0;
2718 //================== Init VIDEO (codec & libvo) ==========================
2719 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2720 current_module = "preinit_libvo";
2722 //shouldn't we set dvideo->id=-2 when we fail?
2723 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2724 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2725 mpctx->key_fifo,
2726 mpctx->input))) {
2727 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2728 "the selected video_out (-vo) device.\n");
2729 goto err_out;
2731 mpctx->initialized_flags |= INITIALIZED_VO;
2734 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2735 &ar) != STREAM_UNSUPPORTED)
2736 mpctx->sh_video->stream_aspect = ar;
2737 current_module = "init_video_filters";
2739 char *vf_arg[] = {
2740 "_oldargs_", (char *)mpctx->video_out, NULL
2742 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2744 #ifdef CONFIG_MENU
2745 if (use_menu) {
2746 char *vf_arg[] = {
2747 "_oldargs_", menu_root, NULL
2749 vf_menu = vf_open_plugin(opts, libmenu_vfs, sh_video->vfilter, "menu",
2750 vf_arg);
2751 if (!vf_menu) {
2752 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open libmenu video filter "
2753 "with root menu %s.\n", menu_root);
2754 use_menu = 0;
2757 if (vf_menu)
2758 sh_video->vfilter = vf_menu;
2759 #endif
2761 #ifdef CONFIG_ASS
2762 if (opts->ass_enabled) {
2763 int i;
2764 int insert = 1;
2765 if (opts->vf_settings)
2766 for (i = 0; opts->vf_settings[i].name; ++i)
2767 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2768 insert = 0;
2769 break;
2771 if (insert) {
2772 extern vf_info_t vf_info_ass;
2773 const vf_info_t *libass_vfs[] = {
2774 &vf_info_ass, NULL
2776 char *vf_arg[] = {
2777 "auto", "1", NULL
2779 int retcode = 0;
2780 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2781 sh_video->vfilter,
2782 "ass", vf_arg,
2783 &retcode);
2784 if (vf_ass)
2785 sh_video->vfilter = vf_ass;
2786 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2787 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2788 else
2789 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2790 "ASS: cannot add video filter\n");
2793 #endif
2795 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2797 #ifdef CONFIG_ASS
2798 if (opts->ass_enabled)
2799 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2800 mpctx->ass_library);
2801 #endif
2803 current_module = "init_video_codec";
2805 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2806 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2807 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2809 if (!sh_video->initialized) {
2810 if (!opts->fixed_vo)
2811 uninit_player(mpctx, INITIALIZED_VO);
2812 goto err_out;
2815 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2817 if (sh_video->codec)
2818 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2819 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2821 sh_video->last_pts = MP_NOPTS_VALUE;
2822 sh_video->num_buffered_pts = 0;
2823 sh_video->next_frame_time = 0;
2825 if (opts->auto_quality > 0) {
2826 // Auto quality option enabled
2827 output_quality = get_video_quality_max(sh_video);
2828 if (opts->auto_quality > output_quality)
2829 opts->auto_quality = output_quality;
2830 else
2831 output_quality = opts->auto_quality;
2832 mp_msg(MSGT_CPLAYER, MSGL_V,
2833 "AutoQ: setting quality to %d.\n", output_quality);
2834 set_video_quality(sh_video, output_quality);
2837 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2839 current_module = "init_vo";
2841 return 1;
2843 err_out:
2844 mpctx->sh_video = mpctx->d_video->sh = NULL;
2845 return 0;
2848 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2850 struct sh_video *sh_video = mpctx->sh_video;
2851 double frame_time = 0;
2852 struct vo *video_out = mpctx->video_out;
2853 while (1) {
2854 current_module = "filter_video";
2855 // In nocorrect-pts mode there is no way to properly time these frames
2856 if (vo_get_buffered_frame(video_out, 0) >= 0)
2857 break;
2858 if (vf_output_queued_frame(sh_video->vfilter))
2859 break;
2860 unsigned char *packet = NULL;
2861 frame_time = sh_video->next_frame_time;
2862 if (mpctx->restart_playback)
2863 frame_time = 0;
2864 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2865 &packet, force_fps);
2866 if (in_size < 0) {
2867 #ifdef CONFIG_DVDNAV
2868 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2869 if (mp_dvdnav_is_eof(mpctx->stream))
2870 return -1;
2871 if (mpctx->d_video)
2872 mpctx->d_video->eof = 0;
2873 if (mpctx->d_audio)
2874 mpctx->d_audio->eof = 0;
2875 mpctx->stream->eof = 0;
2876 } else
2877 #endif
2878 return -1;
2880 if (in_size > max_framesize)
2881 max_framesize = in_size;
2882 sh_video->timer += frame_time;
2883 if (mpctx->sh_audio)
2884 mpctx->delay -= frame_time;
2885 // video_read_frame can change fps (e.g. for ASF video)
2886 vo_fps = sh_video->fps;
2887 int framedrop_type = check_framedrop(mpctx, frame_time);
2888 current_module = "decode video";
2890 void *decoded_frame;
2891 #ifdef CONFIG_DVDNAV
2892 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2893 if (in_size >= 0 && !decoded_frame)
2894 #endif
2895 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2896 sh_video->pts);
2897 #ifdef CONFIG_DVDNAV
2898 // Save last still frame for future display
2899 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2900 #endif
2901 if (decoded_frame) {
2902 current_module = "filter video";
2903 filter_video(sh_video, decoded_frame, sh_video->pts);
2905 break;
2907 return frame_time;
2910 static void determine_frame_pts(struct MPContext *mpctx)
2912 struct sh_video *sh_video = mpctx->sh_video;
2913 struct MPOpts *opts = &mpctx->opts;
2915 if (opts->user_pts_assoc_mode)
2916 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2917 else if (sh_video->pts_assoc_mode == 0) {
2918 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2919 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2920 sh_video->pts_assoc_mode = 1;
2921 else
2922 sh_video->pts_assoc_mode = 2;
2923 } else {
2924 int probcount1 = sh_video->num_reordered_pts_problems;
2925 int probcount2 = sh_video->num_sorted_pts_problems;
2926 if (sh_video->pts_assoc_mode == 2) {
2927 int tmp = probcount1;
2928 probcount1 = probcount2;
2929 probcount2 = tmp;
2931 if (probcount1 >= probcount2 * 1.5 + 2) {
2932 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2933 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2934 "%d.\n", sh_video->pts_assoc_mode);
2937 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2938 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2941 static double update_video(struct MPContext *mpctx)
2943 struct sh_video *sh_video = mpctx->sh_video;
2944 struct vo *video_out = mpctx->video_out;
2945 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2946 mpctx->osd); // hack for vf_expand
2947 if (!mpctx->opts.correct_pts)
2948 return update_video_nocorrect_pts(mpctx);
2950 double pts;
2952 while (1) {
2953 current_module = "filter_video";
2954 if (!mpctx->hrseek_active
2955 && vo_get_buffered_frame(video_out, false) >= 0)
2956 break;
2957 // XXX Time used in this call is not counted in any performance
2958 // timer now
2959 if (vf_output_queued_frame(sh_video->vfilter))
2960 break;
2961 unsigned char *packet = NULL;
2962 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2963 if (pts != MP_NOPTS_VALUE)
2964 pts += mpctx->video_offset;
2965 bool hit_eof = false;
2966 if (in_size < 0) {
2967 // try to extract last frames in case of decoder lag
2968 in_size = 0;
2969 pts = MP_NOPTS_VALUE;
2970 hit_eof = true;
2972 if (in_size > max_framesize)
2973 max_framesize = in_size;
2974 current_module = "decode video";
2975 if (pts >= mpctx->hrseek_pts - .005)
2976 mpctx->hrseek_framedrop = false;
2977 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2978 check_framedrop(mpctx, sh_video->frametime);
2979 void *decoded_frame = decode_video(sh_video, packet, in_size,
2980 framedrop_type, pts);
2981 if (decoded_frame) {
2982 determine_frame_pts(mpctx);
2983 current_module = "filter video";
2984 filter_video(sh_video, decoded_frame, sh_video->pts);
2985 } else if (hit_eof) {
2986 if (vo_get_buffered_frame(video_out, true) < 0)
2987 return -1;
2989 break;
2992 if (!video_out->frame_loaded)
2993 return 0;
2995 pts = video_out->next_pts;
2996 if (pts == MP_NOPTS_VALUE) {
2997 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2998 // Try to use decoder pts from before filters
2999 pts = sh_video->pts;
3000 if (pts == MP_NOPTS_VALUE)
3001 pts = sh_video->last_pts;
3003 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
3004 vo_skip_frame(video_out);
3005 return 0;
3007 mpctx->hrseek_active = false;
3008 sh_video->pts = pts;
3009 if (sh_video->last_pts == MP_NOPTS_VALUE)
3010 sh_video->last_pts = sh_video->pts;
3011 else if (sh_video->last_pts > sh_video->pts) {
3012 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
3013 sh_video->pts, sh_video->last_pts);
3014 /* If the difference in pts is small treat it as jitter around the
3015 * right value (possibly caused by incorrect timestamp ordering) and
3016 * just show this frame immediately after the last one.
3017 * Treat bigger differences as timestamp resets and start counting
3018 * timing of later frames from the position of this one. */
3019 if (sh_video->last_pts - sh_video->pts > 0.5)
3020 sh_video->last_pts = sh_video->pts;
3021 else
3022 sh_video->pts = sh_video->last_pts;
3024 double frame_time = sh_video->pts - sh_video->last_pts;
3025 sh_video->last_pts = sh_video->pts;
3026 sh_video->timer += frame_time;
3027 if (mpctx->sh_audio)
3028 mpctx->delay -= frame_time;
3029 return frame_time;
3032 void pause_player(struct MPContext *mpctx)
3034 if (mpctx->paused)
3035 return;
3036 mpctx->paused = 1;
3037 mpctx->step_frames = 0;
3038 mpctx->time_frame -= get_relative_time(mpctx);
3040 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3041 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3043 if (mpctx->ao && mpctx->sh_audio)
3044 ao_pause(mpctx->ao); // pause audio, keep data if possible
3047 void unpause_player(struct MPContext *mpctx)
3049 if (!mpctx->paused)
3050 return;
3051 mpctx->paused = 0;
3053 if (mpctx->ao && mpctx->sh_audio)
3054 ao_resume(mpctx->ao);
3055 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3056 && !mpctx->step_frames)
3057 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3058 (void)get_relative_time(mpctx); // ignore time that passed during pause
3061 void add_step_frame(struct MPContext *mpctx)
3063 mpctx->step_frames++;
3064 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3065 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3066 unpause_player(mpctx);
3069 static void pause_loop(struct MPContext *mpctx)
3071 struct MPOpts *opts = &mpctx->opts;
3072 mp_cmd_t *cmd;
3073 #ifdef CONFIG_STREAM_CACHE
3074 int old_cache_fill = stream_cache_size > 0 ?
3075 cache_fill_status(mpctx->stream) : 0;
3076 #endif
3077 if (!opts->quiet) {
3078 if (opts->term_osd && !mpctx->sh_video) {
3079 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
3080 update_osd_msg(mpctx);
3081 } else
3082 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
3083 mp_gtext(" ===== PAUSE ====="));
3084 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
3087 while ((cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
3088 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
3089 if (cmd) {
3090 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3091 run_command(mpctx, cmd);
3092 mp_cmd_free(cmd);
3093 continue;
3095 if (mpctx->sh_video && mpctx->video_out)
3096 vo_check_events(mpctx->video_out);
3097 #ifdef CONFIG_MENU
3098 if (vf_menu)
3099 vf_menu_pause_update(vf_menu);
3100 #endif
3101 usec_sleep(20000);
3102 update_osd_msg(mpctx);
3103 int hack = vo_osd_changed(0);
3104 vo_osd_changed(hack);
3105 if (hack)
3106 break;
3107 #ifdef CONFIG_STREAM_CACHE
3108 if (!opts->quiet && stream_cache_size > 0) {
3109 int new_cache_fill = cache_fill_status(mpctx->stream);
3110 if (new_cache_fill != old_cache_fill) {
3111 if (opts->term_osd && !mpctx->sh_video) {
3112 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
3113 mp_gtext(" ===== PAUSE ====="),
3114 new_cache_fill);
3115 update_osd_msg(mpctx);
3116 } else
3117 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
3118 mp_gtext(" ===== PAUSE ====="),
3119 new_cache_fill);
3120 old_cache_fill = new_cache_fill;
3123 #endif
3128 // Find the right mute status and record position for new file position
3129 static void edl_seek_reset(MPContext *mpctx)
3131 mpctx->edl_muted = 0;
3132 next_edl_record = edl_records;
3134 while (next_edl_record) {
3135 if (next_edl_record->start_sec >= get_current_time(mpctx))
3136 break;
3138 if (next_edl_record->action == EDL_MUTE)
3139 mpctx->edl_muted = !mpctx->edl_muted;
3140 next_edl_record = next_edl_record->next;
3142 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3143 mixer_mute(&mpctx->mixer);
3147 // Execute EDL command for the current position if one exists
3148 static void edl_update(MPContext *mpctx)
3150 if (!next_edl_record)
3151 return;
3153 if (!mpctx->sh_video) {
3154 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
3155 "Cannot use EDL without video, disabling.\n");
3156 free_edl(edl_records);
3157 next_edl_record = NULL;
3158 edl_records = NULL;
3159 return;
3162 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3163 if (next_edl_record->action == EDL_SKIP) {
3164 mpctx->osd_function = OSD_FFW;
3165 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3166 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3167 "[%f], length [%f]\n", next_edl_record->start_sec,
3168 next_edl_record->stop_sec, next_edl_record->length_sec);
3169 } else if (next_edl_record->action == EDL_MUTE) {
3170 mpctx->edl_muted = !mpctx->edl_muted;
3171 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3172 mixer_mute(&mpctx->mixer);
3173 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3174 next_edl_record->start_sec);
3176 next_edl_record = next_edl_record->next;
3180 static void reinit_decoders(struct MPContext *mpctx)
3182 reinit_video_chain(mpctx);
3183 reinit_audio_chain(mpctx);
3184 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3187 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3189 if (mpctx->sh_video) {
3190 current_module = "seek_video_reset";
3191 resync_video_stream(mpctx->sh_video);
3192 mpctx->sh_video->timer = 0;
3193 vo_seek_reset(mpctx->video_out);
3194 mpctx->sh_video->timer = 0;
3195 mpctx->sh_video->num_buffered_pts = 0;
3196 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3197 mpctx->delay = 0;
3198 mpctx->time_frame = 0;
3199 mpctx->restart_playback = true;
3200 // Not all demuxers set d_video->pts during seek, so this value
3201 // (which is used by at least vobsub and edl code below) may
3202 // be completely wrong (probably 0).
3203 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3204 mpctx->video_pts = mpctx->sh_video->pts;
3205 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3206 true);
3207 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3210 if (mpctx->sh_audio) {
3211 current_module = "seek_audio_reset";
3212 resync_audio_stream(mpctx->sh_audio);
3213 if (reset_ao)
3214 ao_reset(mpctx->ao);
3215 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3216 mpctx->sh_audio->a_buffer_len = 0;
3217 if (!mpctx->sh_video)
3218 update_subtitles(mpctx, mpctx->sh_audio->pts,
3219 mpctx->video_offset, true);
3222 if (vo_vobsub && mpctx->sh_video) {
3223 current_module = "seek_vobsub_reset";
3224 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3227 edl_seek_reset(mpctx);
3229 mpctx->hrseek_active = false;
3230 mpctx->hrseek_framedrop = false;
3231 mpctx->total_avsync_change = 0;
3232 audio_time_usage = 0;
3233 video_time_usage = 0;
3234 vout_time_usage = 0;
3235 drop_frame_cnt = 0;
3237 current_module = NULL;
3240 static bool timeline_set_part(struct MPContext *mpctx, int i)
3242 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3243 struct timeline_part *n = mpctx->timeline + i;
3244 mpctx->timeline_part = i;
3245 mpctx->video_offset = n->start - n->source_start;
3246 if (n->source == p->source)
3247 return false;
3248 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3249 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3250 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3251 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3252 mpctx->stop_play = orig_stop_play;
3253 mpctx->demuxer = n->source->demuxer;
3254 mpctx->d_video = mpctx->demuxer->video;
3255 mpctx->d_audio = mpctx->demuxer->audio;
3256 mpctx->d_sub = mpctx->demuxer->sub;
3257 mpctx->sh_video = mpctx->d_video->sh;
3258 mpctx->sh_audio = mpctx->d_audio->sh;
3259 return true;
3262 // Given pts, switch playback to the corresponding part.
3263 // Return offset within that part.
3264 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3265 bool *need_reset)
3267 if (pts < 0)
3268 pts = 0;
3269 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3270 struct timeline_part *p = mpctx->timeline + i;
3271 if (pts < (p + 1)->start) {
3272 *need_reset = timeline_set_part(mpctx, i);
3273 return pts - p->start + p->source_start;
3276 return -1;
3280 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3281 static int seek(MPContext *mpctx, struct seek_params seek,
3282 bool timeline_fallthrough)
3284 struct MPOpts *opts = &mpctx->opts;
3286 current_module = "seek";
3287 if (mpctx->stop_play == AT_END_OF_FILE)
3288 mpctx->stop_play = KEEP_PLAYING;
3289 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3290 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3291 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3292 || opts->hr_seek > 0 || seek.exact > 0;
3293 if (seek.type == MPSEEK_FACTOR
3294 || seek.type == MPSEEK_ABSOLUTE
3295 && seek.amount < mpctx->last_chapter_pts
3296 || seek.amount < 0)
3297 mpctx->last_chapter_seek = -2;
3298 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3299 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3300 seek.type = MPSEEK_ABSOLUTE;
3302 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3303 && seek.type == MPSEEK_RELATIVE) {
3304 seek.type = MPSEEK_ABSOLUTE;
3305 seek.direction = seek.amount > 0 ? 1 : -1;
3306 seek.amount += get_current_time(mpctx);
3309 /* At least the liba52 decoder wants to read from the input stream
3310 * during initialization, so reinit must be done after the demux_seek()
3311 * call that clears possible stream EOF. */
3312 bool need_reset = false;
3313 double demuxer_amount = seek.amount;
3314 if (mpctx->timeline) {
3315 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3316 &need_reset);
3317 if (demuxer_amount == -1) {
3318 mpctx->stop_play = AT_END_OF_FILE;
3319 // Clear audio from current position
3320 if (mpctx->sh_audio) {
3321 ao_reset(mpctx->ao);
3322 mpctx->sh_audio->a_buffer_len = 0;
3324 return -1;
3327 int demuxer_style = 0;
3328 switch (seek.type) {
3329 case MPSEEK_FACTOR:
3330 demuxer_style |= SEEK_FACTOR; // fallthrough
3331 case MPSEEK_ABSOLUTE:
3332 demuxer_style |= SEEK_ABSOLUTE;
3334 if (hr_seek || seek.direction < 0)
3335 demuxer_style |= SEEK_BACKWARD;
3336 else if (seek.direction > 0)
3337 demuxer_style |= SEEK_FORWARD;
3339 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3340 demuxer_style);
3341 if (need_reset)
3342 reinit_decoders(mpctx);
3343 if (seekresult == 0)
3344 return -1;
3346 seek_reset(mpctx, !timeline_fallthrough);
3348 /* Use the target time as "current position" for further relative
3349 * seeks etc until a new video frame has been decoded */
3350 if (seek.type == MPSEEK_ABSOLUTE) {
3351 mpctx->video_pts = seek.amount;
3352 mpctx->last_seek_pts = seek.amount;
3353 } else
3354 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3356 if (hr_seek) {
3357 mpctx->hrseek_active = true;
3358 mpctx->hrseek_framedrop = true;
3359 mpctx->hrseek_pts = seek.amount;
3362 mpctx->start_timestamp = GetTimerMS();
3364 return 0;
3367 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3368 int exact)
3370 struct seek_params *seek = &mpctx->seek;
3371 switch (type) {
3372 case MPSEEK_RELATIVE:
3373 if (seek->type == MPSEEK_FACTOR)
3374 return; // Well... not common enough to bother doing better
3375 seek->amount += amount;
3376 seek->exact = FFMAX(seek->exact, exact);
3377 if (seek->type == MPSEEK_NONE)
3378 seek->exact = exact;
3379 if (seek->type == MPSEEK_ABSOLUTE)
3380 return;
3381 if (seek->amount == 0) {
3382 *seek = (struct seek_params){ 0 };
3383 return;
3385 seek->type = MPSEEK_RELATIVE;
3386 return;
3387 case MPSEEK_ABSOLUTE:
3388 case MPSEEK_FACTOR:
3389 *seek = (struct seek_params) {
3390 .type = type,
3391 .amount = amount,
3392 .exact = exact,
3394 return;
3395 case MPSEEK_NONE:
3396 *seek = (struct seek_params){ 0 };
3397 return;
3399 abort();
3403 double get_time_length(struct MPContext *mpctx)
3405 if (mpctx->timeline)
3406 return mpctx->timeline[mpctx->num_timeline_parts].start;
3408 struct demuxer *demuxer = mpctx->demuxer;
3409 double get_time_ans;
3410 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3411 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3412 (void *) &get_time_ans) > 0)
3413 return get_time_ans;
3415 struct sh_video *sh_video = mpctx->d_video->sh;
3416 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3417 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3418 return (double) (demuxer->movi_end - demuxer->movi_start) /
3419 (sh_video->i_bps + sh_audio->i_bps);
3420 if (sh_video && sh_video->i_bps)
3421 return (double) (demuxer->movi_end - demuxer->movi_start) /
3422 sh_video->i_bps;
3423 if (sh_audio && sh_audio->i_bps)
3424 return (double) (demuxer->movi_end - demuxer->movi_start) /
3425 sh_audio->i_bps;
3426 return 0;
3429 /* If there are timestamps from stream level then use those (for example
3430 * DVDs can have consistent times there while the MPEG-level timestamps
3431 * reset). */
3432 double get_current_time(struct MPContext *mpctx)
3434 struct demuxer *demuxer = mpctx->demuxer;
3435 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3436 return demuxer->stream_pts;
3437 struct sh_video *sh_video = demuxer->video->sh;
3438 if (sh_video)
3439 return mpctx->video_pts;
3440 double apts = playing_audio_pts(mpctx);
3441 if (apts != MP_NOPTS_VALUE)
3442 return apts;
3443 return mpctx->last_seek_pts;
3446 int get_percent_pos(struct MPContext *mpctx)
3448 struct demuxer *demuxer = mpctx->demuxer;
3449 int ans = 0;
3450 if (mpctx->timeline)
3451 ans = get_current_time(mpctx) * 100 /
3452 mpctx->timeline[mpctx->num_timeline_parts].start;
3453 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3455 else {
3456 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3457 off_t pos = demuxer->filepos > 0 ?
3458 demuxer->filepos : stream_tell(demuxer->stream);
3459 if (len > 0)
3460 ans = (pos - demuxer->movi_start) / len;
3461 else
3462 ans = 0;
3464 if (ans < 0)
3465 ans = 0;
3466 if (ans > 100)
3467 ans = 100;
3468 return ans;
3471 // -2 is no chapters, -1 is before first chapter
3472 int get_current_chapter(struct MPContext *mpctx)
3474 double current_pts = get_current_time(mpctx);
3475 if (!mpctx->chapters)
3476 return FFMAX(mpctx->last_chapter_seek,
3477 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3479 int i;
3480 for (i = 1; i < mpctx->num_chapters; i++)
3481 if (current_pts < mpctx->chapters[i].start)
3482 break;
3483 return FFMAX(mpctx->last_chapter_seek, i - 1);
3486 // currently returns a string allocated with malloc, not talloc
3487 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3489 if (!mpctx->chapters)
3490 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3491 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3494 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3495 char **chapter_name)
3497 mpctx->last_chapter_seek = -2;
3498 if (!mpctx->chapters) {
3499 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3500 chapter_name);
3501 if (res >= 0) {
3502 if (*seek_pts == -1)
3503 seek_reset(mpctx, true);
3504 else {
3505 mpctx->last_chapter_seek = res;
3506 mpctx->last_chapter_pts = *seek_pts;
3509 return res;
3512 if (chapter >= mpctx->num_chapters)
3513 return -1;
3514 if (chapter < 0)
3515 chapter = 0;
3516 *seek_pts = mpctx->chapters[chapter].start;
3517 mpctx->last_chapter_seek = chapter;
3518 mpctx->last_chapter_pts = *seek_pts;
3519 if (chapter_name)
3520 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3521 return chapter;
3525 static void run_playloop(struct MPContext *mpctx)
3527 struct MPOpts *opts = &mpctx->opts;
3528 float aq_sleep_time = 0;
3529 bool full_audio_buffers = false;
3531 if (opts->chapterrange[1] > 0) {
3532 int cur_chapter = get_current_chapter(mpctx);
3533 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3534 mpctx->stop_play = PT_NEXT_ENTRY;
3537 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3538 mpctx->sh_audio = mpctx->d_audio->sh;
3539 mpctx->sh_audio->ds = mpctx->d_audio;
3540 reinit_audio_chain(mpctx);
3543 /*========================== PLAY AUDIO ============================*/
3545 if (!mpctx->sh_video)
3546 mpctx->restart_playback = false;
3548 if (mpctx->sh_audio && !mpctx->restart_playback) {
3549 int status = fill_audio_out_buffers(mpctx);
3550 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3551 if (status == -2)
3552 // at eof, all audio at least written to ao
3553 if (!mpctx->sh_video)
3554 mpctx->stop_play = AT_END_OF_FILE;
3558 if (!mpctx->sh_video) {
3559 if (mpctx->step_frames) {
3560 mpctx->step_frames = 0;
3561 pause_player(mpctx);
3563 // handle audio-only case:
3564 double a_pos = 0, a_buf = 0;
3565 // sh_audio can be NULL due to video stream switching
3566 // TODO: handle this better
3567 if (mpctx->sh_audio) {
3568 a_buf = ao_get_delay(mpctx->ao);
3569 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3570 a_buf;
3573 print_status(mpctx, a_pos, false);
3575 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3576 update_osd_msg(mpctx);
3577 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3578 mpctx->stop_play = AT_END_OF_FILE;
3579 else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3580 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3581 && mpctx->sh_audio) {
3582 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3583 if (!opts->gapless_audio && p->source != (p + 1)->source
3584 && a_buf > 0.05) {
3585 mpctx->stop_play = KEEP_PLAYING;
3586 mp_input_get_cmd(mpctx->input, (a_buf - .05) * 1000, true);
3587 } else {
3588 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3589 .amount = (p + 1)->start },
3590 true);
3592 } else if (!mpctx->stop_play) {
3593 int sleep_time = 100;
3594 if (mpctx->sh_audio) {
3595 if (mpctx->ao->untimed)
3596 sleep_time = 0;
3597 else if (full_audio_buffers)
3598 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3599 else
3600 sleep_time = 20;
3601 sleep_time = FFMIN(sleep_time, 100);
3603 mp_input_get_cmd(mpctx->input, sleep_time, true);
3605 } else {
3607 /*========================== PLAY VIDEO ============================*/
3609 vo_pts = mpctx->sh_video->timer * 90000.0;
3610 vo_fps = mpctx->sh_video->fps;
3612 bool blit_frame = mpctx->video_out->frame_loaded;
3613 if (!blit_frame || mpctx->hrseek_active) {
3614 double frame_time = update_video(mpctx);
3615 blit_frame = mpctx->video_out->frame_loaded;
3616 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3617 if (mpctx->sh_video->vf_initialized < 0) {
3618 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3619 "\nFATAL: Could not initialize video filters (-vf) "
3620 "or video output (-vo).\n");
3621 mpctx->stop_play = PT_NEXT_ENTRY;
3622 return;
3624 if (frame_time < 0)
3625 mpctx->stop_play = AT_END_OF_FILE;
3626 else if (!mpctx->restart_playback) {
3627 mpctx->time_frame += frame_time / opts->playback_speed;
3628 adjust_sync(mpctx, frame_time);
3631 if (mpctx->timeline) {
3632 struct timeline_part *next =
3633 mpctx->timeline + mpctx->timeline_part + 1;
3634 if (mpctx->sh_video->pts >= next->start
3635 || mpctx->stop_play == AT_END_OF_FILE
3636 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3637 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3638 .amount = next->start },
3639 true);
3640 return;
3644 // ==========================================================================
3646 current_module = "vo_check_events";
3647 vo_check_events(mpctx->video_out);
3649 #ifdef CONFIG_X11
3650 if (stop_xscreensaver) {
3651 current_module = "stop_xscreensaver";
3652 xscreensaver_heartbeat(mpctx->x11_state);
3654 #endif
3655 if (heartbeat_cmd) {
3656 static unsigned last_heartbeat;
3657 unsigned now = GetTimerMS();
3658 if (now - last_heartbeat > 30000) {
3659 last_heartbeat = now;
3660 system(heartbeat_cmd);
3664 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3665 &mpctx->time_frame,
3666 full_audio_buffers,
3667 &aq_sleep_time);
3669 //====================== FLIP PAGE (VIDEO BLT): =========================
3671 current_module = "flip_page";
3672 if (!frame_time_remaining && blit_frame) {
3673 struct sh_video *sh_video = mpctx->sh_video;
3674 mpctx->video_pts = sh_video->pts;
3675 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3676 update_teletext(sh_video, mpctx->demuxer, 0);
3677 update_osd_msg(mpctx);
3678 struct vf_instance *vf = sh_video->vfilter;
3679 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3680 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3681 vo_osd_changed(0);
3683 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3684 aq_sleep_time += mpctx->time_frame;
3685 // flag 256 means: libvo driver does its timing (dvb card)
3686 if (mpctx->time_frame > 0.001
3687 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3688 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3689 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3691 unsigned int t2 = GetTimer();
3692 /* Playing with playback speed it's possible to get pathological
3693 * cases with mpctx->time_frame negative enough to cause an
3694 * overflow in pts_us calculation, thus the FFMAX. */
3695 double time_frame = FFMAX(mpctx->time_frame, -1);
3696 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3697 int duration = -1;
3698 double pts2 = mpctx->video_out->next_pts2;
3699 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3700 && !mpctx->restart_playback) {
3701 // expected A/V sync correction is ignored
3702 double diff = (pts2 - mpctx->video_pts);
3703 diff /= opts->playback_speed;
3704 if (mpctx->time_frame < 0)
3705 diff += mpctx->time_frame;
3706 if (diff < 0)
3707 diff = 0;
3708 if (diff > 10)
3709 diff = 10;
3710 duration = diff * 1e6;
3712 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3714 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3715 vout_time_usage += mpctx->last_vo_flip_duration;
3716 if (mpctx->video_out->driver->flip_page_timed) {
3717 // No need to adjust sync based on flip speed
3718 mpctx->last_vo_flip_duration = 0;
3719 // For print_status - VO call finishing early is OK for sync
3720 mpctx->time_frame -= get_relative_time(mpctx);
3722 if (mpctx->restart_playback) {
3723 mpctx->syncing_audio = true;
3724 if (mpctx->sh_audio)
3725 fill_audio_out_buffers(mpctx);
3726 mpctx->restart_playback = false;
3727 mpctx->time_frame = 0;
3728 get_relative_time(mpctx);
3730 print_status(mpctx, MP_NOPTS_VALUE, true);
3731 } else
3732 print_status(mpctx, MP_NOPTS_VALUE, false);
3734 //============================ Auto QUALITY ============================
3736 /*Output quality adjustments:*/
3737 if (opts->auto_quality > 0) {
3738 current_module = "autoq";
3739 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3740 ++output_quality;
3741 else if (output_quality > 1 && aq_sleep_time < 0)
3742 --output_quality;
3743 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3744 output_quality = 0;
3745 set_video_quality(mpctx->sh_video, output_quality);
3748 if (!frame_time_remaining && blit_frame) {
3749 if (play_n_frames >= 0) {
3750 --play_n_frames;
3751 if (play_n_frames <= 0)
3752 mpctx->stop_play = PT_NEXT_ENTRY;
3754 if (mpctx->step_frames > 0) {
3755 mpctx->step_frames--;
3756 if (mpctx->step_frames == 0)
3757 pause_player(mpctx);
3761 // FIXME: add size based support for -endpos
3762 if (end_at.type == END_AT_TIME &&
3763 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3764 mpctx->stop_play = PT_NEXT_ENTRY;
3766 } // end if(mpctx->sh_video)
3768 #ifdef CONFIG_DVDNAV
3769 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3770 nav_highlight_t hl;
3771 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3772 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3773 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3774 vo_osd_changed(OSDTYPE_DVDNAV);
3775 } else {
3776 osd_set_nav_box(0, 0, 0, 0);
3777 vo_osd_changed(OSDTYPE_DVDNAV);
3778 vo_osd_changed(OSDTYPE_SPU);
3781 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3782 double ar = -1.0;
3783 if (mpctx->sh_video &&
3784 stream_control(mpctx->demuxer->stream,
3785 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3786 != STREAM_UNSUPPORTED)
3787 mpctx->sh_video->stream_aspect = ar;
3790 #endif
3792 //================= Keyboard events, SEEKing ====================
3794 current_module = "key_events";
3796 while (1) {
3797 mp_cmd_t *cmd;
3798 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3799 /* Allow running consecutive seek commands to combine them,
3800 * but execute the seek before running other commands.
3801 * If the user seeks continuously (keeps arrow key down)
3802 * try to finish showing a frame from one location before doing
3803 * another seek (which could lead to unchanging display). */
3804 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3805 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3806 && GetTimerMS() - mpctx->start_timestamp < 300)
3807 break;
3808 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3809 run_command(mpctx, cmd);
3810 mp_cmd_free(cmd);
3811 if (mpctx->stop_play)
3812 break;
3814 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3815 || mpctx->restart_playback)
3816 break;
3817 if (mpctx->sh_video) {
3818 update_osd_msg(mpctx);
3819 int hack = vo_osd_changed(0);
3820 vo_osd_changed(hack);
3821 if (hack) {
3822 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3823 add_step_frame(mpctx);
3824 break;
3825 } else
3826 vo_osd_changed(0);
3829 pause_loop(mpctx);
3832 // handle -sstep
3833 if (step_sec > 0 && !mpctx->paused) {
3834 mpctx->osd_function = OSD_FFW;
3835 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3838 edl_update(mpctx);
3840 /* Looping. */
3841 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3842 mpctx->stop_play == PT_NEXT_ENTRY)) {
3843 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3845 if (opts->loop_times > 1)
3846 opts->loop_times--;
3847 else if (opts->loop_times == 1)
3848 opts->loop_times = -1;
3849 play_n_frames = play_n_frames_mf;
3850 mpctx->stop_play = 0;
3851 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3854 if (mpctx->seek.type) {
3855 seek(mpctx, mpctx->seek, false);
3856 mpctx->seek = (struct seek_params){ 0 };
3861 static int read_keys(void *ctx, int fd)
3863 getch2(ctx);
3864 return MP_INPUT_NOTHING;
3867 static bool attachment_is_font(struct demux_attachment *att)
3869 if (!att->name || !att->type || !att->data || !att->data_size)
3870 return false;
3871 // match against MIME types
3872 if (strcmp(att->type, "application/x-truetype-font") == 0
3873 || strcmp(att->type, "application/x-font") == 0)
3874 return true;
3875 // fallback: match against file extension
3876 if (strlen(att->name) > 4) {
3877 char *ext = att->name + strlen(att->name) - 4;
3878 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3879 || strcasecmp(ext, ".otf") == 0)
3880 return true;
3882 return false;
3885 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3887 if (audio_id == -1)
3888 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3889 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3890 demuxer_switch_audio(demuxer, audio_id);
3891 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3892 demuxer->audio->id = -2;
3893 demuxer->audio->sh = NULL;
3895 return demuxer->audio->id;
3898 static void print_version(const char *name)
3900 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3902 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3903 GetCpuCaps(&gCpuCaps);
3904 #if ARCH_X86
3905 mp_msg(MSGT_CPLAYER, MSGL_V,
3906 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3907 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3908 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3909 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3910 #if CONFIG_RUNTIME_CPUDETECT
3911 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3912 #else
3913 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3914 if (HAVE_MMX)
3915 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3916 if (HAVE_MMX2)
3917 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3918 if (HAVE_AMD3DNOW)
3919 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3920 if (HAVE_AMD3DNOWEXT)
3921 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3922 if (HAVE_SSE)
3923 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3924 if (HAVE_SSE2)
3925 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3926 if (HAVE_SSSE3)
3927 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3928 if (HAVE_CMOV)
3929 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3930 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3931 #endif /* CONFIG_RUNTIME_CPUDETECT */
3932 #endif /* ARCH_X86 */
3935 #ifdef PTW32_STATIC_LIB
3936 static void detach_ptw32(void)
3938 pthread_win32_thread_detach_np();
3939 pthread_win32_process_detach_np();
3941 #endif
3943 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3944 * file for some tools to link against. */
3945 #ifndef DISABLE_MAIN
3946 int main(int argc, char *argv[])
3948 #ifdef PTW32_STATIC_LIB
3949 pthread_win32_process_attach_np();
3950 pthread_win32_thread_attach_np();
3951 atexit(detach_ptw32);
3952 #endif
3953 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3954 || !strcmp(argv[1], "--leak-report")))
3955 talloc_enable_leak_report();
3957 char *mem_ptr;
3959 // movie info:
3961 /* Flag indicating whether MPlayer should exit without playing anything. */
3962 int opt_exit = 0;
3963 int i;
3965 struct MPContext *mpctx = &(struct MPContext){
3966 .osd_function = OSD_PLAY,
3967 .begin_skip = MP_NOPTS_VALUE,
3968 .play_tree_step = 1,
3969 .global_sub_pos = -1,
3970 .set_of_sub_pos = -1,
3971 .file_format = DEMUXER_TYPE_UNKNOWN,
3972 .last_dvb_step = 1,
3975 InitTimer();
3976 srand(GetTimerMS());
3978 mp_msg_init();
3979 init_libav();
3981 #ifdef CONFIG_X11
3982 mpctx->x11_state = vo_x11_init_state();
3983 #endif
3984 struct MPOpts *opts = &mpctx->opts;
3985 set_default_mplayer_options(opts);
3986 // Create the config context and register the options
3987 mpctx->mconfig = m_config_new(opts, cfg_include);
3988 m_config_register_options(mpctx->mconfig, mplayer_opts);
3989 m_config_register_options(mpctx->mconfig, common_opts);
3990 mp_input_register_options(mpctx->mconfig);
3992 // Preparse the command line
3993 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
3995 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3996 set_path_env();
3997 #endif
3999 #ifdef CONFIG_TV
4000 stream_tv_defaults.immediate = 1;
4001 #endif
4003 parse_cfgfiles(mpctx, mpctx->mconfig);
4005 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
4006 if (mpctx->playtree == NULL)
4007 opt_exit = 1;
4008 else {
4009 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
4010 if (mpctx->playtree) {
4011 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4012 mpctx->mconfig);
4013 if (mpctx->playtree_iter) {
4014 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4015 PLAY_TREE_ITER_ENTRY) {
4016 play_tree_iter_free(mpctx->playtree_iter);
4017 mpctx->playtree_iter = NULL;
4019 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
4025 print_version("MPlayer2");
4027 #if defined(__MINGW32__) || defined(__CYGWIN__)
4029 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
4030 BOOL WINAPI (*setDEP)(DWORD) = NULL;
4031 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
4032 if (kernel32) {
4033 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
4034 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
4036 if (setDEP)
4037 setDEP(3);
4038 if (setDllDir)
4039 setDllDir("");
4041 // stop Windows from showing all kinds of annoying error dialogs
4042 SetErrorMode(0x8003);
4043 // request 1ms timer resolution
4044 timeBeginPeriod(1);
4045 #endif
4047 #ifdef CONFIG_PRIORITY
4048 set_priority();
4049 #endif
4051 if (opts->video_driver_list &&
4052 strcmp(opts->video_driver_list[0], "help") == 0) {
4053 list_video_out();
4054 opt_exit = 1;
4057 if (opts->audio_driver_list &&
4058 strcmp(opts->audio_driver_list[0], "help") == 0) {
4059 list_audio_out();
4060 opt_exit = 1;
4063 /* Check codecs.conf. */
4064 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4065 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4066 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4067 if (!parse_codec_cfg(NULL))
4068 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4069 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4070 "Using built-in default codecs.conf.\n");
4073 free(mem_ptr); // release the buffer created by get_path()
4076 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4077 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4078 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4079 list_codecs(1);
4080 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4081 opt_exit = 1;
4083 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4084 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4085 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4086 list_codecs(0);
4087 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4088 opt_exit = 1;
4090 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4091 vfm_help();
4092 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4093 opt_exit = 1;
4095 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4096 afm_help();
4097 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4098 opt_exit = 1;
4100 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4101 af_help();
4102 printf("\n");
4103 opt_exit = 1;
4105 #ifdef CONFIG_X11
4106 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4107 fstype_help();
4108 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4109 opt_exit = 1;
4111 #endif
4112 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4113 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4114 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4115 demuxer_help();
4116 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4117 opt_exit = 1;
4119 if (opts->list_properties) {
4120 property_print_help();
4121 opt_exit = 1;
4124 if (opt_exit)
4125 exit_player(mpctx, EXIT_NONE);
4127 if (!mpctx->filename && !opts->player_idle_mode) {
4128 // no file/vcd/dvd -> show HELP:
4129 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4130 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4133 /* Display what configure line was used */
4134 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4136 // Many users forget to include command line in bugreports...
4137 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4138 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4139 for (i = 1; i < argc; i++)
4140 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4141 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4144 //------ load global data first ------
4146 mpctx->osd = osd_create();
4148 // check font
4149 #ifdef CONFIG_FREETYPE
4150 init_freetype();
4151 #endif
4152 #ifdef CONFIG_FONTCONFIG
4153 if (font_fontconfig <= 0) {
4154 #endif
4155 #ifdef CONFIG_BITMAP_FONT
4156 if (font_name) {
4157 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4158 if (!vo_font)
4159 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4160 filename_recode(font_name));
4161 } else {
4162 // try default:
4163 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4164 font_factor, verbose > 1);
4165 free(mem_ptr); // release the buffer created by get_path()
4166 if (!vo_font)
4167 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4168 font_factor, verbose > 1);
4170 if (sub_font_name)
4171 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4172 verbose > 1);
4173 else
4174 mpctx->osd->sub_font = vo_font;
4175 #endif
4176 #ifdef CONFIG_FONTCONFIG
4178 #endif
4180 #ifdef CONFIG_ASS
4181 mpctx->ass_library = mp_ass_init();
4182 mpctx->osd->ass_library = mpctx->ass_library;
4183 #endif
4185 #ifdef HAVE_RTC
4186 if (opts->rtc) {
4187 char *rtc_device = opts->rtc_device;
4188 // seteuid(0); /* Can't hurt to try to get root here */
4189 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4190 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4191 "(it should be readable by the user.)\n",
4192 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4193 else {
4194 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4196 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4197 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4198 "ioctl (rtc_irqp_set %lu): %s\n",
4199 irqp, strerror(errno));
4200 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4201 close(rtc_fd);
4202 rtc_fd = -1;
4203 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4204 /* variable only by the root */
4205 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4206 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4207 close(rtc_fd);
4208 rtc_fd = -1;
4209 } else
4210 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4211 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4214 if (rtc_fd < 0)
4215 #endif /* HAVE_RTC */
4216 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4217 opts->softsleep ? "software" : timer_name);
4219 #ifdef HAVE_TERMCAP
4220 load_termcap(NULL); // load key-codes
4221 #endif
4223 // ========== Init keyboard FIFO (connection to libvo) ============
4225 // Init input system
4226 current_module = "init_input";
4227 mpctx->input = mp_input_init(&opts->input);
4228 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4229 if (slave_mode)
4230 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4231 else if (opts->consolecontrols)
4232 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4233 // Set the libstream interrupt callback
4234 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4236 #ifdef CONFIG_MENU
4237 if (use_menu) {
4238 if (menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4239 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4240 else {
4241 menu_cfg = get_path("menu.conf");
4242 if (menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4243 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4244 else {
4245 if (menu_init(mpctx, mpctx->mconfig, mpctx->input,
4246 MPLAYER_CONFDIR "/menu.conf"))
4247 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR "/menu.conf");
4248 else {
4249 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4250 use_menu = 0;
4255 #endif
4257 current_module = NULL;
4259 /// Catch signals
4260 #ifndef __MINGW32__
4261 signal(SIGCHLD, child_sighandler);
4262 #endif
4264 #ifdef CONFIG_CRASH_DEBUG
4265 prog_path = argv[0];
4266 #endif
4267 //========= Catch terminate signals: ================
4268 // terminate requests:
4269 signal(SIGTERM, exit_sighandler); // kill
4270 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4272 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4274 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4275 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4276 #ifdef CONFIG_SIGHANDLER
4277 // fatal errors:
4278 signal(SIGBUS, exit_sighandler); // bus error
4279 signal(SIGSEGV, exit_sighandler); // segfault
4280 signal(SIGILL, exit_sighandler); // illegal instruction
4281 signal(SIGFPE, exit_sighandler); // floating point exc.
4282 signal(SIGABRT, exit_sighandler); // abort()
4283 #ifdef CONFIG_CRASH_DEBUG
4284 if (crash_debug)
4285 signal(SIGTRAP, exit_sighandler);
4286 #endif
4287 #endif
4289 // ***************** Now, let's see the per-file stuff ******************
4291 play_next_file:
4293 // init global sub numbers
4294 mpctx->global_sub_size = 0;
4295 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4297 if (mpctx->filename) {
4298 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4299 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4300 load_per_file_config(mpctx->mconfig, mpctx->filename);
4303 if (opts->video_driver_list)
4304 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4305 opts->video_driver_list[0]);
4306 if (opts->audio_driver_list)
4307 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4308 opts->audio_driver_list[0]);
4310 // We must enable getch2 here to be able to interrupt network connection
4311 // or cache filling
4312 if (opts->consolecontrols && !slave_mode) {
4313 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4314 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4315 "WARNING: getch2_init called twice!\n");
4316 else
4317 getch2_enable(); // prepare stdin for hotkeys...
4318 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4319 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4322 // ================= GUI idle loop (STOP state) =========================
4323 while (opts->player_idle_mode && !mpctx->filename) {
4324 play_tree_t *entry = NULL;
4325 mp_cmd_t *cmd;
4326 if (mpctx->video_out && mpctx->video_out->config_ok)
4327 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4328 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4329 if (mpctx->video_out)
4330 vo_check_events(mpctx->video_out);
4331 usec_sleep(20000);
4333 switch (cmd->id) {
4334 case MP_CMD_LOADFILE:
4335 // prepare a tree entry with the new filename
4336 entry = play_tree_new();
4337 play_tree_add_file(entry, cmd->args[0].v.s);
4338 // The entry is added to the main playtree after the switch().
4339 break;
4340 case MP_CMD_LOADLIST:
4341 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4342 break;
4343 case MP_CMD_QUIT:
4344 exit_player_with_rc(mpctx, EXIT_QUIT,
4345 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4346 break;
4347 case MP_CMD_VO_FULLSCREEN:
4348 case MP_CMD_GET_PROPERTY:
4349 case MP_CMD_SET_PROPERTY:
4350 case MP_CMD_STEP_PROPERTY:
4351 run_command(mpctx, cmd);
4352 break;
4355 mp_cmd_free(cmd);
4357 if (entry) { // user entered a command that gave a valid entry
4358 if (mpctx->playtree)
4359 // the playtree is always a node with one child. let's clear it
4360 play_tree_free_list(mpctx->playtree->child, 1);
4361 else
4362 // .. or make a brand new playtree
4363 mpctx->playtree = play_tree_new();
4365 if (!mpctx->playtree)
4366 continue; // couldn't make playtree! wait for next command
4368 play_tree_set_child(mpctx->playtree, entry);
4370 /* Make iterator start at the top the of tree. */
4371 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4372 mpctx->mconfig);
4373 if (!mpctx->playtree_iter)
4374 continue;
4376 // find the first real item in the tree
4377 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4378 PLAY_TREE_ITER_ENTRY) {
4379 // no items!
4380 play_tree_iter_free(mpctx->playtree_iter);
4381 mpctx->playtree_iter = NULL;
4382 continue; // wait for next command
4384 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4387 //---------------------------------------------------------------------------
4388 #ifdef CONFIG_ASS
4389 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4390 #endif
4391 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4392 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4394 if (mpctx->filename) {
4395 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4396 filename_recode(mpctx->filename));
4397 if (use_filename_title && opts->vo_wintitle == NULL)
4398 opts->vo_wintitle = talloc_strdup(NULL,
4399 mp_basename(mpctx->filename));
4402 if (edl_filename) {
4403 if (edl_records)
4404 free_edl(edl_records);
4405 next_edl_record = edl_records = edl_parse_file();
4407 if (edl_output_filename) {
4408 if (edl_fd)
4409 fclose(edl_fd);
4410 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4411 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4412 "Can't open EDL file [%s] for writing.\n",
4413 filename_recode(edl_output_filename));
4417 //==================== Open VOB-Sub ============================
4419 current_module = "vobsub";
4420 if (opts->vobsub_name) {
4421 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4422 if (vo_vobsub == NULL)
4423 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4424 filename_recode(opts->vobsub_name));
4425 } else if (opts->sub_auto && mpctx->filename) {
4426 char **vob = find_vob_subtitles(opts, mpctx->filename);
4427 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4428 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4429 if (vo_vobsub)
4430 break;
4432 talloc_free(vob);
4434 if (vo_vobsub) {
4435 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4436 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4437 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4438 mpctx);
4440 // setup global sub numbering
4441 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4442 vobsub_get_indexes_count(vo_vobsub);
4445 //============ Open & Sync STREAM --- fork cache2 ====================
4447 mpctx->stream = NULL;
4448 mpctx->demuxer = NULL;
4449 mpctx->d_audio = NULL;
4450 mpctx->d_video = NULL;
4451 mpctx->d_sub = NULL;
4452 mpctx->sh_audio = NULL;
4453 mpctx->sh_video = NULL;
4455 current_module = "open_stream";
4456 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4457 if (!mpctx->stream) { // error...
4458 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4459 goto goto_next_file;
4461 mpctx->initialized_flags |= INITIALIZED_STREAM;
4463 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4464 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4465 "playlist support will not be used automatically.\n"
4466 "MPlayer's playlist code is unsafe and should only be used with "
4467 "trusted sources.\nPlayback will probably fail.\n\n");
4468 #if 0
4469 play_tree_t *entry;
4470 // Handle playlist
4471 current_module = "handle_playlist";
4472 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4473 filename_recode(mpctx->filename));
4474 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4475 mpctx->eof = playtree_add_playlist(mpctx, entry);
4476 goto goto_next_file;
4477 #endif
4479 mpctx->stream->start_pos += seek_to_byte;
4481 if (stream_dump_type == 5) {
4482 unsigned char buf[4096];
4483 int len;
4484 FILE *f;
4485 current_module = "dumpstream";
4486 stream_reset(mpctx->stream);
4487 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4488 f = fopen(opts->stream_dump_name, "wb");
4489 if (!f) {
4490 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4491 exit_player(mpctx, EXIT_ERROR);
4493 if (opts->chapterrange[0] > 1) {
4494 int chapter = opts->chapterrange[0] - 1;
4495 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4497 struct stream_dump_progress info;
4498 stream_dump_progress_start(&info);
4499 while (!mpctx->stream->eof && !async_quit_request) {
4500 len = stream_read(mpctx->stream, buf, 4096);
4501 if (len > 0) {
4502 if (fwrite(buf, len, 1, f) != 1) {
4503 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4504 exit_player(mpctx, EXIT_ERROR);
4507 stream_dump_progress(&info, len, mpctx->stream);
4508 if (opts->chapterrange[1] > 0) {
4509 int chapter = -1;
4510 if (stream_control(mpctx->stream,
4511 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4512 && chapter + 1 > opts->chapterrange[1])
4513 break;
4516 if (fclose(f)) {
4517 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4518 opts->stream_dump_name);
4519 exit_player(mpctx, EXIT_ERROR);
4521 stream_dump_progress_end(&info, opts->stream_dump_name);
4522 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4523 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4526 #ifdef CONFIG_DVDREAD
4527 if (mpctx->stream->type == STREAMTYPE_DVD) {
4528 current_module = "dvd lang->id";
4529 if (opts->audio_lang && opts->audio_id == -1)
4530 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4531 if (opts->sub_lang && opts->sub_id == -1)
4532 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4533 // setup global sub numbering
4534 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4535 current_module = NULL;
4537 #endif
4539 #ifdef CONFIG_DVDNAV
4540 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4541 current_module = "dvdnav lang->id";
4542 if (opts->audio_lang && opts->audio_id == -1)
4543 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4544 opts->audio_lang);
4545 dvdsub_lang_id = -3;
4546 if (opts->sub_lang && opts->sub_id == -1)
4547 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4548 mpctx->stream, opts->sub_lang);
4549 // setup global sub numbering
4550 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4551 mpctx->stream);
4552 current_module = NULL;
4554 #endif
4556 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4557 goto_enable_cache:
4558 if (stream_cache_size > 0) {
4559 int res;
4560 float stream_cache_min_percent = opts->stream_cache_min_percent;
4561 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4562 current_module = "enable_cache";
4563 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4564 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4565 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4566 if (res == 0)
4567 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4568 goto goto_next_file;
4571 //============ Open DEMUXERS --- DETECT file type =======================
4572 current_module = "demux_open";
4574 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4575 opts->audio_id, opts->video_id, opts->sub_id,
4576 mpctx->filename);
4578 // HACK to get MOV Reference Files working
4580 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4581 unsigned char *playlist_entry;
4582 play_tree_t *list = NULL, *entry = NULL;
4584 current_module = "handle_demux_playlist";
4585 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4586 char *temp;
4587 const char *bname;
4589 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4590 filename_recode(playlist_entry));
4592 bname = mp_basename(playlist_entry);
4593 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4594 !strncmp(bname + 3, "gateQT", 6))
4595 continue;
4597 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4598 continue;
4600 entry = play_tree_new();
4602 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4603 playlist_entry)) { // add reference path of current file
4604 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4605 mpctx->filename)) + strlen(playlist_entry) + 1));
4606 if (temp) {
4607 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4608 strlen(mp_basename(mpctx->filename)));
4609 temp[strlen(mpctx->filename) - strlen(mp_basename(
4610 mpctx->filename))] = '\0';
4611 strcat(temp, playlist_entry);
4612 if (!strcmp(temp, mpctx->filename)) {
4613 free(temp);
4614 continue;
4616 play_tree_add_file(entry, temp);
4617 mp_msg(MSGT_CPLAYER, MSGL_V,
4618 "Resolving reference to %s.\n", temp);
4619 free(temp);
4621 } else
4622 play_tree_add_file(entry, playlist_entry);
4624 if (!list)
4625 list = entry;
4626 else
4627 play_tree_append_entry(list, entry);
4629 free_demuxer(mpctx->demuxer);
4630 mpctx->demuxer = NULL;
4632 if (list) {
4633 entry = play_tree_new();
4634 play_tree_set_child(entry, list);
4635 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4636 goto goto_next_file;
4640 if (!mpctx->demuxer) {
4641 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4642 goto goto_next_file;
4645 if (mpctx->demuxer->matroska_data.ordered_chapters)
4646 build_ordered_chapter_timeline(mpctx);
4648 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4649 build_edl_timeline(mpctx);
4651 if (mpctx->timeline) {
4652 mpctx->timeline_part = 0;
4653 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4655 int part_count = mpctx->num_timeline_parts;
4656 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4657 "sources. Total length %.3f seconds.\n", part_count,
4658 mpctx->num_sources, mpctx->timeline[part_count].start);
4659 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4660 for (int i = 0; i < mpctx->num_sources; i++)
4661 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4662 filename_recode(mpctx->sources[i].demuxer->filename));
4663 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4664 "source_start, source):\n");
4665 for (int i = 0; i < part_count; i++) {
4666 struct timeline_part *p = mpctx->timeline + i;
4667 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4668 p->source_start, p->source - mpctx->sources);
4670 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4671 mpctx->timeline[part_count].start);
4674 if (!mpctx->sources) {
4675 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4676 *mpctx->sources = (struct content_source){
4677 .stream = mpctx->stream,
4678 .demuxer = mpctx->demuxer
4680 mpctx->num_sources = 1;
4683 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4685 #ifdef CONFIG_ASS
4686 if (opts->ass_enabled && mpctx->ass_library) {
4687 for (int j = 0; j < mpctx->num_sources; j++) {
4688 struct demuxer *d = mpctx->sources[j].demuxer;
4689 for (int i = 0; i < d->num_attachments; i++) {
4690 struct demux_attachment *att = d->attachments + i;
4691 if (use_embedded_fonts && attachment_is_font(att))
4692 ass_add_font(mpctx->ass_library, att->name, att->data,
4693 att->data_size);
4697 #endif
4699 current_module = "demux_open2";
4701 mpctx->d_audio = mpctx->demuxer->audio;
4702 mpctx->d_video = mpctx->demuxer->video;
4703 mpctx->d_sub = mpctx->demuxer->sub;
4705 if (ts_prog) {
4706 int tmp = ts_prog;
4707 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4709 // select audio stream
4710 for (int i = 0; i < mpctx->num_sources; i++)
4711 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4712 opts->audio_lang);
4714 // DUMP STREAMS:
4715 if ((stream_dump_type) && (stream_dump_type < 4)) {
4716 FILE *f;
4717 demux_stream_t *ds = NULL;
4718 current_module = "dump";
4719 // select stream to dump
4720 switch (stream_dump_type) {
4721 case 1: ds = mpctx->d_audio;
4722 break;
4723 case 2: ds = mpctx->d_video;
4724 break;
4725 case 3: ds = mpctx->d_sub;
4726 break;
4728 if (!ds) {
4729 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4730 "dump: FATAL: Selected stream missing!\n");
4731 exit_player(mpctx, EXIT_ERROR);
4733 // disable other streams:
4734 if (mpctx->d_audio && mpctx->d_audio != ds) {
4735 ds_free_packs(mpctx->d_audio);
4736 mpctx->d_audio->id = -2;
4738 if (mpctx->d_video && mpctx->d_video != ds) {
4739 ds_free_packs(mpctx->d_video);
4740 mpctx->d_video->id = -2;
4742 if (mpctx->d_sub && mpctx->d_sub != ds) {
4743 ds_free_packs(mpctx->d_sub);
4744 mpctx->d_sub->id = -2;
4746 // let's dump it!
4747 f = fopen(opts->stream_dump_name, "wb");
4748 if (!f) {
4749 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4750 exit_player(mpctx, EXIT_ERROR);
4752 struct stream_dump_progress info;
4753 stream_dump_progress_start(&info);
4754 while (!ds->eof) {
4755 unsigned char *start;
4756 int in_size = ds_get_packet(ds, &start);
4757 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4758 && stream_dump_type == 2)
4759 fwrite(&in_size, 1, 4, f);
4760 if (in_size > 0) {
4761 fwrite(start, in_size, 1, f);
4762 stream_dump_progress(&info, in_size, mpctx->stream);
4764 if (opts->chapterrange[1] > 0) {
4765 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4766 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4767 break;
4770 fclose(f);
4771 stream_dump_progress_end(&info, opts->stream_dump_name);
4772 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4773 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4776 mpctx->sh_audio = mpctx->d_audio->sh;
4777 mpctx->sh_video = mpctx->d_video->sh;
4779 if (mpctx->sh_video) {
4781 current_module = "video_read_properties";
4782 if (!video_read_properties(mpctx->sh_video)) {
4783 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4784 mpctx->sh_video = mpctx->d_video->sh = NULL;
4785 } else {
4786 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4787 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4788 mpctx->demuxer->file_format, mpctx->sh_video->format,
4789 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4790 mpctx->sh_video->fps, mpctx->sh_video->frametime
4793 /* need to set fps here for output encoders to pick it up in their init */
4794 if (force_fps) {
4795 mpctx->sh_video->fps = force_fps;
4796 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4798 vo_fps = mpctx->sh_video->fps;
4800 if (!mpctx->sh_video->fps && !force_fps) {
4801 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4802 "header or invalid, use the -fps option.\n");
4803 mpctx->opts.correct_pts = 1;
4809 if (!mpctx->sh_video && !mpctx->sh_audio) {
4810 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4811 #ifdef CONFIG_DVBIN
4812 if (mpctx->stream->type == STREAMTYPE_DVB) {
4813 int dir;
4814 int v = mpctx->last_dvb_step;
4815 if (v > 0)
4816 dir = DVB_CHANNEL_HIGHER;
4817 else
4818 dir = DVB_CHANNEL_LOWER;
4820 if (dvb_step_channel(mpctx->stream, dir)) {
4821 mpctx->stop_play = PT_NEXT_ENTRY;
4822 mpctx->dvbin_reopen = 1;
4825 #endif
4826 goto goto_next_file; // exit_player(_("Fatal error"));
4829 /* display clip info */
4830 demux_info_print(mpctx->demuxer);
4832 //================= Read SUBTITLES (DVD & TEXT) =========================
4833 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4834 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4835 init_vo_spudec(mpctx);
4837 // after reading video params we should load subtitles because
4838 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4839 // check .sub
4840 current_module = "read_subtitles_file";
4841 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4842 if (opts->sub_name) {
4843 for (i = 0; opts->sub_name[i] != NULL; ++i)
4844 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4846 if (opts->sub_auto) { // auto load sub file ...
4847 char **tmp = find_text_subtitles(opts, mpctx->filename);
4848 int nsub = MP_TALLOC_ELEMS(tmp);
4849 for (int i = 0; i < nsub; i++)
4850 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4851 talloc_free(tmp);
4853 if (mpctx->set_of_sub_size > 0)
4854 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4856 if (select_subtitle(mpctx)) {
4857 if (mpctx->subdata)
4858 switch (stream_dump_type) {
4859 case 3: list_sub_file(mpctx->subdata);
4860 break;
4861 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4862 break;
4863 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4864 break;
4865 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4866 break;
4867 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4868 break;
4869 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4870 break;
4874 print_file_properties(mpctx, mpctx->filename);
4876 reinit_video_chain(mpctx);
4877 if (mpctx->sh_video) {
4878 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4879 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4880 #ifdef CONFIG_FREETYPE
4881 force_load_font = 1;
4882 #endif
4883 } else if (!mpctx->sh_audio)
4884 goto goto_next_file;
4886 //================== MAIN: ==========================
4887 current_module = "main";
4889 if (opts->playing_msg) {
4890 char *msg = property_expand_string(mpctx, opts->playing_msg);
4891 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4892 free(msg);
4896 // Disable the term OSD in verbose mode
4897 if (verbose)
4898 opts->term_osd = 0;
4900 // Make sure old OSD does not stay around,
4901 // e.g. with -fixed-vo and same-resolution files
4902 clear_osd_msgs();
4903 update_osd_msg(mpctx);
4905 //================ SETUP AUDIO ==========================
4907 if (mpctx->sh_audio) {
4908 reinit_audio_chain(mpctx);
4909 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4910 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4911 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4914 current_module = "av_init";
4916 if (mpctx->sh_video) {
4917 mpctx->sh_video->timer = 0;
4918 if (!ignore_start)
4919 audio_delay += mpctx->sh_video->stream_delay;
4921 if (mpctx->sh_audio) {
4922 if (start_volume >= 0)
4923 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4924 if (!ignore_start)
4925 audio_delay -= mpctx->sh_audio->stream_delay;
4926 mpctx->delay = -audio_delay;
4929 if (!mpctx->sh_audio) {
4930 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4931 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4932 mpctx->d_audio->packs);
4933 ds_free_packs(mpctx->d_audio); // free buffered chunks
4935 if (!mpctx->sh_video) {
4936 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4937 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4938 mpctx->d_video->packs);
4939 ds_free_packs(mpctx->d_video);
4940 mpctx->d_video->id = -2;
4943 if (!mpctx->sh_video && !mpctx->sh_audio)
4944 goto goto_next_file;
4946 if (force_fps && mpctx->sh_video) {
4947 vo_fps = mpctx->sh_video->fps = force_fps;
4948 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4949 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4950 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4951 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4954 mp_input_set_section(mpctx->input, NULL);
4955 //TODO: add desired (stream-based) sections here
4956 if (mpctx->stream->type == STREAMTYPE_TV)
4957 mp_input_set_section(mpctx->input, "tv");
4958 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4959 mp_input_set_section(mpctx->input, "dvdnav");
4961 //==================== START PLAYING =======================
4963 if (opts->loop_times > 1)
4964 opts->loop_times--;
4965 else if (opts->loop_times == 1)
4966 opts->loop_times = -1;
4968 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4970 total_time_usage_start = GetTimer();
4971 audio_time_usage = 0;
4972 video_time_usage = 0;
4973 vout_time_usage = 0;
4974 total_frame_cnt = 0;
4975 drop_frame_cnt = 0; // fix for multifile fps benchmark
4976 play_n_frames = play_n_frames_mf;
4978 if (play_n_frames == 0) {
4979 mpctx->stop_play = PT_NEXT_ENTRY;
4980 goto goto_next_file;
4983 mpctx->time_frame = 0;
4984 mpctx->drop_message_shown = 0;
4985 mpctx->restart_playback = true;
4986 mpctx->video_pts = 0;
4987 mpctx->last_seek_pts = 0;
4988 mpctx->hrseek_active = false;
4989 mpctx->hrseek_framedrop = false;
4990 mpctx->step_frames = 0;
4991 mpctx->total_avsync_change = 0;
4992 mpctx->last_chapter_seek = -2;
4994 // If there's a timeline force an absolute seek to initialize state
4995 if (opts->seek_to_sec || mpctx->timeline) {
4996 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4997 seek(mpctx, mpctx->seek, false);
4998 end_at.pos += opts->seek_to_sec;
5000 if (opts->chapterrange[0] > 0) {
5001 double pts;
5002 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts, NULL) >= 0
5003 && pts > -1.0) {
5004 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
5005 seek(mpctx, mpctx->seek, false);
5009 if (end_at.type == END_AT_SIZE) {
5010 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
5011 "Option -endpos in MPlayer does not yet support size units.\n");
5012 end_at.type = END_AT_NONE;
5015 #ifdef CONFIG_DVDNAV
5016 mp_dvdnav_context_free(mpctx);
5017 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
5018 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
5019 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
5021 #endif
5023 mpctx->seek = (struct seek_params){ 0 };
5024 get_relative_time(mpctx); // reset current delta
5025 // Make sure VO knows current pause state
5026 if (mpctx->sh_video)
5027 vo_control(mpctx->video_out,
5028 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
5030 while (!mpctx->stop_play)
5031 run_playloop(mpctx);
5033 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
5035 #ifdef CONFIG_DVBIN
5036 if (mpctx->dvbin_reopen) {
5037 mpctx->stop_play = 0;
5038 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
5039 cache_uninit(mpctx->stream);
5040 mpctx->dvbin_reopen = 0;
5041 goto goto_enable_cache;
5043 #endif
5045 goto_next_file: // don't jump here after ao/vo/getch initialization!
5047 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
5049 if (opts->benchmark) {
5050 double tot = video_time_usage + vout_time_usage + audio_time_usage;
5051 double total_time_usage;
5052 total_time_usage_start = GetTimer() - total_time_usage_start;
5053 total_time_usage = (float)total_time_usage_start * 0.000001;
5054 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
5055 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
5056 video_time_usage, vout_time_usage, audio_time_usage,
5057 total_time_usage - tot, total_time_usage);
5058 if (total_time_usage > 0.0)
5059 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
5060 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
5061 100.0 * video_time_usage / total_time_usage,
5062 100.0 * vout_time_usage / total_time_usage,
5063 100.0 * audio_time_usage / total_time_usage,
5064 100.0 * (total_time_usage - tot) / total_time_usage,
5065 100.0);
5066 if (total_frame_cnt && frame_dropping)
5067 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
5068 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
5069 total_frame_cnt - drop_frame_cnt,
5070 (total_time_usage > 0.5) ? ((total_frame_cnt -
5071 drop_frame_cnt) / total_time_usage) : 0,
5072 drop_frame_cnt,
5073 100 * drop_frame_cnt / total_frame_cnt,
5074 total_frame_cnt,
5075 (total_time_usage > 0.5) ?
5076 (total_frame_cnt / total_time_usage) : 0);
5079 // time to uninit all, except global stuff:
5080 int uninitialize_parts = INITIALIZED_ALL;
5081 if (opts->fixed_vo)
5082 uninitialize_parts -= INITIALIZED_VO;
5083 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
5084 uninitialize_parts -= INITIALIZED_AO;
5085 uninit_player(mpctx, uninitialize_parts);
5087 if (mpctx->set_of_sub_size > 0) {
5088 current_module = "sub_free";
5089 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5090 sub_free(mpctx->set_of_subtitles[i]);
5091 #ifdef CONFIG_ASS
5092 if (mpctx->set_of_ass_tracks[i])
5093 ass_free_track(mpctx->set_of_ass_tracks[i]);
5094 #endif
5096 mpctx->set_of_sub_size = 0;
5098 mpctx->vo_sub_last = vo_sub = NULL;
5099 mpctx->subdata = NULL;
5100 #ifdef CONFIG_ASS
5101 mpctx->osd->ass_track = NULL;
5102 if (mpctx->ass_library)
5103 ass_clear_fonts(mpctx->ass_library);
5104 #endif
5106 if (!mpctx->stop_play) // In case some goto jumped here...
5107 mpctx->stop_play = PT_NEXT_ENTRY;
5109 int playtree_direction = 1;
5111 if (mpctx->stop_play == PT_NEXT_ENTRY
5112 || mpctx->stop_play == PT_PREV_ENTRY) {
5113 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5114 != PLAY_TREE_ITER_ENTRY) {
5115 play_tree_iter_free(mpctx->playtree_iter);
5116 mpctx->playtree_iter = NULL;
5118 mpctx->play_tree_step = 1;
5119 } else if (mpctx->stop_play == PT_UP_NEXT ||
5120 mpctx->stop_play == PT_UP_PREV) {
5121 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5122 if (mpctx->playtree_iter) {
5123 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5124 PLAY_TREE_ITER_ENTRY) {
5125 play_tree_iter_free(mpctx->playtree_iter);
5126 mpctx->playtree_iter = NULL;
5129 } else if (mpctx->stop_play == PT_STOP) {
5130 play_tree_iter_free(mpctx->playtree_iter);
5131 mpctx->playtree_iter = NULL;
5132 } else // NEXT PREV SRC
5133 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5135 while (mpctx->playtree_iter != NULL) {
5136 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5137 playtree_direction);
5138 if (mpctx->filename == NULL) {
5139 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5140 0) != PLAY_TREE_ITER_ENTRY) {
5141 play_tree_iter_free(mpctx->playtree_iter);
5142 mpctx->playtree_iter = NULL;
5145 } else
5146 break;
5149 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5150 if (!mpctx->playtree_iter)
5151 mpctx->filename = NULL;
5152 mpctx->stop_play = 0;
5153 goto play_next_file;
5156 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5158 return 1;
5160 #endif /* DISABLE_MAIN */