options: support --leak-report (double dash form)
[mplayer.git] / mplayer.c
blob3b8f588c0e0d0f1b9cf7d652cfe3c13e26c3123a
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[128];
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;
1494 int r;
1496 // look if the id is already in the stack
1497 for (msg = osd_msg_stack; msg && msg->id != id;
1498 last = msg, msg = msg->prev) ;
1499 // not found: alloc it
1500 if (!msg) {
1501 msg = calloc(1, sizeof(mp_osd_msg_t));
1502 msg->prev = osd_msg_stack;
1503 osd_msg_stack = msg;
1504 } else if (last) { // found, but it's not on top of the stack
1505 last->prev = msg->prev;
1506 msg->prev = osd_msg_stack;
1507 osd_msg_stack = msg;
1509 // write the msg
1510 r = vsnprintf(msg->msg, 128, fmt, ap);
1511 if (r >= 128)
1512 msg->msg[127] = 0;
1513 // set id and time
1514 msg->id = id;
1515 msg->level = level;
1516 msg->time = time;
1520 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1522 va_list ap;
1523 va_start(ap, fmt);
1524 set_osd_msg_va(id, level, time, fmt, ap);
1525 va_end(ap);
1528 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1530 va_list ap;
1531 va_start(ap, fmt);
1532 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1533 va_end(ap);
1538 * \brief Remove a message from the OSD stack
1540 * This function can be used to get rid of a message right away.
1544 void rm_osd_msg(int id)
1546 mp_osd_msg_t *msg, *last = NULL;
1548 // Search for the msg
1549 for (msg = osd_msg_stack; msg && msg->id != id;
1550 last = msg, msg = msg->prev) ;
1551 if (!msg)
1552 return;
1554 // Detach it from the stack and free it
1555 if (last)
1556 last->prev = msg->prev;
1557 else
1558 osd_msg_stack = msg->prev;
1559 free(msg);
1563 * \brief Remove all messages from the OSD stack
1567 static void clear_osd_msgs(void)
1569 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1570 while (msg) {
1571 prev = msg->prev;
1572 free(msg);
1573 msg = prev;
1575 osd_msg_stack = NULL;
1579 * \brief Get the current message from the OSD stack.
1581 * This function decrements the message timer and destroys the old ones.
1582 * The message that should be displayed is returned (if any).
1586 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1588 struct MPOpts *opts = &mpctx->opts;
1589 mp_osd_msg_t *msg, *prev, *last = NULL;
1590 static unsigned last_update = 0;
1591 unsigned now = GetTimerMS();
1592 unsigned diff;
1593 char hidden_dec_done = 0;
1595 if (mpctx->osd_visible) {
1596 // 36000000 means max timed visibility is 1 hour into the future, if
1597 // the difference is greater assume it's wrapped around from below 0
1598 if (mpctx->osd_visible - now > 36000000) {
1599 mpctx->osd_visible = 0;
1600 vo_osd_progbar_type = -1; // disable
1601 vo_osd_changed(OSDTYPE_PROGBAR);
1602 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1605 if (mpctx->osd_show_percentage_until - now > 36000000)
1606 mpctx->osd_show_percentage_until = 0;
1608 if (!last_update)
1609 last_update = now;
1610 diff = now >= last_update ? now - last_update : 0;
1612 last_update = now;
1614 // Look for the first message in the stack with high enough level.
1615 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1616 prev = msg->prev;
1617 if (msg->level > opts->osd_level && hidden_dec_done)
1618 continue;
1619 // The message has a high enough level or it is the first hidden one
1620 // in both cases we decrement the timer or kill it.
1621 if (!msg->started || msg->time > diff) {
1622 if (msg->started)
1623 msg->time -= diff;
1624 else
1625 msg->started = 1;
1626 // display it
1627 if (msg->level <= opts->osd_level)
1628 return msg;
1629 hidden_dec_done = 1;
1630 continue;
1632 // kill the message
1633 free(msg);
1634 if (last) {
1635 last->prev = prev;
1636 msg = last;
1637 } else {
1638 osd_msg_stack = prev;
1639 msg = NULL;
1642 // Nothing found
1643 return NULL;
1647 * \brief Display the OSD bar.
1649 * Display the OSD bar or fall back on a simple message.
1653 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1654 double min, double max, double val)
1656 struct MPOpts *opts = &mpctx->opts;
1657 if (opts->osd_level < 1)
1658 return;
1660 if (mpctx->sh_video) {
1661 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1662 vo_osd_progbar_type = type;
1663 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1664 vo_osd_changed(OSDTYPE_PROGBAR);
1665 return;
1668 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1669 name, ROUND(100 * (val - min) / (max - min)));
1673 * \brief Display text subtitles on the OSD
1675 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1677 int i;
1678 vo_sub = subs;
1679 vo_osd_changed(OSDTYPE_SUBTITLE);
1680 if (!mpctx->sh_video) {
1681 // reverse order, since newest set_osd_msg is displayed first
1682 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1683 if (!subs || i >= subs->lines || !subs->text[i])
1684 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1685 else {
1686 // HACK: currently display time for each sub line
1687 // except the last is set to 2 seconds.
1688 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1689 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1690 "%s", subs->text[i]);
1697 * \brief Update the OSD message line.
1699 * This function displays the current message on the vo OSD or on the term.
1700 * If the stack is empty and the OSD level is high enough the timer
1701 * is displayed (only on the vo OSD).
1705 static void update_osd_msg(struct MPContext *mpctx)
1707 struct MPOpts *opts = &mpctx->opts;
1708 mp_osd_msg_t *msg;
1709 struct osd_state *osd = mpctx->osd;
1710 char osd_text_timer[128];
1712 if (mpctx->add_osd_seek_info) {
1713 double percentage = get_percent_pos(mpctx);
1714 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1715 if (mpctx->sh_video)
1716 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1717 mpctx->add_osd_seek_info = false;
1720 // Look if we have a msg
1721 if ((msg = get_osd_msg(mpctx))) {
1722 if (strcmp(osd->osd_text, msg->msg)) {
1723 strncpy(osd->osd_text, msg->msg, 127);
1724 if (mpctx->sh_video)
1725 vo_osd_changed(OSDTYPE_OSD);
1726 else if (opts->term_osd)
1727 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1728 msg->msg);
1730 return;
1733 if (mpctx->sh_video) {
1734 // fallback on the timer
1735 if (opts->osd_level >= 2) {
1736 int len = get_time_length(mpctx);
1737 int percentage = -1;
1738 char percentage_text[10];
1739 char fractions_text[4];
1740 double fpts = get_current_time(mpctx);
1741 int pts = fpts;
1743 if (mpctx->osd_show_percentage_until)
1744 percentage = get_percent_pos(mpctx);
1746 if (percentage >= 0)
1747 snprintf(percentage_text, 9, " (%d%%)", percentage);
1748 else
1749 percentage_text[0] = 0;
1751 if (opts->osd_fractions == 1) {
1752 //print fractions as sub-second timestamp
1753 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1754 (int)((fpts - pts) * 100));
1755 } else if (opts->osd_fractions == 2) {
1756 /* Print fractions by estimating the frame count within the
1757 * second.
1759 * Rounding or cutting off numbers after the decimal point
1760 * causes problems because of float's precision and movies
1761 * whose first frame is not exactly at timestamp 0. Therefore,
1762 * we add 0.2 and cut off at the decimal point, which proved
1763 * to be good heuristic.
1765 double fps = mpctx->sh_video->fps;
1766 if (fps <= 1 || fps > 99)
1767 strcpy(fractions_text, ".??");
1768 else
1769 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1770 (int) ((fpts - pts) * fps + 0.2));
1771 } else {
1772 //do not print fractions
1773 fractions_text[0] = 0;
1776 if (opts->osd_level == 3)
1777 snprintf(osd_text_timer, 63,
1778 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1779 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1780 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1781 percentage_text);
1782 else
1783 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s%s",
1784 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1785 pts % 60, fractions_text, percentage_text);
1786 } else
1787 osd_text_timer[0] = 0;
1789 if (strcmp(osd->osd_text, osd_text_timer)) {
1790 strncpy(osd->osd_text, osd_text_timer, 63);
1791 vo_osd_changed(OSDTYPE_OSD);
1793 return;
1796 // Clear the term osd line
1797 if (opts->term_osd && osd->osd_text[0]) {
1798 osd->osd_text[0] = 0;
1799 printf("%s\n", opts->term_osd_esc);
1803 ///@}
1804 // OSDMsgStack
1807 void reinit_audio_chain(struct MPContext *mpctx)
1809 struct MPOpts *opts = &mpctx->opts;
1810 struct ao *ao;
1811 if (!mpctx->sh_audio)
1812 return;
1813 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1814 current_module = "init_audio_codec";
1815 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1816 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1817 goto init_error;
1818 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1819 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1823 current_module = "af_preinit";
1824 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1825 mpctx->initialized_flags |= INITIALIZED_AO;
1826 mpctx->ao = ao_create();
1827 mpctx->ao->samplerate = force_srate;
1828 mpctx->ao->format = opts->audio_output_format;
1830 ao = mpctx->ao;
1832 // first init to detect best values
1833 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1834 // input:
1835 mpctx->sh_audio->samplerate,
1836 // output:
1837 &ao->samplerate, &ao->channels, &ao->format)) {
1838 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1839 "pre-init!\n");
1840 exit_player(mpctx, EXIT_ERROR);
1842 if (!ao->initialized) {
1843 current_module = "ao2_init";
1844 ao->buffersize = opts->ao_buffersize;
1845 ao_init(ao, opts->audio_driver_list);
1846 if (!ao->initialized) {
1847 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1848 "Could not open/initialize audio device -> no sound.\n");
1849 goto init_error;
1851 ao->buffer.start = talloc_new(ao);
1852 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1853 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1854 ao->driver->info->short_name,
1855 ao->samplerate, ao->channels,
1856 af_fmt2str_short(ao->format),
1857 af_fmt2bits(ao->format) / 8);
1858 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1859 ao->driver->info->name, ao->driver->info->author);
1860 if (strlen(ao->driver->info->comment) > 0)
1861 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1862 ao->driver->info->comment);
1865 // init audio filters:
1866 current_module = "af_init";
1867 if (!build_afilter_chain(mpctx)) {
1868 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1869 "Couldn't find matching filter/ao format!\n");
1870 goto init_error;
1872 mpctx->mixer.ao = ao;
1873 mpctx->mixer.volstep = volstep;
1874 mpctx->syncing_audio = true;
1875 return;
1877 init_error:
1878 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1879 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1880 mpctx->d_audio->id = -2;
1884 ///@}
1885 // Command2Property
1888 // Return pts value corresponding to the end point of audio written to the
1889 // ao so far.
1890 static double written_audio_pts(struct MPContext *mpctx)
1892 sh_audio_t *sh_audio = mpctx->sh_audio;
1893 demux_stream_t *d_audio = mpctx->d_audio;
1894 // first calculate the end pts of audio that has been output by decoder
1895 double a_pts = sh_audio->pts;
1896 if (a_pts != MP_NOPTS_VALUE)
1897 // Good, decoder supports new way of calculating audio pts.
1898 // sh_audio->pts is the timestamp of the latest input packet with
1899 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1900 // the amount of bytes the decoder has written after that timestamp.
1901 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1902 else {
1903 // Decoder doesn't support new way of calculating pts (or we're
1904 // being called before it has decoded anything with known timestamp).
1905 // Use the old method of audio pts calculation: take the timestamp
1906 // of last packet with known pts the decoder has read data from,
1907 // and add amount of bytes read after the beginning of that packet
1908 // divided by input bps. This will be inaccurate if the input/output
1909 // ratio is not constant for every audio packet or if it is constant
1910 // but not accurately known in sh_audio->i_bps.
1912 a_pts = d_audio->pts;
1913 if (a_pts == MP_NOPTS_VALUE)
1914 return a_pts;
1916 // ds_tell_pts returns bytes read after last timestamp from
1917 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1918 // it has read but not decoded
1919 if (sh_audio->i_bps)
1920 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1921 (double)sh_audio->i_bps;
1923 // Now a_pts hopefully holds the pts for end of audio from decoder.
1924 // Substract data in buffers between decoder and audio out.
1926 // Decoded but not filtered
1927 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1929 // Data buffered in audio filters, measured in bytes of "missing" output
1930 double buffered_output = af_calc_delay(sh_audio->afilter);
1932 // Data that was ready for ao but was buffered because ao didn't fully
1933 // accept everything to internal buffers yet
1934 buffered_output += mpctx->ao->buffer.len;
1936 // Filters divide audio length by playback_speed, so multiply by it
1937 // to get the length in original units without speedup or slowdown
1938 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1940 return a_pts + mpctx->video_offset;
1943 // Return pts value corresponding to currently playing audio.
1944 double playing_audio_pts(struct MPContext *mpctx)
1946 double pts = written_audio_pts(mpctx);
1947 if (pts == MP_NOPTS_VALUE)
1948 return pts;
1949 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1952 static bool is_av_sub(int type)
1954 return type == 'b' || type == 'p' || type == 'x';
1957 void update_subtitles(struct MPContext *mpctx, double refpts,
1958 double sub_offset, bool reset)
1960 struct MPOpts *opts = &mpctx->opts;
1961 struct sh_video *sh_video = mpctx->sh_video;
1962 struct demux_stream *d_sub = mpctx->d_sub;
1963 double curpts = refpts + sub_delay;
1964 unsigned char *packet = NULL;
1965 int len;
1966 struct sh_sub *sh_sub = d_sub->sh;
1967 int type = sh_sub ? sh_sub->type : 'v';
1968 static subtitle subs;
1969 if (reset) {
1970 if (sh_sub)
1971 sub_reset(sh_sub, mpctx->osd);
1972 sub_clear_text(&subs, MP_NOPTS_VALUE);
1973 if (vo_sub)
1974 set_osd_subtitle(mpctx, NULL);
1975 if (vo_spudec) {
1976 spudec_reset(vo_spudec);
1977 vo_osd_changed(OSDTYPE_SPU);
1979 #ifdef CONFIG_FFMPEG
1980 if (is_av_sub(type))
1981 reset_avsub(sh_sub);
1982 #endif
1983 return;
1985 // find sub
1986 if (mpctx->subdata) {
1987 if (sub_fps == 0)
1988 sub_fps = sh_video ? sh_video->fps : 25;
1989 current_module = "find_sub";
1990 find_sub(mpctx, mpctx->subdata, curpts *
1991 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1992 if (vo_sub)
1993 mpctx->vo_sub_last = vo_sub;
1996 // DVD sub:
1997 if (vobsub_id >= 0 || type == 'v') {
1998 int timestamp;
1999 current_module = "spudec";
2000 /* Get a sub packet from the DVD or a vobsub */
2001 while (1) {
2002 // Vobsub
2003 len = 0;
2004 if (vo_vobsub) {
2005 if (curpts >= 0) {
2006 len = vobsub_get_packet(vo_vobsub, curpts,
2007 (void **)&packet, &timestamp);
2008 if (len > 0)
2009 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
2010 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
2011 len, refpts, sh_video->timer,
2012 timestamp / 90000.0, timestamp);
2014 } else {
2015 // DVD sub
2016 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
2017 if (len > 0) {
2018 // XXX This is wrong, sh_video->pts can be arbitrarily
2019 // much behind demuxing position. Unfortunately using
2020 // d_video->pts which would have been the simplest
2021 // improvement doesn't work because mpeg specific hacks
2022 // in video.c set d_video->pts to 0.
2023 float x = d_sub->pts - refpts;
2024 if (x > -20 && x < 20) // prevent missing subs on pts reset
2025 timestamp = 90000 * d_sub->pts;
2026 else
2027 timestamp = 90000 * curpts;
2028 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
2029 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
2030 refpts, d_sub->pts, timestamp);
2033 if (len <= 0 || !packet)
2034 break;
2035 // create it only here, since with some broken demuxers we might
2036 // type = v but no DVD sub and we currently do not change the
2037 // "original frame size" ever after init, leading to wrong-sized
2038 // PGS subtitles.
2039 if (!vo_spudec)
2040 vo_spudec = spudec_new(NULL);
2041 if (vo_vobsub || timestamp >= 0)
2042 spudec_assemble(vo_spudec, packet, len, timestamp);
2044 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
2045 if (type == 'd' && !d_sub->demuxer->teletext) {
2046 tt_stream_props tsp = { 0 };
2047 void *ptr = &tsp;
2048 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
2049 VBI_CONTROL_TRUE)
2050 d_sub->demuxer->teletext = ptr;
2052 if (d_sub->non_interleaved)
2053 ds_get_next_pts(d_sub);
2055 while (d_sub->first) {
2056 double subpts = ds_get_next_pts(d_sub) + sub_offset;
2057 if (subpts > curpts) {
2058 // Libass handled subs can be fed to it in advance
2059 if (!opts->ass_enabled || !is_text_sub(type))
2060 break;
2061 // Try to avoid demuxing whole file at once
2062 if (d_sub->non_interleaved && subpts > curpts + 1)
2063 break;
2065 double duration = d_sub->first->duration;
2066 len = ds_get_packet_sub(d_sub, &packet);
2067 if (is_av_sub(type)) {
2068 #ifdef CONFIG_FFMPEG
2069 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2070 if (ret < 0)
2071 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2072 "subtitle\n");
2073 #endif
2074 continue;
2076 if (type == 'm') {
2077 if (len < 2)
2078 continue;
2079 len = FFMIN(len - 2, AV_RB16(packet));
2080 packet += 2;
2082 if (type == 'd') {
2083 if (d_sub->demuxer->teletext) {
2084 uint8_t *p = packet;
2085 p++;
2086 len--;
2087 while (len >= 46) {
2088 int sublen = p[1];
2089 if (p[0] == 2 || p[0] == 3)
2090 teletext_control(d_sub->demuxer->teletext,
2091 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2092 p += sublen + 2;
2093 len -= sublen + 2;
2096 continue;
2098 if (sh_sub && sh_sub->active) {
2099 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2100 continue;
2102 if (subpts != MP_NOPTS_VALUE) {
2103 if (duration < 0)
2104 sub_clear_text(&subs, MP_NOPTS_VALUE);
2105 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2106 int i;
2107 unsigned char *p = packet;
2108 for (i = 0; i < 8 && *p != '\0'; p++)
2109 if (*p == ',')
2110 i++;
2111 if (*p == '\0') /* Broken line? */
2112 continue;
2113 len -= p - packet;
2114 packet = p;
2116 double endpts = MP_NOPTS_VALUE;
2117 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2118 endpts = subpts + duration;
2119 sub_add_text(&subs, packet, len, endpts);
2120 set_osd_subtitle(mpctx, &subs);
2122 if (d_sub->non_interleaved)
2123 ds_get_next_pts(d_sub);
2125 if (!opts->ass_enabled)
2126 if (sub_clear_text(&subs, curpts))
2127 set_osd_subtitle(mpctx, &subs);
2129 if (vo_spudec) {
2130 spudec_heartbeat(vo_spudec, 90000 * curpts);
2131 if (spudec_changed(vo_spudec))
2132 vo_osd_changed(OSDTYPE_SPU);
2135 current_module = NULL;
2138 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2140 int page_changed;
2142 if (!demuxer->teletext)
2143 return;
2145 //Also forcing page update when such ioctl is not supported or call error occured
2146 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2147 &page_changed) != VBI_CONTROL_TRUE)
2148 page_changed = 1;
2150 if (!page_changed)
2151 return;
2153 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2154 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2155 vo_osd_teletext_page = NULL;
2156 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2157 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2158 vo_osd_teletext_half = 0;
2159 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2160 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2161 vo_osd_teletext_mode = 0;
2162 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2163 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2164 vo_osd_teletext_format = 0;
2165 vo_osd_changed(OSDTYPE_TELETEXT);
2167 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2170 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2172 struct MPOpts *opts = &mpctx->opts;
2173 // check for frame-drop:
2174 current_module = "check_framedrop";
2175 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2176 static int dropped_frames;
2177 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2178 float d = delay - mpctx->delay;
2179 ++total_frame_cnt;
2180 // we should avoid dropping too many frames in sequence unless we
2181 // are too late. and we allow 100ms A-V delay here:
2182 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2183 && !mpctx->restart_playback) {
2184 ++drop_frame_cnt;
2185 ++dropped_frames;
2186 return frame_dropping;
2187 } else
2188 dropped_frames = 0;
2190 return 0;
2194 #ifdef HAVE_RTC
2195 int rtc_fd = -1;
2196 #endif
2198 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2200 #ifdef HAVE_RTC
2201 if (rtc_fd >= 0) {
2202 // -------- RTC -----------
2203 current_module = "sleep_rtc";
2204 while (time_frame > 0.000) {
2205 unsigned long rtc_ts;
2206 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2207 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2208 "Linux RTC read error: %s\n", strerror(errno));
2209 time_frame -= get_relative_time(mpctx);
2211 } else
2212 #endif
2214 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2215 // unnecessarily high CPU usage
2216 struct MPOpts *opts = &mpctx->opts;
2217 float margin = opts->softsleep ? 0.011 : 0;
2218 current_module = "sleep_timer";
2219 while (time_frame > margin) {
2220 usec_sleep(1000000 * (time_frame - margin));
2221 time_frame -= get_relative_time(mpctx);
2223 if (opts->softsleep) {
2224 current_module = "sleep_soft";
2225 if (time_frame < 0)
2226 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2227 "Warning! Softsleep underflow!\n");
2228 while (time_frame > 0)
2229 time_frame -= get_relative_time(mpctx); // burn the CPU
2232 return time_frame;
2235 static int select_subtitle(MPContext *mpctx)
2237 struct MPOpts *opts = &mpctx->opts;
2238 // find the best sub to use
2239 int id;
2240 int found = 0;
2241 mpctx->global_sub_pos = -1; // no subs by default
2242 if (vobsub_id >= 0) {
2243 // if user asks for a vobsub id, use that first.
2244 id = vobsub_id;
2245 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2246 M_PROPERTY_OK;
2249 if (!found && opts->sub_id >= 0) {
2250 // if user asks for a dvd sub id, use that next.
2251 id = opts->sub_id;
2252 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2253 M_PROPERTY_OK;
2256 if (!found) {
2257 // if there are text subs to use, use those. (autosubs come last here)
2258 id = 0;
2259 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2260 M_PROPERTY_OK;
2263 if (!found && opts->sub_id == -1) {
2264 // finally select subs by language and container hints
2265 if (opts->sub_id == -1)
2266 opts->sub_id =
2267 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2268 opts->sub_lang);
2269 if (opts->sub_id >= 0) {
2270 id = opts->sub_id;
2271 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2272 M_PROPERTY_OK;
2275 return found;
2278 #ifdef CONFIG_DVDNAV
2279 #ifndef FF_B_TYPE
2280 #define FF_B_TYPE 3
2281 #endif
2282 /// store decoded video image
2283 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2284 mp_image_t *from_mpi)
2286 mp_image_t *mpi;
2288 /// Do not store B-frames
2289 if (from_mpi->pict_type == FF_B_TYPE)
2290 return to_mpi;
2292 if (to_mpi &&
2293 to_mpi->w == from_mpi->w &&
2294 to_mpi->h == from_mpi->h &&
2295 to_mpi->imgfmt == from_mpi->imgfmt)
2296 mpi = to_mpi;
2297 else {
2298 if (to_mpi)
2299 free_mp_image(to_mpi);
2300 if (from_mpi->w == 0 || from_mpi->h == 0)
2301 return NULL;
2302 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2305 copy_mpi(mpi, from_mpi);
2306 return mpi;
2309 static void mp_dvdnav_reset_stream(MPContext *ctx)
2311 struct MPOpts *opts = &ctx->opts;
2312 if (ctx->sh_video) {
2313 /// clear video pts
2314 ctx->d_video->pts = 0.0f;
2315 ctx->sh_video->pts = 0.0f;
2316 ctx->sh_video->i_pts = 0.0f;
2317 ctx->sh_video->last_pts = 0.0f;
2318 ctx->sh_video->num_buffered_pts = 0;
2319 ctx->sh_video->num_frames = 0;
2320 ctx->sh_video->num_frames_decoded = 0;
2321 ctx->sh_video->timer = 0.0f;
2322 ctx->sh_video->stream_delay = 0.0f;
2323 ctx->sh_video->timer = 0;
2324 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2327 if (ctx->sh_audio) {
2328 /// free audio packets and reset
2329 ds_free_packs(ctx->d_audio);
2330 audio_delay -= ctx->sh_audio->stream_delay;
2331 ctx->delay = -audio_delay;
2332 ao_reset(ctx->ao);
2333 resync_audio_stream(ctx->sh_audio);
2336 audio_delay = 0.0f;
2337 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2338 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2339 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2340 if (dvdsub_lang_id != opts->sub_id) {
2341 opts->sub_id = dvdsub_lang_id;
2342 select_subtitle(ctx);
2346 /// clear all EOF related flags
2347 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2350 /// Restore last decoded DVDNAV (still frame)
2351 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2352 int *in_size,
2353 unsigned char **start,
2354 mp_image_t *decoded_frame)
2356 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2357 return decoded_frame;
2359 /// a change occurred in dvdnav stream
2360 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2361 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2362 mp_dvdnav_context_free(mpctx);
2363 mp_dvdnav_reset_stream(mpctx);
2364 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2365 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2368 if (*in_size < 0) {
2369 float len;
2371 /// Display still frame, if any
2372 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2373 decoded_frame = mpctx->nav_smpi;
2375 /// increment video frame : continue playing after still frame
2376 len = get_time_length(mpctx);
2377 if (mpctx->sh_video->pts >= len &&
2378 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2379 mp_dvdnav_skip_still(mpctx->stream);
2380 mp_dvdnav_skip_wait(mpctx->stream);
2382 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2384 if (mpctx->nav_buffer) {
2385 *start = mpctx->nav_start;
2386 *in_size = mpctx->nav_in_size;
2387 if (mpctx->nav_start)
2388 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2392 return decoded_frame;
2395 /// Save last decoded DVDNAV (still frame)
2396 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2397 unsigned char *start,
2398 mp_image_t *decoded_frame)
2400 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2401 return;
2403 free(mpctx->nav_buffer);
2404 mpctx->nav_buffer = NULL;
2405 mpctx->nav_start = NULL;
2406 mpctx->nav_in_size = -1;
2408 if (in_size > 0)
2409 mpctx->nav_buffer = malloc(in_size);
2410 if (mpctx->nav_buffer) {
2411 mpctx->nav_start = start;
2412 memcpy(mpctx->nav_buffer, start, in_size);
2415 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2416 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2418 #endif /* CONFIG_DVDNAV */
2420 /* Modify video timing to match the audio timeline. There are two main
2421 * reasons this is needed. First, video and audio can start from different
2422 * positions at beginning of file or after a seek (MPlayer starts both
2423 * immediately even if they have different pts). Second, the file can have
2424 * audio timestamps that are inconsistent with the duration of the audio
2425 * packets, for example two consecutive timestamp values differing by
2426 * one second but only a packet with enough samples for half a second
2427 * of playback between them.
2429 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2431 current_module = "av_sync";
2433 if (!mpctx->sh_audio || mpctx->syncing_audio)
2434 return;
2436 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2437 double v_pts = mpctx->sh_video->pts;
2438 double av_delay = a_pts - v_pts;
2439 // Try to sync vo_flip() so it will *finish* at given time
2440 av_delay += mpctx->last_vo_flip_duration;
2441 av_delay -= audio_delay; // This much pts difference is desired
2443 double change = av_delay * 0.1;
2444 double max_change = default_max_pts_correction >= 0 ?
2445 default_max_pts_correction : frame_time * 0.1;
2446 if (change < -max_change)
2447 change = -max_change;
2448 else if (change > max_change)
2449 change = max_change;
2450 mpctx->delay += change;
2451 mpctx->total_avsync_change += change;
2454 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2455 double pts)
2457 if (mpctx->paused)
2458 return 0;
2459 struct ao *ao = mpctx->ao;
2460 double bps = ao->bps / mpctx->opts.playback_speed;
2461 ao->pts = pts;
2462 // hack used by some mpeg-writing AOs
2463 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2464 mpctx->delay) * 90000.0;
2465 int played = ao_play(mpctx->ao, data, len, flags);
2466 if (played > 0) {
2467 mpctx->delay += played / bps;
2468 // Keep correct pts for remaining data - could be used to flush
2469 // remaining buffer when closing ao.
2470 ao->pts += played / bps;
2472 return played;
2475 #define ASYNC_PLAY_DONE -3
2476 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2478 struct ao *ao = mpctx->ao;
2479 struct MPOpts *opts = &mpctx->opts;
2480 sh_audio_t * const sh_audio = mpctx->sh_audio;
2481 int res;
2483 // Timing info may not be set without
2484 res = decode_audio(sh_audio, &ao->buffer, 1);
2485 if (res < 0)
2486 return res;
2488 int bytes;
2489 bool did_retry = false;
2490 double written_pts;
2491 double bps = ao->bps / opts->playback_speed;
2492 while (1) {
2493 written_pts = written_audio_pts(mpctx);
2494 double ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2495 - audio_delay;
2496 bytes = ptsdiff * bps;
2497 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2499 // ogg demuxers give packets without timing
2500 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2501 if (!did_retry) {
2502 // Try to read more data to see packets that have pts
2503 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2504 if (res < 0)
2505 return res;
2506 did_retry = true;
2507 continue;
2509 bytes = 0;
2512 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2513 bytes = 0;
2515 if (bytes > 0)
2516 break;
2518 mpctx->syncing_audio = false;
2519 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2520 int res = decode_audio(sh_audio, &ao->buffer, a);
2521 bytes += ao->buffer.len;
2522 if (bytes >= 0) {
2523 memmove(ao->buffer.start,
2524 ao->buffer.start + ao->buffer.len - bytes, bytes);
2525 ao->buffer.len = bytes;
2526 if (res < 0)
2527 return res;
2528 return decode_audio(sh_audio, &ao->buffer, playsize);
2530 ao->buffer.len = 0;
2531 if (res < 0)
2532 return res;
2534 int fillbyte = 0;
2535 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2536 fillbyte = 0x80;
2537 if (bytes >= playsize) {
2538 /* This case could fall back to the one below with
2539 * bytes = playsize, but then silence would keep accumulating
2540 * in a_out_buffer if the AO accepts less data than it asks for
2541 * in playsize. */
2542 char *p = malloc(playsize);
2543 memset(p, fillbyte, playsize);
2544 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2545 free(p);
2546 return ASYNC_PLAY_DONE;
2548 mpctx->syncing_audio = false;
2549 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2550 return decode_audio(sh_audio, &ao->buffer, playsize);
2553 static int fill_audio_out_buffers(struct MPContext *mpctx)
2555 struct MPOpts *opts = &mpctx->opts;
2556 struct ao *ao = mpctx->ao;
2557 unsigned int t;
2558 double tt;
2559 int playsize;
2560 int playflags = 0;
2561 bool audio_eof = false;
2562 bool partial_fill = false;
2563 sh_audio_t * const sh_audio = mpctx->sh_audio;
2564 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2565 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2567 current_module = "play_audio";
2569 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2570 return 0;
2572 // hack used by some mpeg-writing AOs
2573 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2574 mpctx->delay) * 90000.0;
2576 if (mpctx->paused)
2577 playsize = 1; // just initialize things (audio pts at least)
2578 else
2579 playsize = ao_get_space(ao);
2581 // Fill buffer if needed:
2582 current_module = "decode_audio";
2583 t = GetTimer();
2585 if (!opts->initial_audio_sync || !modifiable_audio_format)
2586 mpctx->syncing_audio = false;
2588 int res;
2589 if (mpctx->syncing_audio && mpctx->sh_video)
2590 res = audio_start_sync(mpctx, playsize);
2591 else
2592 res = decode_audio(sh_audio, &ao->buffer, playsize);
2593 if (res < 0) { // EOF, error or format change
2594 if (res == -2) {
2595 /* The format change isn't handled too gracefully. A more precise
2596 * implementation would require draining buffered old-format audio
2597 * while displaying video, then doing the output format switch.
2599 uninit_player(mpctx, INITIALIZED_AO);
2600 reinit_audio_chain(mpctx);
2601 return -1;
2602 } else if (res == ASYNC_PLAY_DONE)
2603 return 0;
2604 else if (mpctx->d_audio->eof)
2605 audio_eof = true;
2607 t = GetTimer() - t;
2608 tt = t * 0.000001f;
2609 audio_time_usage += tt;
2610 if (mpctx->timeline && modifiable_audio_format) {
2611 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2612 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2613 * ao->bps / opts->playback_speed;
2614 if (playsize > bytes) {
2615 playsize = FFMAX(bytes, 0);
2616 playflags |= AOPLAY_FINAL_CHUNK;
2617 audio_eof = true;
2618 partial_fill = true;
2622 assert(ao->buffer.len % unitsize == 0);
2623 if (playsize > ao->buffer.len) {
2624 partial_fill = true;
2625 playsize = ao->buffer.len;
2626 if (audio_eof)
2627 playflags |= AOPLAY_FINAL_CHUNK;
2629 playsize -= playsize % unitsize;
2630 if (!playsize)
2631 return partial_fill && audio_eof ? -2 : -partial_fill;
2633 // play audio:
2634 current_module = "play_audio";
2636 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2637 written_audio_pts(mpctx));
2638 assert(played % unitsize == 0);
2639 ao->buffer_playable_size = playsize - played;
2641 if (played > 0) {
2642 ao->buffer.len -= played;
2643 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2644 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2645 // Sanity check to avoid hanging in case current ao doesn't output
2646 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2647 return -2;
2650 return -partial_fill;
2653 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2654 bool sync_to_audio, float *aq_sleep_time)
2656 struct MPOpts *opts = &mpctx->opts;
2657 double audio_limit = 2;
2658 current_module = "calc_sleep_time";
2660 if (mpctx->restart_playback)
2661 return 0;
2663 *time_frame -= get_relative_time(mpctx); // reset timer
2665 if (sync_to_audio) {
2666 float delay = ao_get_delay(mpctx->ao);
2667 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2669 if (opts->autosync) {
2671 * Adjust this raw delay value by calculating the expected
2672 * delay for this frame and generating a new value which is
2673 * weighted between the two. The higher autosync is, the
2674 * closer to the delay value gets to that which "-nosound"
2675 * would have used, and the longer it will take for A/V
2676 * sync to settle at the right value (but it eventually will.)
2677 * This settling time is very short for values below 100.
2679 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2680 float difference = delay - predicted;
2681 delay = predicted + difference / (float)opts->autosync;
2684 *time_frame = delay - mpctx->delay / opts->playback_speed;
2686 // delay = amount of audio buffered in soundcard/driver
2687 delay = FFMIN(delay, 0.5);
2688 delay = FFMAX(delay, 0.1);
2689 audio_limit = delay;
2690 } else {
2691 // If we're lagging more than 200 ms behind the right playback rate,
2692 // don't try to "catch up".
2693 // If benchmark is set always output frames as fast as possible
2694 // without sleeping.
2695 if (*time_frame < -0.2 || opts->benchmark)
2696 *time_frame = 0;
2699 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2701 if (t <= 0.05)
2702 return 0;
2704 t -= 0.05;
2705 if (t > audio_limit * 0.6)
2706 t = audio_limit * 0.5;
2707 *aq_sleep_time += t;
2708 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2709 return 1;
2712 int reinit_video_chain(struct MPContext *mpctx)
2714 struct MPOpts *opts = &mpctx->opts;
2715 sh_video_t * const sh_video = mpctx->sh_video;
2716 if (!sh_video)
2717 return 0;
2718 double ar = -1.0;
2719 //================== Init VIDEO (codec & libvo) ==========================
2720 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2721 current_module = "preinit_libvo";
2723 //shouldn't we set dvideo->id=-2 when we fail?
2724 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2725 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2726 mpctx->key_fifo,
2727 mpctx->input))) {
2728 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2729 "the selected video_out (-vo) device.\n");
2730 goto err_out;
2732 mpctx->initialized_flags |= INITIALIZED_VO;
2735 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2736 &ar) != STREAM_UNSUPPORTED)
2737 mpctx->sh_video->stream_aspect = ar;
2738 current_module = "init_video_filters";
2740 char *vf_arg[] = {
2741 "_oldargs_", (char *)mpctx->video_out, NULL
2743 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2745 #ifdef CONFIG_MENU
2746 if (use_menu) {
2747 char *vf_arg[] = {
2748 "_oldargs_", menu_root, NULL
2750 vf_menu = vf_open_plugin(opts, libmenu_vfs, sh_video->vfilter, "menu",
2751 vf_arg);
2752 if (!vf_menu) {
2753 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open libmenu video filter "
2754 "with root menu %s.\n", menu_root);
2755 use_menu = 0;
2758 if (vf_menu)
2759 sh_video->vfilter = vf_menu;
2760 #endif
2762 #ifdef CONFIG_ASS
2763 if (opts->ass_enabled) {
2764 int i;
2765 int insert = 1;
2766 if (opts->vf_settings)
2767 for (i = 0; opts->vf_settings[i].name; ++i)
2768 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2769 insert = 0;
2770 break;
2772 if (insert) {
2773 extern vf_info_t vf_info_ass;
2774 const vf_info_t *libass_vfs[] = {
2775 &vf_info_ass, NULL
2777 char *vf_arg[] = {
2778 "auto", "1", NULL
2780 int retcode = 0;
2781 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2782 sh_video->vfilter,
2783 "ass", vf_arg,
2784 &retcode);
2785 if (vf_ass)
2786 sh_video->vfilter = vf_ass;
2787 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2788 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2789 else
2790 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2791 "ASS: cannot add video filter\n");
2794 #endif
2796 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2798 #ifdef CONFIG_ASS
2799 if (opts->ass_enabled)
2800 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2801 mpctx->ass_library);
2802 #endif
2804 current_module = "init_video_codec";
2806 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2807 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2808 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2810 if (!sh_video->initialized) {
2811 if (!opts->fixed_vo)
2812 uninit_player(mpctx, INITIALIZED_VO);
2813 goto err_out;
2816 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2818 if (sh_video->codec)
2819 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2820 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2822 sh_video->last_pts = MP_NOPTS_VALUE;
2823 sh_video->num_buffered_pts = 0;
2824 sh_video->next_frame_time = 0;
2826 if (opts->auto_quality > 0) {
2827 // Auto quality option enabled
2828 output_quality = get_video_quality_max(sh_video);
2829 if (opts->auto_quality > output_quality)
2830 opts->auto_quality = output_quality;
2831 else
2832 output_quality = opts->auto_quality;
2833 mp_msg(MSGT_CPLAYER, MSGL_V,
2834 "AutoQ: setting quality to %d.\n", output_quality);
2835 set_video_quality(sh_video, output_quality);
2838 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2840 current_module = "init_vo";
2842 return 1;
2844 err_out:
2845 mpctx->sh_video = mpctx->d_video->sh = NULL;
2846 return 0;
2849 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2851 struct sh_video *sh_video = mpctx->sh_video;
2852 double frame_time = 0;
2853 struct vo *video_out = mpctx->video_out;
2854 while (1) {
2855 current_module = "filter_video";
2856 // In nocorrect-pts mode there is no way to properly time these frames
2857 if (vo_get_buffered_frame(video_out, 0) >= 0)
2858 break;
2859 if (vf_output_queued_frame(sh_video->vfilter))
2860 break;
2861 unsigned char *packet = NULL;
2862 frame_time = sh_video->next_frame_time;
2863 if (mpctx->restart_playback)
2864 frame_time = 0;
2865 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2866 &packet, force_fps);
2867 if (in_size < 0) {
2868 #ifdef CONFIG_DVDNAV
2869 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2870 if (mp_dvdnav_is_eof(mpctx->stream))
2871 return -1;
2872 if (mpctx->d_video)
2873 mpctx->d_video->eof = 0;
2874 if (mpctx->d_audio)
2875 mpctx->d_audio->eof = 0;
2876 mpctx->stream->eof = 0;
2877 } else
2878 #endif
2879 return -1;
2881 if (in_size > max_framesize)
2882 max_framesize = in_size;
2883 sh_video->timer += frame_time;
2884 if (mpctx->sh_audio)
2885 mpctx->delay -= frame_time;
2886 // video_read_frame can change fps (e.g. for ASF video)
2887 vo_fps = sh_video->fps;
2888 int framedrop_type = check_framedrop(mpctx, frame_time);
2889 current_module = "decode video";
2891 void *decoded_frame;
2892 #ifdef CONFIG_DVDNAV
2893 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2894 if (in_size >= 0 && !decoded_frame)
2895 #endif
2896 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2897 sh_video->pts);
2898 #ifdef CONFIG_DVDNAV
2899 // Save last still frame for future display
2900 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2901 #endif
2902 if (decoded_frame) {
2903 current_module = "filter video";
2904 filter_video(sh_video, decoded_frame, sh_video->pts);
2906 break;
2908 return frame_time;
2911 static void determine_frame_pts(struct MPContext *mpctx)
2913 struct sh_video *sh_video = mpctx->sh_video;
2914 struct MPOpts *opts = &mpctx->opts;
2916 if (opts->user_pts_assoc_mode)
2917 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2918 else if (sh_video->pts_assoc_mode == 0) {
2919 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2920 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2921 sh_video->pts_assoc_mode = 1;
2922 else
2923 sh_video->pts_assoc_mode = 2;
2924 } else {
2925 int probcount1 = sh_video->num_reordered_pts_problems;
2926 int probcount2 = sh_video->num_sorted_pts_problems;
2927 if (sh_video->pts_assoc_mode == 2) {
2928 int tmp = probcount1;
2929 probcount1 = probcount2;
2930 probcount2 = tmp;
2932 if (probcount1 >= probcount2 * 1.5 + 2) {
2933 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2934 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2935 "%d.\n", sh_video->pts_assoc_mode);
2938 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2939 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2942 static double update_video(struct MPContext *mpctx)
2944 struct sh_video *sh_video = mpctx->sh_video;
2945 struct vo *video_out = mpctx->video_out;
2946 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2947 mpctx->osd); // hack for vf_expand
2948 if (!mpctx->opts.correct_pts)
2949 return update_video_nocorrect_pts(mpctx);
2951 double pts;
2953 while (1) {
2954 current_module = "filter_video";
2955 if (!mpctx->hrseek_active
2956 && vo_get_buffered_frame(video_out, false) >= 0)
2957 break;
2958 // XXX Time used in this call is not counted in any performance
2959 // timer now
2960 if (vf_output_queued_frame(sh_video->vfilter))
2961 break;
2962 unsigned char *packet = NULL;
2963 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2964 if (pts != MP_NOPTS_VALUE)
2965 pts += mpctx->video_offset;
2966 bool hit_eof = false;
2967 if (in_size < 0) {
2968 // try to extract last frames in case of decoder lag
2969 in_size = 0;
2970 pts = MP_NOPTS_VALUE;
2971 hit_eof = true;
2973 if (in_size > max_framesize)
2974 max_framesize = in_size;
2975 current_module = "decode video";
2976 if (pts >= mpctx->hrseek_pts - .005)
2977 mpctx->hrseek_framedrop = false;
2978 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2979 check_framedrop(mpctx, sh_video->frametime);
2980 void *decoded_frame = decode_video(sh_video, packet, in_size,
2981 framedrop_type, pts);
2982 if (decoded_frame) {
2983 determine_frame_pts(mpctx);
2984 current_module = "filter video";
2985 filter_video(sh_video, decoded_frame, sh_video->pts);
2986 } else if (hit_eof) {
2987 if (vo_get_buffered_frame(video_out, true) < 0)
2988 return -1;
2990 break;
2993 if (!video_out->frame_loaded)
2994 return 0;
2996 pts = video_out->next_pts;
2997 if (pts == MP_NOPTS_VALUE) {
2998 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2999 // Try to use decoder pts from before filters
3000 pts = sh_video->pts;
3001 if (pts == MP_NOPTS_VALUE)
3002 pts = sh_video->last_pts;
3004 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
3005 vo_skip_frame(video_out);
3006 return 0;
3008 mpctx->hrseek_active = false;
3009 sh_video->pts = pts;
3010 if (sh_video->last_pts == MP_NOPTS_VALUE)
3011 sh_video->last_pts = sh_video->pts;
3012 else if (sh_video->last_pts > sh_video->pts) {
3013 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
3014 sh_video->pts, sh_video->last_pts);
3015 /* If the difference in pts is small treat it as jitter around the
3016 * right value (possibly caused by incorrect timestamp ordering) and
3017 * just show this frame immediately after the last one.
3018 * Treat bigger differences as timestamp resets and start counting
3019 * timing of later frames from the position of this one. */
3020 if (sh_video->last_pts - sh_video->pts > 0.5)
3021 sh_video->last_pts = sh_video->pts;
3022 else
3023 sh_video->pts = sh_video->last_pts;
3025 double frame_time = sh_video->pts - sh_video->last_pts;
3026 sh_video->last_pts = sh_video->pts;
3027 sh_video->timer += frame_time;
3028 if (mpctx->sh_audio)
3029 mpctx->delay -= frame_time;
3030 return frame_time;
3033 void pause_player(struct MPContext *mpctx)
3035 if (mpctx->paused)
3036 return;
3037 mpctx->paused = 1;
3038 mpctx->step_frames = 0;
3039 mpctx->time_frame -= get_relative_time(mpctx);
3041 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3042 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3044 if (mpctx->ao && mpctx->sh_audio)
3045 ao_pause(mpctx->ao); // pause audio, keep data if possible
3048 void unpause_player(struct MPContext *mpctx)
3050 if (!mpctx->paused)
3051 return;
3052 mpctx->paused = 0;
3054 if (mpctx->ao && mpctx->sh_audio)
3055 ao_resume(mpctx->ao);
3056 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3057 && !mpctx->step_frames)
3058 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3059 (void)get_relative_time(mpctx); // ignore time that passed during pause
3062 void add_step_frame(struct MPContext *mpctx)
3064 mpctx->step_frames++;
3065 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3066 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3067 unpause_player(mpctx);
3070 static void pause_loop(struct MPContext *mpctx)
3072 struct MPOpts *opts = &mpctx->opts;
3073 mp_cmd_t *cmd;
3074 #ifdef CONFIG_STREAM_CACHE
3075 int old_cache_fill = stream_cache_size > 0 ?
3076 cache_fill_status(mpctx->stream) : 0;
3077 #endif
3078 if (!opts->quiet) {
3079 if (opts->term_osd && !mpctx->sh_video) {
3080 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
3081 update_osd_msg(mpctx);
3082 } else
3083 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
3084 mp_gtext(" ===== PAUSE ====="));
3085 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
3088 while ((cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
3089 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
3090 if (cmd) {
3091 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3092 run_command(mpctx, cmd);
3093 mp_cmd_free(cmd);
3094 continue;
3096 if (mpctx->sh_video && mpctx->video_out)
3097 vo_check_events(mpctx->video_out);
3098 #ifdef CONFIG_MENU
3099 if (vf_menu)
3100 vf_menu_pause_update(vf_menu);
3101 #endif
3102 usec_sleep(20000);
3103 update_osd_msg(mpctx);
3104 int hack = vo_osd_changed(0);
3105 vo_osd_changed(hack);
3106 if (hack)
3107 break;
3108 #ifdef CONFIG_STREAM_CACHE
3109 if (!opts->quiet && stream_cache_size > 0) {
3110 int new_cache_fill = cache_fill_status(mpctx->stream);
3111 if (new_cache_fill != old_cache_fill) {
3112 if (opts->term_osd && !mpctx->sh_video) {
3113 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
3114 mp_gtext(" ===== PAUSE ====="),
3115 new_cache_fill);
3116 update_osd_msg(mpctx);
3117 } else
3118 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
3119 mp_gtext(" ===== PAUSE ====="),
3120 new_cache_fill);
3121 old_cache_fill = new_cache_fill;
3124 #endif
3129 // Find the right mute status and record position for new file position
3130 static void edl_seek_reset(MPContext *mpctx)
3132 mpctx->edl_muted = 0;
3133 next_edl_record = edl_records;
3135 while (next_edl_record) {
3136 if (next_edl_record->start_sec >= get_current_time(mpctx))
3137 break;
3139 if (next_edl_record->action == EDL_MUTE)
3140 mpctx->edl_muted = !mpctx->edl_muted;
3141 next_edl_record = next_edl_record->next;
3143 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3144 mixer_mute(&mpctx->mixer);
3148 // Execute EDL command for the current position if one exists
3149 static void edl_update(MPContext *mpctx)
3151 if (!next_edl_record)
3152 return;
3154 if (!mpctx->sh_video) {
3155 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
3156 "Cannot use EDL without video, disabling.\n");
3157 free_edl(edl_records);
3158 next_edl_record = NULL;
3159 edl_records = NULL;
3160 return;
3163 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3164 if (next_edl_record->action == EDL_SKIP) {
3165 mpctx->osd_function = OSD_FFW;
3166 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3167 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3168 "[%f], length [%f]\n", next_edl_record->start_sec,
3169 next_edl_record->stop_sec, next_edl_record->length_sec);
3170 } else if (next_edl_record->action == EDL_MUTE) {
3171 mpctx->edl_muted = !mpctx->edl_muted;
3172 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3173 mixer_mute(&mpctx->mixer);
3174 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3175 next_edl_record->start_sec);
3177 next_edl_record = next_edl_record->next;
3181 static void reinit_decoders(struct MPContext *mpctx)
3183 reinit_video_chain(mpctx);
3184 reinit_audio_chain(mpctx);
3185 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3188 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3190 if (mpctx->sh_video) {
3191 current_module = "seek_video_reset";
3192 resync_video_stream(mpctx->sh_video);
3193 mpctx->sh_video->timer = 0;
3194 vo_seek_reset(mpctx->video_out);
3195 mpctx->sh_video->timer = 0;
3196 mpctx->sh_video->num_buffered_pts = 0;
3197 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3198 mpctx->delay = 0;
3199 mpctx->time_frame = 0;
3200 mpctx->restart_playback = true;
3201 // Not all demuxers set d_video->pts during seek, so this value
3202 // (which is used by at least vobsub and edl code below) may
3203 // be completely wrong (probably 0).
3204 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3205 mpctx->video_pts = mpctx->sh_video->pts;
3206 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3207 true);
3208 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3211 if (mpctx->sh_audio) {
3212 current_module = "seek_audio_reset";
3213 resync_audio_stream(mpctx->sh_audio);
3214 if (reset_ao)
3215 ao_reset(mpctx->ao);
3216 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3217 mpctx->sh_audio->a_buffer_len = 0;
3218 if (!mpctx->sh_video)
3219 update_subtitles(mpctx, mpctx->sh_audio->pts,
3220 mpctx->video_offset, true);
3223 if (vo_vobsub && mpctx->sh_video) {
3224 current_module = "seek_vobsub_reset";
3225 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3228 edl_seek_reset(mpctx);
3230 mpctx->hrseek_active = false;
3231 mpctx->hrseek_framedrop = false;
3232 mpctx->total_avsync_change = 0;
3233 audio_time_usage = 0;
3234 video_time_usage = 0;
3235 vout_time_usage = 0;
3236 drop_frame_cnt = 0;
3238 current_module = NULL;
3241 static bool timeline_set_part(struct MPContext *mpctx, int i)
3243 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3244 struct timeline_part *n = mpctx->timeline + i;
3245 mpctx->timeline_part = i;
3246 mpctx->video_offset = n->start - n->source_start;
3247 if (n->source == p->source)
3248 return false;
3249 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3250 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3251 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3252 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3253 mpctx->stop_play = orig_stop_play;
3254 mpctx->demuxer = n->source->demuxer;
3255 mpctx->d_video = mpctx->demuxer->video;
3256 mpctx->d_audio = mpctx->demuxer->audio;
3257 mpctx->d_sub = mpctx->demuxer->sub;
3258 mpctx->sh_video = mpctx->d_video->sh;
3259 mpctx->sh_audio = mpctx->d_audio->sh;
3260 return true;
3263 // Given pts, switch playback to the corresponding part.
3264 // Return offset within that part.
3265 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3266 bool *need_reset)
3268 if (pts < 0)
3269 pts = 0;
3270 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3271 struct timeline_part *p = mpctx->timeline + i;
3272 if (pts < (p + 1)->start) {
3273 *need_reset = timeline_set_part(mpctx, i);
3274 return pts - p->start + p->source_start;
3277 return -1;
3281 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3282 static int seek(MPContext *mpctx, struct seek_params seek,
3283 bool timeline_fallthrough)
3285 struct MPOpts *opts = &mpctx->opts;
3287 current_module = "seek";
3288 if (mpctx->stop_play == AT_END_OF_FILE)
3289 mpctx->stop_play = KEEP_PLAYING;
3290 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3291 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3292 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3293 || opts->hr_seek > 0 || seek.exact > 0;
3294 if (seek.type == MPSEEK_FACTOR
3295 || seek.type == MPSEEK_ABSOLUTE
3296 && seek.amount < mpctx->last_chapter_pts
3297 || seek.amount < 0)
3298 mpctx->last_chapter_seek = -2;
3299 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3300 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3301 seek.type = MPSEEK_ABSOLUTE;
3303 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3304 && seek.type == MPSEEK_RELATIVE) {
3305 seek.type = MPSEEK_ABSOLUTE;
3306 seek.direction = seek.amount > 0 ? 1 : -1;
3307 seek.amount += get_current_time(mpctx);
3310 /* At least the liba52 decoder wants to read from the input stream
3311 * during initialization, so reinit must be done after the demux_seek()
3312 * call that clears possible stream EOF. */
3313 bool need_reset = false;
3314 double demuxer_amount = seek.amount;
3315 if (mpctx->timeline) {
3316 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3317 &need_reset);
3318 if (demuxer_amount == -1) {
3319 mpctx->stop_play = AT_END_OF_FILE;
3320 // Clear audio from current position
3321 if (mpctx->sh_audio) {
3322 ao_reset(mpctx->ao);
3323 mpctx->sh_audio->a_buffer_len = 0;
3325 return -1;
3328 int demuxer_style = 0;
3329 switch (seek.type) {
3330 case MPSEEK_FACTOR:
3331 demuxer_style |= SEEK_FACTOR; // fallthrough
3332 case MPSEEK_ABSOLUTE:
3333 demuxer_style |= SEEK_ABSOLUTE;
3335 if (hr_seek || seek.direction < 0)
3336 demuxer_style |= SEEK_BACKWARD;
3337 else if (seek.direction > 0)
3338 demuxer_style |= SEEK_FORWARD;
3340 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3341 demuxer_style);
3342 if (need_reset)
3343 reinit_decoders(mpctx);
3344 if (seekresult == 0)
3345 return -1;
3347 seek_reset(mpctx, !timeline_fallthrough);
3349 /* Use the target time as "current position" for further relative
3350 * seeks etc until a new video frame has been decoded */
3351 if (seek.type == MPSEEK_ABSOLUTE) {
3352 mpctx->video_pts = seek.amount;
3353 mpctx->last_seek_pts = seek.amount;
3354 } else
3355 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3357 if (hr_seek) {
3358 mpctx->hrseek_active = true;
3359 mpctx->hrseek_framedrop = true;
3360 mpctx->hrseek_pts = seek.amount;
3363 mpctx->start_timestamp = GetTimerMS();
3365 return 0;
3368 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3369 int exact)
3371 struct seek_params *seek = &mpctx->seek;
3372 switch (type) {
3373 case MPSEEK_RELATIVE:
3374 if (seek->type == MPSEEK_FACTOR)
3375 return; // Well... not common enough to bother doing better
3376 seek->amount += amount;
3377 seek->exact = FFMAX(seek->exact, exact);
3378 if (seek->type == MPSEEK_NONE)
3379 seek->exact = exact;
3380 if (seek->type == MPSEEK_ABSOLUTE)
3381 return;
3382 if (seek->amount == 0) {
3383 *seek = (struct seek_params){ 0 };
3384 return;
3386 seek->type = MPSEEK_RELATIVE;
3387 return;
3388 case MPSEEK_ABSOLUTE:
3389 case MPSEEK_FACTOR:
3390 *seek = (struct seek_params) {
3391 .type = type,
3392 .amount = amount,
3393 .exact = exact,
3395 return;
3396 case MPSEEK_NONE:
3397 *seek = (struct seek_params){ 0 };
3398 return;
3400 abort();
3404 double get_time_length(struct MPContext *mpctx)
3406 if (mpctx->timeline)
3407 return mpctx->timeline[mpctx->num_timeline_parts].start;
3409 struct demuxer *demuxer = mpctx->demuxer;
3410 double get_time_ans;
3411 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3412 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3413 (void *) &get_time_ans) > 0)
3414 return get_time_ans;
3416 struct sh_video *sh_video = mpctx->d_video->sh;
3417 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3418 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3419 return (double) (demuxer->movi_end - demuxer->movi_start) /
3420 (sh_video->i_bps + sh_audio->i_bps);
3421 if (sh_video && sh_video->i_bps)
3422 return (double) (demuxer->movi_end - demuxer->movi_start) /
3423 sh_video->i_bps;
3424 if (sh_audio && sh_audio->i_bps)
3425 return (double) (demuxer->movi_end - demuxer->movi_start) /
3426 sh_audio->i_bps;
3427 return 0;
3430 /* If there are timestamps from stream level then use those (for example
3431 * DVDs can have consistent times there while the MPEG-level timestamps
3432 * reset). */
3433 double get_current_time(struct MPContext *mpctx)
3435 struct demuxer *demuxer = mpctx->demuxer;
3436 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3437 return demuxer->stream_pts;
3438 struct sh_video *sh_video = demuxer->video->sh;
3439 if (sh_video)
3440 return mpctx->video_pts;
3441 double apts = playing_audio_pts(mpctx);
3442 if (apts != MP_NOPTS_VALUE)
3443 return apts;
3444 return mpctx->last_seek_pts;
3447 int get_percent_pos(struct MPContext *mpctx)
3449 struct demuxer *demuxer = mpctx->demuxer;
3450 int ans = 0;
3451 if (mpctx->timeline)
3452 ans = get_current_time(mpctx) * 100 /
3453 mpctx->timeline[mpctx->num_timeline_parts].start;
3454 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3456 else {
3457 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3458 off_t pos = demuxer->filepos > 0 ?
3459 demuxer->filepos : stream_tell(demuxer->stream);
3460 if (len > 0)
3461 ans = (pos - demuxer->movi_start) / len;
3462 else
3463 ans = 0;
3465 if (ans < 0)
3466 ans = 0;
3467 if (ans > 100)
3468 ans = 100;
3469 return ans;
3472 // -2 is no chapters, -1 is before first chapter
3473 int get_current_chapter(struct MPContext *mpctx)
3475 double current_pts = get_current_time(mpctx);
3476 if (!mpctx->chapters)
3477 return FFMAX(mpctx->last_chapter_seek,
3478 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3480 int i;
3481 for (i = 1; i < mpctx->num_chapters; i++)
3482 if (current_pts < mpctx->chapters[i].start)
3483 break;
3484 return FFMAX(mpctx->last_chapter_seek, i - 1);
3487 // currently returns a string allocated with malloc, not talloc
3488 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3490 if (!mpctx->chapters)
3491 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3492 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3495 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3496 char **chapter_name)
3498 mpctx->last_chapter_seek = -2;
3499 if (!mpctx->chapters) {
3500 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3501 chapter_name);
3502 if (res >= 0) {
3503 if (*seek_pts == -1)
3504 seek_reset(mpctx, true);
3505 else {
3506 mpctx->last_chapter_seek = res;
3507 mpctx->last_chapter_pts = *seek_pts;
3510 return res;
3513 if (chapter >= mpctx->num_chapters)
3514 return -1;
3515 if (chapter < 0)
3516 chapter = 0;
3517 *seek_pts = mpctx->chapters[chapter].start;
3518 mpctx->last_chapter_seek = chapter;
3519 mpctx->last_chapter_pts = *seek_pts;
3520 if (chapter_name)
3521 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3522 return chapter;
3526 static void run_playloop(struct MPContext *mpctx)
3528 struct MPOpts *opts = &mpctx->opts;
3529 float aq_sleep_time = 0;
3530 bool full_audio_buffers = false;
3532 if (opts->chapterrange[1] > 0) {
3533 int cur_chapter = get_current_chapter(mpctx);
3534 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3535 mpctx->stop_play = PT_NEXT_ENTRY;
3538 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3539 mpctx->sh_audio = mpctx->d_audio->sh;
3540 mpctx->sh_audio->ds = mpctx->d_audio;
3541 reinit_audio_chain(mpctx);
3544 /*========================== PLAY AUDIO ============================*/
3546 if (!mpctx->sh_video)
3547 mpctx->restart_playback = false;
3549 if (mpctx->sh_audio && !mpctx->restart_playback) {
3550 int status = fill_audio_out_buffers(mpctx);
3551 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3552 if (status == -2)
3553 // at eof, all audio at least written to ao
3554 if (!mpctx->sh_video)
3555 mpctx->stop_play = AT_END_OF_FILE;
3559 if (!mpctx->sh_video) {
3560 if (mpctx->step_frames) {
3561 mpctx->step_frames = 0;
3562 pause_player(mpctx);
3564 // handle audio-only case:
3565 double a_pos = 0, a_buf = 0;
3566 // sh_audio can be NULL due to video stream switching
3567 // TODO: handle this better
3568 if (mpctx->sh_audio) {
3569 a_buf = ao_get_delay(mpctx->ao);
3570 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3571 a_buf;
3574 print_status(mpctx, a_pos, false);
3576 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3577 update_osd_msg(mpctx);
3578 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3579 mpctx->stop_play = AT_END_OF_FILE;
3580 else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3581 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3582 && mpctx->sh_audio) {
3583 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3584 if (!opts->gapless_audio && p->source != (p + 1)->source
3585 && a_buf > 0.05) {
3586 mpctx->stop_play = KEEP_PLAYING;
3587 mp_input_get_cmd(mpctx->input, (a_buf - .05) * 1000, true);
3588 } else {
3589 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3590 .amount = (p + 1)->start },
3591 true);
3593 } else if (!mpctx->stop_play) {
3594 int sleep_time = 100;
3595 if (mpctx->sh_audio) {
3596 if (mpctx->ao->untimed)
3597 sleep_time = 0;
3598 else if (full_audio_buffers)
3599 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3600 else
3601 sleep_time = 20;
3602 sleep_time = FFMIN(sleep_time, 100);
3604 mp_input_get_cmd(mpctx->input, sleep_time, true);
3606 } else {
3608 /*========================== PLAY VIDEO ============================*/
3610 vo_pts = mpctx->sh_video->timer * 90000.0;
3611 vo_fps = mpctx->sh_video->fps;
3613 bool blit_frame = mpctx->video_out->frame_loaded;
3614 if (!blit_frame || mpctx->hrseek_active) {
3615 double frame_time = update_video(mpctx);
3616 blit_frame = mpctx->video_out->frame_loaded;
3617 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3618 if (mpctx->sh_video->vf_initialized < 0) {
3619 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3620 "\nFATAL: Could not initialize video filters (-vf) "
3621 "or video output (-vo).\n");
3622 mpctx->stop_play = PT_NEXT_ENTRY;
3623 return;
3625 if (frame_time < 0)
3626 mpctx->stop_play = AT_END_OF_FILE;
3627 else if (!mpctx->restart_playback) {
3628 mpctx->time_frame += frame_time / opts->playback_speed;
3629 adjust_sync(mpctx, frame_time);
3632 if (mpctx->timeline) {
3633 struct timeline_part *next =
3634 mpctx->timeline + mpctx->timeline_part + 1;
3635 if (mpctx->sh_video->pts >= next->start
3636 || mpctx->stop_play == AT_END_OF_FILE
3637 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3638 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3639 .amount = next->start },
3640 true);
3641 return;
3645 // ==========================================================================
3647 current_module = "vo_check_events";
3648 vo_check_events(mpctx->video_out);
3650 #ifdef CONFIG_X11
3651 if (stop_xscreensaver) {
3652 current_module = "stop_xscreensaver";
3653 xscreensaver_heartbeat(mpctx->x11_state);
3655 #endif
3656 if (heartbeat_cmd) {
3657 static unsigned last_heartbeat;
3658 unsigned now = GetTimerMS();
3659 if (now - last_heartbeat > 30000) {
3660 last_heartbeat = now;
3661 system(heartbeat_cmd);
3665 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3666 &mpctx->time_frame,
3667 full_audio_buffers,
3668 &aq_sleep_time);
3670 //====================== FLIP PAGE (VIDEO BLT): =========================
3672 current_module = "flip_page";
3673 if (!frame_time_remaining && blit_frame) {
3674 struct sh_video *sh_video = mpctx->sh_video;
3675 mpctx->video_pts = sh_video->pts;
3676 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3677 update_teletext(sh_video, mpctx->demuxer, 0);
3678 update_osd_msg(mpctx);
3679 struct vf_instance *vf = sh_video->vfilter;
3680 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3681 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3682 vo_osd_changed(0);
3684 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3685 aq_sleep_time += mpctx->time_frame;
3686 // flag 256 means: libvo driver does its timing (dvb card)
3687 if (mpctx->time_frame > 0.001
3688 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3689 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3690 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3692 unsigned int t2 = GetTimer();
3693 /* Playing with playback speed it's possible to get pathological
3694 * cases with mpctx->time_frame negative enough to cause an
3695 * overflow in pts_us calculation, thus the FFMAX. */
3696 double time_frame = FFMAX(mpctx->time_frame, -1);
3697 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3698 int duration = -1;
3699 double pts2 = mpctx->video_out->next_pts2;
3700 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3701 && !mpctx->restart_playback) {
3702 // expected A/V sync correction is ignored
3703 double diff = (pts2 - mpctx->video_pts);
3704 diff /= opts->playback_speed;
3705 if (mpctx->time_frame < 0)
3706 diff += mpctx->time_frame;
3707 if (diff < 0)
3708 diff = 0;
3709 if (diff > 10)
3710 diff = 10;
3711 duration = diff * 1e6;
3713 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3715 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3716 vout_time_usage += mpctx->last_vo_flip_duration;
3717 if (mpctx->video_out->driver->flip_page_timed) {
3718 // No need to adjust sync based on flip speed
3719 mpctx->last_vo_flip_duration = 0;
3720 // For print_status - VO call finishing early is OK for sync
3721 mpctx->time_frame -= get_relative_time(mpctx);
3723 if (mpctx->restart_playback) {
3724 mpctx->syncing_audio = true;
3725 if (mpctx->sh_audio)
3726 fill_audio_out_buffers(mpctx);
3727 mpctx->restart_playback = false;
3728 mpctx->time_frame = 0;
3729 get_relative_time(mpctx);
3731 print_status(mpctx, MP_NOPTS_VALUE, true);
3732 } else
3733 print_status(mpctx, MP_NOPTS_VALUE, false);
3735 //============================ Auto QUALITY ============================
3737 /*Output quality adjustments:*/
3738 if (opts->auto_quality > 0) {
3739 current_module = "autoq";
3740 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3741 ++output_quality;
3742 else if (output_quality > 1 && aq_sleep_time < 0)
3743 --output_quality;
3744 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3745 output_quality = 0;
3746 set_video_quality(mpctx->sh_video, output_quality);
3749 if (!frame_time_remaining && blit_frame) {
3750 if (play_n_frames >= 0) {
3751 --play_n_frames;
3752 if (play_n_frames <= 0)
3753 mpctx->stop_play = PT_NEXT_ENTRY;
3755 if (mpctx->step_frames > 0) {
3756 mpctx->step_frames--;
3757 if (mpctx->step_frames == 0)
3758 pause_player(mpctx);
3762 // FIXME: add size based support for -endpos
3763 if (end_at.type == END_AT_TIME &&
3764 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3765 mpctx->stop_play = PT_NEXT_ENTRY;
3767 } // end if(mpctx->sh_video)
3769 #ifdef CONFIG_DVDNAV
3770 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3771 nav_highlight_t hl;
3772 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3773 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3774 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3775 vo_osd_changed(OSDTYPE_DVDNAV);
3776 } else {
3777 osd_set_nav_box(0, 0, 0, 0);
3778 vo_osd_changed(OSDTYPE_DVDNAV);
3779 vo_osd_changed(OSDTYPE_SPU);
3782 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3783 double ar = -1.0;
3784 if (mpctx->sh_video &&
3785 stream_control(mpctx->demuxer->stream,
3786 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3787 != STREAM_UNSUPPORTED)
3788 mpctx->sh_video->stream_aspect = ar;
3791 #endif
3793 //================= Keyboard events, SEEKing ====================
3795 current_module = "key_events";
3797 while (1) {
3798 mp_cmd_t *cmd;
3799 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3800 /* Allow running consecutive seek commands to combine them,
3801 * but execute the seek before running other commands.
3802 * If the user seeks continuously (keeps arrow key down)
3803 * try to finish showing a frame from one location before doing
3804 * another seek (which could lead to unchanging display). */
3805 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3806 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3807 && GetTimerMS() - mpctx->start_timestamp < 300)
3808 break;
3809 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3810 run_command(mpctx, cmd);
3811 mp_cmd_free(cmd);
3812 if (mpctx->stop_play)
3813 break;
3815 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3816 || mpctx->restart_playback)
3817 break;
3818 if (mpctx->sh_video) {
3819 update_osd_msg(mpctx);
3820 int hack = vo_osd_changed(0);
3821 vo_osd_changed(hack);
3822 if (hack) {
3823 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3824 add_step_frame(mpctx);
3825 break;
3826 } else
3827 vo_osd_changed(0);
3830 pause_loop(mpctx);
3833 // handle -sstep
3834 if (step_sec > 0 && !mpctx->paused) {
3835 mpctx->osd_function = OSD_FFW;
3836 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3839 edl_update(mpctx);
3841 /* Looping. */
3842 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3843 mpctx->stop_play == PT_NEXT_ENTRY)) {
3844 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3846 if (opts->loop_times > 1)
3847 opts->loop_times--;
3848 else if (opts->loop_times == 1)
3849 opts->loop_times = -1;
3850 play_n_frames = play_n_frames_mf;
3851 mpctx->stop_play = 0;
3852 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3855 if (mpctx->seek.type) {
3856 seek(mpctx, mpctx->seek, false);
3857 mpctx->seek = (struct seek_params){ 0 };
3862 static int read_keys(void *ctx, int fd)
3864 getch2(ctx);
3865 return MP_INPUT_NOTHING;
3868 static bool attachment_is_font(struct demux_attachment *att)
3870 if (!att->name || !att->type || !att->data || !att->data_size)
3871 return false;
3872 // match against MIME types
3873 if (strcmp(att->type, "application/x-truetype-font") == 0
3874 || strcmp(att->type, "application/x-font") == 0)
3875 return true;
3876 // fallback: match against file extension
3877 if (strlen(att->name) > 4) {
3878 char *ext = att->name + strlen(att->name) - 4;
3879 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3880 || strcasecmp(ext, ".otf") == 0)
3881 return true;
3883 return false;
3886 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3888 if (audio_id == -1)
3889 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3890 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3891 demuxer_switch_audio(demuxer, audio_id);
3892 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3893 demuxer->audio->id = -2;
3894 demuxer->audio->sh = NULL;
3896 return demuxer->audio->id;
3899 static void print_version(const char *name)
3901 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3903 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3904 GetCpuCaps(&gCpuCaps);
3905 #if ARCH_X86
3906 mp_msg(MSGT_CPLAYER, MSGL_V,
3907 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3908 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3909 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3910 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3911 #if CONFIG_RUNTIME_CPUDETECT
3912 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3913 #else
3914 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3915 if (HAVE_MMX)
3916 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3917 if (HAVE_MMX2)
3918 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3919 if (HAVE_AMD3DNOW)
3920 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3921 if (HAVE_AMD3DNOWEXT)
3922 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3923 if (HAVE_SSE)
3924 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3925 if (HAVE_SSE2)
3926 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3927 if (HAVE_SSSE3)
3928 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3929 if (HAVE_CMOV)
3930 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3931 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3932 #endif /* CONFIG_RUNTIME_CPUDETECT */
3933 #endif /* ARCH_X86 */
3936 #ifdef PTW32_STATIC_LIB
3937 static void detach_ptw32(void)
3939 pthread_win32_thread_detach_np();
3940 pthread_win32_process_detach_np();
3942 #endif
3944 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3945 * file for some tools to link against. */
3946 #ifndef DISABLE_MAIN
3947 int main(int argc, char *argv[])
3949 #ifdef PTW32_STATIC_LIB
3950 pthread_win32_process_attach_np();
3951 pthread_win32_thread_attach_np();
3952 atexit(detach_ptw32);
3953 #endif
3954 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3955 || !strcmp(argv[1], "--leak-report")))
3956 talloc_enable_leak_report();
3958 char *mem_ptr;
3960 // movie info:
3962 /* Flag indicating whether MPlayer should exit without playing anything. */
3963 int opt_exit = 0;
3964 int i;
3966 struct MPContext *mpctx = &(struct MPContext){
3967 .osd_function = OSD_PLAY,
3968 .begin_skip = MP_NOPTS_VALUE,
3969 .play_tree_step = 1,
3970 .global_sub_pos = -1,
3971 .set_of_sub_pos = -1,
3972 .file_format = DEMUXER_TYPE_UNKNOWN,
3973 .last_dvb_step = 1,
3976 InitTimer();
3977 srand(GetTimerMS());
3979 mp_msg_init();
3980 init_libav();
3982 #ifdef CONFIG_X11
3983 mpctx->x11_state = vo_x11_init_state();
3984 #endif
3985 struct MPOpts *opts = &mpctx->opts;
3986 set_default_mplayer_options(opts);
3987 // Create the config context and register the options
3988 mpctx->mconfig = m_config_new(opts, cfg_include);
3989 m_config_register_options(mpctx->mconfig, mplayer_opts);
3990 m_config_register_options(mpctx->mconfig, common_opts);
3991 mp_input_register_options(mpctx->mconfig);
3993 // Preparse the command line
3994 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
3996 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3997 set_path_env();
3998 #endif
4000 #ifdef CONFIG_TV
4001 stream_tv_defaults.immediate = 1;
4002 #endif
4004 parse_cfgfiles(mpctx, mpctx->mconfig);
4006 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
4007 if (mpctx->playtree == NULL)
4008 opt_exit = 1;
4009 else {
4010 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
4011 if (mpctx->playtree) {
4012 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4013 mpctx->mconfig);
4014 if (mpctx->playtree_iter) {
4015 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4016 PLAY_TREE_ITER_ENTRY) {
4017 play_tree_iter_free(mpctx->playtree_iter);
4018 mpctx->playtree_iter = NULL;
4020 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
4026 print_version("MPlayer2");
4028 #if defined(__MINGW32__) || defined(__CYGWIN__)
4030 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
4031 BOOL WINAPI (*setDEP)(DWORD) = NULL;
4032 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
4033 if (kernel32) {
4034 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
4035 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
4037 if (setDEP)
4038 setDEP(3);
4039 if (setDllDir)
4040 setDllDir("");
4042 // stop Windows from showing all kinds of annoying error dialogs
4043 SetErrorMode(0x8003);
4044 // request 1ms timer resolution
4045 timeBeginPeriod(1);
4046 #endif
4048 #ifdef CONFIG_PRIORITY
4049 set_priority();
4050 #endif
4052 if (opts->video_driver_list &&
4053 strcmp(opts->video_driver_list[0], "help") == 0) {
4054 list_video_out();
4055 opt_exit = 1;
4058 if (opts->audio_driver_list &&
4059 strcmp(opts->audio_driver_list[0], "help") == 0) {
4060 list_audio_out();
4061 opt_exit = 1;
4064 /* Check codecs.conf. */
4065 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4066 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4067 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4068 if (!parse_codec_cfg(NULL))
4069 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4070 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4071 "Using built-in default codecs.conf.\n");
4074 free(mem_ptr); // release the buffer created by get_path()
4077 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4078 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4079 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4080 list_codecs(1);
4081 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4082 opt_exit = 1;
4084 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4085 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4086 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4087 list_codecs(0);
4088 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4089 opt_exit = 1;
4091 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4092 vfm_help();
4093 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4094 opt_exit = 1;
4096 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4097 afm_help();
4098 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4099 opt_exit = 1;
4101 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4102 af_help();
4103 printf("\n");
4104 opt_exit = 1;
4106 #ifdef CONFIG_X11
4107 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4108 fstype_help();
4109 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4110 opt_exit = 1;
4112 #endif
4113 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4114 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4115 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4116 demuxer_help();
4117 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4118 opt_exit = 1;
4120 if (opts->list_properties) {
4121 property_print_help();
4122 opt_exit = 1;
4125 if (opt_exit)
4126 exit_player(mpctx, EXIT_NONE);
4128 if (!mpctx->filename && !opts->player_idle_mode) {
4129 // no file/vcd/dvd -> show HELP:
4130 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4131 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4134 /* Display what configure line was used */
4135 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4137 // Many users forget to include command line in bugreports...
4138 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4139 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4140 for (i = 1; i < argc; i++)
4141 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4142 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4145 //------ load global data first ------
4147 mpctx->osd = osd_create();
4149 // check font
4150 #ifdef CONFIG_FREETYPE
4151 init_freetype();
4152 #endif
4153 #ifdef CONFIG_FONTCONFIG
4154 if (font_fontconfig <= 0) {
4155 #endif
4156 #ifdef CONFIG_BITMAP_FONT
4157 if (font_name) {
4158 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4159 if (!vo_font)
4160 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4161 filename_recode(font_name));
4162 } else {
4163 // try default:
4164 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4165 font_factor, verbose > 1);
4166 free(mem_ptr); // release the buffer created by get_path()
4167 if (!vo_font)
4168 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4169 font_factor, verbose > 1);
4171 if (sub_font_name)
4172 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4173 verbose > 1);
4174 else
4175 mpctx->osd->sub_font = vo_font;
4176 #endif
4177 #ifdef CONFIG_FONTCONFIG
4179 #endif
4181 #ifdef CONFIG_ASS
4182 mpctx->ass_library = mp_ass_init();
4183 mpctx->osd->ass_library = mpctx->ass_library;
4184 #endif
4186 #ifdef HAVE_RTC
4187 if (opts->rtc) {
4188 char *rtc_device = opts->rtc_device;
4189 // seteuid(0); /* Can't hurt to try to get root here */
4190 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4191 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4192 "(it should be readable by the user.)\n",
4193 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4194 else {
4195 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4197 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4198 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4199 "ioctl (rtc_irqp_set %lu): %s\n",
4200 irqp, strerror(errno));
4201 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4202 close(rtc_fd);
4203 rtc_fd = -1;
4204 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4205 /* variable only by the root */
4206 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4207 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4208 close(rtc_fd);
4209 rtc_fd = -1;
4210 } else
4211 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4212 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4215 if (rtc_fd < 0)
4216 #endif /* HAVE_RTC */
4217 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4218 opts->softsleep ? "software" : timer_name);
4220 #ifdef HAVE_TERMCAP
4221 load_termcap(NULL); // load key-codes
4222 #endif
4224 // ========== Init keyboard FIFO (connection to libvo) ============
4226 // Init input system
4227 current_module = "init_input";
4228 mpctx->input = mp_input_init(&opts->input);
4229 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4230 if (slave_mode)
4231 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4232 else if (opts->consolecontrols)
4233 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4234 // Set the libstream interrupt callback
4235 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4237 #ifdef CONFIG_MENU
4238 if (use_menu) {
4239 if (menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4240 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4241 else {
4242 menu_cfg = get_path("menu.conf");
4243 if (menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4244 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4245 else {
4246 if (menu_init(mpctx, mpctx->mconfig, mpctx->input,
4247 MPLAYER_CONFDIR "/menu.conf"))
4248 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR "/menu.conf");
4249 else {
4250 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4251 use_menu = 0;
4256 #endif
4258 current_module = NULL;
4260 /// Catch signals
4261 #ifndef __MINGW32__
4262 signal(SIGCHLD, child_sighandler);
4263 #endif
4265 #ifdef CONFIG_CRASH_DEBUG
4266 prog_path = argv[0];
4267 #endif
4268 //========= Catch terminate signals: ================
4269 // terminate requests:
4270 signal(SIGTERM, exit_sighandler); // kill
4271 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4273 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4275 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4276 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4277 #ifdef CONFIG_SIGHANDLER
4278 // fatal errors:
4279 signal(SIGBUS, exit_sighandler); // bus error
4280 signal(SIGSEGV, exit_sighandler); // segfault
4281 signal(SIGILL, exit_sighandler); // illegal instruction
4282 signal(SIGFPE, exit_sighandler); // floating point exc.
4283 signal(SIGABRT, exit_sighandler); // abort()
4284 #ifdef CONFIG_CRASH_DEBUG
4285 if (crash_debug)
4286 signal(SIGTRAP, exit_sighandler);
4287 #endif
4288 #endif
4290 // ***************** Now, let's see the per-file stuff ******************
4292 play_next_file:
4294 // init global sub numbers
4295 mpctx->global_sub_size = 0;
4296 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4298 if (mpctx->filename) {
4299 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4300 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4301 load_per_file_config(mpctx->mconfig, mpctx->filename);
4304 if (opts->video_driver_list)
4305 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4306 opts->video_driver_list[0]);
4307 if (opts->audio_driver_list)
4308 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4309 opts->audio_driver_list[0]);
4311 // We must enable getch2 here to be able to interrupt network connection
4312 // or cache filling
4313 if (opts->consolecontrols && !slave_mode) {
4314 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4315 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4316 "WARNING: getch2_init called twice!\n");
4317 else
4318 getch2_enable(); // prepare stdin for hotkeys...
4319 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4320 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4323 // ================= GUI idle loop (STOP state) =========================
4324 while (opts->player_idle_mode && !mpctx->filename) {
4325 play_tree_t *entry = NULL;
4326 mp_cmd_t *cmd;
4327 if (mpctx->video_out && mpctx->video_out->config_ok)
4328 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4329 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4330 if (mpctx->video_out)
4331 vo_check_events(mpctx->video_out);
4332 usec_sleep(20000);
4334 switch (cmd->id) {
4335 case MP_CMD_LOADFILE:
4336 // prepare a tree entry with the new filename
4337 entry = play_tree_new();
4338 play_tree_add_file(entry, cmd->args[0].v.s);
4339 // The entry is added to the main playtree after the switch().
4340 break;
4341 case MP_CMD_LOADLIST:
4342 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4343 break;
4344 case MP_CMD_QUIT:
4345 exit_player_with_rc(mpctx, EXIT_QUIT,
4346 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4347 break;
4348 case MP_CMD_VO_FULLSCREEN:
4349 case MP_CMD_GET_PROPERTY:
4350 case MP_CMD_SET_PROPERTY:
4351 case MP_CMD_STEP_PROPERTY:
4352 run_command(mpctx, cmd);
4353 break;
4356 mp_cmd_free(cmd);
4358 if (entry) { // user entered a command that gave a valid entry
4359 if (mpctx->playtree)
4360 // the playtree is always a node with one child. let's clear it
4361 play_tree_free_list(mpctx->playtree->child, 1);
4362 else
4363 // .. or make a brand new playtree
4364 mpctx->playtree = play_tree_new();
4366 if (!mpctx->playtree)
4367 continue; // couldn't make playtree! wait for next command
4369 play_tree_set_child(mpctx->playtree, entry);
4371 /* Make iterator start at the top the of tree. */
4372 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4373 mpctx->mconfig);
4374 if (!mpctx->playtree_iter)
4375 continue;
4377 // find the first real item in the tree
4378 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4379 PLAY_TREE_ITER_ENTRY) {
4380 // no items!
4381 play_tree_iter_free(mpctx->playtree_iter);
4382 mpctx->playtree_iter = NULL;
4383 continue; // wait for next command
4385 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4388 //---------------------------------------------------------------------------
4389 #ifdef CONFIG_ASS
4390 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4391 #endif
4392 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4393 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4395 if (mpctx->filename) {
4396 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4397 filename_recode(mpctx->filename));
4398 if (use_filename_title && opts->vo_wintitle == NULL)
4399 opts->vo_wintitle = talloc_strdup(NULL,
4400 mp_basename(mpctx->filename));
4403 if (edl_filename) {
4404 if (edl_records)
4405 free_edl(edl_records);
4406 next_edl_record = edl_records = edl_parse_file();
4408 if (edl_output_filename) {
4409 if (edl_fd)
4410 fclose(edl_fd);
4411 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4412 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4413 "Can't open EDL file [%s] for writing.\n",
4414 filename_recode(edl_output_filename));
4418 //==================== Open VOB-Sub ============================
4420 current_module = "vobsub";
4421 if (opts->vobsub_name) {
4422 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4423 if (vo_vobsub == NULL)
4424 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4425 filename_recode(opts->vobsub_name));
4426 } else if (opts->sub_auto && mpctx->filename) {
4427 char **vob = find_vob_subtitles(opts, mpctx->filename);
4428 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4429 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4430 if (vo_vobsub)
4431 break;
4433 talloc_free(vob);
4435 if (vo_vobsub) {
4436 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4437 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4438 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4439 mpctx);
4441 // setup global sub numbering
4442 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4443 vobsub_get_indexes_count(vo_vobsub);
4446 //============ Open & Sync STREAM --- fork cache2 ====================
4448 mpctx->stream = NULL;
4449 mpctx->demuxer = NULL;
4450 mpctx->d_audio = NULL;
4451 mpctx->d_video = NULL;
4452 mpctx->d_sub = NULL;
4453 mpctx->sh_audio = NULL;
4454 mpctx->sh_video = NULL;
4456 current_module = "open_stream";
4457 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4458 if (!mpctx->stream) { // error...
4459 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4460 goto goto_next_file;
4462 mpctx->initialized_flags |= INITIALIZED_STREAM;
4464 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4465 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4466 "playlist support will not be used automatically.\n"
4467 "MPlayer's playlist code is unsafe and should only be used with "
4468 "trusted sources.\nPlayback will probably fail.\n\n");
4469 #if 0
4470 play_tree_t *entry;
4471 // Handle playlist
4472 current_module = "handle_playlist";
4473 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4474 filename_recode(mpctx->filename));
4475 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4476 mpctx->eof = playtree_add_playlist(mpctx, entry);
4477 goto goto_next_file;
4478 #endif
4480 mpctx->stream->start_pos += seek_to_byte;
4482 if (stream_dump_type == 5) {
4483 unsigned char buf[4096];
4484 int len;
4485 FILE *f;
4486 current_module = "dumpstream";
4487 stream_reset(mpctx->stream);
4488 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4489 f = fopen(opts->stream_dump_name, "wb");
4490 if (!f) {
4491 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4492 exit_player(mpctx, EXIT_ERROR);
4494 if (opts->chapterrange[0] > 1) {
4495 int chapter = opts->chapterrange[0] - 1;
4496 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4498 struct stream_dump_progress info;
4499 stream_dump_progress_start(&info);
4500 while (!mpctx->stream->eof && !async_quit_request) {
4501 len = stream_read(mpctx->stream, buf, 4096);
4502 if (len > 0) {
4503 if (fwrite(buf, len, 1, f) != 1) {
4504 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4505 exit_player(mpctx, EXIT_ERROR);
4508 stream_dump_progress(&info, len, mpctx->stream);
4509 if (opts->chapterrange[1] > 0) {
4510 int chapter = -1;
4511 if (stream_control(mpctx->stream,
4512 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4513 && chapter + 1 > opts->chapterrange[1])
4514 break;
4517 if (fclose(f)) {
4518 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4519 opts->stream_dump_name);
4520 exit_player(mpctx, EXIT_ERROR);
4522 stream_dump_progress_end(&info, opts->stream_dump_name);
4523 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4524 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4527 #ifdef CONFIG_DVDREAD
4528 if (mpctx->stream->type == STREAMTYPE_DVD) {
4529 current_module = "dvd lang->id";
4530 if (opts->audio_lang && opts->audio_id == -1)
4531 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4532 if (opts->sub_lang && opts->sub_id == -1)
4533 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4534 // setup global sub numbering
4535 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4536 current_module = NULL;
4538 #endif
4540 #ifdef CONFIG_DVDNAV
4541 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4542 current_module = "dvdnav lang->id";
4543 if (opts->audio_lang && opts->audio_id == -1)
4544 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4545 opts->audio_lang);
4546 dvdsub_lang_id = -3;
4547 if (opts->sub_lang && opts->sub_id == -1)
4548 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4549 mpctx->stream, opts->sub_lang);
4550 // setup global sub numbering
4551 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4552 mpctx->stream);
4553 current_module = NULL;
4555 #endif
4557 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4558 goto_enable_cache:
4559 if (stream_cache_size > 0) {
4560 int res;
4561 float stream_cache_min_percent = opts->stream_cache_min_percent;
4562 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4563 current_module = "enable_cache";
4564 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4565 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4566 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4567 if (res == 0)
4568 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4569 goto goto_next_file;
4572 //============ Open DEMUXERS --- DETECT file type =======================
4573 current_module = "demux_open";
4575 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4576 opts->audio_id, opts->video_id, opts->sub_id,
4577 mpctx->filename);
4579 // HACK to get MOV Reference Files working
4581 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4582 unsigned char *playlist_entry;
4583 play_tree_t *list = NULL, *entry = NULL;
4585 current_module = "handle_demux_playlist";
4586 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4587 char *temp;
4588 const char *bname;
4590 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4591 filename_recode(playlist_entry));
4593 bname = mp_basename(playlist_entry);
4594 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4595 !strncmp(bname + 3, "gateQT", 6))
4596 continue;
4598 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4599 continue;
4601 entry = play_tree_new();
4603 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4604 playlist_entry)) { // add reference path of current file
4605 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4606 mpctx->filename)) + strlen(playlist_entry) + 1));
4607 if (temp) {
4608 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4609 strlen(mp_basename(mpctx->filename)));
4610 temp[strlen(mpctx->filename) - strlen(mp_basename(
4611 mpctx->filename))] = '\0';
4612 strcat(temp, playlist_entry);
4613 if (!strcmp(temp, mpctx->filename)) {
4614 free(temp);
4615 continue;
4617 play_tree_add_file(entry, temp);
4618 mp_msg(MSGT_CPLAYER, MSGL_V,
4619 "Resolving reference to %s.\n", temp);
4620 free(temp);
4622 } else
4623 play_tree_add_file(entry, playlist_entry);
4625 if (!list)
4626 list = entry;
4627 else
4628 play_tree_append_entry(list, entry);
4630 free_demuxer(mpctx->demuxer);
4631 mpctx->demuxer = NULL;
4633 if (list) {
4634 entry = play_tree_new();
4635 play_tree_set_child(entry, list);
4636 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4637 goto goto_next_file;
4641 if (!mpctx->demuxer) {
4642 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4643 goto goto_next_file;
4646 if (mpctx->demuxer->matroska_data.ordered_chapters)
4647 build_ordered_chapter_timeline(mpctx);
4649 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4650 build_edl_timeline(mpctx);
4652 if (mpctx->timeline) {
4653 mpctx->timeline_part = 0;
4654 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4656 int part_count = mpctx->num_timeline_parts;
4657 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4658 "sources. Total length %.3f seconds.\n", part_count,
4659 mpctx->num_sources, mpctx->timeline[part_count].start);
4660 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4661 for (int i = 0; i < mpctx->num_sources; i++)
4662 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4663 filename_recode(mpctx->sources[i].demuxer->filename));
4664 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4665 "source_start, source):\n");
4666 for (int i = 0; i < part_count; i++) {
4667 struct timeline_part *p = mpctx->timeline + i;
4668 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4669 p->source_start, p->source - mpctx->sources);
4671 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4672 mpctx->timeline[part_count].start);
4675 if (!mpctx->sources) {
4676 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4677 *mpctx->sources = (struct content_source){
4678 .stream = mpctx->stream,
4679 .demuxer = mpctx->demuxer
4681 mpctx->num_sources = 1;
4684 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4686 #ifdef CONFIG_ASS
4687 if (opts->ass_enabled && mpctx->ass_library) {
4688 for (int j = 0; j < mpctx->num_sources; j++) {
4689 struct demuxer *d = mpctx->sources[j].demuxer;
4690 for (int i = 0; i < d->num_attachments; i++) {
4691 struct demux_attachment *att = d->attachments + i;
4692 if (use_embedded_fonts && attachment_is_font(att))
4693 ass_add_font(mpctx->ass_library, att->name, att->data,
4694 att->data_size);
4698 #endif
4700 current_module = "demux_open2";
4702 mpctx->d_audio = mpctx->demuxer->audio;
4703 mpctx->d_video = mpctx->demuxer->video;
4704 mpctx->d_sub = mpctx->demuxer->sub;
4706 if (ts_prog) {
4707 int tmp = ts_prog;
4708 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4710 // select audio stream
4711 for (int i = 0; i < mpctx->num_sources; i++)
4712 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4713 opts->audio_lang);
4715 // DUMP STREAMS:
4716 if ((stream_dump_type) && (stream_dump_type < 4)) {
4717 FILE *f;
4718 demux_stream_t *ds = NULL;
4719 current_module = "dump";
4720 // select stream to dump
4721 switch (stream_dump_type) {
4722 case 1: ds = mpctx->d_audio;
4723 break;
4724 case 2: ds = mpctx->d_video;
4725 break;
4726 case 3: ds = mpctx->d_sub;
4727 break;
4729 if (!ds) {
4730 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4731 "dump: FATAL: Selected stream missing!\n");
4732 exit_player(mpctx, EXIT_ERROR);
4734 // disable other streams:
4735 if (mpctx->d_audio && mpctx->d_audio != ds) {
4736 ds_free_packs(mpctx->d_audio);
4737 mpctx->d_audio->id = -2;
4739 if (mpctx->d_video && mpctx->d_video != ds) {
4740 ds_free_packs(mpctx->d_video);
4741 mpctx->d_video->id = -2;
4743 if (mpctx->d_sub && mpctx->d_sub != ds) {
4744 ds_free_packs(mpctx->d_sub);
4745 mpctx->d_sub->id = -2;
4747 // let's dump it!
4748 f = fopen(opts->stream_dump_name, "wb");
4749 if (!f) {
4750 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4751 exit_player(mpctx, EXIT_ERROR);
4753 struct stream_dump_progress info;
4754 stream_dump_progress_start(&info);
4755 while (!ds->eof) {
4756 unsigned char *start;
4757 int in_size = ds_get_packet(ds, &start);
4758 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4759 && stream_dump_type == 2)
4760 fwrite(&in_size, 1, 4, f);
4761 if (in_size > 0) {
4762 fwrite(start, in_size, 1, f);
4763 stream_dump_progress(&info, in_size, mpctx->stream);
4765 if (opts->chapterrange[1] > 0) {
4766 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4767 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4768 break;
4771 fclose(f);
4772 stream_dump_progress_end(&info, opts->stream_dump_name);
4773 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4774 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4777 mpctx->sh_audio = mpctx->d_audio->sh;
4778 mpctx->sh_video = mpctx->d_video->sh;
4780 if (mpctx->sh_video) {
4782 current_module = "video_read_properties";
4783 if (!video_read_properties(mpctx->sh_video)) {
4784 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4785 mpctx->sh_video = mpctx->d_video->sh = NULL;
4786 } else {
4787 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4788 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4789 mpctx->demuxer->file_format, mpctx->sh_video->format,
4790 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4791 mpctx->sh_video->fps, mpctx->sh_video->frametime
4794 /* need to set fps here for output encoders to pick it up in their init */
4795 if (force_fps) {
4796 mpctx->sh_video->fps = force_fps;
4797 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4799 vo_fps = mpctx->sh_video->fps;
4801 if (!mpctx->sh_video->fps && !force_fps) {
4802 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4803 "header or invalid, use the -fps option.\n");
4804 mpctx->opts.correct_pts = 1;
4810 if (!mpctx->sh_video && !mpctx->sh_audio) {
4811 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4812 #ifdef CONFIG_DVBIN
4813 if (mpctx->stream->type == STREAMTYPE_DVB) {
4814 int dir;
4815 int v = mpctx->last_dvb_step;
4816 if (v > 0)
4817 dir = DVB_CHANNEL_HIGHER;
4818 else
4819 dir = DVB_CHANNEL_LOWER;
4821 if (dvb_step_channel(mpctx->stream, dir)) {
4822 mpctx->stop_play = PT_NEXT_ENTRY;
4823 mpctx->dvbin_reopen = 1;
4826 #endif
4827 goto goto_next_file; // exit_player(_("Fatal error"));
4830 /* display clip info */
4831 demux_info_print(mpctx->demuxer);
4833 //================= Read SUBTITLES (DVD & TEXT) =========================
4834 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4835 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4836 init_vo_spudec(mpctx);
4838 // after reading video params we should load subtitles because
4839 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4840 // check .sub
4841 current_module = "read_subtitles_file";
4842 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4843 if (opts->sub_name) {
4844 for (i = 0; opts->sub_name[i] != NULL; ++i)
4845 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4847 if (opts->sub_auto) { // auto load sub file ...
4848 char **tmp = find_text_subtitles(opts, mpctx->filename);
4849 int nsub = MP_TALLOC_ELEMS(tmp);
4850 for (int i = 0; i < nsub; i++)
4851 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4852 talloc_free(tmp);
4854 if (mpctx->set_of_sub_size > 0)
4855 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4857 if (select_subtitle(mpctx)) {
4858 if (mpctx->subdata)
4859 switch (stream_dump_type) {
4860 case 3: list_sub_file(mpctx->subdata);
4861 break;
4862 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4863 break;
4864 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4865 break;
4866 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4867 break;
4868 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4869 break;
4870 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4871 break;
4875 print_file_properties(mpctx, mpctx->filename);
4877 reinit_video_chain(mpctx);
4878 if (mpctx->sh_video) {
4879 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4880 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4881 #ifdef CONFIG_FREETYPE
4882 force_load_font = 1;
4883 #endif
4884 } else if (!mpctx->sh_audio)
4885 goto goto_next_file;
4887 //================== MAIN: ==========================
4888 current_module = "main";
4890 if (opts->playing_msg) {
4891 char *msg = property_expand_string(mpctx, opts->playing_msg);
4892 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4893 free(msg);
4897 // Disable the term OSD in verbose mode
4898 if (verbose)
4899 opts->term_osd = 0;
4901 // Make sure old OSD does not stay around,
4902 // e.g. with -fixed-vo and same-resolution files
4903 clear_osd_msgs();
4904 update_osd_msg(mpctx);
4906 //================ SETUP AUDIO ==========================
4908 if (mpctx->sh_audio) {
4909 reinit_audio_chain(mpctx);
4910 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4911 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4912 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4915 current_module = "av_init";
4917 if (mpctx->sh_video) {
4918 mpctx->sh_video->timer = 0;
4919 if (!ignore_start)
4920 audio_delay += mpctx->sh_video->stream_delay;
4922 if (mpctx->sh_audio) {
4923 if (start_volume >= 0)
4924 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4925 if (!ignore_start)
4926 audio_delay -= mpctx->sh_audio->stream_delay;
4927 mpctx->delay = -audio_delay;
4930 if (!mpctx->sh_audio) {
4931 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4932 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4933 mpctx->d_audio->packs);
4934 ds_free_packs(mpctx->d_audio); // free buffered chunks
4936 if (!mpctx->sh_video) {
4937 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4938 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4939 mpctx->d_video->packs);
4940 ds_free_packs(mpctx->d_video);
4941 mpctx->d_video->id = -2;
4944 if (!mpctx->sh_video && !mpctx->sh_audio)
4945 goto goto_next_file;
4947 if (force_fps && mpctx->sh_video) {
4948 vo_fps = mpctx->sh_video->fps = force_fps;
4949 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4950 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4951 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4952 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4955 mp_input_set_section(mpctx->input, NULL);
4956 //TODO: add desired (stream-based) sections here
4957 if (mpctx->stream->type == STREAMTYPE_TV)
4958 mp_input_set_section(mpctx->input, "tv");
4959 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4960 mp_input_set_section(mpctx->input, "dvdnav");
4962 //==================== START PLAYING =======================
4964 if (opts->loop_times > 1)
4965 opts->loop_times--;
4966 else if (opts->loop_times == 1)
4967 opts->loop_times = -1;
4969 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4971 total_time_usage_start = GetTimer();
4972 audio_time_usage = 0;
4973 video_time_usage = 0;
4974 vout_time_usage = 0;
4975 total_frame_cnt = 0;
4976 drop_frame_cnt = 0; // fix for multifile fps benchmark
4977 play_n_frames = play_n_frames_mf;
4979 if (play_n_frames == 0) {
4980 mpctx->stop_play = PT_NEXT_ENTRY;
4981 goto goto_next_file;
4984 mpctx->time_frame = 0;
4985 mpctx->drop_message_shown = 0;
4986 mpctx->restart_playback = true;
4987 mpctx->video_pts = 0;
4988 mpctx->last_seek_pts = 0;
4989 mpctx->hrseek_active = false;
4990 mpctx->hrseek_framedrop = false;
4991 mpctx->step_frames = 0;
4992 mpctx->total_avsync_change = 0;
4993 mpctx->last_chapter_seek = -2;
4995 // If there's a timeline force an absolute seek to initialize state
4996 if (opts->seek_to_sec || mpctx->timeline) {
4997 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4998 seek(mpctx, mpctx->seek, false);
4999 end_at.pos += opts->seek_to_sec;
5001 if (opts->chapterrange[0] > 0) {
5002 double pts;
5003 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts, NULL) >= 0
5004 && pts > -1.0) {
5005 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
5006 seek(mpctx, mpctx->seek, false);
5010 if (end_at.type == END_AT_SIZE) {
5011 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
5012 "Option -endpos in MPlayer does not yet support size units.\n");
5013 end_at.type = END_AT_NONE;
5016 #ifdef CONFIG_DVDNAV
5017 mp_dvdnav_context_free(mpctx);
5018 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
5019 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
5020 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
5022 #endif
5024 mpctx->seek = (struct seek_params){ 0 };
5025 get_relative_time(mpctx); // reset current delta
5026 // Make sure VO knows current pause state
5027 if (mpctx->sh_video)
5028 vo_control(mpctx->video_out,
5029 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
5031 while (!mpctx->stop_play)
5032 run_playloop(mpctx);
5034 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
5036 #ifdef CONFIG_DVBIN
5037 if (mpctx->dvbin_reopen) {
5038 mpctx->stop_play = 0;
5039 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
5040 cache_uninit(mpctx->stream);
5041 mpctx->dvbin_reopen = 0;
5042 goto goto_enable_cache;
5044 #endif
5046 goto_next_file: // don't jump here after ao/vo/getch initialization!
5048 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
5050 if (opts->benchmark) {
5051 double tot = video_time_usage + vout_time_usage + audio_time_usage;
5052 double total_time_usage;
5053 total_time_usage_start = GetTimer() - total_time_usage_start;
5054 total_time_usage = (float)total_time_usage_start * 0.000001;
5055 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
5056 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
5057 video_time_usage, vout_time_usage, audio_time_usage,
5058 total_time_usage - tot, total_time_usage);
5059 if (total_time_usage > 0.0)
5060 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
5061 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
5062 100.0 * video_time_usage / total_time_usage,
5063 100.0 * vout_time_usage / total_time_usage,
5064 100.0 * audio_time_usage / total_time_usage,
5065 100.0 * (total_time_usage - tot) / total_time_usage,
5066 100.0);
5067 if (total_frame_cnt && frame_dropping)
5068 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
5069 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
5070 total_frame_cnt - drop_frame_cnt,
5071 (total_time_usage > 0.5) ? ((total_frame_cnt -
5072 drop_frame_cnt) / total_time_usage) : 0,
5073 drop_frame_cnt,
5074 100 * drop_frame_cnt / total_frame_cnt,
5075 total_frame_cnt,
5076 (total_time_usage > 0.5) ?
5077 (total_frame_cnt / total_time_usage) : 0);
5080 // time to uninit all, except global stuff:
5081 int uninitialize_parts = INITIALIZED_ALL;
5082 if (opts->fixed_vo)
5083 uninitialize_parts -= INITIALIZED_VO;
5084 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
5085 uninitialize_parts -= INITIALIZED_AO;
5086 uninit_player(mpctx, uninitialize_parts);
5088 if (mpctx->set_of_sub_size > 0) {
5089 current_module = "sub_free";
5090 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5091 sub_free(mpctx->set_of_subtitles[i]);
5092 #ifdef CONFIG_ASS
5093 if (mpctx->set_of_ass_tracks[i])
5094 ass_free_track(mpctx->set_of_ass_tracks[i]);
5095 #endif
5097 mpctx->set_of_sub_size = 0;
5099 mpctx->vo_sub_last = vo_sub = NULL;
5100 mpctx->subdata = NULL;
5101 #ifdef CONFIG_ASS
5102 mpctx->osd->ass_track = NULL;
5103 if (mpctx->ass_library)
5104 ass_clear_fonts(mpctx->ass_library);
5105 #endif
5107 if (!mpctx->stop_play) // In case some goto jumped here...
5108 mpctx->stop_play = PT_NEXT_ENTRY;
5110 int playtree_direction = 1;
5112 if (mpctx->stop_play == PT_NEXT_ENTRY
5113 || mpctx->stop_play == PT_PREV_ENTRY) {
5114 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5115 != PLAY_TREE_ITER_ENTRY) {
5116 play_tree_iter_free(mpctx->playtree_iter);
5117 mpctx->playtree_iter = NULL;
5119 mpctx->play_tree_step = 1;
5120 } else if (mpctx->stop_play == PT_UP_NEXT ||
5121 mpctx->stop_play == PT_UP_PREV) {
5122 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5123 if (mpctx->playtree_iter) {
5124 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5125 PLAY_TREE_ITER_ENTRY) {
5126 play_tree_iter_free(mpctx->playtree_iter);
5127 mpctx->playtree_iter = NULL;
5130 } else if (mpctx->stop_play == PT_STOP) {
5131 play_tree_iter_free(mpctx->playtree_iter);
5132 mpctx->playtree_iter = NULL;
5133 } else // NEXT PREV SRC
5134 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5136 while (mpctx->playtree_iter != NULL) {
5137 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5138 playtree_direction);
5139 if (mpctx->filename == NULL) {
5140 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5141 0) != PLAY_TREE_ITER_ENTRY) {
5142 play_tree_iter_free(mpctx->playtree_iter);
5143 mpctx->playtree_iter = NULL;
5146 } else
5147 break;
5150 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5151 if (!mpctx->playtree_iter)
5152 mpctx->filename = NULL;
5153 mpctx->stop_play = 0;
5154 goto play_next_file;
5157 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5159 return 1;
5161 #endif /* DISABLE_MAIN */