VO: don't keep a persistent X11 connection across VOs
[mplayer.git] / mplayer.c
blobf33cc702537a266b32731bcaf3235e2b357aa7c5
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 // No proper file descriptor event handling; keep waking up to poll input
35 #define WAKEUP_PERIOD 0.02
36 #else
37 /* Even if we can immediately wake up in response to most input events,
38 * there are some timers which are not registered to the event loop
39 * and need to be checked periodically (like automatic mouse cursor hiding).
40 * OSD content updates behave similarly. Also some uncommon input devices
41 * may not have proper FD event support.
43 #define WAKEUP_PERIOD 0.5
44 #endif
45 #include <string.h>
46 #include <unistd.h>
48 // #include <sys/mman.h>
49 #include <sys/types.h>
50 #ifndef __MINGW32__
51 #include <sys/ioctl.h>
52 #include <sys/wait.h>
53 #else
54 #define SIGHUP 1 /* hangup */
55 #define SIGQUIT 3 /* quit */
56 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
57 #define SIGBUS 10 /* bus error */
58 #define SIGPIPE 13 /* broken pipe */
59 #endif
61 #include <sys/time.h>
62 #include <sys/stat.h>
64 #include <signal.h>
65 #include <time.h>
66 #include <fcntl.h>
67 #include <limits.h>
69 #include <errno.h>
71 #include "mp_msg.h"
72 #include "av_log.h"
75 #include "m_option.h"
76 #include "m_config.h"
77 #include "mplayer.h"
78 #include "m_property.h"
80 #include "sub/subreader.h"
81 #include "sub/find_subfiles.h"
82 #include "sub/dec_sub.h"
83 #include "sub/sub_cc.h"
85 #include "mp_osd.h"
86 #include "libvo/video_out.h"
87 #include "screenshot.h"
89 #include "sub/sub.h"
90 #include "libmpcodecs/dec_teletext.h"
91 #include "cpudetect.h"
92 #include "version.h"
94 #ifdef CONFIG_X11
95 #include "libvo/x11_common.h"
96 #endif
98 #include "libao2/audio_out.h"
100 #include "codec-cfg.h"
102 #include "sub/spudec.h"
103 #include "sub/vobsub.h"
105 #include "osdep/getch2.h"
106 #include "osdep/timer.h"
108 #include "input/input.h"
110 int slave_mode = 0;
111 int enable_mouse_movements = 0;
112 float start_volume = -1;
114 #include "osdep/priority.h"
116 char *heartbeat_cmd;
118 #ifdef HAVE_RTC
119 #ifdef __linux__
120 #include <linux/rtc.h>
121 #else
122 #include <rtc.h>
123 #define RTC_IRQP_SET RTCIO_IRQP_SET
124 #define RTC_PIE_ON RTCIO_PIE_ON
125 #endif /* __linux__ */
126 #endif /* HAVE_RTC */
128 #include "stream/tv.h"
129 #include "stream/stream_radio.h"
130 #ifdef CONFIG_DVBIN
131 #include "stream/dvbin.h"
132 #endif
133 #include "stream/cache2.h"
135 //**************************************************************************//
136 // Playtree
137 //**************************************************************************//
138 #include "playtree.h"
139 #include "playtreeparser.h"
141 //**************************************************************************//
142 // Config
143 //**************************************************************************//
144 #include "parser-cfg.h"
145 #include "parser-mpcmd.h"
147 //**************************************************************************//
148 // Config file
149 //**************************************************************************//
151 #include "path.h"
153 //**************************************************************************//
154 //**************************************************************************//
155 // Input media streaming & demultiplexer:
156 //**************************************************************************//
158 static int max_framesize = 0;
160 #include "stream/stream.h"
161 #include "libmpdemux/demuxer.h"
162 #include "libmpdemux/stheader.h"
164 #ifdef CONFIG_DVDREAD
165 #include "stream/stream_dvd.h"
166 #endif
167 #include "stream/stream_dvdnav.h"
169 #include "libmpcodecs/dec_audio.h"
170 #include "libmpcodecs/dec_video.h"
171 #include "libmpcodecs/mp_image.h"
172 #include "libmpcodecs/vf.h"
173 #include "libmpcodecs/vd.h"
175 #include "mixer.h"
177 #include "mp_core.h"
178 #include "options.h"
179 #include "defaultopts.h"
181 static const char help_text[] = _(
182 "Usage: mplayer [options] [url|path/]filename\n"
183 "\n"
184 "Basic options: (complete list in the man page)\n"
185 " -vo <drv> select video output driver ('-vo help' for a list)\n"
186 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
187 #ifdef CONFIG_VCD
188 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
189 #endif
190 #ifdef CONFIG_DVDREAD
191 " dvd://<titleno> play DVD title from device instead of plain file\n"
192 #endif
193 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
194 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
195 " -nosound do not play sound\n"
196 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
197 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
198 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
199 " -playlist <file> specify playlist file\n"
200 " -vid x -aid y select video (x) and audio (y) stream to play\n"
201 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
202 " -pp <quality> enable postprocessing filter (details in the man page)\n"
203 " -framedrop enable frame dropping (for slow machines)\n"
204 "\n"
205 "Basic keys: (complete list in the man page, also check input.conf)\n"
206 " <- or -> seek backward/forward 10 seconds\n"
207 " down or up seek backward/forward 1 minute\n"
208 " pgdown or pgup seek backward/forward 10 minutes\n"
209 " < or > step backward/forward in playlist\n"
210 " p or SPACE pause movie (press any key to continue)\n"
211 " q or ESC stop playing and quit program\n"
212 " + or - adjust audio delay by +/- 0.1 second\n"
213 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
214 " * or / increase or decrease PCM volume\n"
215 " x or z adjust subtitle delay by +/- 0.1 second\n"
216 " r or t adjust subtitle position up/down, also see -vf expand\n"
217 " double click toggle fullscreen\n"
218 " right click pause (press again to continue)\n"
219 "\n"
220 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
221 "\n");
224 #define Exit_SIGILL_RTCpuSel _(\
225 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
226 " It may be a bug in our new runtime CPU-detection code...\n"\
227 " Please read DOCS/HTML/en/bugreports.html.\n")
229 #define Exit_SIGILL _(\
230 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
231 " It usually happens when you run it on a CPU different than the one it was\n"\
232 " compiled/optimized for.\n"\
233 " Verify this!\n")
235 #define Exit_SIGSEGV_SIGFPE _(\
236 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
237 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
238 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
240 #define Exit_SIGCRASH _(\
241 "- MPlayer crashed. This shouldn't happen.\n"\
242 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
243 " gcc version. If you think it's MPlayer's fault, please read\n"\
244 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
245 " won't help unless you provide this information when reporting a possible bug.\n")
247 #define SystemTooSlow _("\n\n"\
248 " ************************************************\n"\
249 " **** Your system is too SLOW to play this! ****\n"\
250 " ************************************************\n\n"\
251 "Possible reasons, problems, workarounds:\n"\
252 "- Most common: broken/buggy _audio_ driver\n"\
253 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
254 " - Experiment with different values for -autosync, 30 is a good start.\n"\
255 "- Slow video output\n"\
256 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
257 "- Slow CPU\n"\
258 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
259 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
260 "- Broken file\n"\
261 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
262 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
263 " - Try -cache 8192.\n"\
264 "- Are you using -cache to play a non-interleaved AVI file?\n"\
265 " - Try -nocache.\n"\
266 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
267 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
270 //**************************************************************************//
271 //**************************************************************************//
273 #include "mp_fifo.h"
275 // benchmark:
276 double video_time_usage;
277 double vout_time_usage;
278 static double audio_time_usage;
279 static int total_time_usage_start;
280 static int total_frame_cnt;
281 static int drop_frame_cnt; // total number of dropped frames
283 // options:
284 static int output_quality;
286 // seek:
287 static off_t seek_to_byte;
288 static off_t step_sec;
290 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
292 // codecs:
293 char **audio_codec_list; // override audio codec
294 char **video_codec_list; // override video codec
295 char **audio_fm_list; // override audio codec family
296 char **video_fm_list; // override video codec family
298 // this dvdsub_id was selected via slang
299 // use this to allow dvdnav to follow -slang across stream resets,
300 // in particular the subtitle ID for a language changes
301 int dvdsub_lang_id;
302 int vobsub_id = -1;
303 static char *spudec_ifo = NULL;
304 int forced_subs_only = 0;
306 // cache2:
307 int stream_cache_size = -1;
309 // dump:
310 int stream_dump_type = 0;
312 // A-V sync:
313 static float default_max_pts_correction = -1;
314 float audio_delay = 0;
315 static int ignore_start = 0;
317 double force_fps = 0;
318 static int force_srate = 0;
319 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
320 static int play_n_frames = -1;
321 static int play_n_frames_mf = -1;
323 #include "sub/ass_mp.h"
325 char *current_module; // for debugging
328 // ---
330 FILE *edl_fd; // file to write to when in -edlout mode.
331 char *edl_output_filename; // file to put EDL entries in (-edlout)
333 int use_filedir_conf;
334 int use_filename_title;
336 #include "mpcommon.h"
337 #include "command.h"
339 #include "metadata.h"
341 static float get_relative_time(struct MPContext *mpctx)
343 unsigned int new_time = GetTimer();
344 unsigned int delta = new_time - mpctx->last_time;
345 mpctx->last_time = new_time;
346 return delta * 0.000001;
349 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
351 switch (type) {
352 /* check for valid video stream */
353 case META_VIDEO_CODEC:
354 case META_VIDEO_BITRATE:
355 case META_VIDEO_RESOLUTION:
356 if (!mpctx->sh_video)
357 return 0;
358 break;
360 /* check for valid audio stream */
361 case META_AUDIO_CODEC:
362 case META_AUDIO_BITRATE:
363 case META_AUDIO_SAMPLES:
364 if (!mpctx->sh_audio)
365 return 0;
366 break;
368 /* check for valid demuxer */
369 case META_INFO_TITLE:
370 case META_INFO_ARTIST:
371 case META_INFO_ALBUM:
372 case META_INFO_YEAR:
373 case META_INFO_COMMENT:
374 case META_INFO_TRACK:
375 case META_INFO_GENRE:
376 if (!mpctx->demuxer)
377 return 0;
378 break;
380 default:
381 break;
384 return 1;
387 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
389 char **info = mpctx->demuxer->info;
390 int n;
392 if (!info || !tag)
393 return talloc_strdup(NULL, "");
395 for (n = 0; info[2 * n] != NULL; n++)
396 if (!strcasecmp(info[2 * n], tag))
397 break;
399 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
402 char *get_metadata(struct MPContext *mpctx, metadata_t type)
404 sh_audio_t * const sh_audio = mpctx->sh_audio;
405 sh_video_t * const sh_video = mpctx->sh_video;
407 if (!is_valid_metadata_type(mpctx, type))
408 return NULL;
410 switch (type) {
411 case META_NAME:
412 return talloc_strdup(NULL, mp_basename(mpctx->filename));
413 case META_VIDEO_CODEC:
414 if (sh_video->format == 0x10000001)
415 return talloc_strdup(NULL, "mpeg1");
416 else if (sh_video->format == 0x10000002)
417 return talloc_strdup(NULL, "mpeg2");
418 else if (sh_video->format == 0x10000004)
419 return talloc_strdup(NULL, "mpeg4");
420 else if (sh_video->format == 0x10000005)
421 return talloc_strdup(NULL, "h264");
422 else if (sh_video->format >= 0x20202020)
423 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
424 else
425 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
426 case META_VIDEO_BITRATE:
427 return talloc_asprintf(NULL, "%d kbps",
428 (int) (sh_video->i_bps * 8 / 1024));
429 case META_VIDEO_RESOLUTION:
430 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
431 sh_video->disp_h);
432 case META_AUDIO_CODEC:
433 if (sh_audio->codec && sh_audio->codec->name)
434 return talloc_strdup(NULL, sh_audio->codec->name);
435 return talloc_strdup(NULL, "");
436 case META_AUDIO_BITRATE:
437 return talloc_asprintf(NULL, "%d kbps",
438 (int) (sh_audio->i_bps * 8 / 1000));
439 case META_AUDIO_SAMPLES:
440 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
441 sh_audio->channels);
443 /* check for valid demuxer */
444 case META_INFO_TITLE:
445 return get_demuxer_info(mpctx, "Title");
447 case META_INFO_ARTIST:
448 return get_demuxer_info(mpctx, "Artist");
450 case META_INFO_ALBUM:
451 return get_demuxer_info(mpctx, "Album");
453 case META_INFO_YEAR:
454 return get_demuxer_info(mpctx, "Year");
456 case META_INFO_COMMENT:
457 return get_demuxer_info(mpctx, "Comment");
459 case META_INFO_TRACK:
460 return get_demuxer_info(mpctx, "Track");
462 case META_INFO_GENRE:
463 return get_demuxer_info(mpctx, "Genre");
465 default:
466 break;
469 return talloc_strdup(NULL, "");
472 static void print_file_properties(struct MPContext *mpctx, const char *filename)
474 double start_pts = MP_NOPTS_VALUE;
475 double video_start_pts = MP_NOPTS_VALUE;
476 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
477 filename_recode(filename));
478 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
479 mpctx->demuxer->desc->name);
480 if (mpctx->sh_video) {
481 /* Assume FOURCC if all bytes >= 0x20 (' ') */
482 if (mpctx->sh_video->format >= 0x20202020)
483 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
484 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
485 else
486 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
487 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
488 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
489 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
490 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
491 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
492 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
493 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
494 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
495 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
496 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
497 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
498 video_start_pts = ds_get_next_pts(mpctx->d_video);
500 if (mpctx->sh_audio) {
501 /* Assume FOURCC if all bytes >= 0x20 (' ') */
502 if (mpctx->sh_audio->format >= 0x20202020)
503 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
504 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
505 else
506 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
507 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
508 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
509 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
510 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
511 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
512 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
513 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
514 start_pts = ds_get_next_pts(mpctx->d_audio);
516 if (video_start_pts != MP_NOPTS_VALUE) {
517 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
518 (mpctx->sh_video && video_start_pts < start_pts))
519 start_pts = video_start_pts;
521 if (start_pts != MP_NOPTS_VALUE)
522 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
523 else
524 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
525 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
526 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
527 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
528 mpctx->stream->seek
529 && (!mpctx->demuxer || mpctx->demuxer->seekable));
530 if (mpctx->demuxer) {
531 int chapter_count = get_chapter_count(mpctx);
532 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
533 for (int i = 0; i < chapter_count; i++) {
534 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
535 // in milliseconds
536 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
537 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
538 char *name = chapter_name(mpctx, i);
539 if (name) {
540 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
541 name);
542 talloc_free(name);
548 /// step size of mixer changes
549 int volstep = 3;
551 #ifdef CONFIG_DVDNAV
552 static void mp_dvdnav_context_free(MPContext *ctx)
554 if (ctx->nav_smpi)
555 free_mp_image(ctx->nav_smpi);
556 ctx->nav_smpi = NULL;
557 free(ctx->nav_buffer);
558 ctx->nav_buffer = NULL;
559 ctx->nav_start = NULL;
560 ctx->nav_in_size = 0;
562 #endif
564 static void uninit_subs(struct demuxer *demuxer)
566 for (int i = 0; i < MAX_S_STREAMS; i++) {
567 struct sh_sub *sh = demuxer->s_streams[i];
568 if (sh && sh->initialized)
569 sub_uninit(sh);
573 void uninit_player(struct MPContext *mpctx, unsigned int mask)
575 mask &= mpctx->initialized_flags;
577 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
579 if (mask & INITIALIZED_ACODEC) {
580 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
581 current_module = "uninit_acodec";
582 if (mpctx->sh_audio)
583 uninit_audio(mpctx->sh_audio);
584 mpctx->sh_audio = NULL;
585 mpctx->mixer.afilter = NULL;
588 if (mask & INITIALIZED_SUB) {
589 mpctx->initialized_flags &= ~INITIALIZED_SUB;
590 if (mpctx->osd->sh_sub)
591 sub_switchoff(mpctx->osd->sh_sub, mpctx->osd);
594 if (mask & INITIALIZED_VCODEC) {
595 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
596 current_module = "uninit_vcodec";
597 if (mpctx->sh_video)
598 uninit_video(mpctx->sh_video);
599 mpctx->sh_video = NULL;
602 if (mask & INITIALIZED_DEMUXER) {
603 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
604 current_module = "free_demuxer";
605 if (mpctx->num_sources) {
606 mpctx->demuxer = mpctx->sources[0].demuxer;
607 for (int i = 1; i < mpctx->num_sources; i++) {
608 uninit_subs(mpctx->sources[i].demuxer);
609 free_stream(mpctx->sources[i].stream);
610 free_demuxer(mpctx->sources[i].demuxer);
613 talloc_free(mpctx->sources);
614 mpctx->sources = NULL;
615 mpctx->num_sources = 0;
616 talloc_free(mpctx->timeline);
617 mpctx->timeline = NULL;
618 mpctx->num_timeline_parts = 0;
619 talloc_free(mpctx->chapters);
620 mpctx->chapters = NULL;
621 mpctx->num_chapters = 0;
622 mpctx->video_offset = 0;
623 if (mpctx->demuxer) {
624 mpctx->stream = mpctx->demuxer->stream;
625 uninit_subs(mpctx->demuxer);
626 free_demuxer(mpctx->demuxer);
628 mpctx->demuxer = NULL;
631 // kill the cache process:
632 if (mask & INITIALIZED_STREAM) {
633 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
634 current_module = "uninit_stream";
635 if (mpctx->stream)
636 free_stream(mpctx->stream);
637 mpctx->stream = NULL;
640 if (mask & INITIALIZED_VO) {
641 mpctx->initialized_flags &= ~INITIALIZED_VO;
642 current_module = "uninit_vo";
643 vo_destroy(mpctx->video_out);
644 mpctx->video_out = NULL;
645 #ifdef CONFIG_DVDNAV
646 mp_dvdnav_context_free(mpctx);
647 #endif
650 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
651 if (mask & INITIALIZED_GETCH2) {
652 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
653 current_module = "uninit_getch2";
654 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
655 // restore terminal:
656 getch2_disable();
659 if (mask & INITIALIZED_VOBSUB) {
660 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
661 current_module = "uninit_vobsub";
662 if (vo_vobsub)
663 vobsub_close(vo_vobsub);
664 vo_vobsub = NULL;
667 if (mask & INITIALIZED_SPUDEC) {
668 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
669 current_module = "uninit_spudec";
670 spudec_free(vo_spudec);
671 vo_spudec = NULL;
674 if (mask & INITIALIZED_AO) {
675 mpctx->initialized_flags &= ~INITIALIZED_AO;
676 current_module = "uninit_ao";
677 if (mpctx->ao) {
678 mixer_uninit(&mpctx->mixer);
679 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
681 mpctx->ao = NULL;
684 current_module = NULL;
687 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
689 uninit_player(mpctx, INITIALIZED_ALL);
690 #if defined(__MINGW32__) || defined(__CYGWIN__)
691 timeEndPeriod(1);
692 #endif
694 current_module = "uninit_input";
695 mp_input_uninit(mpctx->input);
697 osd_free(mpctx->osd);
699 #ifdef CONFIG_ASS
700 ass_library_done(mpctx->ass_library);
701 mpctx->ass_library = NULL;
702 #endif
704 current_module = "exit_player";
706 if (mpctx->playtree_iter)
707 play_tree_iter_free(mpctx->playtree_iter);
708 mpctx->playtree_iter = NULL;
709 if (mpctx->playtree)
710 play_tree_free(mpctx->playtree, 1);
711 mpctx->playtree = NULL;
713 talloc_free(mpctx->key_fifo);
715 switch (how) {
716 case EXIT_QUIT:
717 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
718 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
719 break;
720 case EXIT_EOF:
721 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
722 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
723 break;
724 case EXIT_ERROR:
725 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
726 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
727 break;
728 default:
729 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
731 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
732 "max framesize was %d bytes\n", max_framesize);
734 // must be last since e.g. mp_msg uses option values
735 // that will be freed by this.
736 if (mpctx->mconfig)
737 m_config_free(mpctx->mconfig);
738 mpctx->mconfig = NULL;
740 talloc_free(mpctx);
742 exit(rc);
745 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
747 exit_player_with_rc(mpctx, how, 1);
750 #ifndef __MINGW32__
751 static void child_sighandler(int x)
753 pid_t pid;
754 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
756 #endif
758 #ifdef CONFIG_CRASH_DEBUG
759 static char *prog_path;
760 static int crash_debug = 0;
761 #endif
763 static void exit_sighandler(int x)
765 static int sig_count = 0;
766 #ifdef CONFIG_CRASH_DEBUG
767 if (!crash_debug || x != SIGTRAP)
768 #endif
769 ++sig_count;
770 if (sig_count == 5) {
771 /* We're crashing bad and can't uninit cleanly :(
772 * by popular request, we make one last (dirty)
773 * effort to restore the user's
774 * terminal. */
775 getch2_disable();
776 exit(1);
778 if (sig_count == 6)
779 exit(1);
780 if (sig_count > 6) {
781 // can't stop :(
782 #ifndef __MINGW32__
783 kill(getpid(), SIGKILL);
784 #endif
786 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
787 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
788 "\nMPlayer interrupted by signal %d in module: %s\n", x,
789 current_module ? current_module : "unknown");
790 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
791 if (sig_count <= 1)
792 switch (x) {
793 case SIGINT:
794 case SIGPIPE:
795 case SIGQUIT:
796 case SIGTERM:
797 case SIGKILL:
798 async_quit_request = 1;
799 return; // killed from keyboard (^C) or killed [-9]
800 case SIGILL:
801 #if CONFIG_RUNTIME_CPUDETECT
802 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
803 #else
804 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
805 #endif
806 case SIGFPE:
807 case SIGSEGV:
808 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
809 default:
810 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
811 #ifdef CONFIG_CRASH_DEBUG
812 if (crash_debug) {
813 int gdb_pid;
814 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
815 gdb_pid = fork();
816 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
817 if (gdb_pid == 0) { // We are the child
818 char spid[20];
819 snprintf(spid, sizeof(spid), "%i", getppid());
820 getch2_disable(); // allow terminal to work properly with gdb
821 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
822 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
823 } else if (gdb_pid < 0)
824 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
825 else
826 waitpid(gdb_pid, NULL, 0);
827 if (x == SIGTRAP)
828 return;
830 #endif
832 getch2_disable();
833 exit(1);
836 #include "cfg-mplayer.h"
838 static int cfg_include(struct m_config *conf, char *filename)
840 return m_config_parse_config_file(conf, filename);
843 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
845 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
847 struct MPOpts *opts = &mpctx->opts;
848 char *conffile;
849 int conffile_fd;
850 if (!(opts->noconfig & 2) &&
851 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
852 exit_player(mpctx, EXIT_NONE);
853 if ((conffile = get_path("")) == NULL)
854 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
855 else {
856 mkdir(conffile, 0777);
857 free(conffile);
858 if ((conffile = get_path("config")) == NULL)
859 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
860 else {
861 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
862 0666)) != -1) {
863 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
864 "Creating config file: %s\n", conffile);
865 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
866 close(conffile_fd);
868 if (!(opts->noconfig & 1) &&
869 m_config_parse_config_file(conf, conffile) < 0)
870 exit_player(mpctx, EXIT_NONE);
871 free(conffile);
876 #define PROFILE_CFG_PROTOCOL "protocol."
878 static void load_per_protocol_config(m_config_t *conf, const char * const file)
880 char *str;
881 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
882 m_profile_t *p;
884 /* does filename actually uses a protocol ? */
885 str = strstr(file, "://");
886 if (!str)
887 return;
889 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
890 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
891 p = m_config_get_profile(conf, protocol);
892 if (p) {
893 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
894 "Loading protocol-related profile '%s'\n", protocol);
895 m_config_set_profile(conf, p);
899 #define PROFILE_CFG_EXTENSION "extension."
901 static void load_per_extension_config(m_config_t *conf, const char * const file)
903 char *str;
904 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
905 m_profile_t *p;
907 /* does filename actually have an extension ? */
908 str = strrchr(file, '.');
909 if (!str)
910 return;
912 sprintf(extension, PROFILE_CFG_EXTENSION);
913 strncat(extension, ++str, 7);
914 p = m_config_get_profile(conf, extension);
915 if (p) {
916 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
917 "Loading extension-related profile '%s'\n", extension);
918 m_config_set_profile(conf, p);
922 #define PROFILE_CFG_VO "vo."
923 #define PROFILE_CFG_AO "ao."
925 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
927 char profile[strlen(cfg) + strlen(out) + 1];
928 m_profile_t *p;
930 sprintf(profile, "%s%s", cfg, out);
931 p = m_config_get_profile(conf, profile);
932 if (p) {
933 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
934 "Loading extension-related profile '%s'\n", profile);
935 m_config_set_profile(conf, p);
940 * Tries to load a config file
941 * @return 0 if file was not found, 1 otherwise
943 static int try_load_config(m_config_t *conf, const char *file)
945 if (!mp_path_exists(file))
946 return 0;
947 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
948 m_config_parse_config_file(conf, file);
949 return 1;
952 static void load_per_file_config(m_config_t *conf, const char * const file)
954 char *confpath;
955 char cfg[MP_PATH_MAX];
956 const char *name;
958 if (strlen(file) > MP_PATH_MAX - 14) {
959 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
960 "can not load file or directory specific config files\n");
961 return;
963 sprintf(cfg, "%s.conf", file);
965 name = mp_basename(cfg);
966 if (use_filedir_conf) {
967 char dircfg[MP_PATH_MAX];
968 strcpy(dircfg, cfg);
969 strcpy(dircfg + (name - cfg), "mplayer.conf");
970 try_load_config(conf, dircfg);
972 if (try_load_config(conf, cfg))
973 return;
976 if ((confpath = get_path(name)) != NULL) {
977 try_load_config(conf, confpath);
979 free(confpath);
983 /* When libmpdemux performs a blocking operation (network connection or
984 * cache filling) if the operation fails we use this function to check
985 * if it was interrupted by the user.
986 * The function returns a new value for eof. */
987 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
989 mp_cmd_t *cmd;
990 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
991 switch (cmd->id) {
992 case MP_CMD_QUIT:
993 exit_player_with_rc(mpctx, EXIT_QUIT,
994 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
995 case MP_CMD_PLAY_TREE_STEP: {
996 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
997 mpctx->play_tree_step =
998 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
999 } break;
1000 case MP_CMD_PLAY_TREE_UP_STEP: {
1001 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1002 } break;
1003 case MP_CMD_PLAY_ALT_SRC_STEP: {
1004 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1005 } break;
1007 mp_cmd_free(cmd);
1009 return stop_play;
1012 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1014 play_tree_add_bpf(entry, bstr(mpctx->filename));
1017 if (!entry) {
1018 entry = mpctx->playtree_iter->tree;
1019 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1020 != PLAY_TREE_ITER_ENTRY)
1021 return PT_NEXT_ENTRY;
1022 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1023 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1024 != PLAY_TREE_ITER_ENTRY)
1025 return PT_NEXT_ENTRY;
1027 play_tree_remove(entry, 1, 1);
1028 return PT_NEXT_SRC;
1030 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1031 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1032 entry = mpctx->playtree_iter->tree;
1033 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1034 != PLAY_TREE_ITER_ENTRY)
1035 return PT_NEXT_ENTRY;
1036 play_tree_remove(entry, 1, 1);
1038 return PT_NEXT_SRC;
1041 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1042 int noerr)
1044 struct MPOpts *opts = &mpctx->opts;
1045 sub_data *subd = NULL;
1046 struct sh_sub *sh = NULL;
1048 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1049 return;
1051 if (opts->ass_enabled) {
1052 #ifdef CONFIG_ASS
1053 struct ass_track *asst;
1054 #ifdef CONFIG_ICONV
1055 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1056 #else
1057 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1058 #endif
1059 bool is_native_ass = asst;
1060 if (!asst) {
1061 subd = sub_read_file(filename, fps, &mpctx->opts);
1062 if (subd) {
1063 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1064 sub_free(subd);
1065 subd = NULL;
1068 if (asst)
1069 sh = sd_ass_create_from_track(asst, is_native_ass, opts);
1070 #endif
1071 } else
1072 subd = sub_read_file(filename, fps, &mpctx->opts);
1075 if (!sh && !subd) {
1076 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1077 "Cannot load subtitles: %s\n", filename_recode(filename));
1078 return;
1081 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = sh;
1082 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1083 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1084 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1085 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1086 filename_recode(filename));
1087 ++mpctx->set_of_sub_size;
1088 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1089 mpctx->set_of_sub_size, filename_recode(filename));
1092 void init_vo_spudec(struct MPContext *mpctx)
1094 unsigned width, height;
1095 spudec_free(vo_spudec);
1096 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1097 vo_spudec = NULL;
1099 // we currently can't work without video stream
1100 if (!mpctx->sh_video)
1101 return;
1103 if (spudec_ifo) {
1104 unsigned int palette[16];
1105 current_module = "spudec_init_vobsub";
1106 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1107 1, -1, NULL) >= 0)
1108 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1111 width = mpctx->sh_video->disp_w;
1112 height = mpctx->sh_video->disp_h;
1114 #ifdef CONFIG_DVDREAD
1115 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1116 current_module = "spudec_init_dvdread";
1117 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1118 cur_pgc->palette, width, height, NULL, 0);
1120 #endif
1122 #ifdef CONFIG_DVDNAV
1123 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1124 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1125 current_module = "spudec_init_dvdnav";
1126 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1128 #endif
1130 if (vo_spudec == NULL) {
1131 sh_sub_t *sh = mpctx->d_sub->sh;
1132 current_module = "spudec_init_normal";
1133 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1134 sh->extradata_len);
1135 spudec_set_font_factor(vo_spudec, font_factor);
1138 if (vo_spudec != NULL) {
1139 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1140 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1141 mpctx);
1146 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1147 * make it all work is to use the builtin SDL-bootstrap code, which
1148 * will be done automatically by replacing our main() if we include SDL.h.
1150 #if defined(__APPLE__) && defined(CONFIG_SDL)
1151 #ifdef CONFIG_SDL_SDL_H
1152 #include <SDL/SDL.h>
1153 #else
1154 #include <SDL.h>
1155 #endif
1156 #endif
1159 * \brief append a formatted string
1160 * \param buf buffer to print into
1161 * \param pos position of terminating 0 in buf
1162 * \param len maximum number of characters in buf, not including terminating 0
1163 * \param format printf format string
1165 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1167 va_list va;
1168 va_start(va, format);
1169 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1170 va_end(va);
1171 if (*pos >= len) {
1172 buf[len] = 0;
1173 *pos = len;
1178 * \brief append time in the hh:mm:ss.f format
1179 * \param buf buffer to print into
1180 * \param pos position of terminating 0 in buf
1181 * \param len maximum number of characters in buf, not including terminating 0
1182 * \param time time value to convert/append
1184 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1186 int64_t tenths = 10 * time;
1187 int f1 = tenths % 10;
1188 int ss = (tenths / 10) % 60;
1189 int mm = (tenths / 600) % 60;
1190 int hh = tenths / 36000;
1191 if (time < 0) {
1192 saddf(buf, pos, len, "unknown");
1193 return;
1195 if (hh > 0)
1196 saddf(buf, pos, len, "%2d:", hh);
1197 if (hh > 0 || mm > 0)
1198 saddf(buf, pos, len, "%02d:", mm);
1199 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1202 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1204 struct MPOpts *opts = &mpctx->opts;
1205 sh_video_t * const sh_video = mpctx->sh_video;
1207 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1208 a_pos = playing_audio_pts(mpctx);
1209 if (mpctx->sh_audio && sh_video && at_frame) {
1210 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1211 if (mpctx->time_frame > 0)
1212 mpctx->last_av_difference +=
1213 mpctx->time_frame * opts->playback_speed;
1214 if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
1215 mpctx->last_av_difference = MP_NOPTS_VALUE;
1216 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1217 && !mpctx->drop_message_shown) {
1218 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1219 mpctx->drop_message_shown = true;
1222 if (opts->quiet)
1223 return;
1225 int width;
1226 char *line;
1227 unsigned pos = 0;
1228 get_screen_size();
1229 if (screen_width > 0)
1230 width = screen_width;
1231 else
1232 width = 80;
1233 #if defined(__MINGW32__) || defined(__CYGWIN__)
1234 /* Windows command line is broken (MinGW's rxvt works, but we
1235 * should not depend on that). */
1236 width--;
1237 #endif
1238 line = malloc(width + 1); // one additional char for the terminating null
1240 // Audio time
1241 if (mpctx->sh_audio) {
1242 if (a_pos != MP_NOPTS_VALUE)
1243 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1244 else
1245 saddf(line, &pos, width, "A: ??? ");
1246 if (!sh_video && a_pos != MP_NOPTS_VALUE) {
1247 float len = get_time_length(mpctx);
1248 saddf(line, &pos, width, "(");
1249 sadd_hhmmssf(line, &pos, width, a_pos);
1250 saddf(line, &pos, width, ") of %.1f (", len);
1251 sadd_hhmmssf(line, &pos, width, len);
1252 saddf(line, &pos, width, ") ");
1256 // Video time
1257 if (sh_video) {
1258 if (mpctx->video_pts != MP_NOPTS_VALUE)
1259 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1260 else
1261 saddf(line, &pos, width, "V: ??? ", mpctx->video_pts);
1264 // A-V sync
1265 if (mpctx->sh_audio && sh_video) {
1266 if (mpctx->last_av_difference != MP_NOPTS_VALUE)
1267 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1268 mpctx->last_av_difference, mpctx->total_avsync_change);
1269 else
1270 saddf(line, &pos, width, "A-V: ??? ct:%7.3f ",
1271 mpctx->total_avsync_change);
1274 // Video stats
1275 if (sh_video)
1276 saddf(line, &pos, width, "%3d/%3d ",
1277 (int)sh_video->num_frames,
1278 (int)sh_video->num_frames_decoded);
1280 // CPU usage
1281 if (sh_video) {
1282 if (sh_video->timer > 0.5)
1283 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1284 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1285 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1286 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1287 else
1288 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1289 } else if (mpctx->sh_audio) {
1290 if (mpctx->delay > 0.5)
1291 saddf(line, &pos, width, "%4.1f%% ",
1292 100.0 * audio_time_usage / (double)mpctx->delay);
1293 else
1294 saddf(line, &pos, width, "??,?%% ");
1297 // VO stats
1298 if (sh_video)
1299 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1301 #ifdef CONFIG_STREAM_CACHE
1302 // cache stats
1303 if (stream_cache_size > 0)
1304 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1305 #endif
1307 // other
1308 if (opts->playback_speed != 1)
1309 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1311 // end
1312 if (erase_to_end_of_line) {
1313 line[pos] = 0;
1314 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1315 "%s%s\r", line, erase_to_end_of_line);
1316 } else {
1317 memset(&line[pos], ' ', width - pos);
1318 line[width] = 0;
1319 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1321 free(line);
1323 mpctx->status_printed = true;
1326 struct stream_dump_progress {
1327 uint64_t count;
1328 unsigned start_time;
1329 unsigned last_print_time;
1332 static void stream_dump_progress_start(struct stream_dump_progress *p)
1334 p->start_time = p->last_print_time = GetTimerMS();
1335 p->count = 0;
1338 static void stream_dump_progress(struct stream_dump_progress *p,
1339 uint64_t len, stream_t *stream)
1341 p->count += len;
1342 unsigned t = GetTimerMS();
1343 if (t - p->last_print_time < 1000)
1344 return;
1346 uint64_t start = stream->start_pos;
1347 uint64_t end = stream->end_pos;
1348 uint64_t pos = stream->pos;
1350 p->last_print_time = t;
1351 /* TODO: pretty print sizes; ETA */
1352 if (end > start && pos >= start && pos <= end) {
1353 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1354 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1355 p->count, 100.0 * (pos - start) / (end - start));
1356 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1357 } else {
1358 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1359 "dump: %"PRIu64 " bytes written", p->count);
1360 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1364 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1366 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1367 p->count, name);
1371 * \brief build a chain of audio filters that converts the input format
1372 * to the ao's format, taking into account the current playback_speed.
1373 * sh_audio describes the requested input format of the chain.
1374 * ao describes the requested output format of the chain.
1376 static int build_afilter_chain(struct MPContext *mpctx)
1378 struct sh_audio *sh_audio = mpctx->sh_audio;
1379 struct ao *ao = mpctx->ao;
1380 struct MPOpts *opts = &mpctx->opts;
1381 int new_srate;
1382 int result;
1383 if (!sh_audio) {
1384 mpctx->mixer.afilter = NULL;
1385 return 0;
1387 if (af_control_any_rev(sh_audio->afilter,
1388 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1389 &opts->playback_speed))
1390 new_srate = sh_audio->samplerate;
1391 else {
1392 new_srate = sh_audio->samplerate * opts->playback_speed;
1393 if (new_srate != ao->samplerate) {
1394 // limits are taken from libaf/af_resample.c
1395 if (new_srate < 8000)
1396 new_srate = 8000;
1397 if (new_srate > 192000)
1398 new_srate = 192000;
1399 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1402 result = init_audio_filters(sh_audio, new_srate,
1403 &ao->samplerate, &ao->channels, &ao->format);
1404 mpctx->mixer.afilter = sh_audio->afilter;
1405 return result;
1409 typedef struct mp_osd_msg mp_osd_msg_t;
1410 struct mp_osd_msg {
1411 /// Previous message on the stack.
1412 mp_osd_msg_t *prev;
1413 /// Message text.
1414 char *msg;
1415 int id, level, started;
1416 /// Display duration in ms.
1417 unsigned time;
1418 // Show full OSD for duration of message instead of static text ('P' key)
1419 bool show_position;
1422 /// OSD message stack.
1423 static mp_osd_msg_t *osd_msg_stack = NULL;
1426 * \brief Add a message on the OSD message stack
1428 * If a message with the same id is already present in the stack
1429 * it is pulled on top of the stack, otherwise a new message is created.
1432 static void set_osd_msg_va(int id, int level, int time, bool show_position,
1433 const char *fmt, va_list ap)
1435 mp_osd_msg_t *msg, *last = NULL;
1437 // look if the id is already in the stack
1438 for (msg = osd_msg_stack; msg && msg->id != id;
1439 last = msg, msg = msg->prev) ;
1440 // not found: alloc it
1441 if (!msg) {
1442 msg = talloc_zero(NULL, mp_osd_msg_t);
1443 msg->prev = osd_msg_stack;
1444 osd_msg_stack = msg;
1445 } else if (last) { // found, but it's not on top of the stack
1446 last->prev = msg->prev;
1447 msg->prev = osd_msg_stack;
1448 osd_msg_stack = msg;
1450 talloc_free(msg->msg);
1451 // write the msg
1452 msg->msg = talloc_vasprintf(msg, fmt, ap);
1453 // set id and time
1454 msg->id = id;
1455 msg->level = level;
1456 msg->time = time;
1457 msg->show_position = show_position;
1460 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1462 va_list ap;
1463 va_start(ap, fmt);
1464 set_osd_msg_va(id, level, time, false, fmt, ap);
1465 va_end(ap);
1468 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1470 va_list ap;
1471 va_start(ap, fmt);
1472 set_osd_msg_va(id, level, time, false, mp_gtext(fmt), ap);
1473 va_end(ap);
1476 void set_osd_progressmsg(int id, int level, int time, ...)
1478 va_list ap;
1479 va_start(ap, time);
1480 set_osd_msg_va(id, level, time, true, "", ap);
1481 va_end(ap);
1485 * \brief Remove a message from the OSD stack
1487 * This function can be used to get rid of a message right away.
1491 void rm_osd_msg(int id)
1493 mp_osd_msg_t *msg, *last = NULL;
1495 // Search for the msg
1496 for (msg = osd_msg_stack; msg && msg->id != id;
1497 last = msg, msg = msg->prev) ;
1498 if (!msg)
1499 return;
1501 // Detach it from the stack and free it
1502 if (last)
1503 last->prev = msg->prev;
1504 else
1505 osd_msg_stack = msg->prev;
1506 talloc_free(msg);
1510 * \brief Remove all messages from the OSD stack
1514 static void clear_osd_msgs(void)
1516 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1517 while (msg) {
1518 prev = msg->prev;
1519 talloc_free(msg);
1520 msg = prev;
1522 osd_msg_stack = NULL;
1526 * \brief Get the current message from the OSD stack.
1528 * This function decrements the message timer and destroys the old ones.
1529 * The message that should be displayed is returned (if any).
1533 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1535 struct MPOpts *opts = &mpctx->opts;
1536 mp_osd_msg_t *msg, *prev, *last = NULL;
1537 static unsigned last_update = 0;
1538 unsigned now = GetTimerMS();
1539 unsigned diff;
1540 char hidden_dec_done = 0;
1542 if (mpctx->osd_visible) {
1543 // 36000000 means max timed visibility is 1 hour into the future, if
1544 // the difference is greater assume it's wrapped around from below 0
1545 if (mpctx->osd_visible - now > 36000000) {
1546 mpctx->osd_visible = 0;
1547 vo_osd_progbar_type = -1; // disable
1548 vo_osd_changed(OSDTYPE_PROGBAR);
1549 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1552 if (mpctx->osd_show_percentage_until - now > 36000000)
1553 mpctx->osd_show_percentage_until = 0;
1555 if (!last_update)
1556 last_update = now;
1557 diff = now >= last_update ? now - last_update : 0;
1559 last_update = now;
1561 // Look for the first message in the stack with high enough level.
1562 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1563 prev = msg->prev;
1564 if (msg->level > opts->osd_level && hidden_dec_done)
1565 continue;
1566 // The message has a high enough level or it is the first hidden one
1567 // in both cases we decrement the timer or kill it.
1568 if (!msg->started || msg->time > diff) {
1569 if (msg->started)
1570 msg->time -= diff;
1571 else
1572 msg->started = 1;
1573 // display it
1574 if (msg->level <= opts->osd_level)
1575 return msg;
1576 hidden_dec_done = 1;
1577 continue;
1579 // kill the message
1580 talloc_free(msg);
1581 if (last) {
1582 last->prev = prev;
1583 msg = last;
1584 } else {
1585 osd_msg_stack = prev;
1586 msg = NULL;
1589 // Nothing found
1590 return NULL;
1594 * \brief Display the OSD bar.
1596 * Display the OSD bar or fall back on a simple message.
1600 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1601 double min, double max, double val)
1603 struct MPOpts *opts = &mpctx->opts;
1604 if (opts->osd_level < 1)
1605 return;
1607 if (mpctx->sh_video) {
1608 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1609 vo_osd_progbar_type = type;
1610 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1611 vo_osd_changed(OSDTYPE_PROGBAR);
1612 return;
1615 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1616 name, ROUND(100 * (val - min) / (max - min)));
1620 * \brief Display text subtitles on the OSD
1622 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1624 int i;
1625 vo_sub = subs;
1626 vo_osd_changed(OSDTYPE_SUBTITLE);
1627 if (!mpctx->sh_video) {
1628 // reverse order, since newest set_osd_msg is displayed first
1629 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1630 if (!subs || i >= subs->lines || !subs->text[i])
1631 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1632 else {
1633 // HACK: currently display time for each sub line
1634 // except the last is set to 2 seconds.
1635 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1636 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1637 "%s", subs->text[i]);
1644 * \brief Update the OSD message line.
1646 * This function displays the current message on the vo OSD or on the term.
1647 * If the stack is empty and the OSD level is high enough the timer
1648 * is displayed (only on the vo OSD).
1652 static void update_osd_msg(struct MPContext *mpctx)
1654 struct MPOpts *opts = &mpctx->opts;
1655 mp_osd_msg_t *msg;
1656 struct osd_state *osd = mpctx->osd;
1658 if (mpctx->add_osd_seek_info) {
1659 double percentage = get_percent_pos(mpctx);
1660 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1661 if (mpctx->sh_video)
1662 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1663 mpctx->add_osd_seek_info = false;
1666 // Look if we have a msg
1667 if ((msg = get_osd_msg(mpctx)) && !msg->show_position) {
1668 if (strcmp(osd->osd_text, msg->msg)) {
1669 osd_set_text(osd, msg->msg);
1670 if (mpctx->sh_video)
1671 vo_osd_changed(OSDTYPE_OSD);
1672 else if (opts->term_osd)
1673 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1674 msg->msg);
1676 return;
1679 int osdlevel = opts->osd_level;
1680 if (msg && msg->show_position)
1681 osdlevel = 3;
1683 if (mpctx->sh_video) {
1684 // fallback on the timer
1685 char osd_text_timer[128] = {0};
1686 if (osdlevel >= 2) {
1687 int len = get_time_length(mpctx);
1688 int percentage = -1;
1689 char percentage_text[10];
1690 char fractions_text[4];
1691 double fpts = get_current_time(mpctx);
1692 int pts = fpts;
1694 if (mpctx->osd_show_percentage_until)
1695 percentage = get_percent_pos(mpctx);
1697 if (percentage >= 0)
1698 snprintf(percentage_text, 9, " (%d%%)", percentage);
1699 else
1700 percentage_text[0] = 0;
1702 if (opts->osd_fractions == 1) {
1703 //print fractions as sub-second timestamp
1704 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1705 (int)((fpts - pts) * 100));
1706 } else if (opts->osd_fractions == 2) {
1707 /* Print fractions by estimating the frame count within the
1708 * second.
1710 * Rounding or cutting off numbers after the decimal point
1711 * causes problems because of float's precision and movies
1712 * whose first frame is not exactly at timestamp 0. Therefore,
1713 * we add 0.2 and cut off at the decimal point, which proved
1714 * to be good heuristic.
1716 double fps = mpctx->sh_video->fps;
1717 if (fps <= 1 || fps > 99)
1718 strcpy(fractions_text, ".??");
1719 else
1720 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1721 (int) ((fpts - pts) * fps + 0.2));
1722 } else {
1723 //do not print fractions
1724 fractions_text[0] = 0;
1727 osd_get_function_sym(osd_text_timer, sizeof(osd_text_timer),
1728 mpctx->osd_function);
1729 size_t blen = strlen(osd_text_timer);
1731 if (osdlevel == 3)
1732 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1733 " %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1734 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1735 len / 3600, (len / 60) % 60, len % 60,
1736 percentage_text);
1737 else
1738 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1739 " %02d:%02d:%02d%s%s",
1740 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1741 percentage_text);
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 uninit_player(mpctx, INITIALIZED_AO);
1765 return;
1767 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1768 current_module = "init_audio_codec";
1769 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1770 goto init_error;
1771 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1774 current_module = "af_preinit";
1775 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1776 mpctx->initialized_flags |= INITIALIZED_AO;
1777 mpctx->ao = ao_create(opts, mpctx->input);
1778 mpctx->ao->samplerate = force_srate;
1779 mpctx->ao->format = opts->audio_output_format;
1781 ao = mpctx->ao;
1783 // first init to detect best values
1784 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1785 // input:
1786 mpctx->sh_audio->samplerate,
1787 // output:
1788 &ao->samplerate, &ao->channels, &ao->format)) {
1789 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1790 "pre-init!\n");
1791 exit_player(mpctx, EXIT_ERROR);
1793 if (!ao->initialized) {
1794 current_module = "ao2_init";
1795 ao->buffersize = opts->ao_buffersize;
1796 ao_init(ao, opts->audio_driver_list);
1797 if (!ao->initialized) {
1798 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1799 "Could not open/initialize audio device -> no sound.\n");
1800 goto init_error;
1802 ao->buffer.start = talloc_new(ao);
1803 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1804 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1805 ao->driver->info->short_name,
1806 ao->samplerate, ao->channels,
1807 af_fmt2str_short(ao->format),
1808 af_fmt2bits(ao->format) / 8);
1809 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1810 ao->driver->info->name, ao->driver->info->author);
1811 if (strlen(ao->driver->info->comment) > 0)
1812 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1813 ao->driver->info->comment);
1816 // init audio filters:
1817 current_module = "af_init";
1818 if (!build_afilter_chain(mpctx)) {
1819 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1820 "Couldn't find matching filter/ao format!\n");
1821 goto init_error;
1823 mpctx->mixer.volstep = volstep;
1824 mpctx->mixer.softvol = opts->softvol;
1825 mpctx->mixer.softvol_max = opts->softvol_max;
1826 mixer_reinit(&mpctx->mixer, ao);
1827 mpctx->syncing_audio = true;
1828 return;
1830 init_error:
1831 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1832 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1833 mpctx->d_audio->id = -2;
1837 // Return pts value corresponding to the end point of audio written to the
1838 // ao so far.
1839 static double written_audio_pts(struct MPContext *mpctx)
1841 sh_audio_t *sh_audio = mpctx->sh_audio;
1842 if (!sh_audio)
1843 return MP_NOPTS_VALUE;
1844 demux_stream_t *d_audio = mpctx->d_audio;
1845 // first calculate the end pts of audio that has been output by decoder
1846 double a_pts = sh_audio->pts;
1847 if (a_pts != MP_NOPTS_VALUE)
1848 // Good, decoder supports new way of calculating audio pts.
1849 // sh_audio->pts is the timestamp of the latest input packet with
1850 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1851 // the amount of bytes the decoder has written after that timestamp.
1852 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1853 else {
1854 // Decoder doesn't support new way of calculating pts (or we're
1855 // being called before it has decoded anything with known timestamp).
1856 // Use the old method of audio pts calculation: take the timestamp
1857 // of last packet with known pts the decoder has read data from,
1858 // and add amount of bytes read after the beginning of that packet
1859 // divided by input bps. This will be inaccurate if the input/output
1860 // ratio is not constant for every audio packet or if it is constant
1861 // but not accurately known in sh_audio->i_bps.
1863 a_pts = d_audio->pts;
1864 if (a_pts == MP_NOPTS_VALUE)
1865 return a_pts;
1867 // ds_tell_pts returns bytes read after last timestamp from
1868 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1869 // it has read but not decoded
1870 if (sh_audio->i_bps)
1871 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1872 (double)sh_audio->i_bps;
1874 // Now a_pts hopefully holds the pts for end of audio from decoder.
1875 // Substract data in buffers between decoder and audio out.
1877 // Decoded but not filtered
1878 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1880 // Data buffered in audio filters, measured in bytes of "missing" output
1881 double buffered_output = af_calc_delay(sh_audio->afilter);
1883 // Data that was ready for ao but was buffered because ao didn't fully
1884 // accept everything to internal buffers yet
1885 buffered_output += mpctx->ao->buffer.len;
1887 // Filters divide audio length by playback_speed, so multiply by it
1888 // to get the length in original units without speedup or slowdown
1889 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1891 return a_pts + mpctx->video_offset;
1894 // Return pts value corresponding to currently playing audio.
1895 double playing_audio_pts(struct MPContext *mpctx)
1897 double pts = written_audio_pts(mpctx);
1898 if (pts == MP_NOPTS_VALUE)
1899 return pts;
1900 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1903 static bool is_av_sub(int type)
1905 return type == 'b' || type == 'p' || type == 'x';
1908 void update_subtitles(struct MPContext *mpctx, double refpts_tl, bool reset)
1910 mpctx->osd->sub_offset = mpctx->video_offset;
1911 struct MPOpts *opts = &mpctx->opts;
1912 struct sh_video *sh_video = mpctx->sh_video;
1913 struct demux_stream *d_sub = mpctx->d_sub;
1914 double refpts_s = refpts_tl - mpctx->osd->sub_offset;
1915 double curpts_s = refpts_s + sub_delay;
1916 unsigned char *packet = NULL;
1917 int len;
1918 struct sh_sub *sh_sub = d_sub->sh;
1919 int type = sh_sub ? sh_sub->type : 'v';
1920 static subtitle subs;
1921 if (reset) {
1922 if (sh_sub)
1923 sub_reset(sh_sub, mpctx->osd);
1924 sub_clear_text(&subs, MP_NOPTS_VALUE);
1925 if (vo_sub)
1926 set_osd_subtitle(mpctx, NULL);
1927 if (vo_spudec) {
1928 spudec_reset(vo_spudec);
1929 vo_osd_changed(OSDTYPE_SPU);
1931 return;
1933 // find sub
1934 if (mpctx->subdata) {
1935 if (sub_fps == 0)
1936 sub_fps = sh_video ? sh_video->fps : 25;
1937 current_module = "find_sub";
1938 find_sub(mpctx, mpctx->subdata, curpts_s *
1939 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1940 if (vo_sub)
1941 mpctx->vo_sub_last = vo_sub;
1944 // DVD sub:
1945 if (vobsub_id >= 0 || type == 'v') {
1946 int timestamp;
1947 current_module = "spudec";
1948 /* Get a sub packet from the DVD or a vobsub */
1949 while (1) {
1950 // Vobsub
1951 len = 0;
1952 if (vo_vobsub) {
1953 if (curpts_s >= 0) {
1954 len = vobsub_get_packet(vo_vobsub, curpts_s,
1955 (void **)&packet, &timestamp);
1956 if (len > 0)
1957 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1958 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1959 len, refpts_s, sh_video->timer,
1960 timestamp / 90000.0, timestamp);
1962 } else {
1963 // DVD sub
1964 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1965 if (len > 0) {
1966 // XXX This is wrong, sh_video->pts can be arbitrarily
1967 // much behind demuxing position. Unfortunately using
1968 // d_video->pts which would have been the simplest
1969 // improvement doesn't work because mpeg specific hacks
1970 // in video.c set d_video->pts to 0.
1971 float x = d_sub->pts - refpts_s;
1972 if (x > -20 && x < 20) // prevent missing subs on pts reset
1973 timestamp = 90000 * d_sub->pts;
1974 else
1975 timestamp = 90000 * curpts_s;
1976 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1977 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1978 refpts_s, d_sub->pts, timestamp);
1981 if (len <= 0 || !packet)
1982 break;
1983 // create it only here, since with some broken demuxers we might
1984 // type = v but no DVD sub and we currently do not change the
1985 // "original frame size" ever after init, leading to wrong-sized
1986 // PGS subtitles.
1987 if (!vo_spudec)
1988 vo_spudec = spudec_new(NULL);
1989 if (vo_vobsub || timestamp >= 0)
1990 spudec_assemble(vo_spudec, packet, len, timestamp);
1992 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1993 if (type == 'd' && !d_sub->demuxer->teletext) {
1994 tt_stream_props tsp = { 0 };
1995 void *ptr = &tsp;
1996 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
1997 VBI_CONTROL_TRUE)
1998 d_sub->demuxer->teletext = ptr;
2000 if (d_sub->non_interleaved)
2001 ds_get_next_pts(d_sub);
2003 while (d_sub->first) {
2004 double subpts_s = ds_get_next_pts(d_sub);
2005 if (subpts_s > curpts_s) {
2006 // Libass handled subs can be fed to it in advance
2007 if (!opts->ass_enabled || !is_text_sub(type))
2008 break;
2009 // Try to avoid demuxing whole file at once
2010 if (d_sub->non_interleaved && subpts_s > curpts_s + 1)
2011 break;
2013 double duration = d_sub->first->duration;
2014 len = ds_get_packet_sub(d_sub, &packet);
2015 if (type == 'm') {
2016 if (len < 2)
2017 continue;
2018 len = FFMIN(len - 2, AV_RB16(packet));
2019 packet += 2;
2021 if (type == 'd') {
2022 if (d_sub->demuxer->teletext) {
2023 uint8_t *p = packet;
2024 p++;
2025 len--;
2026 while (len >= 46) {
2027 int sublen = p[1];
2028 if (p[0] == 2 || p[0] == 3)
2029 teletext_control(d_sub->demuxer->teletext,
2030 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2031 p += sublen + 2;
2032 len -= sublen + 2;
2035 continue;
2037 if (sh_sub && sh_sub->active) {
2038 sub_decode(sh_sub, mpctx->osd, packet, len, subpts_s, duration);
2039 continue;
2041 if (subpts_s != MP_NOPTS_VALUE) {
2042 if (duration < 0)
2043 sub_clear_text(&subs, MP_NOPTS_VALUE);
2044 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2045 int i;
2046 unsigned char *p = packet;
2047 for (i = 0; i < 8 && *p != '\0'; p++)
2048 if (*p == ',')
2049 i++;
2050 if (*p == '\0') /* Broken line? */
2051 continue;
2052 len -= p - packet;
2053 packet = p;
2055 double endpts_s = MP_NOPTS_VALUE;
2056 if (subpts_s != MP_NOPTS_VALUE && duration >= 0)
2057 endpts_s = subpts_s + duration;
2058 sub_add_text(&subs, packet, len, endpts_s);
2059 set_osd_subtitle(mpctx, &subs);
2061 if (d_sub->non_interleaved)
2062 ds_get_next_pts(d_sub);
2064 if (!opts->ass_enabled)
2065 if (sub_clear_text(&subs, curpts_s))
2066 set_osd_subtitle(mpctx, &subs);
2068 if (vo_spudec) {
2069 spudec_heartbeat(vo_spudec, 90000 * curpts_s);
2070 if (spudec_changed(vo_spudec))
2071 vo_osd_changed(OSDTYPE_SPU);
2074 current_module = NULL;
2077 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2079 int page_changed;
2081 if (!demuxer->teletext)
2082 return;
2084 //Also forcing page update when such ioctl is not supported or call error occured
2085 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2086 &page_changed) != VBI_CONTROL_TRUE)
2087 page_changed = 1;
2089 if (!page_changed)
2090 return;
2092 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2093 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2094 vo_osd_teletext_page = NULL;
2095 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2096 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2097 vo_osd_teletext_half = 0;
2098 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2099 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2100 vo_osd_teletext_mode = 0;
2101 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2102 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2103 vo_osd_teletext_format = 0;
2104 vo_osd_changed(OSDTYPE_TELETEXT);
2106 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2109 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2111 struct MPOpts *opts = &mpctx->opts;
2112 // check for frame-drop:
2113 current_module = "check_framedrop";
2114 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2115 static int dropped_frames;
2116 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2117 float d = delay - mpctx->delay;
2118 ++total_frame_cnt;
2119 // we should avoid dropping too many frames in sequence unless we
2120 // are too late. and we allow 100ms A-V delay here:
2121 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2122 && !mpctx->restart_playback) {
2123 ++drop_frame_cnt;
2124 ++dropped_frames;
2125 return frame_dropping;
2126 } else
2127 dropped_frames = 0;
2129 return 0;
2133 #ifdef HAVE_RTC
2134 int rtc_fd = -1;
2135 #endif
2137 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2139 #ifdef HAVE_RTC
2140 if (rtc_fd >= 0) {
2141 // -------- RTC -----------
2142 current_module = "sleep_rtc";
2143 while (time_frame > 0.000) {
2144 unsigned long rtc_ts;
2145 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2146 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2147 "Linux RTC read error: %s\n", strerror(errno));
2148 time_frame -= get_relative_time(mpctx);
2150 } else
2151 #endif
2153 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2154 // unnecessarily high CPU usage
2155 struct MPOpts *opts = &mpctx->opts;
2156 float margin = opts->softsleep ? 0.011 : 0;
2157 current_module = "sleep_timer";
2158 while (time_frame > margin) {
2159 usec_sleep(1000000 * (time_frame - margin));
2160 time_frame -= get_relative_time(mpctx);
2162 if (opts->softsleep) {
2163 current_module = "sleep_soft";
2164 if (time_frame < 0)
2165 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2166 "Warning! Softsleep underflow!\n");
2167 while (time_frame > 0)
2168 time_frame -= get_relative_time(mpctx); // burn the CPU
2171 return time_frame;
2174 static int select_subtitle(MPContext *mpctx)
2176 struct MPOpts *opts = &mpctx->opts;
2177 // find the best sub to use
2178 int id;
2179 int found = 0;
2180 mpctx->global_sub_pos = -1; // no subs by default
2181 if (vobsub_id >= 0) {
2182 // if user asks for a vobsub id, use that first.
2183 id = vobsub_id;
2184 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2185 M_PROPERTY_OK;
2188 if (!found && opts->sub_id >= 0) {
2189 // if user asks for a dvd sub id, use that next.
2190 id = opts->sub_id;
2191 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2192 M_PROPERTY_OK;
2195 if (!found) {
2196 // if there are text subs to use, use those. (autosubs come last here)
2197 id = 0;
2198 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2199 M_PROPERTY_OK;
2202 if (!found && opts->sub_id == -1) {
2203 // finally select subs by language and container hints
2204 if (opts->sub_id == -1)
2205 opts->sub_id =
2206 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2207 opts->sub_lang);
2208 if (opts->sub_id >= 0) {
2209 id = opts->sub_id;
2210 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2211 M_PROPERTY_OK;
2214 return found;
2217 #ifdef CONFIG_DVDNAV
2218 #ifndef FF_B_TYPE
2219 #define FF_B_TYPE 3
2220 #endif
2221 /// store decoded video image
2222 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2223 mp_image_t *from_mpi)
2225 mp_image_t *mpi;
2227 /// Do not store B-frames
2228 if (from_mpi->pict_type == FF_B_TYPE)
2229 return to_mpi;
2231 if (to_mpi &&
2232 to_mpi->w == from_mpi->w &&
2233 to_mpi->h == from_mpi->h &&
2234 to_mpi->imgfmt == from_mpi->imgfmt)
2235 mpi = to_mpi;
2236 else {
2237 if (to_mpi)
2238 free_mp_image(to_mpi);
2239 if (from_mpi->w == 0 || from_mpi->h == 0)
2240 return NULL;
2241 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2244 copy_mpi(mpi, from_mpi);
2245 return mpi;
2248 static void mp_dvdnav_reset_stream(MPContext *ctx)
2250 struct MPOpts *opts = &ctx->opts;
2251 if (ctx->sh_video) {
2252 /// clear video pts
2253 ctx->d_video->pts = 0.0f;
2254 ctx->sh_video->pts = 0.0f;
2255 ctx->sh_video->i_pts = 0.0f;
2256 ctx->sh_video->last_pts = 0.0f;
2257 ctx->sh_video->num_buffered_pts = 0;
2258 ctx->sh_video->num_frames = 0;
2259 ctx->sh_video->num_frames_decoded = 0;
2260 ctx->sh_video->timer = 0.0f;
2261 ctx->sh_video->stream_delay = 0.0f;
2262 ctx->sh_video->timer = 0;
2263 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2266 if (ctx->sh_audio) {
2267 /// free audio packets and reset
2268 ds_free_packs(ctx->d_audio);
2269 audio_delay -= ctx->sh_audio->stream_delay;
2270 ctx->delay = -audio_delay;
2271 ao_reset(ctx->ao);
2272 resync_audio_stream(ctx->sh_audio);
2275 audio_delay = 0.0f;
2276 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2277 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2278 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2279 if (dvdsub_lang_id != opts->sub_id) {
2280 opts->sub_id = dvdsub_lang_id;
2281 select_subtitle(ctx);
2285 /// clear all EOF related flags
2286 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2289 /// Restore last decoded DVDNAV (still frame)
2290 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2291 int *in_size,
2292 unsigned char **start,
2293 mp_image_t *decoded_frame)
2295 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2296 return decoded_frame;
2298 /// a change occurred in dvdnav stream
2299 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2300 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2301 mp_dvdnav_context_free(mpctx);
2302 mp_dvdnav_reset_stream(mpctx);
2303 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2304 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2307 if (*in_size < 0) {
2308 float len;
2310 /// Display still frame, if any
2311 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2312 decoded_frame = mpctx->nav_smpi;
2314 /// increment video frame : continue playing after still frame
2315 len = get_time_length(mpctx);
2316 if (mpctx->sh_video->pts >= len &&
2317 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2318 mp_dvdnav_skip_still(mpctx->stream);
2319 mp_dvdnav_skip_wait(mpctx->stream);
2321 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2323 if (mpctx->nav_buffer) {
2324 *start = mpctx->nav_start;
2325 *in_size = mpctx->nav_in_size;
2326 if (mpctx->nav_start)
2327 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2331 return decoded_frame;
2334 /// Save last decoded DVDNAV (still frame)
2335 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2336 unsigned char *start,
2337 mp_image_t *decoded_frame)
2339 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2340 return;
2342 free(mpctx->nav_buffer);
2343 mpctx->nav_buffer = NULL;
2344 mpctx->nav_start = NULL;
2345 mpctx->nav_in_size = -1;
2347 if (in_size > 0)
2348 mpctx->nav_buffer = malloc(in_size);
2349 if (mpctx->nav_buffer) {
2350 mpctx->nav_start = start;
2351 mpctx->nav_in_size = in_size;
2352 memcpy(mpctx->nav_buffer, start, in_size);
2355 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2356 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2358 #endif /* CONFIG_DVDNAV */
2360 /* Modify video timing to match the audio timeline. There are two main
2361 * reasons this is needed. First, video and audio can start from different
2362 * positions at beginning of file or after a seek (MPlayer starts both
2363 * immediately even if they have different pts). Second, the file can have
2364 * audio timestamps that are inconsistent with the duration of the audio
2365 * packets, for example two consecutive timestamp values differing by
2366 * one second but only a packet with enough samples for half a second
2367 * of playback between them.
2369 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2371 current_module = "av_sync";
2373 if (!mpctx->sh_audio || mpctx->syncing_audio)
2374 return;
2376 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2377 double v_pts = mpctx->sh_video->pts;
2378 double av_delay = a_pts - v_pts;
2379 // Try to sync vo_flip() so it will *finish* at given time
2380 av_delay += mpctx->last_vo_flip_duration;
2381 av_delay -= audio_delay; // This much pts difference is desired
2383 double change = av_delay * 0.1;
2384 double max_change = default_max_pts_correction >= 0 ?
2385 default_max_pts_correction : frame_time * 0.1;
2386 if (change < -max_change)
2387 change = -max_change;
2388 else if (change > max_change)
2389 change = max_change;
2390 mpctx->delay += change;
2391 mpctx->total_avsync_change += change;
2394 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2395 double pts)
2397 if (mpctx->paused)
2398 return 0;
2399 struct ao *ao = mpctx->ao;
2400 double bps = ao->bps / mpctx->opts.playback_speed;
2401 ao->pts = pts;
2402 // hack used by some mpeg-writing AOs
2403 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2404 mpctx->delay) * 90000.0;
2405 int played = ao_play(mpctx->ao, data, len, flags);
2406 if (played > 0) {
2407 mpctx->delay += played / bps;
2408 // Keep correct pts for remaining data - could be used to flush
2409 // remaining buffer when closing ao.
2410 ao->pts += played / bps;
2412 return played;
2415 #define ASYNC_PLAY_DONE -3
2416 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2418 struct ao *ao = mpctx->ao;
2419 struct MPOpts *opts = &mpctx->opts;
2420 sh_audio_t * const sh_audio = mpctx->sh_audio;
2421 int res;
2423 // Timing info may not be set without
2424 res = decode_audio(sh_audio, &ao->buffer, 1);
2425 if (res < 0)
2426 return res;
2428 int bytes;
2429 bool did_retry = false;
2430 double written_pts;
2431 double bps = ao->bps / opts->playback_speed;
2432 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2433 mpctx->hrseek_active = false;
2434 while (1) {
2435 written_pts = written_audio_pts(mpctx);
2436 double ptsdiff;
2437 if (hrseek)
2438 ptsdiff = written_pts - mpctx->hrseek_pts;
2439 else
2440 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2441 - audio_delay;
2442 bytes = ptsdiff * bps;
2443 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2445 // ogg demuxers give packets without timing
2446 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2447 if (!did_retry) {
2448 // Try to read more data to see packets that have pts
2449 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2450 if (res < 0)
2451 return res;
2452 did_retry = true;
2453 continue;
2455 bytes = 0;
2458 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2459 bytes = 0;
2461 if (bytes > 0)
2462 break;
2464 mpctx->syncing_audio = false;
2465 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2466 int res = decode_audio(sh_audio, &ao->buffer, a);
2467 bytes += ao->buffer.len;
2468 if (bytes >= 0) {
2469 memmove(ao->buffer.start,
2470 ao->buffer.start + ao->buffer.len - bytes, bytes);
2471 ao->buffer.len = bytes;
2472 if (res < 0)
2473 return res;
2474 return decode_audio(sh_audio, &ao->buffer, playsize);
2476 ao->buffer.len = 0;
2477 if (res < 0)
2478 return res;
2480 if (hrseek)
2481 // Don't add silence in audio-only case even if position is too late
2482 return 0;
2483 int fillbyte = 0;
2484 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2485 fillbyte = 0x80;
2486 if (bytes >= playsize) {
2487 /* This case could fall back to the one below with
2488 * bytes = playsize, but then silence would keep accumulating
2489 * in a_out_buffer if the AO accepts less data than it asks for
2490 * in playsize. */
2491 char *p = malloc(playsize);
2492 memset(p, fillbyte, playsize);
2493 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2494 free(p);
2495 return ASYNC_PLAY_DONE;
2497 mpctx->syncing_audio = false;
2498 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2499 return decode_audio(sh_audio, &ao->buffer, playsize);
2502 static int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
2504 struct MPOpts *opts = &mpctx->opts;
2505 struct ao *ao = mpctx->ao;
2506 unsigned int t;
2507 double tt;
2508 int playsize;
2509 int playflags = 0;
2510 bool audio_eof = false;
2511 bool partial_fill = false;
2512 sh_audio_t * const sh_audio = mpctx->sh_audio;
2513 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2514 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2516 current_module = "play_audio";
2518 // hack used by some mpeg-writing AOs
2519 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2520 mpctx->delay) * 90000.0;
2522 if (mpctx->paused)
2523 playsize = 1; // just initialize things (audio pts at least)
2524 else
2525 playsize = ao_get_space(ao);
2527 // Fill buffer if needed:
2528 current_module = "decode_audio";
2529 t = GetTimer();
2531 // Coming here with hrseek_active still set means audio-only
2532 if (!mpctx->sh_video)
2533 mpctx->syncing_audio = false;
2534 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2535 mpctx->syncing_audio = false;
2536 mpctx->hrseek_active = false;
2539 int res;
2540 if (mpctx->syncing_audio || mpctx->hrseek_active)
2541 res = audio_start_sync(mpctx, playsize);
2542 else
2543 res = decode_audio(sh_audio, &ao->buffer, playsize);
2544 if (res < 0) { // EOF, error or format change
2545 if (res == -2) {
2546 /* The format change isn't handled too gracefully. A more precise
2547 * implementation would require draining buffered old-format audio
2548 * while displaying video, then doing the output format switch.
2550 uninit_player(mpctx, INITIALIZED_AO);
2551 reinit_audio_chain(mpctx);
2552 return -1;
2553 } else if (res == ASYNC_PLAY_DONE)
2554 return 0;
2555 else if (mpctx->d_audio->eof)
2556 audio_eof = true;
2558 t = GetTimer() - t;
2559 tt = t * 0.000001f;
2560 audio_time_usage += tt;
2561 if (endpts != MP_NOPTS_VALUE && modifiable_audio_format) {
2562 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2563 * ao->bps / opts->playback_speed;
2564 if (playsize > bytes) {
2565 playsize = FFMAX(bytes, 0);
2566 playflags |= AOPLAY_FINAL_CHUNK;
2567 audio_eof = true;
2568 partial_fill = true;
2572 assert(ao->buffer.len % unitsize == 0);
2573 if (playsize > ao->buffer.len) {
2574 partial_fill = true;
2575 playsize = ao->buffer.len;
2576 if (audio_eof)
2577 playflags |= AOPLAY_FINAL_CHUNK;
2579 playsize -= playsize % unitsize;
2580 if (!playsize)
2581 return partial_fill && audio_eof ? -2 : -partial_fill;
2583 // play audio:
2584 current_module = "play_audio";
2586 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2587 written_audio_pts(mpctx));
2588 assert(played % unitsize == 0);
2589 ao->buffer_playable_size = playsize - played;
2591 if (played > 0) {
2592 ao->buffer.len -= played;
2593 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2594 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2595 // Sanity check to avoid hanging in case current ao doesn't output
2596 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2597 return -2;
2600 return -partial_fill;
2603 int reinit_video_chain(struct MPContext *mpctx)
2605 struct MPOpts *opts = &mpctx->opts;
2606 sh_video_t * const sh_video = mpctx->sh_video;
2607 if (!sh_video) {
2608 uninit_player(mpctx, INITIALIZED_VO);
2609 return 0;
2611 double ar = -1.0;
2612 //================== Init VIDEO (codec & libvo) ==========================
2613 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2614 current_module = "preinit_libvo";
2616 //shouldn't we set dvideo->id=-2 when we fail?
2617 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2618 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->key_fifo,
2619 mpctx->input))) {
2620 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2621 "the selected video_out (-vo) device.\n");
2622 goto err_out;
2624 mpctx->initialized_flags |= INITIALIZED_VO;
2627 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2628 &ar) != STREAM_UNSUPPORTED)
2629 mpctx->sh_video->stream_aspect = ar;
2630 current_module = "init_video_filters";
2632 char *vf_arg[] = {
2633 "_oldargs_", (char *)mpctx->video_out, NULL
2635 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2638 #ifdef CONFIG_ASS
2639 if (opts->ass_enabled) {
2640 int i;
2641 int insert = 1;
2642 if (opts->vf_settings)
2643 for (i = 0; opts->vf_settings[i].name; ++i)
2644 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2645 insert = 0;
2646 break;
2648 if (insert) {
2649 extern vf_info_t vf_info_ass;
2650 const vf_info_t *libass_vfs[] = {
2651 &vf_info_ass, NULL
2653 char *vf_arg[] = {
2654 "auto", "1", NULL
2656 int retcode = 0;
2657 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2658 sh_video->vfilter,
2659 "ass", vf_arg,
2660 &retcode);
2661 if (vf_ass)
2662 sh_video->vfilter = vf_ass;
2663 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2664 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2665 else
2666 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2667 "ASS: cannot add video filter\n");
2670 #endif
2672 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2674 if (opts->ass_enabled)
2675 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2676 mpctx->ass_library);
2678 current_module = "init_video_codec";
2680 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2682 if (!sh_video->initialized) {
2683 if (!opts->fixed_vo)
2684 uninit_player(mpctx, INITIALIZED_VO);
2685 goto err_out;
2688 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2690 if (sh_video->codec)
2691 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2692 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2694 sh_video->last_pts = MP_NOPTS_VALUE;
2695 sh_video->num_buffered_pts = 0;
2696 sh_video->next_frame_time = 0;
2697 mpctx->restart_playback = true;
2698 mpctx->delay = 0;
2700 if (opts->auto_quality > 0) {
2701 // Auto quality option enabled
2702 output_quality = get_video_quality_max(sh_video);
2703 if (opts->auto_quality > output_quality)
2704 opts->auto_quality = output_quality;
2705 else
2706 output_quality = opts->auto_quality;
2707 mp_msg(MSGT_CPLAYER, MSGL_V,
2708 "AutoQ: setting quality to %d.\n", output_quality);
2709 set_video_quality(sh_video, output_quality);
2712 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2714 current_module = "init_vo";
2716 return 1;
2718 err_out:
2719 mpctx->sh_video = mpctx->d_video->sh = NULL;
2720 return 0;
2723 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2725 struct sh_video *sh_video = mpctx->sh_video;
2726 double frame_time = 0;
2727 struct vo *video_out = mpctx->video_out;
2728 while (1) {
2729 current_module = "filter_video";
2730 // In nocorrect-pts mode there is no way to properly time these frames
2731 if (vo_get_buffered_frame(video_out, 0) >= 0)
2732 break;
2733 if (vf_output_queued_frame(sh_video->vfilter))
2734 break;
2735 unsigned char *packet = NULL;
2736 frame_time = sh_video->next_frame_time;
2737 if (mpctx->restart_playback)
2738 frame_time = 0;
2739 int in_size = 0;
2740 while (!in_size)
2741 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2742 &packet, force_fps);
2743 if (in_size < 0) {
2744 #ifdef CONFIG_DVDNAV
2745 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2746 if (mp_dvdnav_is_eof(mpctx->stream))
2747 return -1;
2748 if (mpctx->d_video)
2749 mpctx->d_video->eof = 0;
2750 if (mpctx->d_audio)
2751 mpctx->d_audio->eof = 0;
2752 mpctx->stream->eof = 0;
2753 } else
2754 #endif
2755 return -1;
2757 if (in_size > max_framesize)
2758 max_framesize = in_size;
2759 sh_video->timer += frame_time;
2760 if (mpctx->sh_audio)
2761 mpctx->delay -= frame_time;
2762 // video_read_frame can change fps (e.g. for ASF video)
2763 vo_fps = sh_video->fps;
2764 int framedrop_type = check_framedrop(mpctx, frame_time);
2765 current_module = "decode video";
2767 void *decoded_frame;
2768 #ifdef CONFIG_DVDNAV
2769 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2770 if (in_size >= 0 && !decoded_frame)
2771 #endif
2772 decoded_frame = decode_video(sh_video, sh_video->ds->current, packet,
2773 in_size, framedrop_type, sh_video->pts);
2774 #ifdef CONFIG_DVDNAV
2775 // Save last still frame for future display
2776 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2777 #endif
2778 if (decoded_frame) {
2779 current_module = "filter video";
2780 filter_video(sh_video, decoded_frame, sh_video->pts);
2782 break;
2784 return frame_time;
2787 static void determine_frame_pts(struct MPContext *mpctx)
2789 struct sh_video *sh_video = mpctx->sh_video;
2790 struct MPOpts *opts = &mpctx->opts;
2792 if (opts->user_pts_assoc_mode)
2793 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2794 else if (sh_video->pts_assoc_mode == 0) {
2795 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2796 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2797 sh_video->pts_assoc_mode = 1;
2798 else
2799 sh_video->pts_assoc_mode = 2;
2800 } else {
2801 int probcount1 = sh_video->num_reordered_pts_problems;
2802 int probcount2 = sh_video->num_sorted_pts_problems;
2803 if (sh_video->pts_assoc_mode == 2) {
2804 int tmp = probcount1;
2805 probcount1 = probcount2;
2806 probcount2 = tmp;
2808 if (probcount1 >= probcount2 * 1.5 + 2) {
2809 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2810 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2811 "%d.\n", sh_video->pts_assoc_mode);
2814 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2815 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2818 static double update_video(struct MPContext *mpctx)
2820 struct sh_video *sh_video = mpctx->sh_video;
2821 struct vo *video_out = mpctx->video_out;
2822 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2823 mpctx->osd); // hack for vf_expand
2824 if (!mpctx->opts.correct_pts)
2825 return update_video_nocorrect_pts(mpctx);
2827 double pts;
2829 while (1) {
2830 current_module = "filter_video";
2831 if (vo_get_buffered_frame(video_out, false) >= 0)
2832 break;
2833 // XXX Time used in this call is not counted in any performance
2834 // timer now
2835 if (vf_output_queued_frame(sh_video->vfilter))
2836 break;
2837 int in_size = 0;
2838 unsigned char *buf = NULL;
2839 pts = MP_NOPTS_VALUE;
2840 struct demux_packet *pkt;
2841 while (1) {
2842 pkt = ds_get_packet2(mpctx->d_video, false);
2843 if (!pkt || pkt->len)
2844 break;
2845 /* Packets with size 0 are assumed to not correspond to frames,
2846 * but to indicate the absence of a frame in formats like AVI
2847 * that must have packets at fixed timecode intervals. */
2849 if (pkt) {
2850 in_size = pkt->len;
2851 buf = pkt->buffer;
2852 pts = pkt->pts;
2854 if (pts != MP_NOPTS_VALUE)
2855 pts += mpctx->video_offset;
2856 if (in_size > max_framesize)
2857 max_framesize = in_size;
2858 current_module = "decode video";
2859 if (pts >= mpctx->hrseek_pts - .005)
2860 mpctx->hrseek_framedrop = false;
2861 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2862 check_framedrop(mpctx, sh_video->frametime);
2863 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2864 framedrop_type, pts);
2865 if (decoded_frame) {
2866 determine_frame_pts(mpctx);
2867 current_module = "filter video";
2868 filter_video(sh_video, decoded_frame, sh_video->pts);
2869 } else if (!pkt) {
2870 if (vo_get_buffered_frame(video_out, true) < 0)
2871 return -1;
2873 break;
2876 if (!video_out->frame_loaded)
2877 return 0;
2879 pts = video_out->next_pts;
2880 if (pts == MP_NOPTS_VALUE) {
2881 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2882 // Try to use decoder pts from before filters
2883 pts = sh_video->pts;
2884 if (pts == MP_NOPTS_VALUE)
2885 pts = sh_video->last_pts;
2887 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2888 vo_skip_frame(video_out);
2889 return 0;
2891 mpctx->hrseek_active = false;
2892 sh_video->pts = pts;
2893 if (sh_video->last_pts == MP_NOPTS_VALUE)
2894 sh_video->last_pts = sh_video->pts;
2895 else if (sh_video->last_pts > sh_video->pts) {
2896 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2897 sh_video->pts, sh_video->last_pts);
2898 /* If the difference in pts is small treat it as jitter around the
2899 * right value (possibly caused by incorrect timestamp ordering) and
2900 * just show this frame immediately after the last one.
2901 * Treat bigger differences as timestamp resets and start counting
2902 * timing of later frames from the position of this one. */
2903 if (sh_video->last_pts - sh_video->pts > 0.5)
2904 sh_video->last_pts = sh_video->pts;
2905 else
2906 sh_video->pts = sh_video->last_pts;
2908 double frame_time = sh_video->pts - sh_video->last_pts;
2909 sh_video->last_pts = sh_video->pts;
2910 sh_video->timer += frame_time;
2911 if (mpctx->sh_audio)
2912 mpctx->delay -= frame_time;
2913 return frame_time;
2916 static int get_cache_fill(struct MPContext *mpctx)
2918 #ifdef CONFIG_STREAM_CACHE
2919 if (stream_cache_size > 0)
2920 return cache_fill_status(mpctx->stream);
2921 #endif
2922 return -1;
2925 static void update_pause_message(struct MPContext *mpctx)
2927 struct MPOpts *opts = &mpctx->opts;
2929 if (opts->quiet)
2930 return;
2932 int cache_fill = get_cache_fill(mpctx);
2933 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2935 if (!mpctx->status_printed && !cache_changed)
2936 return;
2938 char *msg = mp_gtext(" ===== PAUSE =====");
2939 char *tmpmem = NULL;
2940 if (cache_fill >= 0)
2941 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
2943 if (opts->term_osd && !mpctx->sh_video) {
2944 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
2945 update_osd_msg(mpctx);
2946 } else {
2947 if (mpctx->status_printed)
2948 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
2949 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
2952 mpctx->paused_cache_fill = cache_fill;
2953 mpctx->status_printed = false;
2955 talloc_free(tmpmem);
2958 void pause_player(struct MPContext *mpctx)
2960 if (mpctx->paused)
2961 return;
2962 mpctx->paused = 1;
2963 mpctx->step_frames = 0;
2964 mpctx->time_frame -= get_relative_time(mpctx);
2965 mpctx->osd_function = OSD_PAUSE;
2967 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2968 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2970 if (mpctx->ao && mpctx->sh_audio)
2971 ao_pause(mpctx->ao); // pause audio, keep data if possible
2973 mpctx->paused_cache_fill = get_cache_fill(mpctx);
2974 mpctx->status_printed = true;
2975 update_pause_message(mpctx);
2977 if (!mpctx->opts.quiet)
2978 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2981 void unpause_player(struct MPContext *mpctx)
2983 if (!mpctx->paused)
2984 return;
2985 mpctx->paused = 0;
2986 if (!mpctx->step_frames)
2987 mpctx->osd_function = OSD_PLAY;
2989 if (mpctx->ao && mpctx->sh_audio)
2990 ao_resume(mpctx->ao);
2991 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2992 && !mpctx->step_frames)
2993 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2994 (void)get_relative_time(mpctx); // ignore time that passed during pause
2997 static int redraw_osd(struct MPContext *mpctx)
2999 struct sh_video *sh_video = mpctx->sh_video;
3000 struct vf_instance *vf = sh_video->vfilter;
3001 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3002 return -1;
3003 if (vo_redraw_frame(mpctx->video_out) < 0)
3004 return -1;
3005 mpctx->osd->sub_pts = mpctx->video_pts;
3006 if (mpctx->osd->sub_pts != MP_NOPTS_VALUE)
3007 mpctx->osd->sub_pts += sub_delay - mpctx->osd->sub_offset;
3009 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3010 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3011 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3012 vo_flip_page(mpctx->video_out, 0, -1);
3013 return 0;
3016 void add_step_frame(struct MPContext *mpctx)
3018 mpctx->step_frames++;
3019 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3020 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3021 unpause_player(mpctx);
3024 static void seek_reset(struct MPContext *mpctx, bool reset_ao, bool reset_ac)
3026 if (mpctx->sh_video) {
3027 current_module = "seek_video_reset";
3028 resync_video_stream(mpctx->sh_video);
3029 mpctx->sh_video->timer = 0;
3030 vo_seek_reset(mpctx->video_out);
3031 mpctx->sh_video->timer = 0;
3032 mpctx->sh_video->num_buffered_pts = 0;
3033 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3034 mpctx->delay = 0;
3035 mpctx->time_frame = 0;
3036 // Not all demuxers set d_video->pts during seek, so this value
3037 // (which is used by at least vobsub code below) may be completely
3038 // wrong (probably 0).
3039 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3040 mpctx->video_pts = mpctx->sh_video->pts;
3041 update_subtitles(mpctx, mpctx->sh_video->pts, true);
3042 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3045 if (mpctx->sh_audio && reset_ac) {
3046 current_module = "seek_audio_reset";
3047 resync_audio_stream(mpctx->sh_audio);
3048 if (reset_ao)
3049 ao_reset(mpctx->ao);
3050 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3051 mpctx->sh_audio->a_buffer_len = 0;
3052 if (!mpctx->sh_video)
3053 update_subtitles(mpctx, mpctx->sh_audio->pts, true);
3056 if (vo_vobsub && mpctx->sh_video) {
3057 current_module = "seek_vobsub_reset";
3058 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3061 mpctx->restart_playback = true;
3062 mpctx->hrseek_active = false;
3063 mpctx->hrseek_framedrop = false;
3064 mpctx->total_avsync_change = 0;
3065 audio_time_usage = 0;
3066 video_time_usage = 0;
3067 vout_time_usage = 0;
3068 drop_frame_cnt = 0;
3070 current_module = NULL;
3073 static bool timeline_set_part(struct MPContext *mpctx, int i)
3075 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3076 struct timeline_part *n = mpctx->timeline + i;
3077 mpctx->timeline_part = i;
3078 mpctx->video_offset = n->start - n->source_start;
3079 if (n->source == p->source)
3080 return false;
3081 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3082 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3083 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3084 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3085 mpctx->stop_play = orig_stop_play;
3086 mpctx->demuxer = n->source->demuxer;
3087 mpctx->d_video = mpctx->demuxer->video;
3088 mpctx->d_audio = mpctx->demuxer->audio;
3089 mpctx->d_sub = mpctx->demuxer->sub;
3090 mpctx->sh_video = mpctx->d_video->sh;
3091 mpctx->sh_audio = mpctx->d_audio->sh;
3092 return true;
3095 // Given pts, switch playback to the corresponding part.
3096 // Return offset within that part.
3097 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3098 bool *need_reset)
3100 if (pts < 0)
3101 pts = 0;
3102 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3103 struct timeline_part *p = mpctx->timeline + i;
3104 if (pts < (p + 1)->start) {
3105 *need_reset = timeline_set_part(mpctx, i);
3106 return pts - p->start + p->source_start;
3109 return -1;
3113 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3114 static int seek(MPContext *mpctx, struct seek_params seek,
3115 bool timeline_fallthrough)
3117 struct MPOpts *opts = &mpctx->opts;
3119 current_module = "seek";
3120 if (mpctx->stop_play == AT_END_OF_FILE)
3121 mpctx->stop_play = KEEP_PLAYING;
3122 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3123 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3124 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3125 || opts->hr_seek > 0 || seek.exact > 0;
3126 if (seek.type == MPSEEK_FACTOR
3127 || seek.type == MPSEEK_ABSOLUTE
3128 && seek.amount < mpctx->last_chapter_pts
3129 || seek.amount < 0)
3130 mpctx->last_chapter_seek = -2;
3131 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3132 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3133 seek.type = MPSEEK_ABSOLUTE;
3135 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3136 && seek.type == MPSEEK_RELATIVE) {
3137 seek.type = MPSEEK_ABSOLUTE;
3138 seek.direction = seek.amount > 0 ? 1 : -1;
3139 seek.amount += get_current_time(mpctx);
3142 /* At least the liba52 decoder wants to read from the input stream
3143 * during initialization, so reinit must be done after the demux_seek()
3144 * call that clears possible stream EOF. */
3145 bool need_reset = false;
3146 double demuxer_amount = seek.amount;
3147 if (mpctx->timeline) {
3148 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3149 &need_reset);
3150 if (demuxer_amount == -1) {
3151 mpctx->stop_play = AT_END_OF_FILE;
3152 // Clear audio from current position
3153 if (mpctx->sh_audio && !timeline_fallthrough) {
3154 ao_reset(mpctx->ao);
3155 mpctx->sh_audio->a_buffer_len = 0;
3157 return -1;
3160 if (need_reset) {
3161 reinit_video_chain(mpctx);
3162 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos},
3163 mpctx);
3166 int demuxer_style = 0;
3167 switch (seek.type) {
3168 case MPSEEK_FACTOR:
3169 demuxer_style |= SEEK_FACTOR; // fallthrough
3170 case MPSEEK_ABSOLUTE:
3171 demuxer_style |= SEEK_ABSOLUTE;
3173 if (hr_seek || seek.direction < 0)
3174 demuxer_style |= SEEK_BACKWARD;
3175 else if (seek.direction > 0)
3176 demuxer_style |= SEEK_FORWARD;
3178 if (hr_seek)
3179 demuxer_amount -= opts->hr_seek_demuxer_offset;
3180 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3181 demuxer_style);
3182 if (seekresult == 0) {
3183 if (need_reset) {
3184 reinit_audio_chain(mpctx);
3185 seek_reset(mpctx, !timeline_fallthrough, false);
3187 return -1;
3190 if (need_reset)
3191 reinit_audio_chain(mpctx);
3192 /* If we just reinitialized audio it doesn't need to be reset,
3193 * and resetting could lose audio some decoders produce during init. */
3194 seek_reset(mpctx, !timeline_fallthrough, !need_reset);
3196 /* Use the target time as "current position" for further relative
3197 * seeks etc until a new video frame has been decoded */
3198 if (seek.type == MPSEEK_ABSOLUTE) {
3199 mpctx->video_pts = seek.amount;
3200 mpctx->last_seek_pts = seek.amount;
3201 } else
3202 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3204 if (hr_seek) {
3205 mpctx->hrseek_active = true;
3206 mpctx->hrseek_framedrop = true;
3207 mpctx->hrseek_pts = seek.amount;
3210 mpctx->start_timestamp = GetTimerMS();
3212 return 0;
3215 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3216 int exact)
3218 struct seek_params *seek = &mpctx->seek;
3219 switch (type) {
3220 case MPSEEK_RELATIVE:
3221 if (seek->type == MPSEEK_FACTOR)
3222 return; // Well... not common enough to bother doing better
3223 seek->amount += amount;
3224 seek->exact = FFMAX(seek->exact, exact);
3225 if (seek->type == MPSEEK_NONE)
3226 seek->exact = exact;
3227 if (seek->type == MPSEEK_ABSOLUTE)
3228 return;
3229 if (seek->amount == 0) {
3230 *seek = (struct seek_params){ 0 };
3231 return;
3233 seek->type = MPSEEK_RELATIVE;
3234 return;
3235 case MPSEEK_ABSOLUTE:
3236 case MPSEEK_FACTOR:
3237 *seek = (struct seek_params) {
3238 .type = type,
3239 .amount = amount,
3240 .exact = exact,
3242 return;
3243 case MPSEEK_NONE:
3244 *seek = (struct seek_params){ 0 };
3245 return;
3247 abort();
3251 double get_time_length(struct MPContext *mpctx)
3253 if (mpctx->timeline)
3254 return mpctx->timeline[mpctx->num_timeline_parts].start;
3256 struct demuxer *demuxer = mpctx->demuxer;
3257 double get_time_ans;
3258 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3259 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3260 (void *) &get_time_ans) > 0)
3261 return get_time_ans;
3263 struct sh_video *sh_video = mpctx->d_video->sh;
3264 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3265 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3266 return (double) (demuxer->movi_end - demuxer->movi_start) /
3267 (sh_video->i_bps + sh_audio->i_bps);
3268 if (sh_video && sh_video->i_bps)
3269 return (double) (demuxer->movi_end - demuxer->movi_start) /
3270 sh_video->i_bps;
3271 if (sh_audio && sh_audio->i_bps)
3272 return (double) (demuxer->movi_end - demuxer->movi_start) /
3273 sh_audio->i_bps;
3274 return 0;
3277 /* If there are timestamps from stream level then use those (for example
3278 * DVDs can have consistent times there while the MPEG-level timestamps
3279 * reset). */
3280 double get_current_time(struct MPContext *mpctx)
3282 struct demuxer *demuxer = mpctx->demuxer;
3283 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3284 return demuxer->stream_pts;
3285 if (mpctx->sh_video) {
3286 double pts = mpctx->video_pts;
3287 if (pts != MP_NOPTS_VALUE)
3288 return pts;
3290 double apts = playing_audio_pts(mpctx);
3291 if (apts != MP_NOPTS_VALUE)
3292 return apts;
3293 return mpctx->last_seek_pts;
3296 int get_percent_pos(struct MPContext *mpctx)
3298 struct demuxer *demuxer = mpctx->demuxer;
3299 int ans = 0;
3300 if (mpctx->timeline)
3301 ans = get_current_time(mpctx) * 100 /
3302 mpctx->timeline[mpctx->num_timeline_parts].start;
3303 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3305 else {
3306 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3307 off_t pos = demuxer->filepos > 0 ?
3308 demuxer->filepos : stream_tell(demuxer->stream);
3309 if (len > 0)
3310 ans = (pos - demuxer->movi_start) / len;
3311 else
3312 ans = 0;
3314 if (ans < 0)
3315 ans = 0;
3316 if (ans > 100)
3317 ans = 100;
3318 return ans;
3321 // -2 is no chapters, -1 is before first chapter
3322 int get_current_chapter(struct MPContext *mpctx)
3324 double current_pts = get_current_time(mpctx);
3325 if (!mpctx->chapters)
3326 return FFMAX(mpctx->last_chapter_seek,
3327 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3329 int i;
3330 for (i = 1; i < mpctx->num_chapters; i++)
3331 if (current_pts < mpctx->chapters[i].start)
3332 break;
3333 return FFMAX(mpctx->last_chapter_seek, i - 1);
3336 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3338 char *name = chapter_name(mpctx, chapter);
3339 if (name) {
3340 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3341 } else {
3342 int chapter_count = get_chapter_count(mpctx);
3343 if (chapter_count <= 0)
3344 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3345 else
3346 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3347 chapter_count);
3349 return name;
3352 // returns NULL if chapter name unavailable
3353 char *chapter_name(struct MPContext *mpctx, int chapter)
3355 if (!mpctx->chapters)
3356 return demuxer_chapter_name(mpctx->demuxer, chapter);
3357 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3360 // returns the start of the chapter in seconds
3361 double chapter_start_time(struct MPContext *mpctx, int chapter)
3363 if (!mpctx->chapters)
3364 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3365 return mpctx->chapters[chapter].start;
3368 int get_chapter_count(struct MPContext *mpctx)
3370 if (!mpctx->chapters)
3371 return demuxer_chapter_count(mpctx->demuxer);
3372 return mpctx->num_chapters;
3375 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3377 mpctx->last_chapter_seek = -2;
3378 if (!mpctx->chapters) {
3379 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3380 if (res >= 0) {
3381 if (*seek_pts == -1)
3382 seek_reset(mpctx, true, true);
3383 else {
3384 mpctx->last_chapter_seek = res;
3385 mpctx->last_chapter_pts = *seek_pts;
3388 return res;
3391 if (chapter >= mpctx->num_chapters)
3392 return -1;
3393 if (chapter < 0)
3394 chapter = 0;
3395 *seek_pts = mpctx->chapters[chapter].start;
3396 mpctx->last_chapter_seek = chapter;
3397 mpctx->last_chapter_pts = *seek_pts;
3398 return chapter;
3402 static void run_playloop(struct MPContext *mpctx)
3404 struct MPOpts *opts = &mpctx->opts;
3405 bool full_audio_buffers = false;
3406 bool audio_left = false, video_left = false;
3407 double endpts = end_at.type == END_AT_TIME ? end_at.pos : MP_NOPTS_VALUE;
3408 bool end_is_chapter = false;
3409 double sleeptime = WAKEUP_PERIOD;
3410 bool was_restart = mpctx->restart_playback;
3412 if (mpctx->timeline) {
3413 double end = mpctx->timeline[mpctx->timeline_part + 1].start;
3414 if (endpts == MP_NOPTS_VALUE || end < endpts) {
3415 endpts = end;
3416 end_is_chapter = true;
3420 if (opts->chapterrange[1] > 0) {
3421 int cur_chapter = get_current_chapter(mpctx);
3422 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3423 mpctx->stop_play = PT_NEXT_ENTRY;
3426 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3427 mpctx->sh_audio = mpctx->d_audio->sh;
3428 mpctx->sh_audio->ds = mpctx->d_audio;
3429 reinit_audio_chain(mpctx);
3432 if (mpctx->step_frames && !mpctx->sh_video) {
3433 mpctx->step_frames = 0;
3434 pause_player(mpctx);
3437 if (mpctx->sh_audio && !mpctx->restart_playback && !mpctx->ao->untimed) {
3438 int status = fill_audio_out_buffers(mpctx, endpts);
3439 full_audio_buffers = status >= 0;
3440 // Not at audio stream EOF yet
3441 audio_left = status > -2;
3444 double buffered_audio = -1;
3445 while (mpctx->sh_video) { // never loops, for "break;" only
3446 struct vo *vo = mpctx->video_out;
3447 vo_pts = mpctx->sh_video->timer * 90000.0;
3448 vo_fps = mpctx->sh_video->fps;
3450 video_left = vo->hasframe || vo->frame_loaded;
3451 if (!vo->frame_loaded && (!mpctx->paused || mpctx->restart_playback)) {
3452 double frame_time = update_video(mpctx);
3453 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3454 if (mpctx->sh_video->vf_initialized < 0) {
3455 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3456 "\nFATAL: Could not initialize video filters (-vf) "
3457 "or video output (-vo).\n");
3458 mpctx->stop_play = PT_NEXT_ENTRY;
3459 return;
3461 video_left = frame_time >= 0;
3462 if (video_left && !mpctx->restart_playback) {
3463 mpctx->time_frame += frame_time / opts->playback_speed;
3464 adjust_sync(mpctx, frame_time);
3468 if (endpts != MP_NOPTS_VALUE)
3469 video_left &= mpctx->sh_video->pts < endpts;
3471 // ================================================================
3473 current_module = "vo_check_events";
3474 vo_check_events(vo);
3476 #ifdef CONFIG_X11
3477 if (stop_xscreensaver && vo->x11)
3478 xscreensaver_heartbeat(vo->x11);
3479 #endif
3480 if (heartbeat_cmd) {
3481 static unsigned last_heartbeat;
3482 unsigned now = GetTimerMS();
3483 if (now - last_heartbeat > 30000) {
3484 last_heartbeat = now;
3485 system(heartbeat_cmd);
3489 if (!video_left || (mpctx->paused && !mpctx->restart_playback))
3490 break;
3491 if (!vo->frame_loaded) {
3492 sleeptime = 0;
3493 break;
3496 mpctx->time_frame -= get_relative_time(mpctx);
3497 if (full_audio_buffers && !mpctx->restart_playback) {
3498 buffered_audio = ao_get_delay(mpctx->ao);
3499 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", buffered_audio);
3501 if (opts->autosync) {
3502 /* Smooth reported playback position from AO by averaging
3503 * it with the value expected based on previus value and
3504 * time elapsed since then. May help smooth video timing
3505 * with audio output that have inaccurate position reporting.
3506 * This is badly implemented; the behavior of the smoothing
3507 * now undesirably depends on how often this code runs
3508 * (mainly depends on video frame rate). */
3509 float predicted = (mpctx->delay / opts->playback_speed +
3510 mpctx->time_frame);
3511 float difference = buffered_audio - predicted;
3512 buffered_audio = predicted + difference / opts->autosync;
3515 mpctx->time_frame = (buffered_audio -
3516 mpctx->delay / opts->playback_speed);
3517 } else {
3518 /* If we're more than 200 ms behind the right playback
3519 * position, don't try to speed up display of following
3520 * frames to catch up; continue with default speed from
3521 * the current frame instead.
3522 * If benchmark is set always output frames immediately
3523 * without sleeping.
3525 if (mpctx->time_frame < -0.2 || opts->benchmark)
3526 mpctx->time_frame = 0;
3529 double vsleep = mpctx->time_frame - vo->flip_queue_offset;
3530 if (vsleep > 0.050) {
3531 sleeptime = FFMIN(sleeptime, vsleep - 0.040);
3532 break;
3534 sleeptime = 0;
3536 //=================== FLIP PAGE (VIDEO BLT): ======================
3538 current_module = "flip_page";
3539 vo_new_frame_imminent(vo);
3540 struct sh_video *sh_video = mpctx->sh_video;
3541 mpctx->video_pts = sh_video->pts;
3542 update_subtitles(mpctx, sh_video->pts, false);
3543 update_teletext(sh_video, mpctx->demuxer, 0);
3544 update_osd_msg(mpctx);
3545 struct vf_instance *vf = sh_video->vfilter;
3546 mpctx->osd->sub_pts = mpctx->video_pts;
3547 if (mpctx->osd->sub_pts != MP_NOPTS_VALUE)
3548 mpctx->osd->sub_pts += sub_delay - mpctx->osd->sub_offset;
3549 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3550 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3551 vo_osd_changed(0);
3553 mpctx->time_frame -= get_relative_time(mpctx);
3554 mpctx->time_frame -= vo->flip_queue_offset;
3555 float aq_sleep_time = mpctx->time_frame;
3556 if (mpctx->time_frame > 0.001
3557 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3558 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3559 mpctx->time_frame += vo->flip_queue_offset;
3561 unsigned int t2 = GetTimer();
3562 /* Playing with playback speed it's possible to get pathological
3563 * cases with mpctx->time_frame negative enough to cause an
3564 * overflow in pts_us calculation, thus the FFMAX. */
3565 double time_frame = FFMAX(mpctx->time_frame, -1);
3566 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3567 int duration = -1;
3568 double pts2 = vo->next_pts2;
3569 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts &&
3570 !mpctx->restart_playback) {
3571 // expected A/V sync correction is ignored
3572 double diff = (pts2 - mpctx->video_pts);
3573 diff /= opts->playback_speed;
3574 if (mpctx->time_frame < 0)
3575 diff += mpctx->time_frame;
3576 if (diff < 0)
3577 diff = 0;
3578 if (diff > 10)
3579 diff = 10;
3580 duration = diff * 1e6;
3582 vo_flip_page(vo, pts_us | 1, duration);
3584 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3585 vout_time_usage += mpctx->last_vo_flip_duration;
3586 if (vo->driver->flip_page_timed) {
3587 // No need to adjust sync based on flip speed
3588 mpctx->last_vo_flip_duration = 0;
3589 // For print_status - VO call finishing early is OK for sync
3590 mpctx->time_frame -= get_relative_time(mpctx);
3592 if (mpctx->restart_playback) {
3593 mpctx->syncing_audio = true;
3594 if (mpctx->sh_audio)
3595 fill_audio_out_buffers(mpctx, endpts);
3596 mpctx->restart_playback = false;
3597 mpctx->time_frame = 0;
3598 get_relative_time(mpctx);
3600 print_status(mpctx, MP_NOPTS_VALUE, true);
3601 screenshot_flip(mpctx);
3603 if (opts->auto_quality > 0) {
3604 current_module = "autoq";
3605 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3606 ++output_quality;
3607 else if (output_quality > 1 && aq_sleep_time < 0)
3608 --output_quality;
3609 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3610 output_quality = 0;
3611 set_video_quality(mpctx->sh_video, output_quality);
3614 if (play_n_frames >= 0) {
3615 --play_n_frames;
3616 if (play_n_frames <= 0)
3617 mpctx->stop_play = PT_NEXT_ENTRY;
3619 if (mpctx->step_frames > 0) {
3620 mpctx->step_frames--;
3621 if (mpctx->step_frames == 0)
3622 pause_player(mpctx);
3624 break;
3625 } // video
3627 #ifdef CONFIG_DVDNAV
3628 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3629 nav_highlight_t hl;
3630 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3631 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3632 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3633 vo_osd_changed(OSDTYPE_DVDNAV);
3634 } else {
3635 osd_set_nav_box(0, 0, 0, 0);
3636 vo_osd_changed(OSDTYPE_DVDNAV);
3637 vo_osd_changed(OSDTYPE_SPU);
3640 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3641 double ar = -1.0;
3642 if (mpctx->sh_video &&
3643 stream_control(mpctx->demuxer->stream,
3644 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3645 != STREAM_UNSUPPORTED)
3646 mpctx->sh_video->stream_aspect = ar;
3649 #endif
3651 if (mpctx->sh_audio && (mpctx->restart_playback ? !video_left :
3652 mpctx->ao->untimed && (mpctx->delay <= 0 ||
3653 !video_left))) {
3654 int status = fill_audio_out_buffers(mpctx, endpts);
3655 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3656 // Not at audio stream EOF yet
3657 audio_left = status > -2;
3659 if (!video_left)
3660 mpctx->restart_playback = false;
3661 if (mpctx->sh_audio && buffered_audio == -1)
3662 buffered_audio = mpctx->paused ? 0 : ao_get_delay(mpctx->ao);
3664 update_osd_msg(mpctx);
3665 if (mpctx->paused)
3666 update_pause_message(mpctx);
3667 if (!video_left && (!mpctx->paused || was_restart)) {
3668 double a_pos = 0;
3669 if (mpctx->sh_audio) {
3670 a_pos = (written_audio_pts(mpctx) -
3671 mpctx->opts.playback_speed * buffered_audio);
3673 print_status(mpctx, a_pos, false);
3675 if (!mpctx->sh_video)
3676 update_subtitles(mpctx, a_pos, false);
3679 /* It's possible for the user to simultaneously switch both audio
3680 * and video streams to "disabled" at runtime. Handle this by waiting
3681 * rather than immediately stopping playback due to EOF.
3683 * When all audio has been written to output driver, stay in the
3684 * main loop handling commands until it has been mostly consumed,
3685 * except in the gapless case, where the next file will be started
3686 * while audio from the current one still remains to be played.
3688 * We want this check to trigger if we seeked to this position,
3689 * but not if we paused at it with audio possibly still buffered in
3690 * the AO. There's currently no working way to check buffered audio
3691 * inside AO while paused. Thus the "was_restart" check below, which
3692 * should trigger after seek only, when we know there's no audio
3693 * buffered.
3695 if ((mpctx->sh_audio || mpctx->sh_video) && !audio_left && !video_left
3696 && (opts->gapless_audio || buffered_audio < 0.05)
3697 && (!mpctx->paused || was_restart)) {
3698 if (end_is_chapter) {
3699 seek(mpctx, (struct seek_params){
3700 .type = MPSEEK_ABSOLUTE,
3701 .amount = mpctx->timeline[mpctx->timeline_part+1].start
3702 }, true);
3703 } else
3704 mpctx->stop_play = AT_END_OF_FILE;
3705 } else if (!mpctx->stop_play) {
3706 double audio_sleep = 9;
3707 if (mpctx->sh_audio && !mpctx->paused) {
3708 if (mpctx->ao->untimed) {
3709 if (!video_left)
3710 audio_sleep = 0;
3711 } else if (full_audio_buffers) {
3712 audio_sleep = buffered_audio - 0.050;
3713 // Keep extra safety margin if the buffers are large
3714 if (audio_sleep > 0.100)
3715 audio_sleep = FFMAX(audio_sleep - 0.200, 0.100);
3716 else
3717 audio_sleep = FFMAX(audio_sleep, 0.020);
3718 } else
3719 audio_sleep = 0.020;
3721 sleeptime = FFMIN(sleeptime, audio_sleep);
3722 if (sleeptime > 0) {
3723 if (!mpctx->sh_video)
3724 goto novideo;
3725 int hack = vo_osd_changed(0);
3726 vo_osd_changed(hack);
3727 if (hack || mpctx->video_out->want_redraw) {
3728 if (redraw_osd(mpctx) < 0) {
3729 if (mpctx->paused && video_left)
3730 add_step_frame(mpctx);
3731 else
3732 goto novideo;
3733 } else
3734 vo_osd_changed(0);
3735 } else {
3736 novideo:
3737 mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
3742 //================= Keyboard events, SEEKing ====================
3744 current_module = "key_events";
3746 mp_cmd_t *cmd;
3747 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3748 /* Allow running consecutive seek commands to combine them,
3749 * but execute the seek before running other commands.
3750 * If the user seeks continuously (keeps arrow key down)
3751 * try to finish showing a frame from one location before doing
3752 * another seek (which could lead to unchanging display). */
3753 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3754 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3755 && GetTimerMS() - mpctx->start_timestamp < 300)
3756 break;
3757 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3758 run_command(mpctx, cmd);
3759 mp_cmd_free(cmd);
3760 if (mpctx->stop_play)
3761 break;
3764 // handle -sstep
3765 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3766 mpctx->osd_function = OSD_FFW;
3767 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3770 /* Looping. */
3771 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3772 mpctx->stop_play == PT_NEXT_ENTRY)) {
3773 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3775 if (opts->loop_times > 1)
3776 opts->loop_times--;
3777 else if (opts->loop_times == 1)
3778 opts->loop_times = -1;
3779 play_n_frames = play_n_frames_mf;
3780 mpctx->stop_play = 0;
3781 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3784 if (mpctx->seek.type) {
3785 seek(mpctx, mpctx->seek, false);
3786 mpctx->seek = (struct seek_params){ 0 };
3791 static int read_keys(void *ctx, int fd)
3793 if (getch2(ctx))
3794 return MP_INPUT_NOTHING;
3795 return MP_INPUT_DEAD;
3798 static bool attachment_is_font(struct demux_attachment *att)
3800 if (!att->name || !att->type || !att->data || !att->data_size)
3801 return false;
3802 // match against MIME types
3803 if (strcmp(att->type, "application/x-truetype-font") == 0
3804 || strcmp(att->type, "application/x-font") == 0)
3805 return true;
3806 // fallback: match against file extension
3807 if (strlen(att->name) > 4) {
3808 char *ext = att->name + strlen(att->name) - 4;
3809 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3810 || strcasecmp(ext, ".otf") == 0)
3811 return true;
3813 return false;
3816 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3818 if (audio_id == -1)
3819 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3820 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3821 demuxer_switch_audio(demuxer, audio_id);
3822 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3823 demuxer->audio->id = -2;
3824 demuxer->audio->sh = NULL;
3826 return demuxer->audio->id;
3829 static void print_version(const char *name)
3831 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3833 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3834 GetCpuCaps(&gCpuCaps);
3835 #if ARCH_X86
3836 mp_msg(MSGT_CPLAYER, MSGL_V,
3837 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3838 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3839 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3840 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3841 #if CONFIG_RUNTIME_CPUDETECT
3842 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3843 #else
3844 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3845 if (HAVE_MMX)
3846 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3847 if (HAVE_MMX2)
3848 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3849 if (HAVE_AMD3DNOW)
3850 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3851 if (HAVE_AMD3DNOWEXT)
3852 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3853 if (HAVE_SSE)
3854 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3855 if (HAVE_SSE2)
3856 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3857 if (HAVE_SSSE3)
3858 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3859 if (HAVE_CMOV)
3860 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3861 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3862 #endif /* CONFIG_RUNTIME_CPUDETECT */
3863 #endif /* ARCH_X86 */
3864 print_libav_versions();
3867 #ifdef PTW32_STATIC_LIB
3868 static void detach_ptw32(void)
3870 pthread_win32_thread_detach_np();
3871 pthread_win32_process_detach_np();
3873 #endif
3875 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3876 * file for some tools to link against. */
3877 #ifndef DISABLE_MAIN
3878 int main(int argc, char *argv[])
3880 #ifdef PTW32_STATIC_LIB
3881 pthread_win32_process_attach_np();
3882 pthread_win32_thread_attach_np();
3883 atexit(detach_ptw32);
3884 #endif
3885 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3886 || !strcmp(argv[1], "--leak-report")))
3887 talloc_enable_leak_report();
3889 #ifdef __MINGW32__
3890 mp_get_converted_argv(&argc, &argv);
3891 #endif
3893 char *mem_ptr;
3895 // movie info:
3897 /* Flag indicating whether MPlayer should exit without playing anything. */
3898 int opt_exit = 0;
3899 int i;
3901 struct MPContext *mpctx = talloc(NULL, MPContext);
3902 *mpctx = (struct MPContext){
3903 .osd_function = OSD_PLAY,
3904 .begin_skip = MP_NOPTS_VALUE,
3905 .play_tree_step = 1,
3906 .global_sub_pos = -1,
3907 .set_of_sub_pos = -1,
3908 .file_format = DEMUXER_TYPE_UNKNOWN,
3909 .last_dvb_step = 1,
3910 .paused_cache_fill = -1,
3913 InitTimer();
3914 srand(GetTimerMS());
3916 mp_msg_init();
3917 init_libav();
3919 struct MPOpts *opts = &mpctx->opts;
3920 set_default_mplayer_options(opts);
3921 // Create the config context and register the options
3922 mpctx->mconfig = m_config_new(opts, cfg_include);
3923 m_config_register_options(mpctx->mconfig, mplayer_opts);
3924 m_config_register_options(mpctx->mconfig, common_opts);
3925 mp_input_register_options(mpctx->mconfig);
3926 m_config_initialize(mpctx->mconfig, opts);
3928 // Preparse the command line
3929 m_config_preparse_command_line(mpctx->mconfig, argc, argv, &verbose);
3931 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3932 set_path_env();
3933 #endif
3935 #ifdef CONFIG_TV
3936 stream_tv_defaults.immediate = 1;
3937 #endif
3939 parse_cfgfiles(mpctx, mpctx->mconfig);
3941 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3942 if (mpctx->playtree == NULL)
3943 opt_exit = 1;
3944 else {
3945 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3946 if (mpctx->playtree) {
3947 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3948 mpctx->mconfig);
3949 if (mpctx->playtree_iter) {
3950 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3951 PLAY_TREE_ITER_ENTRY) {
3952 play_tree_iter_free(mpctx->playtree_iter);
3953 mpctx->playtree_iter = NULL;
3955 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3961 print_version("MPlayer2");
3963 #if defined(__MINGW32__) || defined(__CYGWIN__)
3965 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3966 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3967 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3968 if (kernel32) {
3969 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3970 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3972 if (setDEP)
3973 setDEP(3);
3974 if (setDllDir)
3975 setDllDir("");
3977 // stop Windows from showing all kinds of annoying error dialogs
3978 SetErrorMode(0x8003);
3979 // request 1ms timer resolution
3980 timeBeginPeriod(1);
3981 #endif
3983 #ifdef CONFIG_PRIORITY
3984 set_priority();
3985 #endif
3987 if (opts->video_driver_list &&
3988 strcmp(opts->video_driver_list[0], "help") == 0) {
3989 list_video_out();
3990 opt_exit = 1;
3993 if (opts->audio_driver_list &&
3994 strcmp(opts->audio_driver_list[0], "help") == 0) {
3995 list_audio_out();
3996 opt_exit = 1;
3999 /* Check codecs.conf. */
4000 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4001 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4002 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4003 if (!parse_codec_cfg(NULL))
4004 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4005 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4006 "Using built-in default codecs.conf.\n");
4009 free(mem_ptr); // release the buffer created by get_path()
4012 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4013 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4014 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4015 list_codecs(1);
4016 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4017 opt_exit = 1;
4019 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4020 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4021 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4022 list_codecs(0);
4023 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4024 opt_exit = 1;
4026 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4027 vfm_help();
4028 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4029 opt_exit = 1;
4031 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4032 afm_help();
4033 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4034 opt_exit = 1;
4036 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4037 af_help();
4038 printf("\n");
4039 opt_exit = 1;
4041 #ifdef CONFIG_X11
4042 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4043 fstype_help();
4044 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4045 opt_exit = 1;
4047 #endif
4048 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4049 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4050 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4051 demuxer_help();
4052 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4053 opt_exit = 1;
4055 if (opts->list_properties) {
4056 property_print_help();
4057 opt_exit = 1;
4060 if (opt_exit)
4061 exit_player(mpctx, EXIT_NONE);
4063 if (!mpctx->filename && !opts->player_idle_mode) {
4064 // no file/vcd/dvd -> show HELP:
4065 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4066 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4069 /* Display what configure line was used */
4070 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4072 // Many users forget to include command line in bugreports...
4073 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4074 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4075 for (i = 1; i < argc; i++)
4076 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4077 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4080 //------ load global data first ------
4082 #ifdef CONFIG_ASS
4083 mpctx->ass_library = mp_ass_init(opts);
4084 #endif
4086 mpctx->osd = osd_create(opts, mpctx->ass_library);
4088 #ifdef HAVE_RTC
4089 if (opts->rtc) {
4090 char *rtc_device = opts->rtc_device;
4091 // seteuid(0); /* Can't hurt to try to get root here */
4092 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4093 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4094 "(it should be readable by the user.)\n",
4095 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4096 else {
4097 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4099 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4100 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4101 "ioctl (rtc_irqp_set %lu): %s\n",
4102 irqp, strerror(errno));
4103 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4104 close(rtc_fd);
4105 rtc_fd = -1;
4106 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4107 /* variable only by the root */
4108 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4109 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4110 close(rtc_fd);
4111 rtc_fd = -1;
4112 } else
4113 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4114 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4117 if (rtc_fd < 0)
4118 #endif /* HAVE_RTC */
4119 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4120 opts->softsleep ? "software" : timer_name);
4122 #ifdef HAVE_TERMCAP
4123 load_termcap(NULL); // load key-codes
4124 #endif
4126 // ========== Init keyboard FIFO (connection to libvo) ============
4128 // Init input system
4129 current_module = "init_input";
4130 mpctx->input = mp_input_init(&opts->input);
4131 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4132 if (slave_mode)
4133 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4134 else if (opts->consolecontrols)
4135 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4136 // Set the libstream interrupt callback
4137 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4139 current_module = NULL;
4141 /// Catch signals
4142 #ifndef __MINGW32__
4143 signal(SIGCHLD, child_sighandler);
4144 #endif
4146 #ifdef CONFIG_CRASH_DEBUG
4147 prog_path = argv[0];
4148 #endif
4149 //========= Catch terminate signals: ================
4150 // terminate requests:
4151 signal(SIGTERM, exit_sighandler); // kill
4152 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4154 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4156 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4157 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4158 #ifdef CONFIG_SIGHANDLER
4159 // fatal errors:
4160 signal(SIGBUS, exit_sighandler); // bus error
4161 signal(SIGSEGV, exit_sighandler); // segfault
4162 signal(SIGILL, exit_sighandler); // illegal instruction
4163 signal(SIGFPE, exit_sighandler); // floating point exc.
4164 signal(SIGABRT, exit_sighandler); // abort()
4165 #ifdef CONFIG_CRASH_DEBUG
4166 if (crash_debug)
4167 signal(SIGTRAP, exit_sighandler);
4168 #endif
4169 #endif
4171 // ***************** Now, let's see the per-file stuff ******************
4173 play_next_file:
4175 // init global sub numbers
4176 mpctx->global_sub_size = 0;
4177 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4179 if (mpctx->filename) {
4180 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4181 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4182 load_per_file_config(mpctx->mconfig, mpctx->filename);
4185 if (opts->video_driver_list)
4186 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4187 opts->video_driver_list[0]);
4188 if (opts->audio_driver_list)
4189 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4190 opts->audio_driver_list[0]);
4192 // We must enable getch2 here to be able to interrupt network connection
4193 // or cache filling
4194 if (opts->consolecontrols && !slave_mode) {
4195 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4196 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4197 "WARNING: getch2_init called twice!\n");
4198 else
4199 getch2_enable(); // prepare stdin for hotkeys...
4200 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4201 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4204 // ================= idle loop (STOP state) =========================
4205 while (opts->player_idle_mode && !mpctx->filename) {
4206 uninit_player(mpctx, INITIALIZED_AO | INITIALIZED_VO);
4207 play_tree_t *entry = NULL;
4208 mp_cmd_t *cmd;
4209 while (!(cmd = mp_input_get_cmd(mpctx->input, WAKEUP_PERIOD * 1000,
4210 false)));
4211 switch (cmd->id) {
4212 case MP_CMD_LOADFILE:
4213 // prepare a tree entry with the new filename
4214 entry = play_tree_new();
4215 play_tree_add_file(entry, cmd->args[0].v.s);
4216 // The entry is added to the main playtree after the switch().
4217 break;
4218 case MP_CMD_LOADLIST:
4219 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4220 break;
4221 case MP_CMD_QUIT:
4222 exit_player_with_rc(mpctx, EXIT_QUIT,
4223 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4224 break;
4225 case MP_CMD_VO_FULLSCREEN:
4226 case MP_CMD_GET_PROPERTY:
4227 case MP_CMD_SET_PROPERTY:
4228 case MP_CMD_STEP_PROPERTY:
4229 run_command(mpctx, cmd);
4230 break;
4233 mp_cmd_free(cmd);
4235 if (entry) { // user entered a command that gave a valid entry
4236 if (mpctx->playtree)
4237 // the playtree is always a node with one child. let's clear it
4238 play_tree_free_list(mpctx->playtree->child, 1);
4239 else
4240 // .. or make a brand new playtree
4241 mpctx->playtree = play_tree_new();
4243 if (!mpctx->playtree)
4244 continue; // couldn't make playtree! wait for next command
4246 play_tree_set_child(mpctx->playtree, entry);
4248 /* Make iterator start at the top the of tree. */
4249 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4250 mpctx->mconfig);
4251 if (!mpctx->playtree_iter)
4252 continue;
4254 // find the first real item in the tree
4255 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4256 PLAY_TREE_ITER_ENTRY) {
4257 // no items!
4258 play_tree_iter_free(mpctx->playtree_iter);
4259 mpctx->playtree_iter = NULL;
4260 continue; // wait for next command
4262 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4266 #ifdef CONFIG_ASS
4267 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4268 #endif
4269 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4270 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4272 if (mpctx->filename) {
4273 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4274 filename_recode(mpctx->filename));
4275 if (use_filename_title && opts->vo_wintitle == NULL)
4276 opts->vo_wintitle = talloc_strdup(NULL,
4277 mp_basename(mpctx->filename));
4280 if (edl_output_filename) {
4281 if (edl_fd)
4282 fclose(edl_fd);
4283 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4284 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4285 "Can't open EDL file [%s] for writing.\n",
4286 filename_recode(edl_output_filename));
4290 //==================== Open VOB-Sub ============================
4292 current_module = "vobsub";
4293 if (opts->vobsub_name) {
4294 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4295 if (vo_vobsub == NULL)
4296 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4297 filename_recode(opts->vobsub_name));
4298 } else if (opts->sub_auto && mpctx->filename) {
4299 char **vob = find_vob_subtitles(opts, mpctx->filename);
4300 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4301 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4302 if (vo_vobsub)
4303 break;
4305 talloc_free(vob);
4307 if (vo_vobsub) {
4308 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4309 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4310 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4311 mpctx);
4313 // setup global sub numbering
4314 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4315 vobsub_get_indexes_count(vo_vobsub);
4318 //============ Open & Sync STREAM --- fork cache2 ====================
4320 mpctx->stream = NULL;
4321 mpctx->demuxer = NULL;
4322 mpctx->d_audio = NULL;
4323 mpctx->d_video = NULL;
4324 mpctx->d_sub = NULL;
4325 mpctx->sh_audio = NULL;
4326 mpctx->sh_video = NULL;
4328 current_module = "open_stream";
4329 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4330 if (!mpctx->stream) { // error...
4331 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4332 goto goto_next_file;
4334 mpctx->initialized_flags |= INITIALIZED_STREAM;
4336 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4337 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4338 "playlist support will not be used automatically.\n"
4339 "MPlayer's playlist code is unsafe and should only be used with "
4340 "trusted sources.\nPlayback will probably fail.\n\n");
4341 #if 0
4342 play_tree_t *entry;
4343 // Handle playlist
4344 current_module = "handle_playlist";
4345 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4346 filename_recode(mpctx->filename));
4347 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4348 mpctx->eof = playtree_add_playlist(mpctx, entry);
4349 goto goto_next_file;
4350 #endif
4352 mpctx->stream->start_pos += seek_to_byte;
4354 if (stream_dump_type == 5) {
4355 unsigned char buf[4096];
4356 int len;
4357 FILE *f;
4358 current_module = "dumpstream";
4359 stream_reset(mpctx->stream);
4360 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4361 f = fopen(opts->stream_dump_name, "wb");
4362 if (!f) {
4363 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4364 exit_player(mpctx, EXIT_ERROR);
4366 if (opts->chapterrange[0] > 1) {
4367 int chapter = opts->chapterrange[0] - 1;
4368 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4370 struct stream_dump_progress info;
4371 stream_dump_progress_start(&info);
4372 while (!mpctx->stream->eof && !async_quit_request) {
4373 len = stream_read(mpctx->stream, buf, 4096);
4374 if (len > 0) {
4375 if (fwrite(buf, len, 1, f) != 1) {
4376 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4377 exit_player(mpctx, EXIT_ERROR);
4380 stream_dump_progress(&info, len, mpctx->stream);
4381 if (opts->chapterrange[1] > 0) {
4382 int chapter = -1;
4383 if (stream_control(mpctx->stream,
4384 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4385 && chapter + 1 > opts->chapterrange[1])
4386 break;
4389 if (fclose(f)) {
4390 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4391 opts->stream_dump_name);
4392 exit_player(mpctx, EXIT_ERROR);
4394 stream_dump_progress_end(&info, opts->stream_dump_name);
4395 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4396 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4399 #ifdef CONFIG_DVDREAD
4400 if (mpctx->stream->type == STREAMTYPE_DVD) {
4401 current_module = "dvd lang->id";
4402 if (opts->audio_lang && opts->audio_id == -1)
4403 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4404 if (opts->sub_lang && opts->sub_id == -1)
4405 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4406 // setup global sub numbering
4407 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4408 current_module = NULL;
4410 #endif
4412 #ifdef CONFIG_DVDNAV
4413 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4414 current_module = "dvdnav lang->id";
4415 if (opts->audio_lang && opts->audio_id == -1)
4416 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4417 opts->audio_lang);
4418 dvdsub_lang_id = -3;
4419 if (opts->sub_lang && opts->sub_id == -1)
4420 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4421 mpctx->stream, opts->sub_lang);
4422 // setup global sub numbering
4423 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4424 mpctx->stream);
4425 current_module = NULL;
4427 #endif
4429 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4430 goto_enable_cache:
4431 if (stream_cache_size > 0) {
4432 int res;
4433 float stream_cache_min_percent = opts->stream_cache_min_percent;
4434 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4435 current_module = "enable_cache";
4436 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4437 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4438 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4439 if (res == 0)
4440 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4441 goto goto_next_file;
4444 //============ Open DEMUXERS --- DETECT file type =======================
4445 current_module = "demux_open";
4447 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4448 opts->audio_id, opts->video_id, opts->sub_id,
4449 mpctx->filename);
4451 // HACK to get MOV Reference Files working
4453 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4454 unsigned char *playlist_entry;
4455 play_tree_t *list = NULL, *entry = NULL;
4457 current_module = "handle_demux_playlist";
4458 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4459 char *temp;
4460 const char *bname;
4462 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4463 filename_recode(playlist_entry));
4465 bname = mp_basename(playlist_entry);
4466 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4467 !strncmp(bname + 3, "gateQT", 6))
4468 continue;
4470 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4471 continue;
4473 entry = play_tree_new();
4475 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4476 playlist_entry)) { // add reference path of current file
4477 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4478 mpctx->filename)) + strlen(playlist_entry) + 1));
4479 if (temp) {
4480 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4481 strlen(mp_basename(mpctx->filename)));
4482 temp[strlen(mpctx->filename) - strlen(mp_basename(
4483 mpctx->filename))] = '\0';
4484 strcat(temp, playlist_entry);
4485 if (!strcmp(temp, mpctx->filename)) {
4486 free(temp);
4487 continue;
4489 play_tree_add_file(entry, temp);
4490 mp_msg(MSGT_CPLAYER, MSGL_V,
4491 "Resolving reference to %s.\n", temp);
4492 free(temp);
4494 } else
4495 play_tree_add_file(entry, playlist_entry);
4497 if (!list)
4498 list = entry;
4499 else
4500 play_tree_append_entry(list, entry);
4502 free_demuxer(mpctx->demuxer);
4503 mpctx->demuxer = NULL;
4505 if (list) {
4506 entry = play_tree_new();
4507 play_tree_set_child(entry, list);
4508 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4509 goto goto_next_file;
4513 if (!mpctx->demuxer) {
4514 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4515 goto goto_next_file;
4518 if (mpctx->demuxer->matroska_data.ordered_chapters)
4519 build_ordered_chapter_timeline(mpctx);
4521 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4522 build_edl_timeline(mpctx);
4524 if (mpctx->timeline) {
4525 mpctx->timeline_part = 0;
4526 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4528 int part_count = mpctx->num_timeline_parts;
4529 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4530 "sources. Total length %.3f seconds.\n", part_count,
4531 mpctx->num_sources, mpctx->timeline[part_count].start);
4532 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4533 for (int i = 0; i < mpctx->num_sources; i++)
4534 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4535 filename_recode(mpctx->sources[i].demuxer->filename));
4536 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4537 "source_start, source):\n");
4538 for (int i = 0; i < part_count; i++) {
4539 struct timeline_part *p = mpctx->timeline + i;
4540 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4541 p->source_start, p->source - mpctx->sources);
4543 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4544 mpctx->timeline[part_count].start);
4547 if (!mpctx->sources) {
4548 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4549 *mpctx->sources = (struct content_source){
4550 .stream = mpctx->stream,
4551 .demuxer = mpctx->demuxer
4553 mpctx->num_sources = 1;
4556 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4558 #ifdef CONFIG_ASS
4559 if (opts->ass_enabled) {
4560 for (int j = 0; j < mpctx->num_sources; j++) {
4561 struct demuxer *d = mpctx->sources[j].demuxer;
4562 for (int i = 0; i < d->num_attachments; i++) {
4563 struct demux_attachment *att = d->attachments + i;
4564 if (opts->use_embedded_fonts && attachment_is_font(att))
4565 ass_add_font(mpctx->ass_library, att->name, att->data,
4566 att->data_size);
4570 /* libass seems to misbehave if fonts are changed while a renderer
4571 * exists, so we (re)create the renderer after fonts are set.
4573 assert(!mpctx->osd->ass_renderer);
4574 mpctx->osd->ass_renderer = ass_renderer_init(mpctx->osd->ass_library);
4575 if (!mpctx->osd->ass_renderer) {
4576 mp_msg(MSGT_OSD, MSGL_FATAL, "Failed to create libass renderer\n");
4577 exit_player(mpctx, EXIT_ERROR);
4579 mp_ass_configure_fonts(mpctx->osd->ass_renderer);
4580 #endif
4582 current_module = "demux_open2";
4584 mpctx->d_audio = mpctx->demuxer->audio;
4585 mpctx->d_video = mpctx->demuxer->video;
4586 mpctx->d_sub = mpctx->demuxer->sub;
4588 if (ts_prog) {
4589 int tmp = ts_prog;
4590 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4592 // select audio stream
4593 for (int i = 0; i < mpctx->num_sources; i++)
4594 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4595 opts->audio_lang);
4597 // DUMP STREAMS:
4598 if ((stream_dump_type) && (stream_dump_type < 4)) {
4599 FILE *f;
4600 demux_stream_t *ds = NULL;
4601 current_module = "dump";
4602 // select stream to dump
4603 switch (stream_dump_type) {
4604 case 1: ds = mpctx->d_audio;
4605 break;
4606 case 2: ds = mpctx->d_video;
4607 break;
4608 case 3: ds = mpctx->d_sub;
4609 break;
4611 if (!ds) {
4612 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4613 "dump: FATAL: Selected stream missing!\n");
4614 exit_player(mpctx, EXIT_ERROR);
4616 // disable other streams:
4617 if (mpctx->d_audio && mpctx->d_audio != ds) {
4618 ds_free_packs(mpctx->d_audio);
4619 mpctx->d_audio->id = -2;
4621 if (mpctx->d_video && mpctx->d_video != ds) {
4622 ds_free_packs(mpctx->d_video);
4623 mpctx->d_video->id = -2;
4625 if (mpctx->d_sub && mpctx->d_sub != ds) {
4626 ds_free_packs(mpctx->d_sub);
4627 mpctx->d_sub->id = -2;
4629 // let's dump it!
4630 f = fopen(opts->stream_dump_name, "wb");
4631 if (!f) {
4632 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4633 exit_player(mpctx, EXIT_ERROR);
4635 struct stream_dump_progress info;
4636 stream_dump_progress_start(&info);
4637 while (!ds->eof) {
4638 unsigned char *start;
4639 int in_size = ds_get_packet(ds, &start);
4640 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4641 && stream_dump_type == 2)
4642 fwrite(&in_size, 1, 4, f);
4643 if (in_size > 0) {
4644 fwrite(start, in_size, 1, f);
4645 stream_dump_progress(&info, in_size, mpctx->stream);
4647 if (opts->chapterrange[1] > 0) {
4648 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4649 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4650 break;
4653 fclose(f);
4654 stream_dump_progress_end(&info, opts->stream_dump_name);
4655 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4656 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4659 mpctx->sh_audio = mpctx->d_audio->sh;
4660 mpctx->sh_video = mpctx->d_video->sh;
4662 if (mpctx->sh_video) {
4663 current_module = "video_read_properties";
4664 if (!video_read_properties(mpctx->sh_video)) {
4665 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4666 mpctx->sh_video = mpctx->d_video->sh = NULL;
4667 } else {
4668 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4669 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4670 mpctx->demuxer->file_format, mpctx->sh_video->format,
4671 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4672 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4673 if (force_fps) {
4674 mpctx->sh_video->fps = force_fps;
4675 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4677 vo_fps = mpctx->sh_video->fps;
4679 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4680 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4681 "header or invalid, use the -fps option.\n");
4687 if (!mpctx->sh_video && !mpctx->sh_audio) {
4688 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4689 #ifdef CONFIG_DVBIN
4690 if (mpctx->stream->type == STREAMTYPE_DVB) {
4691 int dir;
4692 int v = mpctx->last_dvb_step;
4693 if (v > 0)
4694 dir = DVB_CHANNEL_HIGHER;
4695 else
4696 dir = DVB_CHANNEL_LOWER;
4698 if (dvb_step_channel(mpctx->stream, dir)) {
4699 mpctx->stop_play = PT_NEXT_ENTRY;
4700 mpctx->dvbin_reopen = 1;
4703 #endif
4704 goto goto_next_file; // exit_player(_("Fatal error"));
4707 /* display clip info */
4708 demux_info_print(mpctx->demuxer);
4710 //================= Read SUBTITLES (DVD & TEXT) =========================
4711 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4712 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4713 init_vo_spudec(mpctx);
4715 // after reading video params we should load subtitles because
4716 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4717 // check .sub
4718 current_module = "read_subtitles_file";
4719 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4720 if (opts->sub_name) {
4721 for (i = 0; opts->sub_name[i] != NULL; ++i)
4722 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4724 if (opts->sub_auto) { // auto load sub file ...
4725 char **tmp = find_text_subtitles(opts, mpctx->filename);
4726 int nsub = MP_TALLOC_ELEMS(tmp);
4727 for (int i = 0; i < nsub; i++)
4728 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4729 talloc_free(tmp);
4731 if (mpctx->set_of_sub_size > 0)
4732 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4734 if (select_subtitle(mpctx)) {
4735 if (mpctx->subdata)
4736 switch (stream_dump_type) {
4737 case 3: list_sub_file(mpctx->subdata);
4738 break;
4739 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4740 break;
4741 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4742 break;
4743 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4744 break;
4745 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4746 break;
4747 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4748 break;
4752 print_file_properties(mpctx, mpctx->filename);
4754 reinit_video_chain(mpctx);
4755 if (!mpctx->sh_video && !mpctx->sh_audio)
4756 goto goto_next_file;
4758 //================== MAIN: ==========================
4759 current_module = "main";
4761 if (opts->playing_msg) {
4762 char *msg = property_expand_string(mpctx, opts->playing_msg);
4763 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4764 free(msg);
4768 // Disable the term OSD in verbose mode
4769 if (verbose)
4770 opts->term_osd = 0;
4772 // Make sure old OSD does not stay around
4773 clear_osd_msgs();
4775 //================ SETUP AUDIO ==========================
4777 if (mpctx->sh_audio) {
4778 reinit_audio_chain(mpctx);
4779 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4780 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4781 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4784 current_module = "av_init";
4786 if (mpctx->sh_video) {
4787 mpctx->sh_video->timer = 0;
4788 if (!ignore_start)
4789 audio_delay += mpctx->sh_video->stream_delay;
4791 if (mpctx->sh_audio) {
4792 if (start_volume >= 0)
4793 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4794 if (!ignore_start)
4795 audio_delay -= mpctx->sh_audio->stream_delay;
4798 if (!mpctx->sh_audio) {
4799 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4800 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4801 mpctx->d_audio->packs);
4802 ds_free_packs(mpctx->d_audio); // free buffered chunks
4804 if (!mpctx->sh_video) {
4805 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4806 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4807 mpctx->d_video->packs);
4808 ds_free_packs(mpctx->d_video);
4809 mpctx->d_video->id = -2;
4812 if (!mpctx->sh_video && !mpctx->sh_audio)
4813 goto goto_next_file;
4815 if (force_fps && mpctx->sh_video) {
4816 vo_fps = mpctx->sh_video->fps = force_fps;
4817 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4818 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4819 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4820 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4823 mp_input_set_section(mpctx->input, NULL);
4824 //TODO: add desired (stream-based) sections here
4825 if (mpctx->stream->type == STREAMTYPE_TV)
4826 mp_input_set_section(mpctx->input, "tv");
4827 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4828 mp_input_set_section(mpctx->input, "dvdnav");
4830 //==================== START PLAYING =======================
4832 if (opts->loop_times > 1)
4833 opts->loop_times--;
4834 else if (opts->loop_times == 1)
4835 opts->loop_times = -1;
4837 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4839 total_time_usage_start = GetTimer();
4840 audio_time_usage = 0;
4841 video_time_usage = 0;
4842 vout_time_usage = 0;
4843 total_frame_cnt = 0;
4844 drop_frame_cnt = 0; // fix for multifile fps benchmark
4845 play_n_frames = play_n_frames_mf;
4847 if (play_n_frames == 0) {
4848 mpctx->stop_play = PT_NEXT_ENTRY;
4849 goto goto_next_file;
4852 mpctx->time_frame = 0;
4853 mpctx->drop_message_shown = 0;
4854 mpctx->restart_playback = true;
4855 mpctx->video_pts = 0;
4856 mpctx->last_seek_pts = 0;
4857 mpctx->hrseek_active = false;
4858 mpctx->hrseek_framedrop = false;
4859 mpctx->step_frames = 0;
4860 mpctx->total_avsync_change = 0;
4861 mpctx->last_chapter_seek = -2;
4863 // If there's a timeline force an absolute seek to initialize state
4864 if (opts->seek_to_sec || mpctx->timeline) {
4865 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4866 seek(mpctx, mpctx->seek, false);
4867 end_at.pos += opts->seek_to_sec;
4869 if (opts->chapterrange[0] > 0) {
4870 double pts;
4871 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4872 && pts > -1.0) {
4873 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4874 seek(mpctx, mpctx->seek, false);
4878 if (end_at.type == END_AT_SIZE) {
4879 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4880 "Option -endpos in MPlayer does not yet support size units.\n");
4881 end_at.type = END_AT_NONE;
4884 #ifdef CONFIG_DVDNAV
4885 mp_dvdnav_context_free(mpctx);
4886 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4887 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4888 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4890 #endif
4892 mpctx->seek = (struct seek_params){ 0 };
4893 get_relative_time(mpctx); // reset current delta
4894 // Make sure VO knows current pause state
4895 if (mpctx->sh_video)
4896 vo_control(mpctx->video_out,
4897 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4899 while (!mpctx->stop_play)
4900 run_playloop(mpctx);
4902 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4904 #ifdef CONFIG_DVBIN
4905 if (mpctx->dvbin_reopen) {
4906 mpctx->stop_play = 0;
4907 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4908 cache_uninit(mpctx->stream);
4909 mpctx->dvbin_reopen = 0;
4910 goto goto_enable_cache;
4912 #endif
4914 goto_next_file: // don't jump here after ao/vo/getch initialization!
4916 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4918 if (opts->benchmark) {
4919 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4920 double total_time_usage;
4921 total_time_usage_start = GetTimer() - total_time_usage_start;
4922 total_time_usage = (float)total_time_usage_start * 0.000001;
4923 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4924 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4925 video_time_usage, vout_time_usage, audio_time_usage,
4926 total_time_usage - tot, total_time_usage);
4927 if (total_time_usage > 0.0)
4928 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4929 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4930 100.0 * video_time_usage / total_time_usage,
4931 100.0 * vout_time_usage / total_time_usage,
4932 100.0 * audio_time_usage / total_time_usage,
4933 100.0 * (total_time_usage - tot) / total_time_usage,
4934 100.0);
4935 if (total_frame_cnt && frame_dropping)
4936 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4937 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4938 total_frame_cnt - drop_frame_cnt,
4939 (total_time_usage > 0.5) ? ((total_frame_cnt -
4940 drop_frame_cnt) / total_time_usage) : 0,
4941 drop_frame_cnt,
4942 100 * drop_frame_cnt / total_frame_cnt,
4943 total_frame_cnt,
4944 (total_time_usage > 0.5) ?
4945 (total_frame_cnt / total_time_usage) : 0);
4948 // time to uninit all, except global stuff:
4949 int uninitialize_parts = INITIALIZED_ALL;
4950 if (opts->fixed_vo)
4951 uninitialize_parts -= INITIALIZED_VO;
4952 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4953 uninitialize_parts -= INITIALIZED_AO;
4954 uninit_player(mpctx, uninitialize_parts);
4956 if (mpctx->set_of_sub_size > 0) {
4957 current_module = "sub_free";
4958 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
4959 sub_free(mpctx->set_of_subtitles[i]);
4960 talloc_free(mpctx->set_of_ass_tracks[i]);
4962 mpctx->set_of_sub_size = 0;
4964 mpctx->vo_sub_last = vo_sub = NULL;
4965 mpctx->subdata = NULL;
4966 #ifdef CONFIG_ASS
4967 if (mpctx->osd->ass_renderer)
4968 ass_renderer_done(mpctx->osd->ass_renderer);
4969 mpctx->osd->ass_renderer = NULL;
4970 ass_clear_fonts(mpctx->ass_library);
4971 #endif
4973 if (!mpctx->stop_play) // In case some goto jumped here...
4974 mpctx->stop_play = PT_NEXT_ENTRY;
4976 int playtree_direction = 1;
4978 if (mpctx->stop_play == PT_NEXT_ENTRY
4979 || mpctx->stop_play == PT_PREV_ENTRY) {
4980 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
4981 != PLAY_TREE_ITER_ENTRY) {
4982 play_tree_iter_free(mpctx->playtree_iter);
4983 mpctx->playtree_iter = NULL;
4985 mpctx->play_tree_step = 1;
4986 } else if (mpctx->stop_play == PT_UP_NEXT ||
4987 mpctx->stop_play == PT_UP_PREV) {
4988 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4989 if (mpctx->playtree_iter) {
4990 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
4991 PLAY_TREE_ITER_ENTRY) {
4992 play_tree_iter_free(mpctx->playtree_iter);
4993 mpctx->playtree_iter = NULL;
4996 } else if (mpctx->stop_play == PT_STOP) {
4997 play_tree_iter_free(mpctx->playtree_iter);
4998 mpctx->playtree_iter = NULL;
4999 } else // NEXT PREV SRC
5000 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5002 while (mpctx->playtree_iter != NULL) {
5003 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5004 playtree_direction);
5005 if (mpctx->filename == NULL) {
5006 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5007 0) != PLAY_TREE_ITER_ENTRY) {
5008 play_tree_iter_free(mpctx->playtree_iter);
5009 mpctx->playtree_iter = NULL;
5012 } else
5013 break;
5016 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5017 if (!mpctx->playtree_iter)
5018 mpctx->filename = NULL;
5019 mpctx->stop_play = 0;
5020 goto play_next_file;
5023 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5025 return 1;
5027 #endif /* DISABLE_MAIN */