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