osd: rewrite OSD rendering to use libass
[mplayer.git] / mplayer.c
blobbf8986c03b477cb78be934fa203a8fe28ec08a8c
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 "sub/av_sub.h"
91 #include "libmpcodecs/dec_teletext.h"
92 #include "cpudetect.h"
93 #include "version.h"
95 #ifdef CONFIG_X11
96 #include "libvo/x11_common.h"
97 #endif
99 #include "libao2/audio_out.h"
101 #include "codec-cfg.h"
103 #include "sub/spudec.h"
104 #include "sub/vobsub.h"
106 #include "osdep/getch2.h"
107 #include "osdep/timer.h"
109 #include "input/input.h"
111 int slave_mode = 0;
112 int enable_mouse_movements = 0;
113 float start_volume = -1;
115 #include "osdep/priority.h"
117 char *heartbeat_cmd;
119 #ifdef HAVE_RTC
120 #ifdef __linux__
121 #include <linux/rtc.h>
122 #else
123 #include <rtc.h>
124 #define RTC_IRQP_SET RTCIO_IRQP_SET
125 #define RTC_PIE_ON RTCIO_PIE_ON
126 #endif /* __linux__ */
127 #endif /* HAVE_RTC */
129 #include "stream/tv.h"
130 #include "stream/stream_radio.h"
131 #ifdef CONFIG_DVBIN
132 #include "stream/dvbin.h"
133 #endif
134 #include "stream/cache2.h"
136 //**************************************************************************//
137 // Playtree
138 //**************************************************************************//
139 #include "playtree.h"
140 #include "playtreeparser.h"
142 //**************************************************************************//
143 // Config
144 //**************************************************************************//
145 #include "parser-cfg.h"
146 #include "parser-mpcmd.h"
148 //**************************************************************************//
149 // Config file
150 //**************************************************************************//
152 #include "path.h"
154 //**************************************************************************//
155 //**************************************************************************//
156 // Input media streaming & demultiplexer:
157 //**************************************************************************//
159 static int max_framesize = 0;
161 #include "stream/stream.h"
162 #include "libmpdemux/demuxer.h"
163 #include "libmpdemux/stheader.h"
165 #ifdef CONFIG_DVDREAD
166 #include "stream/stream_dvd.h"
167 #endif
168 #include "stream/stream_dvdnav.h"
170 #include "libmpcodecs/dec_audio.h"
171 #include "libmpcodecs/dec_video.h"
172 #include "libmpcodecs/mp_image.h"
173 #include "libmpcodecs/vf.h"
174 #include "libmpcodecs/vd.h"
176 #include "mixer.h"
178 #include "mp_core.h"
179 #include "options.h"
180 #include "defaultopts.h"
182 static const char help_text[] = _(
183 "Usage: mplayer [options] [url|path/]filename\n"
184 "\n"
185 "Basic options: (complete list in the man page)\n"
186 " -vo <drv> select video output driver ('-vo help' for a list)\n"
187 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
188 #ifdef CONFIG_VCD
189 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
190 #endif
191 #ifdef CONFIG_DVDREAD
192 " dvd://<titleno> play DVD title from device instead of plain file\n"
193 #endif
194 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
195 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
196 " -nosound do not play sound\n"
197 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
198 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
199 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
200 " -playlist <file> specify playlist file\n"
201 " -vid x -aid y select video (x) and audio (y) stream to play\n"
202 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
203 " -pp <quality> enable postprocessing filter (details in the man page)\n"
204 " -framedrop enable frame dropping (for slow machines)\n"
205 "\n"
206 "Basic keys: (complete list in the man page, also check input.conf)\n"
207 " <- or -> seek backward/forward 10 seconds\n"
208 " down or up seek backward/forward 1 minute\n"
209 " pgdown or pgup seek backward/forward 10 minutes\n"
210 " < or > step backward/forward in playlist\n"
211 " p or SPACE pause movie (press any key to continue)\n"
212 " q or ESC stop playing and quit program\n"
213 " + or - adjust audio delay by +/- 0.1 second\n"
214 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
215 " * or / increase or decrease PCM volume\n"
216 " x or z adjust subtitle delay by +/- 0.1 second\n"
217 " r or t adjust subtitle position up/down, also see -vf expand\n"
218 " double click toggle fullscreen\n"
219 " right click pause (press again to continue)\n"
220 "\n"
221 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
222 "\n");
225 #define Exit_SIGILL_RTCpuSel _(\
226 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
227 " It may be a bug in our new runtime CPU-detection code...\n"\
228 " Please read DOCS/HTML/en/bugreports.html.\n")
230 #define Exit_SIGILL _(\
231 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
232 " It usually happens when you run it on a CPU different than the one it was\n"\
233 " compiled/optimized for.\n"\
234 " Verify this!\n")
236 #define Exit_SIGSEGV_SIGFPE _(\
237 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
238 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
239 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
241 #define Exit_SIGCRASH _(\
242 "- MPlayer crashed. This shouldn't happen.\n"\
243 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
244 " gcc version. If you think it's MPlayer's fault, please read\n"\
245 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
246 " won't help unless you provide this information when reporting a possible bug.\n")
248 #define SystemTooSlow _("\n\n"\
249 " ************************************************\n"\
250 " **** Your system is too SLOW to play this! ****\n"\
251 " ************************************************\n\n"\
252 "Possible reasons, problems, workarounds:\n"\
253 "- Most common: broken/buggy _audio_ driver\n"\
254 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
255 " - Experiment with different values for -autosync, 30 is a good start.\n"\
256 "- Slow video output\n"\
257 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
258 "- Slow CPU\n"\
259 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
260 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
261 "- Broken file\n"\
262 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
263 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
264 " - Try -cache 8192.\n"\
265 "- Are you using -cache to play a non-interleaved AVI file?\n"\
266 " - Try -nocache.\n"\
267 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
268 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
271 //**************************************************************************//
272 //**************************************************************************//
274 #include "mp_fifo.h"
276 // benchmark:
277 double video_time_usage;
278 double vout_time_usage;
279 static double audio_time_usage;
280 static int total_time_usage_start;
281 static int total_frame_cnt;
282 static int drop_frame_cnt; // total number of dropped frames
284 // options:
285 static int output_quality;
287 // seek:
288 static off_t seek_to_byte;
289 static off_t step_sec;
291 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
293 // codecs:
294 char **audio_codec_list; // override audio codec
295 char **video_codec_list; // override video codec
296 char **audio_fm_list; // override audio codec family
297 char **video_fm_list; // override video codec family
299 // this dvdsub_id was selected via slang
300 // use this to allow dvdnav to follow -slang across stream resets,
301 // in particular the subtitle ID for a language changes
302 int dvdsub_lang_id;
303 int vobsub_id = -1;
304 static char *spudec_ifo = NULL;
305 int forced_subs_only = 0;
307 // cache2:
308 int stream_cache_size = -1;
310 // dump:
311 int stream_dump_type = 0;
313 // A-V sync:
314 static float default_max_pts_correction = -1;
315 float audio_delay = 0;
316 static int ignore_start = 0;
318 double force_fps = 0;
319 static int force_srate = 0;
320 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
321 static int play_n_frames = -1;
322 static int play_n_frames_mf = -1;
324 #include "sub/ass_mp.h"
326 char *current_module; // for debugging
329 // ---
331 FILE *edl_fd; // file to write to when in -edlout mode.
332 char *edl_output_filename; // file to put EDL entries in (-edlout)
334 int use_filedir_conf;
335 int use_filename_title;
337 #include "mpcommon.h"
338 #include "command.h"
340 #include "metadata.h"
342 static float get_relative_time(struct MPContext *mpctx)
344 unsigned int new_time = GetTimer();
345 unsigned int delta = new_time - mpctx->last_time;
346 mpctx->last_time = new_time;
347 return delta * 0.000001;
350 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
352 switch (type) {
353 /* check for valid video stream */
354 case META_VIDEO_CODEC:
355 case META_VIDEO_BITRATE:
356 case META_VIDEO_RESOLUTION:
357 if (!mpctx->sh_video)
358 return 0;
359 break;
361 /* check for valid audio stream */
362 case META_AUDIO_CODEC:
363 case META_AUDIO_BITRATE:
364 case META_AUDIO_SAMPLES:
365 if (!mpctx->sh_audio)
366 return 0;
367 break;
369 /* check for valid demuxer */
370 case META_INFO_TITLE:
371 case META_INFO_ARTIST:
372 case META_INFO_ALBUM:
373 case META_INFO_YEAR:
374 case META_INFO_COMMENT:
375 case META_INFO_TRACK:
376 case META_INFO_GENRE:
377 if (!mpctx->demuxer)
378 return 0;
379 break;
381 default:
382 break;
385 return 1;
388 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
390 char **info = mpctx->demuxer->info;
391 int n;
393 if (!info || !tag)
394 return talloc_strdup(NULL, "");
396 for (n = 0; info[2 * n] != NULL; n++)
397 if (!strcasecmp(info[2 * n], tag))
398 break;
400 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
403 char *get_metadata(struct MPContext *mpctx, metadata_t type)
405 sh_audio_t * const sh_audio = mpctx->sh_audio;
406 sh_video_t * const sh_video = mpctx->sh_video;
408 if (!is_valid_metadata_type(mpctx, type))
409 return NULL;
411 switch (type) {
412 case META_NAME:
413 return talloc_strdup(NULL, mp_basename(mpctx->filename));
414 case META_VIDEO_CODEC:
415 if (sh_video->format == 0x10000001)
416 return talloc_strdup(NULL, "mpeg1");
417 else if (sh_video->format == 0x10000002)
418 return talloc_strdup(NULL, "mpeg2");
419 else if (sh_video->format == 0x10000004)
420 return talloc_strdup(NULL, "mpeg4");
421 else if (sh_video->format == 0x10000005)
422 return talloc_strdup(NULL, "h264");
423 else if (sh_video->format >= 0x20202020)
424 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
425 else
426 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
427 case META_VIDEO_BITRATE:
428 return talloc_asprintf(NULL, "%d kbps",
429 (int) (sh_video->i_bps * 8 / 1024));
430 case META_VIDEO_RESOLUTION:
431 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
432 sh_video->disp_h);
433 case META_AUDIO_CODEC:
434 if (sh_audio->codec && sh_audio->codec->name)
435 return talloc_strdup(NULL, sh_audio->codec->name);
436 return talloc_strdup(NULL, "");
437 case META_AUDIO_BITRATE:
438 return talloc_asprintf(NULL, "%d kbps",
439 (int) (sh_audio->i_bps * 8 / 1000));
440 case META_AUDIO_SAMPLES:
441 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
442 sh_audio->channels);
444 /* check for valid demuxer */
445 case META_INFO_TITLE:
446 return get_demuxer_info(mpctx, "Title");
448 case META_INFO_ARTIST:
449 return get_demuxer_info(mpctx, "Artist");
451 case META_INFO_ALBUM:
452 return get_demuxer_info(mpctx, "Album");
454 case META_INFO_YEAR:
455 return get_demuxer_info(mpctx, "Year");
457 case META_INFO_COMMENT:
458 return get_demuxer_info(mpctx, "Comment");
460 case META_INFO_TRACK:
461 return get_demuxer_info(mpctx, "Track");
463 case META_INFO_GENRE:
464 return get_demuxer_info(mpctx, "Genre");
466 default:
467 break;
470 return talloc_strdup(NULL, "");
473 static void print_file_properties(struct MPContext *mpctx, const char *filename)
475 double start_pts = MP_NOPTS_VALUE;
476 double video_start_pts = MP_NOPTS_VALUE;
477 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
478 filename_recode(filename));
479 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
480 mpctx->demuxer->desc->name);
481 if (mpctx->sh_video) {
482 /* Assume FOURCC if all bytes >= 0x20 (' ') */
483 if (mpctx->sh_video->format >= 0x20202020)
484 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
485 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
486 else
487 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
488 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
489 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
490 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
491 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
492 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
493 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
494 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
495 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
496 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
497 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
498 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
499 video_start_pts = ds_get_next_pts(mpctx->d_video);
501 if (mpctx->sh_audio) {
502 /* Assume FOURCC if all bytes >= 0x20 (' ') */
503 if (mpctx->sh_audio->format >= 0x20202020)
504 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
505 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
506 else
507 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
508 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
509 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
510 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
511 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
512 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
513 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
514 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
515 start_pts = ds_get_next_pts(mpctx->d_audio);
517 if (video_start_pts != MP_NOPTS_VALUE) {
518 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
519 (mpctx->sh_video && video_start_pts < start_pts))
520 start_pts = video_start_pts;
522 if (start_pts != MP_NOPTS_VALUE)
523 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
524 else
525 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
526 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
527 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
528 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
529 mpctx->stream->seek
530 && (!mpctx->demuxer || mpctx->demuxer->seekable));
531 if (mpctx->demuxer) {
532 int chapter_count = get_chapter_count(mpctx);
533 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
534 for (int i = 0; i < chapter_count; i++) {
535 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
536 // in milliseconds
537 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
538 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
539 char *name = chapter_name(mpctx, i);
540 if (name) {
541 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
542 name);
543 talloc_free(name);
549 /// step size of mixer changes
550 int volstep = 3;
552 #ifdef CONFIG_DVDNAV
553 static void mp_dvdnav_context_free(MPContext *ctx)
555 if (ctx->nav_smpi)
556 free_mp_image(ctx->nav_smpi);
557 ctx->nav_smpi = NULL;
558 free(ctx->nav_buffer);
559 ctx->nav_buffer = NULL;
560 ctx->nav_start = NULL;
561 ctx->nav_in_size = 0;
563 #endif
565 static void uninit_subs(struct demuxer *demuxer)
567 for (int i = 0; i < MAX_S_STREAMS; i++) {
568 struct sh_sub *sh = demuxer->s_streams[i];
569 if (sh && sh->initialized)
570 sub_uninit(sh);
574 void uninit_player(struct MPContext *mpctx, unsigned int mask)
576 mask &= mpctx->initialized_flags;
578 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
580 if (mask & INITIALIZED_ACODEC) {
581 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
582 current_module = "uninit_acodec";
583 if (mpctx->sh_audio)
584 uninit_audio(mpctx->sh_audio);
585 mpctx->sh_audio = NULL;
586 mpctx->mixer.afilter = NULL;
589 if (mask & INITIALIZED_SUB) {
590 mpctx->initialized_flags &= ~INITIALIZED_SUB;
591 if (mpctx->d_sub->sh)
592 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
595 if (mask & INITIALIZED_VCODEC) {
596 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
597 current_module = "uninit_vcodec";
598 if (mpctx->sh_video)
599 uninit_video(mpctx->sh_video);
600 mpctx->sh_video = NULL;
603 if (mask & INITIALIZED_DEMUXER) {
604 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
605 current_module = "free_demuxer";
606 if (mpctx->num_sources) {
607 mpctx->demuxer = mpctx->sources[0].demuxer;
608 for (int i = 1; i < mpctx->num_sources; i++) {
609 uninit_subs(mpctx->sources[i].demuxer);
610 free_stream(mpctx->sources[i].stream);
611 free_demuxer(mpctx->sources[i].demuxer);
614 talloc_free(mpctx->sources);
615 mpctx->sources = NULL;
616 mpctx->num_sources = 0;
617 talloc_free(mpctx->timeline);
618 mpctx->timeline = NULL;
619 mpctx->num_timeline_parts = 0;
620 talloc_free(mpctx->chapters);
621 mpctx->chapters = NULL;
622 mpctx->num_chapters = 0;
623 mpctx->video_offset = 0;
624 if (mpctx->demuxer) {
625 mpctx->stream = mpctx->demuxer->stream;
626 uninit_subs(mpctx->demuxer);
627 free_demuxer(mpctx->demuxer);
629 mpctx->demuxer = NULL;
632 // kill the cache process:
633 if (mask & INITIALIZED_STREAM) {
634 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
635 current_module = "uninit_stream";
636 if (mpctx->stream)
637 free_stream(mpctx->stream);
638 mpctx->stream = NULL;
641 if (mask & INITIALIZED_VO) {
642 mpctx->initialized_flags &= ~INITIALIZED_VO;
643 current_module = "uninit_vo";
644 vo_destroy(mpctx->video_out);
645 mpctx->video_out = NULL;
646 #ifdef CONFIG_DVDNAV
647 mp_dvdnav_context_free(mpctx);
648 #endif
651 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
652 if (mask & INITIALIZED_GETCH2) {
653 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
654 current_module = "uninit_getch2";
655 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
656 // restore terminal:
657 getch2_disable();
660 if (mask & INITIALIZED_VOBSUB) {
661 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
662 current_module = "uninit_vobsub";
663 if (vo_vobsub)
664 vobsub_close(vo_vobsub);
665 vo_vobsub = NULL;
668 if (mask & INITIALIZED_SPUDEC) {
669 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
670 current_module = "uninit_spudec";
671 spudec_free(vo_spudec);
672 vo_spudec = NULL;
675 if (mask & INITIALIZED_AO) {
676 mpctx->initialized_flags &= ~INITIALIZED_AO;
677 current_module = "uninit_ao";
678 if (mpctx->ao) {
679 mixer_uninit(&mpctx->mixer);
680 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
682 mpctx->ao = NULL;
685 current_module = NULL;
688 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
690 uninit_player(mpctx, INITIALIZED_ALL);
691 #if defined(__MINGW32__) || defined(__CYGWIN__)
692 timeEndPeriod(1);
693 #endif
694 #ifdef CONFIG_X11
695 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
696 #endif
698 current_module = "uninit_input";
699 mp_input_uninit(mpctx->input);
701 osd_free(mpctx->osd);
703 #ifdef CONFIG_ASS
704 ass_library_done(mpctx->ass_library);
705 mpctx->ass_library = NULL;
706 #endif
708 current_module = "exit_player";
710 if (mpctx->playtree_iter)
711 play_tree_iter_free(mpctx->playtree_iter);
712 mpctx->playtree_iter = NULL;
713 if (mpctx->playtree)
714 play_tree_free(mpctx->playtree, 1);
715 mpctx->playtree = NULL;
717 talloc_free(mpctx->key_fifo);
719 switch (how) {
720 case EXIT_QUIT:
721 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
722 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
723 break;
724 case EXIT_EOF:
725 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
726 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
727 break;
728 case EXIT_ERROR:
729 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
730 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
731 break;
732 default:
733 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
735 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
736 "max framesize was %d bytes\n", max_framesize);
738 // must be last since e.g. mp_msg uses option values
739 // that will be freed by this.
740 if (mpctx->mconfig)
741 m_config_free(mpctx->mconfig);
742 mpctx->mconfig = NULL;
744 talloc_free(mpctx);
746 exit(rc);
749 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
751 exit_player_with_rc(mpctx, how, 1);
754 #ifndef __MINGW32__
755 static void child_sighandler(int x)
757 pid_t pid;
758 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
760 #endif
762 #ifdef CONFIG_CRASH_DEBUG
763 static char *prog_path;
764 static int crash_debug = 0;
765 #endif
767 static void exit_sighandler(int x)
769 static int sig_count = 0;
770 #ifdef CONFIG_CRASH_DEBUG
771 if (!crash_debug || x != SIGTRAP)
772 #endif
773 ++sig_count;
774 if (sig_count == 5) {
775 /* We're crashing bad and can't uninit cleanly :(
776 * by popular request, we make one last (dirty)
777 * effort to restore the user's
778 * terminal. */
779 getch2_disable();
780 exit(1);
782 if (sig_count == 6)
783 exit(1);
784 if (sig_count > 6) {
785 // can't stop :(
786 #ifndef __MINGW32__
787 kill(getpid(), SIGKILL);
788 #endif
790 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
791 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
792 "\nMPlayer interrupted by signal %d in module: %s\n", x,
793 current_module ? current_module : "unknown");
794 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
795 if (sig_count <= 1)
796 switch (x) {
797 case SIGINT:
798 case SIGPIPE:
799 case SIGQUIT:
800 case SIGTERM:
801 case SIGKILL:
802 async_quit_request = 1;
803 return; // killed from keyboard (^C) or killed [-9]
804 case SIGILL:
805 #if CONFIG_RUNTIME_CPUDETECT
806 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
807 #else
808 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
809 #endif
810 case SIGFPE:
811 case SIGSEGV:
812 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
813 default:
814 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
815 #ifdef CONFIG_CRASH_DEBUG
816 if (crash_debug) {
817 int gdb_pid;
818 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
819 gdb_pid = fork();
820 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
821 if (gdb_pid == 0) { // We are the child
822 char spid[20];
823 snprintf(spid, sizeof(spid), "%i", getppid());
824 getch2_disable(); // allow terminal to work properly with gdb
825 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
826 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
827 } else if (gdb_pid < 0)
828 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
829 else
830 waitpid(gdb_pid, NULL, 0);
831 if (x == SIGTRAP)
832 return;
834 #endif
836 getch2_disable();
837 exit(1);
840 #include "cfg-mplayer.h"
842 static int cfg_include(struct m_config *conf, char *filename)
844 return m_config_parse_config_file(conf, filename);
847 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
849 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
851 struct MPOpts *opts = &mpctx->opts;
852 char *conffile;
853 int conffile_fd;
854 if (!(opts->noconfig & 2) &&
855 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
856 exit_player(mpctx, EXIT_NONE);
857 if ((conffile = get_path("")) == NULL)
858 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
859 else {
860 mkdir(conffile, 0777);
861 free(conffile);
862 if ((conffile = get_path("config")) == NULL)
863 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
864 else {
865 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
866 0666)) != -1) {
867 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
868 "Creating config file: %s\n", conffile);
869 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
870 close(conffile_fd);
872 if (!(opts->noconfig & 1) &&
873 m_config_parse_config_file(conf, conffile) < 0)
874 exit_player(mpctx, EXIT_NONE);
875 free(conffile);
880 #define PROFILE_CFG_PROTOCOL "protocol."
882 static void load_per_protocol_config(m_config_t *conf, const char * const file)
884 char *str;
885 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
886 m_profile_t *p;
888 /* does filename actually uses a protocol ? */
889 str = strstr(file, "://");
890 if (!str)
891 return;
893 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
894 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
895 p = m_config_get_profile(conf, protocol);
896 if (p) {
897 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
898 "Loading protocol-related profile '%s'\n", protocol);
899 m_config_set_profile(conf, p);
903 #define PROFILE_CFG_EXTENSION "extension."
905 static void load_per_extension_config(m_config_t *conf, const char * const file)
907 char *str;
908 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
909 m_profile_t *p;
911 /* does filename actually have an extension ? */
912 str = strrchr(file, '.');
913 if (!str)
914 return;
916 sprintf(extension, PROFILE_CFG_EXTENSION);
917 strncat(extension, ++str, 7);
918 p = m_config_get_profile(conf, extension);
919 if (p) {
920 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
921 "Loading extension-related profile '%s'\n", extension);
922 m_config_set_profile(conf, p);
926 #define PROFILE_CFG_VO "vo."
927 #define PROFILE_CFG_AO "ao."
929 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
931 char profile[strlen(cfg) + strlen(out) + 1];
932 m_profile_t *p;
934 sprintf(profile, "%s%s", cfg, out);
935 p = m_config_get_profile(conf, profile);
936 if (p) {
937 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
938 "Loading extension-related profile '%s'\n", profile);
939 m_config_set_profile(conf, p);
944 * Tries to load a config file
945 * @return 0 if file was not found, 1 otherwise
947 static int try_load_config(m_config_t *conf, const char *file)
949 if (!mp_path_exists(file))
950 return 0;
951 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
952 m_config_parse_config_file(conf, file);
953 return 1;
956 static void load_per_file_config(m_config_t *conf, const char * const file)
958 char *confpath;
959 char cfg[MP_PATH_MAX];
960 const char *name;
962 if (strlen(file) > MP_PATH_MAX - 14) {
963 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
964 "can not load file or directory specific config files\n");
965 return;
967 sprintf(cfg, "%s.conf", file);
969 name = mp_basename(cfg);
970 if (use_filedir_conf) {
971 char dircfg[MP_PATH_MAX];
972 strcpy(dircfg, cfg);
973 strcpy(dircfg + (name - cfg), "mplayer.conf");
974 try_load_config(conf, dircfg);
976 if (try_load_config(conf, cfg))
977 return;
980 if ((confpath = get_path(name)) != NULL) {
981 try_load_config(conf, confpath);
983 free(confpath);
987 /* When libmpdemux performs a blocking operation (network connection or
988 * cache filling) if the operation fails we use this function to check
989 * if it was interrupted by the user.
990 * The function returns a new value for eof. */
991 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
993 mp_cmd_t *cmd;
994 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
995 switch (cmd->id) {
996 case MP_CMD_QUIT:
997 exit_player_with_rc(mpctx, EXIT_QUIT,
998 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
999 case MP_CMD_PLAY_TREE_STEP: {
1000 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1001 mpctx->play_tree_step =
1002 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1003 } break;
1004 case MP_CMD_PLAY_TREE_UP_STEP: {
1005 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1006 } break;
1007 case MP_CMD_PLAY_ALT_SRC_STEP: {
1008 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1009 } break;
1011 mp_cmd_free(cmd);
1013 return stop_play;
1016 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1018 play_tree_add_bpf(entry, bstr(mpctx->filename));
1021 if (!entry) {
1022 entry = mpctx->playtree_iter->tree;
1023 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1024 != PLAY_TREE_ITER_ENTRY)
1025 return PT_NEXT_ENTRY;
1026 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1027 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1028 != PLAY_TREE_ITER_ENTRY)
1029 return PT_NEXT_ENTRY;
1031 play_tree_remove(entry, 1, 1);
1032 return PT_NEXT_SRC;
1034 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1035 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1036 entry = mpctx->playtree_iter->tree;
1037 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1038 != PLAY_TREE_ITER_ENTRY)
1039 return PT_NEXT_ENTRY;
1040 play_tree_remove(entry, 1, 1);
1042 return PT_NEXT_SRC;
1045 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1046 int noerr)
1048 struct MPOpts *opts = &mpctx->opts;
1049 sub_data *subd = NULL;
1050 struct ass_track *asst = NULL;
1051 bool is_native_ass = false;
1053 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1054 return;
1056 #ifdef CONFIG_ASS
1057 if (opts->ass_enabled) {
1058 #ifdef CONFIG_ICONV
1059 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1060 #else
1061 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1062 #endif
1063 is_native_ass = asst;
1064 if (!asst) {
1065 subd = sub_read_file(filename, fps, &mpctx->opts);
1066 if (subd) {
1067 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1068 sub_free(subd);
1069 subd = NULL;
1072 } else
1073 #endif
1074 subd = sub_read_file(filename, fps, &mpctx->opts);
1077 if (!asst && !subd) {
1078 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1079 "Cannot load subtitles: %s\n", filename_recode(filename));
1080 return;
1083 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1084 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1085 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1086 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1087 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1088 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1089 filename_recode(filename));
1090 ++mpctx->set_of_sub_size;
1091 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1092 mpctx->set_of_sub_size, filename_recode(filename));
1095 void init_vo_spudec(struct MPContext *mpctx)
1097 unsigned width, height;
1098 spudec_free(vo_spudec);
1099 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1100 vo_spudec = NULL;
1102 // we currently can't work without video stream
1103 if (!mpctx->sh_video)
1104 return;
1106 if (spudec_ifo) {
1107 unsigned int palette[16];
1108 current_module = "spudec_init_vobsub";
1109 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1110 1, -1, NULL) >= 0)
1111 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1114 width = mpctx->sh_video->disp_w;
1115 height = mpctx->sh_video->disp_h;
1117 #ifdef CONFIG_DVDREAD
1118 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1119 current_module = "spudec_init_dvdread";
1120 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1121 cur_pgc->palette, width, height, NULL, 0);
1123 #endif
1125 #ifdef CONFIG_DVDNAV
1126 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1127 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1128 current_module = "spudec_init_dvdnav";
1129 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1131 #endif
1133 if (vo_spudec == NULL) {
1134 sh_sub_t *sh = mpctx->d_sub->sh;
1135 current_module = "spudec_init_normal";
1136 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1137 sh->extradata_len);
1138 spudec_set_font_factor(vo_spudec, font_factor);
1141 if (vo_spudec != NULL) {
1142 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1143 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1144 mpctx);
1149 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1150 * make it all work is to use the builtin SDL-bootstrap code, which
1151 * will be done automatically by replacing our main() if we include SDL.h.
1153 #if defined(__APPLE__) && defined(CONFIG_SDL)
1154 #ifdef CONFIG_SDL_SDL_H
1155 #include <SDL/SDL.h>
1156 #else
1157 #include <SDL.h>
1158 #endif
1159 #endif
1162 * \brief append a formatted string
1163 * \param buf buffer to print into
1164 * \param pos position of terminating 0 in buf
1165 * \param len maximum number of characters in buf, not including terminating 0
1166 * \param format printf format string
1168 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1170 va_list va;
1171 va_start(va, format);
1172 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1173 va_end(va);
1174 if (*pos >= len) {
1175 buf[len] = 0;
1176 *pos = len;
1181 * \brief append time in the hh:mm:ss.f format
1182 * \param buf buffer to print into
1183 * \param pos position of terminating 0 in buf
1184 * \param len maximum number of characters in buf, not including terminating 0
1185 * \param time time value to convert/append
1187 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1189 int64_t tenths = 10 * time;
1190 int f1 = tenths % 10;
1191 int ss = (tenths / 10) % 60;
1192 int mm = (tenths / 600) % 60;
1193 int hh = tenths / 36000;
1194 if (time < 0) {
1195 saddf(buf, pos, len, "unknown");
1196 return;
1198 if (hh > 0)
1199 saddf(buf, pos, len, "%2d:", hh);
1200 if (hh > 0 || mm > 0)
1201 saddf(buf, pos, len, "%02d:", mm);
1202 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1205 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1207 struct MPOpts *opts = &mpctx->opts;
1208 sh_video_t * const sh_video = mpctx->sh_video;
1210 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1211 a_pos = playing_audio_pts(mpctx);
1212 if (mpctx->sh_audio && sh_video && at_frame) {
1213 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1214 if (mpctx->time_frame > 0)
1215 mpctx->last_av_difference +=
1216 mpctx->time_frame * opts->playback_speed;
1217 if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
1218 mpctx->last_av_difference = MP_NOPTS_VALUE;
1219 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1220 && !mpctx->drop_message_shown) {
1221 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1222 mpctx->drop_message_shown = true;
1225 if (opts->quiet)
1226 return;
1228 int width;
1229 char *line;
1230 unsigned pos = 0;
1231 get_screen_size();
1232 if (screen_width > 0)
1233 width = screen_width;
1234 else
1235 width = 80;
1236 #if defined(__MINGW32__) || defined(__CYGWIN__)
1237 /* Windows command line is broken (MinGW's rxvt works, but we
1238 * should not depend on that). */
1239 width--;
1240 #endif
1241 line = malloc(width + 1); // one additional char for the terminating null
1243 // Audio time
1244 if (mpctx->sh_audio) {
1245 if (a_pos != MP_NOPTS_VALUE)
1246 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1247 else
1248 saddf(line, &pos, width, "A: ??? ");
1249 if (!sh_video && a_pos != MP_NOPTS_VALUE) {
1250 float len = get_time_length(mpctx);
1251 saddf(line, &pos, width, "(");
1252 sadd_hhmmssf(line, &pos, width, a_pos);
1253 saddf(line, &pos, width, ") of %.1f (", len);
1254 sadd_hhmmssf(line, &pos, width, len);
1255 saddf(line, &pos, width, ") ");
1259 // Video time
1260 if (sh_video) {
1261 if (mpctx->video_pts != MP_NOPTS_VALUE)
1262 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1263 else
1264 saddf(line, &pos, width, "V: ??? ", mpctx->video_pts);
1267 // A-V sync
1268 if (mpctx->sh_audio && sh_video) {
1269 if (mpctx->last_av_difference != MP_NOPTS_VALUE)
1270 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1271 mpctx->last_av_difference, mpctx->total_avsync_change);
1272 else
1273 saddf(line, &pos, width, "A-V: ??? ct:%7.3f ",
1274 mpctx->total_avsync_change);
1277 // Video stats
1278 if (sh_video)
1279 saddf(line, &pos, width, "%3d/%3d ",
1280 (int)sh_video->num_frames,
1281 (int)sh_video->num_frames_decoded);
1283 // CPU usage
1284 if (sh_video) {
1285 if (sh_video->timer > 0.5)
1286 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1287 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1288 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1289 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1290 else
1291 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1292 } else if (mpctx->sh_audio) {
1293 if (mpctx->delay > 0.5)
1294 saddf(line, &pos, width, "%4.1f%% ",
1295 100.0 * audio_time_usage / (double)mpctx->delay);
1296 else
1297 saddf(line, &pos, width, "??,?%% ");
1300 // VO stats
1301 if (sh_video)
1302 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1304 #ifdef CONFIG_STREAM_CACHE
1305 // cache stats
1306 if (stream_cache_size > 0)
1307 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1308 #endif
1310 // other
1311 if (opts->playback_speed != 1)
1312 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1314 // end
1315 if (erase_to_end_of_line) {
1316 line[pos] = 0;
1317 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1318 "%s%s\r", line, erase_to_end_of_line);
1319 } else {
1320 memset(&line[pos], ' ', width - pos);
1321 line[width] = 0;
1322 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1324 free(line);
1326 mpctx->status_printed = true;
1329 struct stream_dump_progress {
1330 uint64_t count;
1331 unsigned start_time;
1332 unsigned last_print_time;
1335 static void stream_dump_progress_start(struct stream_dump_progress *p)
1337 p->start_time = p->last_print_time = GetTimerMS();
1338 p->count = 0;
1341 static void stream_dump_progress(struct stream_dump_progress *p,
1342 uint64_t len, stream_t *stream)
1344 p->count += len;
1345 unsigned t = GetTimerMS();
1346 if (t - p->last_print_time < 1000)
1347 return;
1349 uint64_t start = stream->start_pos;
1350 uint64_t end = stream->end_pos;
1351 uint64_t pos = stream->pos;
1353 p->last_print_time = t;
1354 /* TODO: pretty print sizes; ETA */
1355 if (end > start && pos >= start && pos <= end) {
1356 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1357 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1358 p->count, 100.0 * (pos - start) / (end - start));
1359 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1360 } else {
1361 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1362 "dump: %"PRIu64 " bytes written", p->count);
1363 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1367 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1369 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1370 p->count, name);
1374 * \brief build a chain of audio filters that converts the input format
1375 * to the ao's format, taking into account the current playback_speed.
1376 * sh_audio describes the requested input format of the chain.
1377 * ao describes the requested output format of the chain.
1379 static int build_afilter_chain(struct MPContext *mpctx)
1381 struct sh_audio *sh_audio = mpctx->sh_audio;
1382 struct ao *ao = mpctx->ao;
1383 struct MPOpts *opts = &mpctx->opts;
1384 int new_srate;
1385 int result;
1386 if (!sh_audio) {
1387 mpctx->mixer.afilter = NULL;
1388 return 0;
1390 if (af_control_any_rev(sh_audio->afilter,
1391 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1392 &opts->playback_speed))
1393 new_srate = sh_audio->samplerate;
1394 else {
1395 new_srate = sh_audio->samplerate * opts->playback_speed;
1396 if (new_srate != ao->samplerate) {
1397 // limits are taken from libaf/af_resample.c
1398 if (new_srate < 8000)
1399 new_srate = 8000;
1400 if (new_srate > 192000)
1401 new_srate = 192000;
1402 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1405 result = init_audio_filters(sh_audio, new_srate,
1406 &ao->samplerate, &ao->channels, &ao->format);
1407 mpctx->mixer.afilter = sh_audio->afilter;
1408 return result;
1412 typedef struct mp_osd_msg mp_osd_msg_t;
1413 struct mp_osd_msg {
1414 /// Previous message on the stack.
1415 mp_osd_msg_t *prev;
1416 /// Message text.
1417 char *msg;
1418 int id, level, started;
1419 /// Display duration in ms.
1420 unsigned time;
1421 // Show full OSD for duration of message instead of static text ('P' key)
1422 bool show_position;
1425 /// OSD message stack.
1426 static mp_osd_msg_t *osd_msg_stack = NULL;
1429 * \brief Add a message on the OSD message stack
1431 * If a message with the same id is already present in the stack
1432 * it is pulled on top of the stack, otherwise a new message is created.
1435 static void set_osd_msg_va(int id, int level, int time, bool show_position,
1436 const char *fmt, va_list ap)
1438 mp_osd_msg_t *msg, *last = NULL;
1440 // look if the id is already in the stack
1441 for (msg = osd_msg_stack; msg && msg->id != id;
1442 last = msg, msg = msg->prev) ;
1443 // not found: alloc it
1444 if (!msg) {
1445 msg = talloc_zero(NULL, mp_osd_msg_t);
1446 msg->prev = osd_msg_stack;
1447 osd_msg_stack = msg;
1448 } else if (last) { // found, but it's not on top of the stack
1449 last->prev = msg->prev;
1450 msg->prev = osd_msg_stack;
1451 osd_msg_stack = msg;
1453 talloc_free(msg->msg);
1454 // write the msg
1455 msg->msg = talloc_vasprintf(msg, fmt, ap);
1456 // set id and time
1457 msg->id = id;
1458 msg->level = level;
1459 msg->time = time;
1460 msg->show_position = show_position;
1463 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1465 va_list ap;
1466 va_start(ap, fmt);
1467 set_osd_msg_va(id, level, time, false, fmt, ap);
1468 va_end(ap);
1471 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1473 va_list ap;
1474 va_start(ap, fmt);
1475 set_osd_msg_va(id, level, time, false, mp_gtext(fmt), ap);
1476 va_end(ap);
1479 void set_osd_progressmsg(int id, int level, int time, ...)
1481 va_list ap;
1482 va_start(ap, time);
1483 set_osd_msg_va(id, level, time, true, "", ap);
1484 va_end(ap);
1488 * \brief Remove a message from the OSD stack
1490 * This function can be used to get rid of a message right away.
1494 void rm_osd_msg(int id)
1496 mp_osd_msg_t *msg, *last = NULL;
1498 // Search for the msg
1499 for (msg = osd_msg_stack; msg && msg->id != id;
1500 last = msg, msg = msg->prev) ;
1501 if (!msg)
1502 return;
1504 // Detach it from the stack and free it
1505 if (last)
1506 last->prev = msg->prev;
1507 else
1508 osd_msg_stack = msg->prev;
1509 talloc_free(msg);
1513 * \brief Remove all messages from the OSD stack
1517 static void clear_osd_msgs(void)
1519 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1520 while (msg) {
1521 prev = msg->prev;
1522 talloc_free(msg);
1523 msg = prev;
1525 osd_msg_stack = NULL;
1529 * \brief Get the current message from the OSD stack.
1531 * This function decrements the message timer and destroys the old ones.
1532 * The message that should be displayed is returned (if any).
1536 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1538 struct MPOpts *opts = &mpctx->opts;
1539 mp_osd_msg_t *msg, *prev, *last = NULL;
1540 static unsigned last_update = 0;
1541 unsigned now = GetTimerMS();
1542 unsigned diff;
1543 char hidden_dec_done = 0;
1545 if (mpctx->osd_visible) {
1546 // 36000000 means max timed visibility is 1 hour into the future, if
1547 // the difference is greater assume it's wrapped around from below 0
1548 if (mpctx->osd_visible - now > 36000000) {
1549 mpctx->osd_visible = 0;
1550 vo_osd_progbar_type = -1; // disable
1551 vo_osd_changed(OSDTYPE_PROGBAR);
1552 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1555 if (mpctx->osd_show_percentage_until - now > 36000000)
1556 mpctx->osd_show_percentage_until = 0;
1558 if (!last_update)
1559 last_update = now;
1560 diff = now >= last_update ? now - last_update : 0;
1562 last_update = now;
1564 // Look for the first message in the stack with high enough level.
1565 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1566 prev = msg->prev;
1567 if (msg->level > opts->osd_level && hidden_dec_done)
1568 continue;
1569 // The message has a high enough level or it is the first hidden one
1570 // in both cases we decrement the timer or kill it.
1571 if (!msg->started || msg->time > diff) {
1572 if (msg->started)
1573 msg->time -= diff;
1574 else
1575 msg->started = 1;
1576 // display it
1577 if (msg->level <= opts->osd_level)
1578 return msg;
1579 hidden_dec_done = 1;
1580 continue;
1582 // kill the message
1583 talloc_free(msg);
1584 if (last) {
1585 last->prev = prev;
1586 msg = last;
1587 } else {
1588 osd_msg_stack = prev;
1589 msg = NULL;
1592 // Nothing found
1593 return NULL;
1597 * \brief Display the OSD bar.
1599 * Display the OSD bar or fall back on a simple message.
1603 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1604 double min, double max, double val)
1606 struct MPOpts *opts = &mpctx->opts;
1607 if (opts->osd_level < 1)
1608 return;
1610 if (mpctx->sh_video) {
1611 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1612 vo_osd_progbar_type = type;
1613 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1614 vo_osd_changed(OSDTYPE_PROGBAR);
1615 return;
1618 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1619 name, ROUND(100 * (val - min) / (max - min)));
1623 * \brief Display text subtitles on the OSD
1625 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1627 int i;
1628 vo_sub = subs;
1629 vo_osd_changed(OSDTYPE_SUBTITLE);
1630 if (!mpctx->sh_video) {
1631 // reverse order, since newest set_osd_msg is displayed first
1632 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1633 if (!subs || i >= subs->lines || !subs->text[i])
1634 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1635 else {
1636 // HACK: currently display time for each sub line
1637 // except the last is set to 2 seconds.
1638 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1639 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1640 "%s", subs->text[i]);
1647 * \brief Update the OSD message line.
1649 * This function displays the current message on the vo OSD or on the term.
1650 * If the stack is empty and the OSD level is high enough the timer
1651 * is displayed (only on the vo OSD).
1655 static void update_osd_msg(struct MPContext *mpctx)
1657 struct MPOpts *opts = &mpctx->opts;
1658 mp_osd_msg_t *msg;
1659 struct osd_state *osd = mpctx->osd;
1661 if (mpctx->add_osd_seek_info) {
1662 double percentage = get_percent_pos(mpctx);
1663 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1664 if (mpctx->sh_video)
1665 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1666 mpctx->add_osd_seek_info = false;
1669 // Look if we have a msg
1670 if ((msg = get_osd_msg(mpctx)) && !msg->show_position) {
1671 if (strcmp(osd->osd_text, msg->msg)) {
1672 osd_set_text(osd, msg->msg);
1673 if (mpctx->sh_video)
1674 vo_osd_changed(OSDTYPE_OSD);
1675 else if (opts->term_osd)
1676 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1677 msg->msg);
1679 return;
1682 int osdlevel = opts->osd_level;
1683 if (msg && msg->show_position)
1684 osdlevel = 3;
1686 if (mpctx->sh_video) {
1687 // fallback on the timer
1688 char osd_text_timer[128] = {0};
1689 if (osdlevel >= 2) {
1690 int len = get_time_length(mpctx);
1691 int percentage = -1;
1692 char percentage_text[10];
1693 char fractions_text[4];
1694 double fpts = get_current_time(mpctx);
1695 int pts = fpts;
1697 if (mpctx->osd_show_percentage_until)
1698 percentage = get_percent_pos(mpctx);
1700 if (percentage >= 0)
1701 snprintf(percentage_text, 9, " (%d%%)", percentage);
1702 else
1703 percentage_text[0] = 0;
1705 if (opts->osd_fractions == 1) {
1706 //print fractions as sub-second timestamp
1707 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1708 (int)((fpts - pts) * 100));
1709 } else if (opts->osd_fractions == 2) {
1710 /* Print fractions by estimating the frame count within the
1711 * second.
1713 * Rounding or cutting off numbers after the decimal point
1714 * causes problems because of float's precision and movies
1715 * whose first frame is not exactly at timestamp 0. Therefore,
1716 * we add 0.2 and cut off at the decimal point, which proved
1717 * to be good heuristic.
1719 double fps = mpctx->sh_video->fps;
1720 if (fps <= 1 || fps > 99)
1721 strcpy(fractions_text, ".??");
1722 else
1723 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1724 (int) ((fpts - pts) * fps + 0.2));
1725 } else {
1726 //do not print fractions
1727 fractions_text[0] = 0;
1730 osd_get_function_sym(osd_text_timer, sizeof(osd_text_timer),
1731 mpctx->osd_function);
1732 size_t blen = strlen(osd_text_timer);
1734 if (osdlevel == 3)
1735 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1736 " %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1737 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1738 len / 3600, (len / 60) % 60, len % 60,
1739 percentage_text);
1740 else
1741 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1742 " %02d:%02d:%02d%s%s",
1743 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1744 percentage_text);
1747 if (strcmp(osd->osd_text, osd_text_timer)) {
1748 osd_set_text(osd, osd_text_timer);
1749 vo_osd_changed(OSDTYPE_OSD);
1751 return;
1754 // Clear the term osd line
1755 if (opts->term_osd && osd->osd_text[0]) {
1756 osd->osd_text[0] = 0;
1757 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1762 void reinit_audio_chain(struct MPContext *mpctx)
1764 struct MPOpts *opts = &mpctx->opts;
1765 struct ao *ao;
1766 if (!mpctx->sh_audio) {
1767 uninit_player(mpctx, INITIALIZED_AO);
1768 return;
1770 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1771 current_module = "init_audio_codec";
1772 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1773 goto init_error;
1774 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1777 current_module = "af_preinit";
1778 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1779 mpctx->initialized_flags |= INITIALIZED_AO;
1780 mpctx->ao = ao_create(opts, mpctx->input);
1781 mpctx->ao->samplerate = force_srate;
1782 mpctx->ao->format = opts->audio_output_format;
1784 ao = mpctx->ao;
1786 // first init to detect best values
1787 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1788 // input:
1789 mpctx->sh_audio->samplerate,
1790 // output:
1791 &ao->samplerate, &ao->channels, &ao->format)) {
1792 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1793 "pre-init!\n");
1794 exit_player(mpctx, EXIT_ERROR);
1796 if (!ao->initialized) {
1797 current_module = "ao2_init";
1798 ao->buffersize = opts->ao_buffersize;
1799 ao_init(ao, opts->audio_driver_list);
1800 if (!ao->initialized) {
1801 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1802 "Could not open/initialize audio device -> no sound.\n");
1803 goto init_error;
1805 ao->buffer.start = talloc_new(ao);
1806 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1807 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1808 ao->driver->info->short_name,
1809 ao->samplerate, ao->channels,
1810 af_fmt2str_short(ao->format),
1811 af_fmt2bits(ao->format) / 8);
1812 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1813 ao->driver->info->name, ao->driver->info->author);
1814 if (strlen(ao->driver->info->comment) > 0)
1815 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1816 ao->driver->info->comment);
1819 // init audio filters:
1820 current_module = "af_init";
1821 if (!build_afilter_chain(mpctx)) {
1822 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1823 "Couldn't find matching filter/ao format!\n");
1824 goto init_error;
1826 mpctx->mixer.volstep = volstep;
1827 mpctx->mixer.softvol = opts->softvol;
1828 mpctx->mixer.softvol_max = opts->softvol_max;
1829 mixer_reinit(&mpctx->mixer, ao);
1830 mpctx->syncing_audio = true;
1831 return;
1833 init_error:
1834 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1835 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1836 mpctx->d_audio->id = -2;
1840 // Return pts value corresponding to the end point of audio written to the
1841 // ao so far.
1842 static double written_audio_pts(struct MPContext *mpctx)
1844 sh_audio_t *sh_audio = mpctx->sh_audio;
1845 if (!sh_audio)
1846 return MP_NOPTS_VALUE;
1847 demux_stream_t *d_audio = mpctx->d_audio;
1848 // first calculate the end pts of audio that has been output by decoder
1849 double a_pts = sh_audio->pts;
1850 if (a_pts != MP_NOPTS_VALUE)
1851 // Good, decoder supports new way of calculating audio pts.
1852 // sh_audio->pts is the timestamp of the latest input packet with
1853 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1854 // the amount of bytes the decoder has written after that timestamp.
1855 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1856 else {
1857 // Decoder doesn't support new way of calculating pts (or we're
1858 // being called before it has decoded anything with known timestamp).
1859 // Use the old method of audio pts calculation: take the timestamp
1860 // of last packet with known pts the decoder has read data from,
1861 // and add amount of bytes read after the beginning of that packet
1862 // divided by input bps. This will be inaccurate if the input/output
1863 // ratio is not constant for every audio packet or if it is constant
1864 // but not accurately known in sh_audio->i_bps.
1866 a_pts = d_audio->pts;
1867 if (a_pts == MP_NOPTS_VALUE)
1868 return a_pts;
1870 // ds_tell_pts returns bytes read after last timestamp from
1871 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1872 // it has read but not decoded
1873 if (sh_audio->i_bps)
1874 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1875 (double)sh_audio->i_bps;
1877 // Now a_pts hopefully holds the pts for end of audio from decoder.
1878 // Substract data in buffers between decoder and audio out.
1880 // Decoded but not filtered
1881 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1883 // Data buffered in audio filters, measured in bytes of "missing" output
1884 double buffered_output = af_calc_delay(sh_audio->afilter);
1886 // Data that was ready for ao but was buffered because ao didn't fully
1887 // accept everything to internal buffers yet
1888 buffered_output += mpctx->ao->buffer.len;
1890 // Filters divide audio length by playback_speed, so multiply by it
1891 // to get the length in original units without speedup or slowdown
1892 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1894 return a_pts + mpctx->video_offset;
1897 // Return pts value corresponding to currently playing audio.
1898 double playing_audio_pts(struct MPContext *mpctx)
1900 double pts = written_audio_pts(mpctx);
1901 if (pts == MP_NOPTS_VALUE)
1902 return pts;
1903 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1906 static bool is_av_sub(int type)
1908 return type == 'b' || type == 'p' || type == 'x';
1911 void update_subtitles(struct MPContext *mpctx, double refpts_tl, bool reset)
1913 mpctx->osd->sub_offset = mpctx->video_offset;
1914 struct MPOpts *opts = &mpctx->opts;
1915 struct sh_video *sh_video = mpctx->sh_video;
1916 struct demux_stream *d_sub = mpctx->d_sub;
1917 double refpts_s = refpts_tl - mpctx->osd->sub_offset;
1918 double curpts_s = refpts_s + sub_delay;
1919 unsigned char *packet = NULL;
1920 int len;
1921 struct sh_sub *sh_sub = d_sub->sh;
1922 int type = sh_sub ? sh_sub->type : 'v';
1923 static subtitle subs;
1924 if (reset) {
1925 if (sh_sub)
1926 sub_reset(sh_sub, mpctx->osd);
1927 sub_clear_text(&subs, MP_NOPTS_VALUE);
1928 if (vo_sub)
1929 set_osd_subtitle(mpctx, NULL);
1930 if (vo_spudec) {
1931 spudec_reset(vo_spudec);
1932 vo_osd_changed(OSDTYPE_SPU);
1934 if (is_av_sub(type))
1935 reset_avsub(sh_sub);
1936 return;
1938 // find sub
1939 if (mpctx->subdata) {
1940 if (sub_fps == 0)
1941 sub_fps = sh_video ? sh_video->fps : 25;
1942 current_module = "find_sub";
1943 find_sub(mpctx, mpctx->subdata, curpts_s *
1944 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1945 if (vo_sub)
1946 mpctx->vo_sub_last = vo_sub;
1949 // DVD sub:
1950 if (vobsub_id >= 0 || type == 'v') {
1951 int timestamp;
1952 current_module = "spudec";
1953 /* Get a sub packet from the DVD or a vobsub */
1954 while (1) {
1955 // Vobsub
1956 len = 0;
1957 if (vo_vobsub) {
1958 if (curpts_s >= 0) {
1959 len = vobsub_get_packet(vo_vobsub, curpts_s,
1960 (void **)&packet, &timestamp);
1961 if (len > 0)
1962 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1963 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1964 len, refpts_s, sh_video->timer,
1965 timestamp / 90000.0, timestamp);
1967 } else {
1968 // DVD sub
1969 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1970 if (len > 0) {
1971 // XXX This is wrong, sh_video->pts can be arbitrarily
1972 // much behind demuxing position. Unfortunately using
1973 // d_video->pts which would have been the simplest
1974 // improvement doesn't work because mpeg specific hacks
1975 // in video.c set d_video->pts to 0.
1976 float x = d_sub->pts - refpts_s;
1977 if (x > -20 && x < 20) // prevent missing subs on pts reset
1978 timestamp = 90000 * d_sub->pts;
1979 else
1980 timestamp = 90000 * curpts_s;
1981 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1982 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1983 refpts_s, d_sub->pts, timestamp);
1986 if (len <= 0 || !packet)
1987 break;
1988 // create it only here, since with some broken demuxers we might
1989 // type = v but no DVD sub and we currently do not change the
1990 // "original frame size" ever after init, leading to wrong-sized
1991 // PGS subtitles.
1992 if (!vo_spudec)
1993 vo_spudec = spudec_new(NULL);
1994 if (vo_vobsub || timestamp >= 0)
1995 spudec_assemble(vo_spudec, packet, len, timestamp);
1997 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1998 if (type == 'd' && !d_sub->demuxer->teletext) {
1999 tt_stream_props tsp = { 0 };
2000 void *ptr = &tsp;
2001 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
2002 VBI_CONTROL_TRUE)
2003 d_sub->demuxer->teletext = ptr;
2005 if (d_sub->non_interleaved)
2006 ds_get_next_pts(d_sub);
2008 while (d_sub->first) {
2009 double subpts_s = ds_get_next_pts(d_sub);
2010 if (subpts_s > curpts_s) {
2011 // Libass handled subs can be fed to it in advance
2012 if (!opts->ass_enabled || !is_text_sub(type))
2013 break;
2014 // Try to avoid demuxing whole file at once
2015 if (d_sub->non_interleaved && subpts_s > curpts_s + 1)
2016 break;
2018 double duration = d_sub->first->duration;
2019 len = ds_get_packet_sub(d_sub, &packet);
2020 if (is_av_sub(type)) {
2021 int ret = decode_avsub(sh_sub, packet, len, subpts_s, duration);
2022 if (ret < 0)
2023 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2024 "subtitle\n");
2025 continue;
2027 if (type == 'm') {
2028 if (len < 2)
2029 continue;
2030 len = FFMIN(len - 2, AV_RB16(packet));
2031 packet += 2;
2033 if (type == 'd') {
2034 if (d_sub->demuxer->teletext) {
2035 uint8_t *p = packet;
2036 p++;
2037 len--;
2038 while (len >= 46) {
2039 int sublen = p[1];
2040 if (p[0] == 2 || p[0] == 3)
2041 teletext_control(d_sub->demuxer->teletext,
2042 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2043 p += sublen + 2;
2044 len -= sublen + 2;
2047 continue;
2049 if (sh_sub && sh_sub->active) {
2050 sub_decode(sh_sub, mpctx->osd, packet, len, subpts_s, duration);
2051 continue;
2053 if (subpts_s != MP_NOPTS_VALUE) {
2054 if (duration < 0)
2055 sub_clear_text(&subs, MP_NOPTS_VALUE);
2056 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2057 int i;
2058 unsigned char *p = packet;
2059 for (i = 0; i < 8 && *p != '\0'; p++)
2060 if (*p == ',')
2061 i++;
2062 if (*p == '\0') /* Broken line? */
2063 continue;
2064 len -= p - packet;
2065 packet = p;
2067 double endpts_s = MP_NOPTS_VALUE;
2068 if (subpts_s != MP_NOPTS_VALUE && duration >= 0)
2069 endpts_s = subpts_s + duration;
2070 sub_add_text(&subs, packet, len, endpts_s);
2071 set_osd_subtitle(mpctx, &subs);
2073 if (d_sub->non_interleaved)
2074 ds_get_next_pts(d_sub);
2076 if (!opts->ass_enabled)
2077 if (sub_clear_text(&subs, curpts_s))
2078 set_osd_subtitle(mpctx, &subs);
2080 if (vo_spudec) {
2081 spudec_heartbeat(vo_spudec, 90000 * curpts_s);
2082 if (spudec_changed(vo_spudec))
2083 vo_osd_changed(OSDTYPE_SPU);
2086 current_module = NULL;
2089 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2091 int page_changed;
2093 if (!demuxer->teletext)
2094 return;
2096 //Also forcing page update when such ioctl is not supported or call error occured
2097 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2098 &page_changed) != VBI_CONTROL_TRUE)
2099 page_changed = 1;
2101 if (!page_changed)
2102 return;
2104 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2105 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2106 vo_osd_teletext_page = NULL;
2107 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2108 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2109 vo_osd_teletext_half = 0;
2110 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2111 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2112 vo_osd_teletext_mode = 0;
2113 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2114 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2115 vo_osd_teletext_format = 0;
2116 vo_osd_changed(OSDTYPE_TELETEXT);
2118 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2121 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2123 struct MPOpts *opts = &mpctx->opts;
2124 // check for frame-drop:
2125 current_module = "check_framedrop";
2126 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2127 static int dropped_frames;
2128 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2129 float d = delay - mpctx->delay;
2130 ++total_frame_cnt;
2131 // we should avoid dropping too many frames in sequence unless we
2132 // are too late. and we allow 100ms A-V delay here:
2133 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2134 && !mpctx->restart_playback) {
2135 ++drop_frame_cnt;
2136 ++dropped_frames;
2137 return frame_dropping;
2138 } else
2139 dropped_frames = 0;
2141 return 0;
2145 #ifdef HAVE_RTC
2146 int rtc_fd = -1;
2147 #endif
2149 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2151 #ifdef HAVE_RTC
2152 if (rtc_fd >= 0) {
2153 // -------- RTC -----------
2154 current_module = "sleep_rtc";
2155 while (time_frame > 0.000) {
2156 unsigned long rtc_ts;
2157 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2158 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2159 "Linux RTC read error: %s\n", strerror(errno));
2160 time_frame -= get_relative_time(mpctx);
2162 } else
2163 #endif
2165 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2166 // unnecessarily high CPU usage
2167 struct MPOpts *opts = &mpctx->opts;
2168 float margin = opts->softsleep ? 0.011 : 0;
2169 current_module = "sleep_timer";
2170 while (time_frame > margin) {
2171 usec_sleep(1000000 * (time_frame - margin));
2172 time_frame -= get_relative_time(mpctx);
2174 if (opts->softsleep) {
2175 current_module = "sleep_soft";
2176 if (time_frame < 0)
2177 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2178 "Warning! Softsleep underflow!\n");
2179 while (time_frame > 0)
2180 time_frame -= get_relative_time(mpctx); // burn the CPU
2183 return time_frame;
2186 static int select_subtitle(MPContext *mpctx)
2188 struct MPOpts *opts = &mpctx->opts;
2189 // find the best sub to use
2190 int id;
2191 int found = 0;
2192 mpctx->global_sub_pos = -1; // no subs by default
2193 if (vobsub_id >= 0) {
2194 // if user asks for a vobsub id, use that first.
2195 id = vobsub_id;
2196 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2197 M_PROPERTY_OK;
2200 if (!found && opts->sub_id >= 0) {
2201 // if user asks for a dvd sub id, use that next.
2202 id = opts->sub_id;
2203 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2204 M_PROPERTY_OK;
2207 if (!found) {
2208 // if there are text subs to use, use those. (autosubs come last here)
2209 id = 0;
2210 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2211 M_PROPERTY_OK;
2214 if (!found && opts->sub_id == -1) {
2215 // finally select subs by language and container hints
2216 if (opts->sub_id == -1)
2217 opts->sub_id =
2218 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2219 opts->sub_lang);
2220 if (opts->sub_id >= 0) {
2221 id = opts->sub_id;
2222 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2223 M_PROPERTY_OK;
2226 return found;
2229 #ifdef CONFIG_DVDNAV
2230 #ifndef FF_B_TYPE
2231 #define FF_B_TYPE 3
2232 #endif
2233 /// store decoded video image
2234 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2235 mp_image_t *from_mpi)
2237 mp_image_t *mpi;
2239 /// Do not store B-frames
2240 if (from_mpi->pict_type == FF_B_TYPE)
2241 return to_mpi;
2243 if (to_mpi &&
2244 to_mpi->w == from_mpi->w &&
2245 to_mpi->h == from_mpi->h &&
2246 to_mpi->imgfmt == from_mpi->imgfmt)
2247 mpi = to_mpi;
2248 else {
2249 if (to_mpi)
2250 free_mp_image(to_mpi);
2251 if (from_mpi->w == 0 || from_mpi->h == 0)
2252 return NULL;
2253 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2256 copy_mpi(mpi, from_mpi);
2257 return mpi;
2260 static void mp_dvdnav_reset_stream(MPContext *ctx)
2262 struct MPOpts *opts = &ctx->opts;
2263 if (ctx->sh_video) {
2264 /// clear video pts
2265 ctx->d_video->pts = 0.0f;
2266 ctx->sh_video->pts = 0.0f;
2267 ctx->sh_video->i_pts = 0.0f;
2268 ctx->sh_video->last_pts = 0.0f;
2269 ctx->sh_video->num_buffered_pts = 0;
2270 ctx->sh_video->num_frames = 0;
2271 ctx->sh_video->num_frames_decoded = 0;
2272 ctx->sh_video->timer = 0.0f;
2273 ctx->sh_video->stream_delay = 0.0f;
2274 ctx->sh_video->timer = 0;
2275 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2278 if (ctx->sh_audio) {
2279 /// free audio packets and reset
2280 ds_free_packs(ctx->d_audio);
2281 audio_delay -= ctx->sh_audio->stream_delay;
2282 ctx->delay = -audio_delay;
2283 ao_reset(ctx->ao);
2284 resync_audio_stream(ctx->sh_audio);
2287 audio_delay = 0.0f;
2288 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2289 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2290 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2291 if (dvdsub_lang_id != opts->sub_id) {
2292 opts->sub_id = dvdsub_lang_id;
2293 select_subtitle(ctx);
2297 /// clear all EOF related flags
2298 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2301 /// Restore last decoded DVDNAV (still frame)
2302 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2303 int *in_size,
2304 unsigned char **start,
2305 mp_image_t *decoded_frame)
2307 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2308 return decoded_frame;
2310 /// a change occurred in dvdnav stream
2311 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2312 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2313 mp_dvdnav_context_free(mpctx);
2314 mp_dvdnav_reset_stream(mpctx);
2315 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2316 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2319 if (*in_size < 0) {
2320 float len;
2322 /// Display still frame, if any
2323 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2324 decoded_frame = mpctx->nav_smpi;
2326 /// increment video frame : continue playing after still frame
2327 len = get_time_length(mpctx);
2328 if (mpctx->sh_video->pts >= len &&
2329 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2330 mp_dvdnav_skip_still(mpctx->stream);
2331 mp_dvdnav_skip_wait(mpctx->stream);
2333 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2335 if (mpctx->nav_buffer) {
2336 *start = mpctx->nav_start;
2337 *in_size = mpctx->nav_in_size;
2338 if (mpctx->nav_start)
2339 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2343 return decoded_frame;
2346 /// Save last decoded DVDNAV (still frame)
2347 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2348 unsigned char *start,
2349 mp_image_t *decoded_frame)
2351 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2352 return;
2354 free(mpctx->nav_buffer);
2355 mpctx->nav_buffer = NULL;
2356 mpctx->nav_start = NULL;
2357 mpctx->nav_in_size = -1;
2359 if (in_size > 0)
2360 mpctx->nav_buffer = malloc(in_size);
2361 if (mpctx->nav_buffer) {
2362 mpctx->nav_start = start;
2363 mpctx->nav_in_size = in_size;
2364 memcpy(mpctx->nav_buffer, start, in_size);
2367 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2368 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2370 #endif /* CONFIG_DVDNAV */
2372 /* Modify video timing to match the audio timeline. There are two main
2373 * reasons this is needed. First, video and audio can start from different
2374 * positions at beginning of file or after a seek (MPlayer starts both
2375 * immediately even if they have different pts). Second, the file can have
2376 * audio timestamps that are inconsistent with the duration of the audio
2377 * packets, for example two consecutive timestamp values differing by
2378 * one second but only a packet with enough samples for half a second
2379 * of playback between them.
2381 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2383 current_module = "av_sync";
2385 if (!mpctx->sh_audio || mpctx->syncing_audio)
2386 return;
2388 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2389 double v_pts = mpctx->sh_video->pts;
2390 double av_delay = a_pts - v_pts;
2391 // Try to sync vo_flip() so it will *finish* at given time
2392 av_delay += mpctx->last_vo_flip_duration;
2393 av_delay -= audio_delay; // This much pts difference is desired
2395 double change = av_delay * 0.1;
2396 double max_change = default_max_pts_correction >= 0 ?
2397 default_max_pts_correction : frame_time * 0.1;
2398 if (change < -max_change)
2399 change = -max_change;
2400 else if (change > max_change)
2401 change = max_change;
2402 mpctx->delay += change;
2403 mpctx->total_avsync_change += change;
2406 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2407 double pts)
2409 if (mpctx->paused)
2410 return 0;
2411 struct ao *ao = mpctx->ao;
2412 double bps = ao->bps / mpctx->opts.playback_speed;
2413 ao->pts = pts;
2414 // hack used by some mpeg-writing AOs
2415 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2416 mpctx->delay) * 90000.0;
2417 int played = ao_play(mpctx->ao, data, len, flags);
2418 if (played > 0) {
2419 mpctx->delay += played / bps;
2420 // Keep correct pts for remaining data - could be used to flush
2421 // remaining buffer when closing ao.
2422 ao->pts += played / bps;
2424 return played;
2427 #define ASYNC_PLAY_DONE -3
2428 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2430 struct ao *ao = mpctx->ao;
2431 struct MPOpts *opts = &mpctx->opts;
2432 sh_audio_t * const sh_audio = mpctx->sh_audio;
2433 int res;
2435 // Timing info may not be set without
2436 res = decode_audio(sh_audio, &ao->buffer, 1);
2437 if (res < 0)
2438 return res;
2440 int bytes;
2441 bool did_retry = false;
2442 double written_pts;
2443 double bps = ao->bps / opts->playback_speed;
2444 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2445 mpctx->hrseek_active = false;
2446 while (1) {
2447 written_pts = written_audio_pts(mpctx);
2448 double ptsdiff;
2449 if (hrseek)
2450 ptsdiff = written_pts - mpctx->hrseek_pts;
2451 else
2452 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2453 - audio_delay;
2454 bytes = ptsdiff * bps;
2455 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2457 // ogg demuxers give packets without timing
2458 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2459 if (!did_retry) {
2460 // Try to read more data to see packets that have pts
2461 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2462 if (res < 0)
2463 return res;
2464 did_retry = true;
2465 continue;
2467 bytes = 0;
2470 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2471 bytes = 0;
2473 if (bytes > 0)
2474 break;
2476 mpctx->syncing_audio = false;
2477 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2478 int res = decode_audio(sh_audio, &ao->buffer, a);
2479 bytes += ao->buffer.len;
2480 if (bytes >= 0) {
2481 memmove(ao->buffer.start,
2482 ao->buffer.start + ao->buffer.len - bytes, bytes);
2483 ao->buffer.len = bytes;
2484 if (res < 0)
2485 return res;
2486 return decode_audio(sh_audio, &ao->buffer, playsize);
2488 ao->buffer.len = 0;
2489 if (res < 0)
2490 return res;
2492 if (hrseek)
2493 // Don't add silence in audio-only case even if position is too late
2494 return 0;
2495 int fillbyte = 0;
2496 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2497 fillbyte = 0x80;
2498 if (bytes >= playsize) {
2499 /* This case could fall back to the one below with
2500 * bytes = playsize, but then silence would keep accumulating
2501 * in a_out_buffer if the AO accepts less data than it asks for
2502 * in playsize. */
2503 char *p = malloc(playsize);
2504 memset(p, fillbyte, playsize);
2505 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2506 free(p);
2507 return ASYNC_PLAY_DONE;
2509 mpctx->syncing_audio = false;
2510 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2511 return decode_audio(sh_audio, &ao->buffer, playsize);
2514 static int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
2516 struct MPOpts *opts = &mpctx->opts;
2517 struct ao *ao = mpctx->ao;
2518 unsigned int t;
2519 double tt;
2520 int playsize;
2521 int playflags = 0;
2522 bool audio_eof = false;
2523 bool partial_fill = false;
2524 sh_audio_t * const sh_audio = mpctx->sh_audio;
2525 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2526 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2528 current_module = "play_audio";
2530 // hack used by some mpeg-writing AOs
2531 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2532 mpctx->delay) * 90000.0;
2534 if (mpctx->paused)
2535 playsize = 1; // just initialize things (audio pts at least)
2536 else
2537 playsize = ao_get_space(ao);
2539 // Fill buffer if needed:
2540 current_module = "decode_audio";
2541 t = GetTimer();
2543 // Coming here with hrseek_active still set means audio-only
2544 if (!mpctx->sh_video)
2545 mpctx->syncing_audio = false;
2546 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2547 mpctx->syncing_audio = false;
2548 mpctx->hrseek_active = false;
2551 int res;
2552 if (mpctx->syncing_audio || mpctx->hrseek_active)
2553 res = audio_start_sync(mpctx, playsize);
2554 else
2555 res = decode_audio(sh_audio, &ao->buffer, playsize);
2556 if (res < 0) { // EOF, error or format change
2557 if (res == -2) {
2558 /* The format change isn't handled too gracefully. A more precise
2559 * implementation would require draining buffered old-format audio
2560 * while displaying video, then doing the output format switch.
2562 uninit_player(mpctx, INITIALIZED_AO);
2563 reinit_audio_chain(mpctx);
2564 return -1;
2565 } else if (res == ASYNC_PLAY_DONE)
2566 return 0;
2567 else if (mpctx->d_audio->eof)
2568 audio_eof = true;
2570 t = GetTimer() - t;
2571 tt = t * 0.000001f;
2572 audio_time_usage += tt;
2573 if (endpts != MP_NOPTS_VALUE && modifiable_audio_format) {
2574 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2575 * ao->bps / opts->playback_speed;
2576 if (playsize > bytes) {
2577 playsize = FFMAX(bytes, 0);
2578 playflags |= AOPLAY_FINAL_CHUNK;
2579 audio_eof = true;
2580 partial_fill = true;
2584 assert(ao->buffer.len % unitsize == 0);
2585 if (playsize > ao->buffer.len) {
2586 partial_fill = true;
2587 playsize = ao->buffer.len;
2588 if (audio_eof)
2589 playflags |= AOPLAY_FINAL_CHUNK;
2591 playsize -= playsize % unitsize;
2592 if (!playsize)
2593 return partial_fill && audio_eof ? -2 : -partial_fill;
2595 // play audio:
2596 current_module = "play_audio";
2598 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2599 written_audio_pts(mpctx));
2600 assert(played % unitsize == 0);
2601 ao->buffer_playable_size = playsize - played;
2603 if (played > 0) {
2604 ao->buffer.len -= played;
2605 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2606 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2607 // Sanity check to avoid hanging in case current ao doesn't output
2608 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2609 return -2;
2612 return -partial_fill;
2615 int reinit_video_chain(struct MPContext *mpctx)
2617 struct MPOpts *opts = &mpctx->opts;
2618 sh_video_t * const sh_video = mpctx->sh_video;
2619 if (!sh_video) {
2620 uninit_player(mpctx, INITIALIZED_VO);
2621 return 0;
2623 double ar = -1.0;
2624 //================== Init VIDEO (codec & libvo) ==========================
2625 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2626 current_module = "preinit_libvo";
2628 //shouldn't we set dvideo->id=-2 when we fail?
2629 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2630 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2631 mpctx->key_fifo,
2632 mpctx->input))) {
2633 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2634 "the selected video_out (-vo) device.\n");
2635 goto err_out;
2637 mpctx->initialized_flags |= INITIALIZED_VO;
2640 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2641 &ar) != STREAM_UNSUPPORTED)
2642 mpctx->sh_video->stream_aspect = ar;
2643 current_module = "init_video_filters";
2645 char *vf_arg[] = {
2646 "_oldargs_", (char *)mpctx->video_out, NULL
2648 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2651 #ifdef CONFIG_ASS
2652 if (opts->ass_enabled) {
2653 int i;
2654 int insert = 1;
2655 if (opts->vf_settings)
2656 for (i = 0; opts->vf_settings[i].name; ++i)
2657 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2658 insert = 0;
2659 break;
2661 if (insert) {
2662 extern vf_info_t vf_info_ass;
2663 const vf_info_t *libass_vfs[] = {
2664 &vf_info_ass, NULL
2666 char *vf_arg[] = {
2667 "auto", "1", NULL
2669 int retcode = 0;
2670 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2671 sh_video->vfilter,
2672 "ass", vf_arg,
2673 &retcode);
2674 if (vf_ass)
2675 sh_video->vfilter = vf_ass;
2676 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2677 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2678 else
2679 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2680 "ASS: cannot add video filter\n");
2683 #endif
2685 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2687 #ifdef CONFIG_ASS
2688 if (opts->ass_enabled)
2689 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2690 mpctx->ass_library);
2691 #endif
2693 current_module = "init_video_codec";
2695 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2697 if (!sh_video->initialized) {
2698 if (!opts->fixed_vo)
2699 uninit_player(mpctx, INITIALIZED_VO);
2700 goto err_out;
2703 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2705 if (sh_video->codec)
2706 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2707 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2709 sh_video->last_pts = MP_NOPTS_VALUE;
2710 sh_video->num_buffered_pts = 0;
2711 sh_video->next_frame_time = 0;
2712 mpctx->restart_playback = true;
2713 mpctx->delay = 0;
2715 if (opts->auto_quality > 0) {
2716 // Auto quality option enabled
2717 output_quality = get_video_quality_max(sh_video);
2718 if (opts->auto_quality > output_quality)
2719 opts->auto_quality = output_quality;
2720 else
2721 output_quality = opts->auto_quality;
2722 mp_msg(MSGT_CPLAYER, MSGL_V,
2723 "AutoQ: setting quality to %d.\n", output_quality);
2724 set_video_quality(sh_video, output_quality);
2727 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2729 current_module = "init_vo";
2731 return 1;
2733 err_out:
2734 mpctx->sh_video = mpctx->d_video->sh = NULL;
2735 return 0;
2738 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2740 struct sh_video *sh_video = mpctx->sh_video;
2741 double frame_time = 0;
2742 struct vo *video_out = mpctx->video_out;
2743 while (1) {
2744 current_module = "filter_video";
2745 // In nocorrect-pts mode there is no way to properly time these frames
2746 if (vo_get_buffered_frame(video_out, 0) >= 0)
2747 break;
2748 if (vf_output_queued_frame(sh_video->vfilter))
2749 break;
2750 unsigned char *packet = NULL;
2751 frame_time = sh_video->next_frame_time;
2752 if (mpctx->restart_playback)
2753 frame_time = 0;
2754 int in_size = 0;
2755 while (!in_size)
2756 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2757 &packet, force_fps);
2758 if (in_size < 0) {
2759 #ifdef CONFIG_DVDNAV
2760 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2761 if (mp_dvdnav_is_eof(mpctx->stream))
2762 return -1;
2763 if (mpctx->d_video)
2764 mpctx->d_video->eof = 0;
2765 if (mpctx->d_audio)
2766 mpctx->d_audio->eof = 0;
2767 mpctx->stream->eof = 0;
2768 } else
2769 #endif
2770 return -1;
2772 if (in_size > max_framesize)
2773 max_framesize = in_size;
2774 sh_video->timer += frame_time;
2775 if (mpctx->sh_audio)
2776 mpctx->delay -= frame_time;
2777 // video_read_frame can change fps (e.g. for ASF video)
2778 vo_fps = sh_video->fps;
2779 int framedrop_type = check_framedrop(mpctx, frame_time);
2780 current_module = "decode video";
2782 void *decoded_frame;
2783 #ifdef CONFIG_DVDNAV
2784 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2785 if (in_size >= 0 && !decoded_frame)
2786 #endif
2787 decoded_frame = decode_video(sh_video, sh_video->ds->current, packet,
2788 in_size, framedrop_type, sh_video->pts);
2789 #ifdef CONFIG_DVDNAV
2790 // Save last still frame for future display
2791 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2792 #endif
2793 if (decoded_frame) {
2794 current_module = "filter video";
2795 filter_video(sh_video, decoded_frame, sh_video->pts);
2797 break;
2799 return frame_time;
2802 static void determine_frame_pts(struct MPContext *mpctx)
2804 struct sh_video *sh_video = mpctx->sh_video;
2805 struct MPOpts *opts = &mpctx->opts;
2807 if (opts->user_pts_assoc_mode)
2808 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2809 else if (sh_video->pts_assoc_mode == 0) {
2810 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2811 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2812 sh_video->pts_assoc_mode = 1;
2813 else
2814 sh_video->pts_assoc_mode = 2;
2815 } else {
2816 int probcount1 = sh_video->num_reordered_pts_problems;
2817 int probcount2 = sh_video->num_sorted_pts_problems;
2818 if (sh_video->pts_assoc_mode == 2) {
2819 int tmp = probcount1;
2820 probcount1 = probcount2;
2821 probcount2 = tmp;
2823 if (probcount1 >= probcount2 * 1.5 + 2) {
2824 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2825 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2826 "%d.\n", sh_video->pts_assoc_mode);
2829 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2830 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2833 static double update_video(struct MPContext *mpctx)
2835 struct sh_video *sh_video = mpctx->sh_video;
2836 struct vo *video_out = mpctx->video_out;
2837 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2838 mpctx->osd); // hack for vf_expand
2839 if (!mpctx->opts.correct_pts)
2840 return update_video_nocorrect_pts(mpctx);
2842 double pts;
2844 while (1) {
2845 current_module = "filter_video";
2846 if (vo_get_buffered_frame(video_out, false) >= 0)
2847 break;
2848 // XXX Time used in this call is not counted in any performance
2849 // timer now
2850 if (vf_output_queued_frame(sh_video->vfilter))
2851 break;
2852 int in_size = 0;
2853 unsigned char *buf = NULL;
2854 pts = MP_NOPTS_VALUE;
2855 struct demux_packet *pkt;
2856 while (1) {
2857 pkt = ds_get_packet2(mpctx->d_video, false);
2858 if (!pkt || pkt->len)
2859 break;
2860 /* Packets with size 0 are assumed to not correspond to frames,
2861 * but to indicate the absence of a frame in formats like AVI
2862 * that must have packets at fixed timecode intervals. */
2864 if (pkt) {
2865 in_size = pkt->len;
2866 buf = pkt->buffer;
2867 pts = pkt->pts;
2869 if (pts != MP_NOPTS_VALUE)
2870 pts += mpctx->video_offset;
2871 if (in_size > max_framesize)
2872 max_framesize = in_size;
2873 current_module = "decode video";
2874 if (pts >= mpctx->hrseek_pts - .005)
2875 mpctx->hrseek_framedrop = false;
2876 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2877 check_framedrop(mpctx, sh_video->frametime);
2878 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2879 framedrop_type, pts);
2880 if (decoded_frame) {
2881 determine_frame_pts(mpctx);
2882 current_module = "filter video";
2883 filter_video(sh_video, decoded_frame, sh_video->pts);
2884 } else if (!pkt) {
2885 if (vo_get_buffered_frame(video_out, true) < 0)
2886 return -1;
2888 break;
2891 if (!video_out->frame_loaded)
2892 return 0;
2894 pts = video_out->next_pts;
2895 if (pts == MP_NOPTS_VALUE) {
2896 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2897 // Try to use decoder pts from before filters
2898 pts = sh_video->pts;
2899 if (pts == MP_NOPTS_VALUE)
2900 pts = sh_video->last_pts;
2902 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2903 vo_skip_frame(video_out);
2904 return 0;
2906 mpctx->hrseek_active = false;
2907 sh_video->pts = pts;
2908 if (sh_video->last_pts == MP_NOPTS_VALUE)
2909 sh_video->last_pts = sh_video->pts;
2910 else if (sh_video->last_pts > sh_video->pts) {
2911 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2912 sh_video->pts, sh_video->last_pts);
2913 /* If the difference in pts is small treat it as jitter around the
2914 * right value (possibly caused by incorrect timestamp ordering) and
2915 * just show this frame immediately after the last one.
2916 * Treat bigger differences as timestamp resets and start counting
2917 * timing of later frames from the position of this one. */
2918 if (sh_video->last_pts - sh_video->pts > 0.5)
2919 sh_video->last_pts = sh_video->pts;
2920 else
2921 sh_video->pts = sh_video->last_pts;
2923 double frame_time = sh_video->pts - sh_video->last_pts;
2924 sh_video->last_pts = sh_video->pts;
2925 sh_video->timer += frame_time;
2926 if (mpctx->sh_audio)
2927 mpctx->delay -= frame_time;
2928 return frame_time;
2931 static int get_cache_fill(struct MPContext *mpctx)
2933 #ifdef CONFIG_STREAM_CACHE
2934 if (stream_cache_size > 0)
2935 return cache_fill_status(mpctx->stream);
2936 #endif
2937 return -1;
2940 static void update_pause_message(struct MPContext *mpctx)
2942 struct MPOpts *opts = &mpctx->opts;
2944 if (opts->quiet)
2945 return;
2947 int cache_fill = get_cache_fill(mpctx);
2948 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2950 if (!mpctx->status_printed && !cache_changed)
2951 return;
2953 char *msg = mp_gtext(" ===== PAUSE =====");
2954 char *tmpmem = NULL;
2955 if (cache_fill >= 0)
2956 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
2958 if (opts->term_osd && !mpctx->sh_video) {
2959 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
2960 update_osd_msg(mpctx);
2961 } else {
2962 if (mpctx->status_printed)
2963 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
2964 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
2967 mpctx->paused_cache_fill = cache_fill;
2968 mpctx->status_printed = false;
2970 talloc_free(tmpmem);
2973 void pause_player(struct MPContext *mpctx)
2975 if (mpctx->paused)
2976 return;
2977 mpctx->paused = 1;
2978 mpctx->step_frames = 0;
2979 mpctx->time_frame -= get_relative_time(mpctx);
2980 mpctx->osd_function = OSD_PAUSE;
2982 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2983 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2985 if (mpctx->ao && mpctx->sh_audio)
2986 ao_pause(mpctx->ao); // pause audio, keep data if possible
2988 mpctx->paused_cache_fill = get_cache_fill(mpctx);
2989 mpctx->status_printed = true;
2990 update_pause_message(mpctx);
2992 if (!mpctx->opts.quiet)
2993 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2996 void unpause_player(struct MPContext *mpctx)
2998 if (!mpctx->paused)
2999 return;
3000 mpctx->paused = 0;
3001 if (!mpctx->step_frames)
3002 mpctx->osd_function = OSD_PLAY;
3004 if (mpctx->ao && mpctx->sh_audio)
3005 ao_resume(mpctx->ao);
3006 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3007 && !mpctx->step_frames)
3008 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3009 (void)get_relative_time(mpctx); // ignore time that passed during pause
3012 static int redraw_osd(struct MPContext *mpctx)
3014 struct sh_video *sh_video = mpctx->sh_video;
3015 struct vf_instance *vf = sh_video->vfilter;
3016 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3017 return -1;
3018 if (vo_redraw_frame(mpctx->video_out) < 0)
3019 return -1;
3020 mpctx->osd->pts = mpctx->video_pts - mpctx->osd->sub_offset;
3021 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3022 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3023 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3024 vo_flip_page(mpctx->video_out, 0, -1);
3025 return 0;
3028 void add_step_frame(struct MPContext *mpctx)
3030 mpctx->step_frames++;
3031 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3032 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3033 unpause_player(mpctx);
3036 static void seek_reset(struct MPContext *mpctx, bool reset_ao, bool reset_ac)
3038 if (mpctx->sh_video) {
3039 current_module = "seek_video_reset";
3040 resync_video_stream(mpctx->sh_video);
3041 mpctx->sh_video->timer = 0;
3042 vo_seek_reset(mpctx->video_out);
3043 mpctx->sh_video->timer = 0;
3044 mpctx->sh_video->num_buffered_pts = 0;
3045 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3046 mpctx->delay = 0;
3047 mpctx->time_frame = 0;
3048 // Not all demuxers set d_video->pts during seek, so this value
3049 // (which is used by at least vobsub code below) may be completely
3050 // wrong (probably 0).
3051 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3052 mpctx->video_pts = mpctx->sh_video->pts;
3053 update_subtitles(mpctx, mpctx->sh_video->pts, true);
3054 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3057 if (mpctx->sh_audio && reset_ac) {
3058 current_module = "seek_audio_reset";
3059 resync_audio_stream(mpctx->sh_audio);
3060 if (reset_ao)
3061 ao_reset(mpctx->ao);
3062 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3063 mpctx->sh_audio->a_buffer_len = 0;
3064 if (!mpctx->sh_video)
3065 update_subtitles(mpctx, mpctx->sh_audio->pts, true);
3068 if (vo_vobsub && mpctx->sh_video) {
3069 current_module = "seek_vobsub_reset";
3070 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3073 mpctx->restart_playback = true;
3074 mpctx->hrseek_active = false;
3075 mpctx->hrseek_framedrop = false;
3076 mpctx->total_avsync_change = 0;
3077 audio_time_usage = 0;
3078 video_time_usage = 0;
3079 vout_time_usage = 0;
3080 drop_frame_cnt = 0;
3082 current_module = NULL;
3085 static bool timeline_set_part(struct MPContext *mpctx, int i)
3087 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3088 struct timeline_part *n = mpctx->timeline + i;
3089 mpctx->timeline_part = i;
3090 mpctx->video_offset = n->start - n->source_start;
3091 if (n->source == p->source)
3092 return false;
3093 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3094 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3095 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3096 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3097 mpctx->stop_play = orig_stop_play;
3098 mpctx->demuxer = n->source->demuxer;
3099 mpctx->d_video = mpctx->demuxer->video;
3100 mpctx->d_audio = mpctx->demuxer->audio;
3101 mpctx->d_sub = mpctx->demuxer->sub;
3102 mpctx->sh_video = mpctx->d_video->sh;
3103 mpctx->sh_audio = mpctx->d_audio->sh;
3104 return true;
3107 // Given pts, switch playback to the corresponding part.
3108 // Return offset within that part.
3109 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3110 bool *need_reset)
3112 if (pts < 0)
3113 pts = 0;
3114 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3115 struct timeline_part *p = mpctx->timeline + i;
3116 if (pts < (p + 1)->start) {
3117 *need_reset = timeline_set_part(mpctx, i);
3118 return pts - p->start + p->source_start;
3121 return -1;
3125 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3126 static int seek(MPContext *mpctx, struct seek_params seek,
3127 bool timeline_fallthrough)
3129 struct MPOpts *opts = &mpctx->opts;
3131 current_module = "seek";
3132 if (mpctx->stop_play == AT_END_OF_FILE)
3133 mpctx->stop_play = KEEP_PLAYING;
3134 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3135 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3136 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3137 || opts->hr_seek > 0 || seek.exact > 0;
3138 if (seek.type == MPSEEK_FACTOR
3139 || seek.type == MPSEEK_ABSOLUTE
3140 && seek.amount < mpctx->last_chapter_pts
3141 || seek.amount < 0)
3142 mpctx->last_chapter_seek = -2;
3143 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3144 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3145 seek.type = MPSEEK_ABSOLUTE;
3147 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3148 && seek.type == MPSEEK_RELATIVE) {
3149 seek.type = MPSEEK_ABSOLUTE;
3150 seek.direction = seek.amount > 0 ? 1 : -1;
3151 seek.amount += get_current_time(mpctx);
3154 /* At least the liba52 decoder wants to read from the input stream
3155 * during initialization, so reinit must be done after the demux_seek()
3156 * call that clears possible stream EOF. */
3157 bool need_reset = false;
3158 double demuxer_amount = seek.amount;
3159 if (mpctx->timeline) {
3160 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3161 &need_reset);
3162 if (demuxer_amount == -1) {
3163 mpctx->stop_play = AT_END_OF_FILE;
3164 // Clear audio from current position
3165 if (mpctx->sh_audio && !timeline_fallthrough) {
3166 ao_reset(mpctx->ao);
3167 mpctx->sh_audio->a_buffer_len = 0;
3169 return -1;
3172 if (need_reset) {
3173 reinit_video_chain(mpctx);
3174 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos},
3175 mpctx);
3178 int demuxer_style = 0;
3179 switch (seek.type) {
3180 case MPSEEK_FACTOR:
3181 demuxer_style |= SEEK_FACTOR; // fallthrough
3182 case MPSEEK_ABSOLUTE:
3183 demuxer_style |= SEEK_ABSOLUTE;
3185 if (hr_seek || seek.direction < 0)
3186 demuxer_style |= SEEK_BACKWARD;
3187 else if (seek.direction > 0)
3188 demuxer_style |= SEEK_FORWARD;
3190 if (hr_seek)
3191 demuxer_amount -= opts->hr_seek_demuxer_offset;
3192 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3193 demuxer_style);
3194 if (seekresult == 0) {
3195 if (need_reset) {
3196 reinit_audio_chain(mpctx);
3197 seek_reset(mpctx, !timeline_fallthrough, false);
3199 return -1;
3202 if (need_reset)
3203 reinit_audio_chain(mpctx);
3204 /* If we just reinitialized audio it doesn't need to be reset,
3205 * and resetting could lose audio some decoders produce during init. */
3206 seek_reset(mpctx, !timeline_fallthrough, !need_reset);
3208 /* Use the target time as "current position" for further relative
3209 * seeks etc until a new video frame has been decoded */
3210 if (seek.type == MPSEEK_ABSOLUTE) {
3211 mpctx->video_pts = seek.amount;
3212 mpctx->last_seek_pts = seek.amount;
3213 } else
3214 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3216 if (hr_seek) {
3217 mpctx->hrseek_active = true;
3218 mpctx->hrseek_framedrop = true;
3219 mpctx->hrseek_pts = seek.amount;
3222 mpctx->start_timestamp = GetTimerMS();
3224 return 0;
3227 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3228 int exact)
3230 struct seek_params *seek = &mpctx->seek;
3231 switch (type) {
3232 case MPSEEK_RELATIVE:
3233 if (seek->type == MPSEEK_FACTOR)
3234 return; // Well... not common enough to bother doing better
3235 seek->amount += amount;
3236 seek->exact = FFMAX(seek->exact, exact);
3237 if (seek->type == MPSEEK_NONE)
3238 seek->exact = exact;
3239 if (seek->type == MPSEEK_ABSOLUTE)
3240 return;
3241 if (seek->amount == 0) {
3242 *seek = (struct seek_params){ 0 };
3243 return;
3245 seek->type = MPSEEK_RELATIVE;
3246 return;
3247 case MPSEEK_ABSOLUTE:
3248 case MPSEEK_FACTOR:
3249 *seek = (struct seek_params) {
3250 .type = type,
3251 .amount = amount,
3252 .exact = exact,
3254 return;
3255 case MPSEEK_NONE:
3256 *seek = (struct seek_params){ 0 };
3257 return;
3259 abort();
3263 double get_time_length(struct MPContext *mpctx)
3265 if (mpctx->timeline)
3266 return mpctx->timeline[mpctx->num_timeline_parts].start;
3268 struct demuxer *demuxer = mpctx->demuxer;
3269 double get_time_ans;
3270 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3271 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3272 (void *) &get_time_ans) > 0)
3273 return get_time_ans;
3275 struct sh_video *sh_video = mpctx->d_video->sh;
3276 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3277 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3278 return (double) (demuxer->movi_end - demuxer->movi_start) /
3279 (sh_video->i_bps + sh_audio->i_bps);
3280 if (sh_video && sh_video->i_bps)
3281 return (double) (demuxer->movi_end - demuxer->movi_start) /
3282 sh_video->i_bps;
3283 if (sh_audio && sh_audio->i_bps)
3284 return (double) (demuxer->movi_end - demuxer->movi_start) /
3285 sh_audio->i_bps;
3286 return 0;
3289 /* If there are timestamps from stream level then use those (for example
3290 * DVDs can have consistent times there while the MPEG-level timestamps
3291 * reset). */
3292 double get_current_time(struct MPContext *mpctx)
3294 struct demuxer *demuxer = mpctx->demuxer;
3295 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3296 return demuxer->stream_pts;
3297 if (mpctx->sh_video) {
3298 double pts = mpctx->video_pts;
3299 if (pts != MP_NOPTS_VALUE)
3300 return pts;
3302 double apts = playing_audio_pts(mpctx);
3303 if (apts != MP_NOPTS_VALUE)
3304 return apts;
3305 return mpctx->last_seek_pts;
3308 int get_percent_pos(struct MPContext *mpctx)
3310 struct demuxer *demuxer = mpctx->demuxer;
3311 int ans = 0;
3312 if (mpctx->timeline)
3313 ans = get_current_time(mpctx) * 100 /
3314 mpctx->timeline[mpctx->num_timeline_parts].start;
3315 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3317 else {
3318 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3319 off_t pos = demuxer->filepos > 0 ?
3320 demuxer->filepos : stream_tell(demuxer->stream);
3321 if (len > 0)
3322 ans = (pos - demuxer->movi_start) / len;
3323 else
3324 ans = 0;
3326 if (ans < 0)
3327 ans = 0;
3328 if (ans > 100)
3329 ans = 100;
3330 return ans;
3333 // -2 is no chapters, -1 is before first chapter
3334 int get_current_chapter(struct MPContext *mpctx)
3336 double current_pts = get_current_time(mpctx);
3337 if (!mpctx->chapters)
3338 return FFMAX(mpctx->last_chapter_seek,
3339 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3341 int i;
3342 for (i = 1; i < mpctx->num_chapters; i++)
3343 if (current_pts < mpctx->chapters[i].start)
3344 break;
3345 return FFMAX(mpctx->last_chapter_seek, i - 1);
3348 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3350 char *name = chapter_name(mpctx, chapter);
3351 if (name) {
3352 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3353 } else {
3354 int chapter_count = get_chapter_count(mpctx);
3355 if (chapter_count <= 0)
3356 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3357 else
3358 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3359 chapter_count);
3361 return name;
3364 // returns NULL if chapter name unavailable
3365 char *chapter_name(struct MPContext *mpctx, int chapter)
3367 if (!mpctx->chapters)
3368 return demuxer_chapter_name(mpctx->demuxer, chapter);
3369 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3372 // returns the start of the chapter in seconds
3373 double chapter_start_time(struct MPContext *mpctx, int chapter)
3375 if (!mpctx->chapters)
3376 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3377 return mpctx->chapters[chapter].start;
3380 int get_chapter_count(struct MPContext *mpctx)
3382 if (!mpctx->chapters)
3383 return demuxer_chapter_count(mpctx->demuxer);
3384 return mpctx->num_chapters;
3387 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3389 mpctx->last_chapter_seek = -2;
3390 if (!mpctx->chapters) {
3391 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3392 if (res >= 0) {
3393 if (*seek_pts == -1)
3394 seek_reset(mpctx, true, true);
3395 else {
3396 mpctx->last_chapter_seek = res;
3397 mpctx->last_chapter_pts = *seek_pts;
3400 return res;
3403 if (chapter >= mpctx->num_chapters)
3404 return -1;
3405 if (chapter < 0)
3406 chapter = 0;
3407 *seek_pts = mpctx->chapters[chapter].start;
3408 mpctx->last_chapter_seek = chapter;
3409 mpctx->last_chapter_pts = *seek_pts;
3410 return chapter;
3414 static void run_playloop(struct MPContext *mpctx)
3416 struct MPOpts *opts = &mpctx->opts;
3417 bool full_audio_buffers = false;
3418 bool audio_left = false, video_left = false;
3419 double endpts = end_at.type == END_AT_TIME ? end_at.pos : MP_NOPTS_VALUE;
3420 bool end_is_chapter = false;
3421 double sleeptime = WAKEUP_PERIOD;
3422 bool was_restart = mpctx->restart_playback;
3424 if (mpctx->timeline) {
3425 double end = mpctx->timeline[mpctx->timeline_part + 1].start;
3426 if (endpts == MP_NOPTS_VALUE || end < endpts) {
3427 endpts = end;
3428 end_is_chapter = true;
3432 if (opts->chapterrange[1] > 0) {
3433 int cur_chapter = get_current_chapter(mpctx);
3434 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3435 mpctx->stop_play = PT_NEXT_ENTRY;
3438 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3439 mpctx->sh_audio = mpctx->d_audio->sh;
3440 mpctx->sh_audio->ds = mpctx->d_audio;
3441 reinit_audio_chain(mpctx);
3444 if (mpctx->step_frames && !mpctx->sh_video) {
3445 mpctx->step_frames = 0;
3446 pause_player(mpctx);
3449 if (mpctx->sh_audio && !mpctx->restart_playback && !mpctx->ao->untimed) {
3450 int status = fill_audio_out_buffers(mpctx, endpts);
3451 full_audio_buffers = status >= 0;
3452 // Not at audio stream EOF yet
3453 audio_left = status > -2;
3456 double buffered_audio = -1;
3457 while (mpctx->sh_video) { // never loops, for "break;" only
3458 struct vo *vo = mpctx->video_out;
3459 vo_pts = mpctx->sh_video->timer * 90000.0;
3460 vo_fps = mpctx->sh_video->fps;
3462 video_left = vo->hasframe || vo->frame_loaded;
3463 if (!vo->frame_loaded && (!mpctx->paused || mpctx->restart_playback)) {
3464 double frame_time = update_video(mpctx);
3465 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3466 if (mpctx->sh_video->vf_initialized < 0) {
3467 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3468 "\nFATAL: Could not initialize video filters (-vf) "
3469 "or video output (-vo).\n");
3470 mpctx->stop_play = PT_NEXT_ENTRY;
3471 return;
3473 video_left = frame_time >= 0;
3474 if (video_left && !mpctx->restart_playback) {
3475 mpctx->time_frame += frame_time / opts->playback_speed;
3476 adjust_sync(mpctx, frame_time);
3480 if (endpts != MP_NOPTS_VALUE)
3481 video_left &= mpctx->sh_video->pts < endpts;
3483 // ================================================================
3485 current_module = "vo_check_events";
3486 vo_check_events(vo);
3488 #ifdef CONFIG_X11
3489 if (stop_xscreensaver) {
3490 current_module = "stop_xscreensaver";
3491 xscreensaver_heartbeat(mpctx->x11_state);
3493 #endif
3494 if (heartbeat_cmd) {
3495 static unsigned last_heartbeat;
3496 unsigned now = GetTimerMS();
3497 if (now - last_heartbeat > 30000) {
3498 last_heartbeat = now;
3499 system(heartbeat_cmd);
3503 if (!video_left || (mpctx->paused && !mpctx->restart_playback))
3504 break;
3505 if (!vo->frame_loaded) {
3506 sleeptime = 0;
3507 break;
3510 mpctx->time_frame -= get_relative_time(mpctx);
3511 if (full_audio_buffers && !mpctx->restart_playback) {
3512 buffered_audio = ao_get_delay(mpctx->ao);
3513 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", buffered_audio);
3515 if (opts->autosync) {
3516 /* Smooth reported playback position from AO by averaging
3517 * it with the value expected based on previus value and
3518 * time elapsed since then. May help smooth video timing
3519 * with audio output that have inaccurate position reporting.
3520 * This is badly implemented; the behavior of the smoothing
3521 * now undesirably depends on how often this code runs
3522 * (mainly depends on video frame rate). */
3523 float predicted = (mpctx->delay / opts->playback_speed +
3524 mpctx->time_frame);
3525 float difference = buffered_audio - predicted;
3526 buffered_audio = predicted + difference / opts->autosync;
3529 mpctx->time_frame = (buffered_audio -
3530 mpctx->delay / opts->playback_speed);
3531 } else {
3532 /* If we're more than 200 ms behind the right playback
3533 * position, don't try to speed up display of following
3534 * frames to catch up; continue with default speed from
3535 * the current frame instead.
3536 * If benchmark is set always output frames immediately
3537 * without sleeping.
3539 if (mpctx->time_frame < -0.2 || opts->benchmark)
3540 mpctx->time_frame = 0;
3543 double vsleep = mpctx->time_frame - vo->flip_queue_offset;
3544 if (vsleep > 0.050) {
3545 sleeptime = FFMIN(sleeptime, vsleep - 0.040);
3546 break;
3548 sleeptime = 0;
3550 //=================== FLIP PAGE (VIDEO BLT): ======================
3552 current_module = "flip_page";
3553 vo_new_frame_imminent(vo);
3554 struct sh_video *sh_video = mpctx->sh_video;
3555 mpctx->video_pts = sh_video->pts;
3556 update_subtitles(mpctx, sh_video->pts, false);
3557 update_teletext(sh_video, mpctx->demuxer, 0);
3558 update_osd_msg(mpctx);
3559 struct vf_instance *vf = sh_video->vfilter;
3560 mpctx->osd->pts = mpctx->video_pts - mpctx->osd->sub_offset;
3561 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3562 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3563 vo_osd_changed(0);
3565 mpctx->time_frame -= get_relative_time(mpctx);
3566 mpctx->time_frame -= vo->flip_queue_offset;
3567 float aq_sleep_time = mpctx->time_frame;
3568 if (mpctx->time_frame > 0.001
3569 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3570 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3571 mpctx->time_frame += vo->flip_queue_offset;
3573 unsigned int t2 = GetTimer();
3574 /* Playing with playback speed it's possible to get pathological
3575 * cases with mpctx->time_frame negative enough to cause an
3576 * overflow in pts_us calculation, thus the FFMAX. */
3577 double time_frame = FFMAX(mpctx->time_frame, -1);
3578 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3579 int duration = -1;
3580 double pts2 = vo->next_pts2;
3581 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts &&
3582 !mpctx->restart_playback) {
3583 // expected A/V sync correction is ignored
3584 double diff = (pts2 - mpctx->video_pts);
3585 diff /= opts->playback_speed;
3586 if (mpctx->time_frame < 0)
3587 diff += mpctx->time_frame;
3588 if (diff < 0)
3589 diff = 0;
3590 if (diff > 10)
3591 diff = 10;
3592 duration = diff * 1e6;
3594 vo_flip_page(vo, pts_us | 1, duration);
3596 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3597 vout_time_usage += mpctx->last_vo_flip_duration;
3598 if (vo->driver->flip_page_timed) {
3599 // No need to adjust sync based on flip speed
3600 mpctx->last_vo_flip_duration = 0;
3601 // For print_status - VO call finishing early is OK for sync
3602 mpctx->time_frame -= get_relative_time(mpctx);
3604 if (mpctx->restart_playback) {
3605 mpctx->syncing_audio = true;
3606 if (mpctx->sh_audio)
3607 fill_audio_out_buffers(mpctx, endpts);
3608 mpctx->restart_playback = false;
3609 mpctx->time_frame = 0;
3610 get_relative_time(mpctx);
3612 print_status(mpctx, MP_NOPTS_VALUE, true);
3613 screenshot_flip(mpctx);
3615 if (opts->auto_quality > 0) {
3616 current_module = "autoq";
3617 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3618 ++output_quality;
3619 else if (output_quality > 1 && aq_sleep_time < 0)
3620 --output_quality;
3621 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3622 output_quality = 0;
3623 set_video_quality(mpctx->sh_video, output_quality);
3626 if (play_n_frames >= 0) {
3627 --play_n_frames;
3628 if (play_n_frames <= 0)
3629 mpctx->stop_play = PT_NEXT_ENTRY;
3631 if (mpctx->step_frames > 0) {
3632 mpctx->step_frames--;
3633 if (mpctx->step_frames == 0)
3634 pause_player(mpctx);
3636 break;
3637 } // video
3639 #ifdef CONFIG_DVDNAV
3640 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3641 nav_highlight_t hl;
3642 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3643 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3644 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3645 vo_osd_changed(OSDTYPE_DVDNAV);
3646 } else {
3647 osd_set_nav_box(0, 0, 0, 0);
3648 vo_osd_changed(OSDTYPE_DVDNAV);
3649 vo_osd_changed(OSDTYPE_SPU);
3652 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3653 double ar = -1.0;
3654 if (mpctx->sh_video &&
3655 stream_control(mpctx->demuxer->stream,
3656 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3657 != STREAM_UNSUPPORTED)
3658 mpctx->sh_video->stream_aspect = ar;
3661 #endif
3663 if (mpctx->sh_audio && (mpctx->restart_playback ? !video_left :
3664 mpctx->ao->untimed && (mpctx->delay <= 0 ||
3665 !video_left))) {
3666 int status = fill_audio_out_buffers(mpctx, endpts);
3667 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3668 // Not at audio stream EOF yet
3669 audio_left = status > -2;
3671 if (!video_left)
3672 mpctx->restart_playback = false;
3673 if (mpctx->sh_audio && buffered_audio == -1)
3674 buffered_audio = mpctx->paused ? 0 : ao_get_delay(mpctx->ao);
3676 update_osd_msg(mpctx);
3677 if (mpctx->paused)
3678 update_pause_message(mpctx);
3679 if (!video_left && (!mpctx->paused || was_restart)) {
3680 double a_pos = 0;
3681 if (mpctx->sh_audio) {
3682 a_pos = (written_audio_pts(mpctx) -
3683 mpctx->opts.playback_speed * buffered_audio);
3685 print_status(mpctx, a_pos, false);
3687 if (!mpctx->sh_video)
3688 update_subtitles(mpctx, a_pos, false);
3691 /* It's possible for the user to simultaneously switch both audio
3692 * and video streams to "disabled" at runtime. Handle this by waiting
3693 * rather than immediately stopping playback due to EOF.
3695 * When all audio has been written to output driver, stay in the
3696 * main loop handling commands until it has been mostly consumed,
3697 * except in the gapless case, where the next file will be started
3698 * while audio from the current one still remains to be played.
3700 * We want this check to trigger if we seeked to this position,
3701 * but not if we paused at it with audio possibly still buffered in
3702 * the AO. There's currently no working way to check buffered audio
3703 * inside AO while paused. Thus the "was_restart" check below, which
3704 * should trigger after seek only, when we know there's no audio
3705 * buffered.
3707 if ((mpctx->sh_audio || mpctx->sh_video) && !audio_left && !video_left
3708 && (opts->gapless_audio || buffered_audio < 0.05)
3709 && (!mpctx->paused || was_restart)) {
3710 if (end_is_chapter) {
3711 seek(mpctx, (struct seek_params){
3712 .type = MPSEEK_ABSOLUTE,
3713 .amount = mpctx->timeline[mpctx->timeline_part+1].start
3714 }, true);
3715 } else
3716 mpctx->stop_play = AT_END_OF_FILE;
3717 } else if (!mpctx->stop_play) {
3718 double audio_sleep = 9;
3719 if (mpctx->sh_audio && !mpctx->paused) {
3720 if (mpctx->ao->untimed) {
3721 if (!video_left)
3722 audio_sleep = 0;
3723 } else if (full_audio_buffers) {
3724 audio_sleep = buffered_audio - 0.050;
3725 // Keep extra safety margin if the buffers are large
3726 if (audio_sleep > 0.100)
3727 audio_sleep = FFMAX(audio_sleep - 0.200, 0.100);
3728 else
3729 audio_sleep = FFMAX(audio_sleep, 0.020);
3730 } else
3731 audio_sleep = 0.020;
3733 sleeptime = FFMIN(sleeptime, audio_sleep);
3734 if (sleeptime > 0) {
3735 if (!mpctx->sh_video)
3736 goto novideo;
3737 int hack = vo_osd_changed(0);
3738 vo_osd_changed(hack);
3739 if (hack || mpctx->video_out->want_redraw) {
3740 if (redraw_osd(mpctx) < 0) {
3741 if (mpctx->paused && video_left)
3742 add_step_frame(mpctx);
3743 else
3744 goto novideo;
3745 } else
3746 vo_osd_changed(0);
3747 } else {
3748 novideo:
3749 mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
3754 //================= Keyboard events, SEEKing ====================
3756 current_module = "key_events";
3758 mp_cmd_t *cmd;
3759 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3760 /* Allow running consecutive seek commands to combine them,
3761 * but execute the seek before running other commands.
3762 * If the user seeks continuously (keeps arrow key down)
3763 * try to finish showing a frame from one location before doing
3764 * another seek (which could lead to unchanging display). */
3765 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3766 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3767 && GetTimerMS() - mpctx->start_timestamp < 300)
3768 break;
3769 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3770 run_command(mpctx, cmd);
3771 mp_cmd_free(cmd);
3772 if (mpctx->stop_play)
3773 break;
3776 // handle -sstep
3777 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3778 mpctx->osd_function = OSD_FFW;
3779 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3782 /* Looping. */
3783 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3784 mpctx->stop_play == PT_NEXT_ENTRY)) {
3785 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3787 if (opts->loop_times > 1)
3788 opts->loop_times--;
3789 else if (opts->loop_times == 1)
3790 opts->loop_times = -1;
3791 play_n_frames = play_n_frames_mf;
3792 mpctx->stop_play = 0;
3793 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3796 if (mpctx->seek.type) {
3797 seek(mpctx, mpctx->seek, false);
3798 mpctx->seek = (struct seek_params){ 0 };
3803 static int read_keys(void *ctx, int fd)
3805 if (getch2(ctx))
3806 return MP_INPUT_NOTHING;
3807 return MP_INPUT_DEAD;
3810 static bool attachment_is_font(struct demux_attachment *att)
3812 if (!att->name || !att->type || !att->data || !att->data_size)
3813 return false;
3814 // match against MIME types
3815 if (strcmp(att->type, "application/x-truetype-font") == 0
3816 || strcmp(att->type, "application/x-font") == 0)
3817 return true;
3818 // fallback: match against file extension
3819 if (strlen(att->name) > 4) {
3820 char *ext = att->name + strlen(att->name) - 4;
3821 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3822 || strcasecmp(ext, ".otf") == 0)
3823 return true;
3825 return false;
3828 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3830 if (audio_id == -1)
3831 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3832 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3833 demuxer_switch_audio(demuxer, audio_id);
3834 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3835 demuxer->audio->id = -2;
3836 demuxer->audio->sh = NULL;
3838 return demuxer->audio->id;
3841 static void print_version(const char *name)
3843 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3845 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3846 GetCpuCaps(&gCpuCaps);
3847 #if ARCH_X86
3848 mp_msg(MSGT_CPLAYER, MSGL_V,
3849 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3850 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3851 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3852 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3853 #if CONFIG_RUNTIME_CPUDETECT
3854 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3855 #else
3856 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3857 if (HAVE_MMX)
3858 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3859 if (HAVE_MMX2)
3860 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3861 if (HAVE_AMD3DNOW)
3862 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3863 if (HAVE_AMD3DNOWEXT)
3864 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3865 if (HAVE_SSE)
3866 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3867 if (HAVE_SSE2)
3868 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3869 if (HAVE_SSSE3)
3870 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3871 if (HAVE_CMOV)
3872 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3873 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3874 #endif /* CONFIG_RUNTIME_CPUDETECT */
3875 #endif /* ARCH_X86 */
3876 print_libav_versions();
3879 #ifdef PTW32_STATIC_LIB
3880 static void detach_ptw32(void)
3882 pthread_win32_thread_detach_np();
3883 pthread_win32_process_detach_np();
3885 #endif
3887 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3888 * file for some tools to link against. */
3889 #ifndef DISABLE_MAIN
3890 int main(int argc, char *argv[])
3892 #ifdef PTW32_STATIC_LIB
3893 pthread_win32_process_attach_np();
3894 pthread_win32_thread_attach_np();
3895 atexit(detach_ptw32);
3896 #endif
3897 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3898 || !strcmp(argv[1], "--leak-report")))
3899 talloc_enable_leak_report();
3901 #ifdef __MINGW32__
3902 mp_get_converted_argv(&argc, &argv);
3903 #endif
3905 char *mem_ptr;
3907 // movie info:
3909 /* Flag indicating whether MPlayer should exit without playing anything. */
3910 int opt_exit = 0;
3911 int i;
3913 struct MPContext *mpctx = talloc(NULL, MPContext);
3914 *mpctx = (struct MPContext){
3915 .osd_function = OSD_PLAY,
3916 .begin_skip = MP_NOPTS_VALUE,
3917 .play_tree_step = 1,
3918 .global_sub_pos = -1,
3919 .set_of_sub_pos = -1,
3920 .file_format = DEMUXER_TYPE_UNKNOWN,
3921 .last_dvb_step = 1,
3922 .paused_cache_fill = -1,
3925 InitTimer();
3926 srand(GetTimerMS());
3928 mp_msg_init();
3929 init_libav();
3931 #ifdef CONFIG_X11
3932 mpctx->x11_state = vo_x11_init_state();
3933 #endif
3934 struct MPOpts *opts = &mpctx->opts;
3935 set_default_mplayer_options(opts);
3936 // Create the config context and register the options
3937 mpctx->mconfig = m_config_new(opts, cfg_include);
3938 m_config_register_options(mpctx->mconfig, mplayer_opts);
3939 m_config_register_options(mpctx->mconfig, common_opts);
3940 mp_input_register_options(mpctx->mconfig);
3941 m_config_initialize(mpctx->mconfig, opts);
3943 // Preparse the command line
3944 m_config_preparse_command_line(mpctx->mconfig, argc, argv, &verbose);
3946 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3947 set_path_env();
3948 #endif
3950 #ifdef CONFIG_TV
3951 stream_tv_defaults.immediate = 1;
3952 #endif
3954 parse_cfgfiles(mpctx, mpctx->mconfig);
3956 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3957 if (mpctx->playtree == NULL)
3958 opt_exit = 1;
3959 else {
3960 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3961 if (mpctx->playtree) {
3962 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3963 mpctx->mconfig);
3964 if (mpctx->playtree_iter) {
3965 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3966 PLAY_TREE_ITER_ENTRY) {
3967 play_tree_iter_free(mpctx->playtree_iter);
3968 mpctx->playtree_iter = NULL;
3970 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3976 print_version("MPlayer2");
3978 #if defined(__MINGW32__) || defined(__CYGWIN__)
3980 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3981 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3982 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3983 if (kernel32) {
3984 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3985 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3987 if (setDEP)
3988 setDEP(3);
3989 if (setDllDir)
3990 setDllDir("");
3992 // stop Windows from showing all kinds of annoying error dialogs
3993 SetErrorMode(0x8003);
3994 // request 1ms timer resolution
3995 timeBeginPeriod(1);
3996 #endif
3998 #ifdef CONFIG_PRIORITY
3999 set_priority();
4000 #endif
4002 if (opts->video_driver_list &&
4003 strcmp(opts->video_driver_list[0], "help") == 0) {
4004 list_video_out();
4005 opt_exit = 1;
4008 if (opts->audio_driver_list &&
4009 strcmp(opts->audio_driver_list[0], "help") == 0) {
4010 list_audio_out();
4011 opt_exit = 1;
4014 /* Check codecs.conf. */
4015 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4016 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4017 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4018 if (!parse_codec_cfg(NULL))
4019 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4020 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4021 "Using built-in default codecs.conf.\n");
4024 free(mem_ptr); // release the buffer created by get_path()
4027 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4028 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4029 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4030 list_codecs(1);
4031 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4032 opt_exit = 1;
4034 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4035 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4036 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4037 list_codecs(0);
4038 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4039 opt_exit = 1;
4041 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4042 vfm_help();
4043 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4044 opt_exit = 1;
4046 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4047 afm_help();
4048 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4049 opt_exit = 1;
4051 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4052 af_help();
4053 printf("\n");
4054 opt_exit = 1;
4056 #ifdef CONFIG_X11
4057 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4058 fstype_help();
4059 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4060 opt_exit = 1;
4062 #endif
4063 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4064 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4065 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4066 demuxer_help();
4067 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4068 opt_exit = 1;
4070 if (opts->list_properties) {
4071 property_print_help();
4072 opt_exit = 1;
4075 if (opt_exit)
4076 exit_player(mpctx, EXIT_NONE);
4078 if (!mpctx->filename && !opts->player_idle_mode) {
4079 // no file/vcd/dvd -> show HELP:
4080 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4081 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4084 /* Display what configure line was used */
4085 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4087 // Many users forget to include command line in bugreports...
4088 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4089 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4090 for (i = 1; i < argc; i++)
4091 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4092 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4095 //------ load global data first ------
4097 #ifdef CONFIG_ASS
4098 mpctx->ass_library = mp_ass_init(opts);
4099 #endif
4101 mpctx->osd = osd_create(opts, mpctx->ass_library);
4103 #ifdef HAVE_RTC
4104 if (opts->rtc) {
4105 char *rtc_device = opts->rtc_device;
4106 // seteuid(0); /* Can't hurt to try to get root here */
4107 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4108 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4109 "(it should be readable by the user.)\n",
4110 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4111 else {
4112 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4114 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4115 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4116 "ioctl (rtc_irqp_set %lu): %s\n",
4117 irqp, strerror(errno));
4118 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4119 close(rtc_fd);
4120 rtc_fd = -1;
4121 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4122 /* variable only by the root */
4123 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4124 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4125 close(rtc_fd);
4126 rtc_fd = -1;
4127 } else
4128 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4129 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4132 if (rtc_fd < 0)
4133 #endif /* HAVE_RTC */
4134 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4135 opts->softsleep ? "software" : timer_name);
4137 #ifdef HAVE_TERMCAP
4138 load_termcap(NULL); // load key-codes
4139 #endif
4141 // ========== Init keyboard FIFO (connection to libvo) ============
4143 // Init input system
4144 current_module = "init_input";
4145 mpctx->input = mp_input_init(&opts->input);
4146 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4147 if (slave_mode)
4148 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4149 else if (opts->consolecontrols)
4150 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4151 // Set the libstream interrupt callback
4152 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4154 current_module = NULL;
4156 /// Catch signals
4157 #ifndef __MINGW32__
4158 signal(SIGCHLD, child_sighandler);
4159 #endif
4161 #ifdef CONFIG_CRASH_DEBUG
4162 prog_path = argv[0];
4163 #endif
4164 //========= Catch terminate signals: ================
4165 // terminate requests:
4166 signal(SIGTERM, exit_sighandler); // kill
4167 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4169 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4171 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4172 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4173 #ifdef CONFIG_SIGHANDLER
4174 // fatal errors:
4175 signal(SIGBUS, exit_sighandler); // bus error
4176 signal(SIGSEGV, exit_sighandler); // segfault
4177 signal(SIGILL, exit_sighandler); // illegal instruction
4178 signal(SIGFPE, exit_sighandler); // floating point exc.
4179 signal(SIGABRT, exit_sighandler); // abort()
4180 #ifdef CONFIG_CRASH_DEBUG
4181 if (crash_debug)
4182 signal(SIGTRAP, exit_sighandler);
4183 #endif
4184 #endif
4186 // ***************** Now, let's see the per-file stuff ******************
4188 play_next_file:
4190 // init global sub numbers
4191 mpctx->global_sub_size = 0;
4192 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4194 if (mpctx->filename) {
4195 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4196 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4197 load_per_file_config(mpctx->mconfig, mpctx->filename);
4200 if (opts->video_driver_list)
4201 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4202 opts->video_driver_list[0]);
4203 if (opts->audio_driver_list)
4204 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4205 opts->audio_driver_list[0]);
4207 // We must enable getch2 here to be able to interrupt network connection
4208 // or cache filling
4209 if (opts->consolecontrols && !slave_mode) {
4210 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4211 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4212 "WARNING: getch2_init called twice!\n");
4213 else
4214 getch2_enable(); // prepare stdin for hotkeys...
4215 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4216 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4219 // ================= idle loop (STOP state) =========================
4220 while (opts->player_idle_mode && !mpctx->filename) {
4221 uninit_player(mpctx, INITIALIZED_AO | INITIALIZED_VO);
4222 play_tree_t *entry = NULL;
4223 mp_cmd_t *cmd;
4224 while (!(cmd = mp_input_get_cmd(mpctx->input, WAKEUP_PERIOD * 1000,
4225 false)));
4226 switch (cmd->id) {
4227 case MP_CMD_LOADFILE:
4228 // prepare a tree entry with the new filename
4229 entry = play_tree_new();
4230 play_tree_add_file(entry, cmd->args[0].v.s);
4231 // The entry is added to the main playtree after the switch().
4232 break;
4233 case MP_CMD_LOADLIST:
4234 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4235 break;
4236 case MP_CMD_QUIT:
4237 exit_player_with_rc(mpctx, EXIT_QUIT,
4238 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4239 break;
4240 case MP_CMD_VO_FULLSCREEN:
4241 case MP_CMD_GET_PROPERTY:
4242 case MP_CMD_SET_PROPERTY:
4243 case MP_CMD_STEP_PROPERTY:
4244 run_command(mpctx, cmd);
4245 break;
4248 mp_cmd_free(cmd);
4250 if (entry) { // user entered a command that gave a valid entry
4251 if (mpctx->playtree)
4252 // the playtree is always a node with one child. let's clear it
4253 play_tree_free_list(mpctx->playtree->child, 1);
4254 else
4255 // .. or make a brand new playtree
4256 mpctx->playtree = play_tree_new();
4258 if (!mpctx->playtree)
4259 continue; // couldn't make playtree! wait for next command
4261 play_tree_set_child(mpctx->playtree, entry);
4263 /* Make iterator start at the top the of tree. */
4264 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4265 mpctx->mconfig);
4266 if (!mpctx->playtree_iter)
4267 continue;
4269 // find the first real item in the tree
4270 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4271 PLAY_TREE_ITER_ENTRY) {
4272 // no items!
4273 play_tree_iter_free(mpctx->playtree_iter);
4274 mpctx->playtree_iter = NULL;
4275 continue; // wait for next command
4277 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4281 #ifdef CONFIG_ASS
4282 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4283 #endif
4284 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4285 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4287 if (mpctx->filename) {
4288 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4289 filename_recode(mpctx->filename));
4290 if (use_filename_title && opts->vo_wintitle == NULL)
4291 opts->vo_wintitle = talloc_strdup(NULL,
4292 mp_basename(mpctx->filename));
4295 if (edl_output_filename) {
4296 if (edl_fd)
4297 fclose(edl_fd);
4298 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4299 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4300 "Can't open EDL file [%s] for writing.\n",
4301 filename_recode(edl_output_filename));
4305 //==================== Open VOB-Sub ============================
4307 current_module = "vobsub";
4308 if (opts->vobsub_name) {
4309 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4310 if (vo_vobsub == NULL)
4311 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4312 filename_recode(opts->vobsub_name));
4313 } else if (opts->sub_auto && mpctx->filename) {
4314 char **vob = find_vob_subtitles(opts, mpctx->filename);
4315 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4316 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4317 if (vo_vobsub)
4318 break;
4320 talloc_free(vob);
4322 if (vo_vobsub) {
4323 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4324 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4325 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4326 mpctx);
4328 // setup global sub numbering
4329 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4330 vobsub_get_indexes_count(vo_vobsub);
4333 //============ Open & Sync STREAM --- fork cache2 ====================
4335 mpctx->stream = NULL;
4336 mpctx->demuxer = NULL;
4337 mpctx->d_audio = NULL;
4338 mpctx->d_video = NULL;
4339 mpctx->d_sub = NULL;
4340 mpctx->sh_audio = NULL;
4341 mpctx->sh_video = NULL;
4343 current_module = "open_stream";
4344 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4345 if (!mpctx->stream) { // error...
4346 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4347 goto goto_next_file;
4349 mpctx->initialized_flags |= INITIALIZED_STREAM;
4351 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4352 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4353 "playlist support will not be used automatically.\n"
4354 "MPlayer's playlist code is unsafe and should only be used with "
4355 "trusted sources.\nPlayback will probably fail.\n\n");
4356 #if 0
4357 play_tree_t *entry;
4358 // Handle playlist
4359 current_module = "handle_playlist";
4360 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4361 filename_recode(mpctx->filename));
4362 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4363 mpctx->eof = playtree_add_playlist(mpctx, entry);
4364 goto goto_next_file;
4365 #endif
4367 mpctx->stream->start_pos += seek_to_byte;
4369 if (stream_dump_type == 5) {
4370 unsigned char buf[4096];
4371 int len;
4372 FILE *f;
4373 current_module = "dumpstream";
4374 stream_reset(mpctx->stream);
4375 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4376 f = fopen(opts->stream_dump_name, "wb");
4377 if (!f) {
4378 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4379 exit_player(mpctx, EXIT_ERROR);
4381 if (opts->chapterrange[0] > 1) {
4382 int chapter = opts->chapterrange[0] - 1;
4383 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4385 struct stream_dump_progress info;
4386 stream_dump_progress_start(&info);
4387 while (!mpctx->stream->eof && !async_quit_request) {
4388 len = stream_read(mpctx->stream, buf, 4096);
4389 if (len > 0) {
4390 if (fwrite(buf, len, 1, f) != 1) {
4391 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4392 exit_player(mpctx, EXIT_ERROR);
4395 stream_dump_progress(&info, len, mpctx->stream);
4396 if (opts->chapterrange[1] > 0) {
4397 int chapter = -1;
4398 if (stream_control(mpctx->stream,
4399 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4400 && chapter + 1 > opts->chapterrange[1])
4401 break;
4404 if (fclose(f)) {
4405 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4406 opts->stream_dump_name);
4407 exit_player(mpctx, EXIT_ERROR);
4409 stream_dump_progress_end(&info, opts->stream_dump_name);
4410 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4411 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4414 #ifdef CONFIG_DVDREAD
4415 if (mpctx->stream->type == STREAMTYPE_DVD) {
4416 current_module = "dvd lang->id";
4417 if (opts->audio_lang && opts->audio_id == -1)
4418 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4419 if (opts->sub_lang && opts->sub_id == -1)
4420 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4421 // setup global sub numbering
4422 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4423 current_module = NULL;
4425 #endif
4427 #ifdef CONFIG_DVDNAV
4428 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4429 current_module = "dvdnav lang->id";
4430 if (opts->audio_lang && opts->audio_id == -1)
4431 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4432 opts->audio_lang);
4433 dvdsub_lang_id = -3;
4434 if (opts->sub_lang && opts->sub_id == -1)
4435 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4436 mpctx->stream, opts->sub_lang);
4437 // setup global sub numbering
4438 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4439 mpctx->stream);
4440 current_module = NULL;
4442 #endif
4444 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4445 goto_enable_cache:
4446 if (stream_cache_size > 0) {
4447 int res;
4448 float stream_cache_min_percent = opts->stream_cache_min_percent;
4449 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4450 current_module = "enable_cache";
4451 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4452 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4453 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4454 if (res == 0)
4455 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4456 goto goto_next_file;
4459 //============ Open DEMUXERS --- DETECT file type =======================
4460 current_module = "demux_open";
4462 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4463 opts->audio_id, opts->video_id, opts->sub_id,
4464 mpctx->filename);
4466 // HACK to get MOV Reference Files working
4468 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4469 unsigned char *playlist_entry;
4470 play_tree_t *list = NULL, *entry = NULL;
4472 current_module = "handle_demux_playlist";
4473 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4474 char *temp;
4475 const char *bname;
4477 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4478 filename_recode(playlist_entry));
4480 bname = mp_basename(playlist_entry);
4481 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4482 !strncmp(bname + 3, "gateQT", 6))
4483 continue;
4485 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4486 continue;
4488 entry = play_tree_new();
4490 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4491 playlist_entry)) { // add reference path of current file
4492 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4493 mpctx->filename)) + strlen(playlist_entry) + 1));
4494 if (temp) {
4495 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4496 strlen(mp_basename(mpctx->filename)));
4497 temp[strlen(mpctx->filename) - strlen(mp_basename(
4498 mpctx->filename))] = '\0';
4499 strcat(temp, playlist_entry);
4500 if (!strcmp(temp, mpctx->filename)) {
4501 free(temp);
4502 continue;
4504 play_tree_add_file(entry, temp);
4505 mp_msg(MSGT_CPLAYER, MSGL_V,
4506 "Resolving reference to %s.\n", temp);
4507 free(temp);
4509 } else
4510 play_tree_add_file(entry, playlist_entry);
4512 if (!list)
4513 list = entry;
4514 else
4515 play_tree_append_entry(list, entry);
4517 free_demuxer(mpctx->demuxer);
4518 mpctx->demuxer = NULL;
4520 if (list) {
4521 entry = play_tree_new();
4522 play_tree_set_child(entry, list);
4523 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4524 goto goto_next_file;
4528 if (!mpctx->demuxer) {
4529 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4530 goto goto_next_file;
4533 if (mpctx->demuxer->matroska_data.ordered_chapters)
4534 build_ordered_chapter_timeline(mpctx);
4536 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4537 build_edl_timeline(mpctx);
4539 if (mpctx->timeline) {
4540 mpctx->timeline_part = 0;
4541 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4543 int part_count = mpctx->num_timeline_parts;
4544 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4545 "sources. Total length %.3f seconds.\n", part_count,
4546 mpctx->num_sources, mpctx->timeline[part_count].start);
4547 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4548 for (int i = 0; i < mpctx->num_sources; i++)
4549 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4550 filename_recode(mpctx->sources[i].demuxer->filename));
4551 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4552 "source_start, source):\n");
4553 for (int i = 0; i < part_count; i++) {
4554 struct timeline_part *p = mpctx->timeline + i;
4555 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4556 p->source_start, p->source - mpctx->sources);
4558 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4559 mpctx->timeline[part_count].start);
4562 if (!mpctx->sources) {
4563 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4564 *mpctx->sources = (struct content_source){
4565 .stream = mpctx->stream,
4566 .demuxer = mpctx->demuxer
4568 mpctx->num_sources = 1;
4571 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4573 #ifdef CONFIG_ASS
4574 if (opts->ass_enabled && mpctx->ass_library) {
4575 for (int j = 0; j < mpctx->num_sources; j++) {
4576 struct demuxer *d = mpctx->sources[j].demuxer;
4577 for (int i = 0; i < d->num_attachments; i++) {
4578 struct demux_attachment *att = d->attachments + i;
4579 if (opts->use_embedded_fonts && attachment_is_font(att))
4580 ass_add_font(mpctx->ass_library, att->name, att->data,
4581 att->data_size);
4585 #endif
4587 current_module = "demux_open2";
4589 mpctx->d_audio = mpctx->demuxer->audio;
4590 mpctx->d_video = mpctx->demuxer->video;
4591 mpctx->d_sub = mpctx->demuxer->sub;
4593 if (ts_prog) {
4594 int tmp = ts_prog;
4595 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4597 // select audio stream
4598 for (int i = 0; i < mpctx->num_sources; i++)
4599 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4600 opts->audio_lang);
4602 // DUMP STREAMS:
4603 if ((stream_dump_type) && (stream_dump_type < 4)) {
4604 FILE *f;
4605 demux_stream_t *ds = NULL;
4606 current_module = "dump";
4607 // select stream to dump
4608 switch (stream_dump_type) {
4609 case 1: ds = mpctx->d_audio;
4610 break;
4611 case 2: ds = mpctx->d_video;
4612 break;
4613 case 3: ds = mpctx->d_sub;
4614 break;
4616 if (!ds) {
4617 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4618 "dump: FATAL: Selected stream missing!\n");
4619 exit_player(mpctx, EXIT_ERROR);
4621 // disable other streams:
4622 if (mpctx->d_audio && mpctx->d_audio != ds) {
4623 ds_free_packs(mpctx->d_audio);
4624 mpctx->d_audio->id = -2;
4626 if (mpctx->d_video && mpctx->d_video != ds) {
4627 ds_free_packs(mpctx->d_video);
4628 mpctx->d_video->id = -2;
4630 if (mpctx->d_sub && mpctx->d_sub != ds) {
4631 ds_free_packs(mpctx->d_sub);
4632 mpctx->d_sub->id = -2;
4634 // let's dump it!
4635 f = fopen(opts->stream_dump_name, "wb");
4636 if (!f) {
4637 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4638 exit_player(mpctx, EXIT_ERROR);
4640 struct stream_dump_progress info;
4641 stream_dump_progress_start(&info);
4642 while (!ds->eof) {
4643 unsigned char *start;
4644 int in_size = ds_get_packet(ds, &start);
4645 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4646 && stream_dump_type == 2)
4647 fwrite(&in_size, 1, 4, f);
4648 if (in_size > 0) {
4649 fwrite(start, in_size, 1, f);
4650 stream_dump_progress(&info, in_size, mpctx->stream);
4652 if (opts->chapterrange[1] > 0) {
4653 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4654 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4655 break;
4658 fclose(f);
4659 stream_dump_progress_end(&info, opts->stream_dump_name);
4660 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4661 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4664 mpctx->sh_audio = mpctx->d_audio->sh;
4665 mpctx->sh_video = mpctx->d_video->sh;
4667 if (mpctx->sh_video) {
4668 current_module = "video_read_properties";
4669 if (!video_read_properties(mpctx->sh_video)) {
4670 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4671 mpctx->sh_video = mpctx->d_video->sh = NULL;
4672 } else {
4673 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4674 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4675 mpctx->demuxer->file_format, mpctx->sh_video->format,
4676 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4677 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4678 if (force_fps) {
4679 mpctx->sh_video->fps = force_fps;
4680 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4682 vo_fps = mpctx->sh_video->fps;
4684 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4685 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4686 "header or invalid, use the -fps option.\n");
4692 if (!mpctx->sh_video && !mpctx->sh_audio) {
4693 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4694 #ifdef CONFIG_DVBIN
4695 if (mpctx->stream->type == STREAMTYPE_DVB) {
4696 int dir;
4697 int v = mpctx->last_dvb_step;
4698 if (v > 0)
4699 dir = DVB_CHANNEL_HIGHER;
4700 else
4701 dir = DVB_CHANNEL_LOWER;
4703 if (dvb_step_channel(mpctx->stream, dir)) {
4704 mpctx->stop_play = PT_NEXT_ENTRY;
4705 mpctx->dvbin_reopen = 1;
4708 #endif
4709 goto goto_next_file; // exit_player(_("Fatal error"));
4712 /* display clip info */
4713 demux_info_print(mpctx->demuxer);
4715 //================= Read SUBTITLES (DVD & TEXT) =========================
4716 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4717 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4718 init_vo_spudec(mpctx);
4720 // after reading video params we should load subtitles because
4721 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4722 // check .sub
4723 current_module = "read_subtitles_file";
4724 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4725 if (opts->sub_name) {
4726 for (i = 0; opts->sub_name[i] != NULL; ++i)
4727 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4729 if (opts->sub_auto) { // auto load sub file ...
4730 char **tmp = find_text_subtitles(opts, mpctx->filename);
4731 int nsub = MP_TALLOC_ELEMS(tmp);
4732 for (int i = 0; i < nsub; i++)
4733 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4734 talloc_free(tmp);
4736 if (mpctx->set_of_sub_size > 0)
4737 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4739 if (select_subtitle(mpctx)) {
4740 if (mpctx->subdata)
4741 switch (stream_dump_type) {
4742 case 3: list_sub_file(mpctx->subdata);
4743 break;
4744 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4745 break;
4746 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4747 break;
4748 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4749 break;
4750 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4751 break;
4752 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4753 break;
4757 print_file_properties(mpctx, mpctx->filename);
4759 reinit_video_chain(mpctx);
4760 if (!mpctx->sh_video && !mpctx->sh_audio)
4761 goto goto_next_file;
4763 //================== MAIN: ==========================
4764 current_module = "main";
4766 if (opts->playing_msg) {
4767 char *msg = property_expand_string(mpctx, opts->playing_msg);
4768 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4769 free(msg);
4773 // Disable the term OSD in verbose mode
4774 if (verbose)
4775 opts->term_osd = 0;
4777 // Make sure old OSD does not stay around
4778 clear_osd_msgs();
4780 //================ SETUP AUDIO ==========================
4782 if (mpctx->sh_audio) {
4783 reinit_audio_chain(mpctx);
4784 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4785 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4786 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4789 current_module = "av_init";
4791 if (mpctx->sh_video) {
4792 mpctx->sh_video->timer = 0;
4793 if (!ignore_start)
4794 audio_delay += mpctx->sh_video->stream_delay;
4796 if (mpctx->sh_audio) {
4797 if (start_volume >= 0)
4798 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4799 if (!ignore_start)
4800 audio_delay -= mpctx->sh_audio->stream_delay;
4803 if (!mpctx->sh_audio) {
4804 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4805 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4806 mpctx->d_audio->packs);
4807 ds_free_packs(mpctx->d_audio); // free buffered chunks
4809 if (!mpctx->sh_video) {
4810 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4811 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4812 mpctx->d_video->packs);
4813 ds_free_packs(mpctx->d_video);
4814 mpctx->d_video->id = -2;
4817 if (!mpctx->sh_video && !mpctx->sh_audio)
4818 goto goto_next_file;
4820 if (force_fps && mpctx->sh_video) {
4821 vo_fps = mpctx->sh_video->fps = force_fps;
4822 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4823 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4824 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4825 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4828 mp_input_set_section(mpctx->input, NULL);
4829 //TODO: add desired (stream-based) sections here
4830 if (mpctx->stream->type == STREAMTYPE_TV)
4831 mp_input_set_section(mpctx->input, "tv");
4832 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4833 mp_input_set_section(mpctx->input, "dvdnav");
4835 //==================== START PLAYING =======================
4837 if (opts->loop_times > 1)
4838 opts->loop_times--;
4839 else if (opts->loop_times == 1)
4840 opts->loop_times = -1;
4842 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4844 total_time_usage_start = GetTimer();
4845 audio_time_usage = 0;
4846 video_time_usage = 0;
4847 vout_time_usage = 0;
4848 total_frame_cnt = 0;
4849 drop_frame_cnt = 0; // fix for multifile fps benchmark
4850 play_n_frames = play_n_frames_mf;
4852 if (play_n_frames == 0) {
4853 mpctx->stop_play = PT_NEXT_ENTRY;
4854 goto goto_next_file;
4857 mpctx->time_frame = 0;
4858 mpctx->drop_message_shown = 0;
4859 mpctx->restart_playback = true;
4860 mpctx->video_pts = 0;
4861 mpctx->last_seek_pts = 0;
4862 mpctx->hrseek_active = false;
4863 mpctx->hrseek_framedrop = false;
4864 mpctx->step_frames = 0;
4865 mpctx->total_avsync_change = 0;
4866 mpctx->last_chapter_seek = -2;
4868 // If there's a timeline force an absolute seek to initialize state
4869 if (opts->seek_to_sec || mpctx->timeline) {
4870 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4871 seek(mpctx, mpctx->seek, false);
4872 end_at.pos += opts->seek_to_sec;
4874 if (opts->chapterrange[0] > 0) {
4875 double pts;
4876 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4877 && pts > -1.0) {
4878 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4879 seek(mpctx, mpctx->seek, false);
4883 if (end_at.type == END_AT_SIZE) {
4884 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4885 "Option -endpos in MPlayer does not yet support size units.\n");
4886 end_at.type = END_AT_NONE;
4889 #ifdef CONFIG_DVDNAV
4890 mp_dvdnav_context_free(mpctx);
4891 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4892 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4893 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4895 #endif
4897 mpctx->seek = (struct seek_params){ 0 };
4898 get_relative_time(mpctx); // reset current delta
4899 // Make sure VO knows current pause state
4900 if (mpctx->sh_video)
4901 vo_control(mpctx->video_out,
4902 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4904 while (!mpctx->stop_play)
4905 run_playloop(mpctx);
4907 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4909 #ifdef CONFIG_DVBIN
4910 if (mpctx->dvbin_reopen) {
4911 mpctx->stop_play = 0;
4912 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4913 cache_uninit(mpctx->stream);
4914 mpctx->dvbin_reopen = 0;
4915 goto goto_enable_cache;
4917 #endif
4919 goto_next_file: // don't jump here after ao/vo/getch initialization!
4921 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4923 if (opts->benchmark) {
4924 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4925 double total_time_usage;
4926 total_time_usage_start = GetTimer() - total_time_usage_start;
4927 total_time_usage = (float)total_time_usage_start * 0.000001;
4928 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4929 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4930 video_time_usage, vout_time_usage, audio_time_usage,
4931 total_time_usage - tot, total_time_usage);
4932 if (total_time_usage > 0.0)
4933 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4934 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4935 100.0 * video_time_usage / total_time_usage,
4936 100.0 * vout_time_usage / total_time_usage,
4937 100.0 * audio_time_usage / total_time_usage,
4938 100.0 * (total_time_usage - tot) / total_time_usage,
4939 100.0);
4940 if (total_frame_cnt && frame_dropping)
4941 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4942 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4943 total_frame_cnt - drop_frame_cnt,
4944 (total_time_usage > 0.5) ? ((total_frame_cnt -
4945 drop_frame_cnt) / total_time_usage) : 0,
4946 drop_frame_cnt,
4947 100 * drop_frame_cnt / total_frame_cnt,
4948 total_frame_cnt,
4949 (total_time_usage > 0.5) ?
4950 (total_frame_cnt / total_time_usage) : 0);
4953 // time to uninit all, except global stuff:
4954 int uninitialize_parts = INITIALIZED_ALL;
4955 if (opts->fixed_vo)
4956 uninitialize_parts -= INITIALIZED_VO;
4957 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4958 uninitialize_parts -= INITIALIZED_AO;
4959 uninit_player(mpctx, uninitialize_parts);
4961 if (mpctx->set_of_sub_size > 0) {
4962 current_module = "sub_free";
4963 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
4964 sub_free(mpctx->set_of_subtitles[i]);
4965 #ifdef CONFIG_ASS
4966 if (mpctx->set_of_ass_tracks[i])
4967 ass_free_track(mpctx->set_of_ass_tracks[i]);
4968 #endif
4970 mpctx->set_of_sub_size = 0;
4972 mpctx->vo_sub_last = vo_sub = NULL;
4973 mpctx->subdata = NULL;
4974 #ifdef CONFIG_ASS
4975 mpctx->osd->ass_track = NULL;
4976 if (mpctx->ass_library)
4977 ass_clear_fonts(mpctx->ass_library);
4978 #endif
4980 if (!mpctx->stop_play) // In case some goto jumped here...
4981 mpctx->stop_play = PT_NEXT_ENTRY;
4983 int playtree_direction = 1;
4985 if (mpctx->stop_play == PT_NEXT_ENTRY
4986 || mpctx->stop_play == PT_PREV_ENTRY) {
4987 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
4988 != PLAY_TREE_ITER_ENTRY) {
4989 play_tree_iter_free(mpctx->playtree_iter);
4990 mpctx->playtree_iter = NULL;
4992 mpctx->play_tree_step = 1;
4993 } else if (mpctx->stop_play == PT_UP_NEXT ||
4994 mpctx->stop_play == PT_UP_PREV) {
4995 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4996 if (mpctx->playtree_iter) {
4997 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
4998 PLAY_TREE_ITER_ENTRY) {
4999 play_tree_iter_free(mpctx->playtree_iter);
5000 mpctx->playtree_iter = NULL;
5003 } else if (mpctx->stop_play == PT_STOP) {
5004 play_tree_iter_free(mpctx->playtree_iter);
5005 mpctx->playtree_iter = NULL;
5006 } else // NEXT PREV SRC
5007 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5009 while (mpctx->playtree_iter != NULL) {
5010 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5011 playtree_direction);
5012 if (mpctx->filename == NULL) {
5013 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5014 0) != PLAY_TREE_ITER_ENTRY) {
5015 play_tree_iter_free(mpctx->playtree_iter);
5016 mpctx->playtree_iter = NULL;
5019 } else
5020 break;
5023 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5024 if (!mpctx->playtree_iter)
5025 mpctx->filename = NULL;
5026 mpctx->stop_play = 0;
5027 goto play_next_file;
5030 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5032 return 1;
5034 #endif /* DISABLE_MAIN */