cleanup: remove XvMC remains, reformat img_format.c
[mplayer.git] / mplayer.c
blobafc124977642ef7ae37446640f6a45bf39d69277
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"
84 #include "mp_osd.h"
85 #include "libvo/video_out.h"
86 #include "screenshot.h"
88 #include "sub/font_load.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 // sub:
325 char *font_name = NULL;
326 char *sub_font_name = NULL;
327 extern int font_fontconfig;
328 float font_factor = 0.75;
329 float sub_delay = 0;
330 float sub_fps = 0;
331 int subcc_enabled = 0;
332 int suboverlap_enabled = 1;
334 #include "sub/ass_mp.h"
336 char *current_module; // for debugging
339 // ---
341 FILE *edl_fd; // file to write to when in -edlout mode.
342 char *edl_output_filename; // file to put EDL entries in (-edlout)
344 int use_filedir_conf;
345 int use_filename_title;
347 #include "mpcommon.h"
348 #include "command.h"
350 #include "metadata.h"
352 static float get_relative_time(struct MPContext *mpctx)
354 unsigned int new_time = GetTimer();
355 unsigned int delta = new_time - mpctx->last_time;
356 mpctx->last_time = new_time;
357 return delta * 0.000001;
360 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
362 switch (type) {
363 /* check for valid video stream */
364 case META_VIDEO_CODEC:
365 case META_VIDEO_BITRATE:
366 case META_VIDEO_RESOLUTION:
367 if (!mpctx->sh_video)
368 return 0;
369 break;
371 /* check for valid audio stream */
372 case META_AUDIO_CODEC:
373 case META_AUDIO_BITRATE:
374 case META_AUDIO_SAMPLES:
375 if (!mpctx->sh_audio)
376 return 0;
377 break;
379 /* check for valid demuxer */
380 case META_INFO_TITLE:
381 case META_INFO_ARTIST:
382 case META_INFO_ALBUM:
383 case META_INFO_YEAR:
384 case META_INFO_COMMENT:
385 case META_INFO_TRACK:
386 case META_INFO_GENRE:
387 if (!mpctx->demuxer)
388 return 0;
389 break;
391 default:
392 break;
395 return 1;
398 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
400 char **info = mpctx->demuxer->info;
401 int n;
403 if (!info || !tag)
404 return talloc_strdup(NULL, "");
406 for (n = 0; info[2 * n] != NULL; n++)
407 if (!strcasecmp(info[2 * n], tag))
408 break;
410 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
413 char *get_metadata(struct MPContext *mpctx, metadata_t type)
415 sh_audio_t * const sh_audio = mpctx->sh_audio;
416 sh_video_t * const sh_video = mpctx->sh_video;
418 if (!is_valid_metadata_type(mpctx, type))
419 return NULL;
421 switch (type) {
422 case META_NAME:
423 return talloc_strdup(NULL, mp_basename(mpctx->filename));
424 case META_VIDEO_CODEC:
425 if (sh_video->format == 0x10000001)
426 return talloc_strdup(NULL, "mpeg1");
427 else if (sh_video->format == 0x10000002)
428 return talloc_strdup(NULL, "mpeg2");
429 else if (sh_video->format == 0x10000004)
430 return talloc_strdup(NULL, "mpeg4");
431 else if (sh_video->format == 0x10000005)
432 return talloc_strdup(NULL, "h264");
433 else if (sh_video->format >= 0x20202020)
434 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
435 else
436 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
437 case META_VIDEO_BITRATE:
438 return talloc_asprintf(NULL, "%d kbps",
439 (int) (sh_video->i_bps * 8 / 1024));
440 case META_VIDEO_RESOLUTION:
441 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
442 sh_video->disp_h);
443 case META_AUDIO_CODEC:
444 if (sh_audio->codec && sh_audio->codec->name)
445 return talloc_strdup(NULL, sh_audio->codec->name);
446 return talloc_strdup(NULL, "");
447 case META_AUDIO_BITRATE:
448 return talloc_asprintf(NULL, "%d kbps",
449 (int) (sh_audio->i_bps * 8 / 1000));
450 case META_AUDIO_SAMPLES:
451 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
452 sh_audio->channels);
454 /* check for valid demuxer */
455 case META_INFO_TITLE:
456 return get_demuxer_info(mpctx, "Title");
458 case META_INFO_ARTIST:
459 return get_demuxer_info(mpctx, "Artist");
461 case META_INFO_ALBUM:
462 return get_demuxer_info(mpctx, "Album");
464 case META_INFO_YEAR:
465 return get_demuxer_info(mpctx, "Year");
467 case META_INFO_COMMENT:
468 return get_demuxer_info(mpctx, "Comment");
470 case META_INFO_TRACK:
471 return get_demuxer_info(mpctx, "Track");
473 case META_INFO_GENRE:
474 return get_demuxer_info(mpctx, "Genre");
476 default:
477 break;
480 return talloc_strdup(NULL, "");
483 static void print_file_properties(struct MPContext *mpctx, const char *filename)
485 double start_pts = MP_NOPTS_VALUE;
486 double video_start_pts = MP_NOPTS_VALUE;
487 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
488 filename_recode(filename));
489 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
490 mpctx->demuxer->desc->name);
491 if (mpctx->sh_video) {
492 /* Assume FOURCC if all bytes >= 0x20 (' ') */
493 if (mpctx->sh_video->format >= 0x20202020)
494 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
495 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
496 else
497 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
498 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
499 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
500 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
501 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
502 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
503 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
504 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
505 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
506 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
507 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
508 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
509 video_start_pts = ds_get_next_pts(mpctx->d_video);
511 if (mpctx->sh_audio) {
512 /* Assume FOURCC if all bytes >= 0x20 (' ') */
513 if (mpctx->sh_audio->format >= 0x20202020)
514 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
515 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
516 else
517 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
518 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
519 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
520 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
521 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
522 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
523 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
524 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
525 start_pts = ds_get_next_pts(mpctx->d_audio);
527 if (video_start_pts != MP_NOPTS_VALUE) {
528 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
529 (mpctx->sh_video && video_start_pts < start_pts))
530 start_pts = video_start_pts;
532 if (start_pts != MP_NOPTS_VALUE)
533 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
534 else
535 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
536 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
537 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
538 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
539 mpctx->stream->seek
540 && (!mpctx->demuxer || mpctx->demuxer->seekable));
541 if (mpctx->demuxer) {
542 int chapter_count = get_chapter_count(mpctx);
543 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
544 for (int i = 0; i < chapter_count; i++) {
545 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
546 // in milliseconds
547 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
548 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
549 char *name = chapter_name(mpctx, i);
550 if (name) {
551 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
552 name);
553 talloc_free(name);
559 /// step size of mixer changes
560 int volstep = 3;
562 #ifdef CONFIG_DVDNAV
563 static void mp_dvdnav_context_free(MPContext *ctx)
565 if (ctx->nav_smpi)
566 free_mp_image(ctx->nav_smpi);
567 ctx->nav_smpi = NULL;
568 free(ctx->nav_buffer);
569 ctx->nav_buffer = NULL;
570 ctx->nav_start = NULL;
571 ctx->nav_in_size = 0;
573 #endif
575 static void uninit_subs(struct demuxer *demuxer)
577 for (int i = 0; i < MAX_S_STREAMS; i++) {
578 struct sh_sub *sh = demuxer->s_streams[i];
579 if (sh && sh->initialized)
580 sub_uninit(sh);
584 void uninit_player(struct MPContext *mpctx, unsigned int mask)
586 mask &= mpctx->initialized_flags;
588 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
590 if (mask & INITIALIZED_ACODEC) {
591 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
592 current_module = "uninit_acodec";
593 if (mpctx->sh_audio)
594 uninit_audio(mpctx->sh_audio);
595 mpctx->sh_audio = NULL;
596 mpctx->mixer.afilter = NULL;
599 if (mask & INITIALIZED_SUB) {
600 mpctx->initialized_flags &= ~INITIALIZED_SUB;
601 if (mpctx->d_sub->sh)
602 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
605 if (mask & INITIALIZED_VCODEC) {
606 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
607 current_module = "uninit_vcodec";
608 if (mpctx->sh_video)
609 uninit_video(mpctx->sh_video);
610 mpctx->sh_video = NULL;
613 if (mask & INITIALIZED_DEMUXER) {
614 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
615 current_module = "free_demuxer";
616 if (mpctx->num_sources) {
617 mpctx->demuxer = mpctx->sources[0].demuxer;
618 for (int i = 1; i < mpctx->num_sources; i++) {
619 uninit_subs(mpctx->sources[i].demuxer);
620 free_stream(mpctx->sources[i].stream);
621 free_demuxer(mpctx->sources[i].demuxer);
624 talloc_free(mpctx->sources);
625 mpctx->sources = NULL;
626 mpctx->num_sources = 0;
627 talloc_free(mpctx->timeline);
628 mpctx->timeline = NULL;
629 mpctx->num_timeline_parts = 0;
630 talloc_free(mpctx->chapters);
631 mpctx->chapters = NULL;
632 mpctx->num_chapters = 0;
633 mpctx->video_offset = 0;
634 if (mpctx->demuxer) {
635 mpctx->stream = mpctx->demuxer->stream;
636 uninit_subs(mpctx->demuxer);
637 free_demuxer(mpctx->demuxer);
639 mpctx->demuxer = NULL;
642 // kill the cache process:
643 if (mask & INITIALIZED_STREAM) {
644 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
645 current_module = "uninit_stream";
646 if (mpctx->stream)
647 free_stream(mpctx->stream);
648 mpctx->stream = NULL;
651 if (mask & INITIALIZED_VO) {
652 mpctx->initialized_flags &= ~INITIALIZED_VO;
653 current_module = "uninit_vo";
654 vo_destroy(mpctx->video_out);
655 mpctx->video_out = NULL;
656 #ifdef CONFIG_DVDNAV
657 mp_dvdnav_context_free(mpctx);
658 #endif
661 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
662 if (mask & INITIALIZED_GETCH2) {
663 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
664 current_module = "uninit_getch2";
665 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
666 // restore terminal:
667 getch2_disable();
670 if (mask & INITIALIZED_VOBSUB) {
671 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
672 current_module = "uninit_vobsub";
673 if (vo_vobsub)
674 vobsub_close(vo_vobsub);
675 vo_vobsub = NULL;
678 if (mask & INITIALIZED_SPUDEC) {
679 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
680 current_module = "uninit_spudec";
681 spudec_free(vo_spudec);
682 vo_spudec = NULL;
685 if (mask & INITIALIZED_AO) {
686 mpctx->initialized_flags &= ~INITIALIZED_AO;
687 current_module = "uninit_ao";
688 if (mpctx->ao) {
689 mixer_uninit(&mpctx->mixer);
690 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
692 mpctx->ao = NULL;
695 current_module = NULL;
698 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
700 uninit_player(mpctx, INITIALIZED_ALL);
701 #if defined(__MINGW32__) || defined(__CYGWIN__)
702 timeEndPeriod(1);
703 #endif
704 #ifdef CONFIG_X11
705 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
706 #endif
708 current_module = "uninit_input";
709 mp_input_uninit(mpctx->input);
711 #ifdef CONFIG_FREETYPE
712 current_module = "uninit_font";
713 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
714 free_font_desc(mpctx->osd->sub_font);
715 free_font_desc(vo_font);
716 vo_font = NULL;
717 done_freetype();
718 #endif
719 osd_free(mpctx->osd);
721 #ifdef CONFIG_ASS
722 ass_library_done(mpctx->ass_library);
723 mpctx->ass_library = NULL;
724 #endif
726 current_module = "exit_player";
728 if (mpctx->playtree_iter)
729 play_tree_iter_free(mpctx->playtree_iter);
730 mpctx->playtree_iter = NULL;
731 if (mpctx->playtree)
732 play_tree_free(mpctx->playtree, 1);
733 mpctx->playtree = NULL;
735 talloc_free(mpctx->key_fifo);
737 switch (how) {
738 case EXIT_QUIT:
739 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
740 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
741 break;
742 case EXIT_EOF:
743 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
744 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
745 break;
746 case EXIT_ERROR:
747 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
748 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
749 break;
750 default:
751 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
753 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
754 "max framesize was %d bytes\n", max_framesize);
756 // must be last since e.g. mp_msg uses option values
757 // that will be freed by this.
758 if (mpctx->mconfig)
759 m_config_free(mpctx->mconfig);
760 mpctx->mconfig = NULL;
762 talloc_free(mpctx);
764 exit(rc);
767 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
769 exit_player_with_rc(mpctx, how, 1);
772 #ifndef __MINGW32__
773 static void child_sighandler(int x)
775 pid_t pid;
776 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
778 #endif
780 #ifdef CONFIG_CRASH_DEBUG
781 static char *prog_path;
782 static int crash_debug = 0;
783 #endif
785 static void exit_sighandler(int x)
787 static int sig_count = 0;
788 #ifdef CONFIG_CRASH_DEBUG
789 if (!crash_debug || x != SIGTRAP)
790 #endif
791 ++sig_count;
792 if (sig_count == 5) {
793 /* We're crashing bad and can't uninit cleanly :(
794 * by popular request, we make one last (dirty)
795 * effort to restore the user's
796 * terminal. */
797 getch2_disable();
798 exit(1);
800 if (sig_count == 6)
801 exit(1);
802 if (sig_count > 6) {
803 // can't stop :(
804 #ifndef __MINGW32__
805 kill(getpid(), SIGKILL);
806 #endif
808 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
809 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
810 "\nMPlayer interrupted by signal %d in module: %s\n", x,
811 current_module ? current_module : "unknown");
812 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
813 if (sig_count <= 1)
814 switch (x) {
815 case SIGINT:
816 case SIGPIPE:
817 case SIGQUIT:
818 case SIGTERM:
819 case SIGKILL:
820 async_quit_request = 1;
821 return; // killed from keyboard (^C) or killed [-9]
822 case SIGILL:
823 #if CONFIG_RUNTIME_CPUDETECT
824 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
825 #else
826 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
827 #endif
828 case SIGFPE:
829 case SIGSEGV:
830 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
831 default:
832 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
833 #ifdef CONFIG_CRASH_DEBUG
834 if (crash_debug) {
835 int gdb_pid;
836 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
837 gdb_pid = fork();
838 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
839 if (gdb_pid == 0) { // We are the child
840 char spid[20];
841 snprintf(spid, sizeof(spid), "%i", getppid());
842 getch2_disable(); // allow terminal to work properly with gdb
843 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
844 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
845 } else if (gdb_pid < 0)
846 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
847 else
848 waitpid(gdb_pid, NULL, 0);
849 if (x == SIGTRAP)
850 return;
852 #endif
854 getch2_disable();
855 exit(1);
858 #include "cfg-mplayer.h"
860 static int cfg_include(struct m_config *conf, char *filename)
862 return m_config_parse_config_file(conf, filename);
865 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
867 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
869 struct MPOpts *opts = &mpctx->opts;
870 char *conffile;
871 int conffile_fd;
872 if (!(opts->noconfig & 2) &&
873 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
874 exit_player(mpctx, EXIT_NONE);
875 if ((conffile = get_path("")) == NULL)
876 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
877 else {
878 mkdir(conffile, 0777);
879 free(conffile);
880 if ((conffile = get_path("config")) == NULL)
881 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
882 else {
883 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
884 0666)) != -1) {
885 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
886 "Creating config file: %s\n", conffile);
887 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
888 close(conffile_fd);
890 if (!(opts->noconfig & 1) &&
891 m_config_parse_config_file(conf, conffile) < 0)
892 exit_player(mpctx, EXIT_NONE);
893 free(conffile);
898 #define PROFILE_CFG_PROTOCOL "protocol."
900 static void load_per_protocol_config(m_config_t *conf, const char * const file)
902 char *str;
903 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
904 m_profile_t *p;
906 /* does filename actually uses a protocol ? */
907 str = strstr(file, "://");
908 if (!str)
909 return;
911 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
912 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
913 p = m_config_get_profile(conf, protocol);
914 if (p) {
915 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
916 "Loading protocol-related profile '%s'\n", protocol);
917 m_config_set_profile(conf, p);
921 #define PROFILE_CFG_EXTENSION "extension."
923 static void load_per_extension_config(m_config_t *conf, const char * const file)
925 char *str;
926 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
927 m_profile_t *p;
929 /* does filename actually have an extension ? */
930 str = strrchr(file, '.');
931 if (!str)
932 return;
934 sprintf(extension, PROFILE_CFG_EXTENSION);
935 strncat(extension, ++str, 7);
936 p = m_config_get_profile(conf, extension);
937 if (p) {
938 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
939 "Loading extension-related profile '%s'\n", extension);
940 m_config_set_profile(conf, p);
944 #define PROFILE_CFG_VO "vo."
945 #define PROFILE_CFG_AO "ao."
947 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
949 char profile[strlen(cfg) + strlen(out) + 1];
950 m_profile_t *p;
952 sprintf(profile, "%s%s", cfg, out);
953 p = m_config_get_profile(conf, profile);
954 if (p) {
955 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
956 "Loading extension-related profile '%s'\n", profile);
957 m_config_set_profile(conf, p);
962 * Tries to load a config file
963 * @return 0 if file was not found, 1 otherwise
965 static int try_load_config(m_config_t *conf, const char *file)
967 if (!mp_path_exists(file))
968 return 0;
969 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
970 m_config_parse_config_file(conf, file);
971 return 1;
974 static void load_per_file_config(m_config_t *conf, const char * const file)
976 char *confpath;
977 char cfg[MP_PATH_MAX];
978 const char *name;
980 if (strlen(file) > MP_PATH_MAX - 14) {
981 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
982 "can not load file or directory specific config files\n");
983 return;
985 sprintf(cfg, "%s.conf", file);
987 name = mp_basename(cfg);
988 if (use_filedir_conf) {
989 char dircfg[MP_PATH_MAX];
990 strcpy(dircfg, cfg);
991 strcpy(dircfg + (name - cfg), "mplayer.conf");
992 try_load_config(conf, dircfg);
994 if (try_load_config(conf, cfg))
995 return;
998 if ((confpath = get_path(name)) != NULL) {
999 try_load_config(conf, confpath);
1001 free(confpath);
1005 /* When libmpdemux performs a blocking operation (network connection or
1006 * cache filling) if the operation fails we use this function to check
1007 * if it was interrupted by the user.
1008 * The function returns a new value for eof. */
1009 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1011 mp_cmd_t *cmd;
1012 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1013 switch (cmd->id) {
1014 case MP_CMD_QUIT:
1015 exit_player_with_rc(mpctx, EXIT_QUIT,
1016 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1017 case MP_CMD_PLAY_TREE_STEP: {
1018 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1019 mpctx->play_tree_step =
1020 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1021 } break;
1022 case MP_CMD_PLAY_TREE_UP_STEP: {
1023 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1024 } break;
1025 case MP_CMD_PLAY_ALT_SRC_STEP: {
1026 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1027 } break;
1029 mp_cmd_free(cmd);
1031 return stop_play;
1034 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1036 play_tree_add_bpf(entry, bstr(mpctx->filename));
1039 if (!entry) {
1040 entry = mpctx->playtree_iter->tree;
1041 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1042 != PLAY_TREE_ITER_ENTRY)
1043 return PT_NEXT_ENTRY;
1044 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1045 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1046 != PLAY_TREE_ITER_ENTRY)
1047 return PT_NEXT_ENTRY;
1049 play_tree_remove(entry, 1, 1);
1050 return PT_NEXT_SRC;
1052 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1053 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1054 entry = mpctx->playtree_iter->tree;
1055 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1056 != PLAY_TREE_ITER_ENTRY)
1057 return PT_NEXT_ENTRY;
1058 play_tree_remove(entry, 1, 1);
1060 return PT_NEXT_SRC;
1063 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1064 int noerr)
1066 struct MPOpts *opts = &mpctx->opts;
1067 sub_data *subd = NULL;
1068 struct ass_track *asst = NULL;
1069 bool is_native_ass = false;
1071 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1072 return;
1074 #ifdef CONFIG_ASS
1075 if (opts->ass_enabled) {
1076 #ifdef CONFIG_ICONV
1077 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1078 #else
1079 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1080 #endif
1081 is_native_ass = asst;
1082 if (!asst) {
1083 subd = sub_read_file(filename, fps, &mpctx->opts);
1084 if (subd) {
1085 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1086 sub_free(subd);
1087 subd = NULL;
1090 } else
1091 #endif
1092 subd = sub_read_file(filename, fps, &mpctx->opts);
1095 if (!asst && !subd) {
1096 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1097 "Cannot load subtitles: %s\n", filename_recode(filename));
1098 return;
1101 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1102 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1103 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1104 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1105 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1106 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1107 filename_recode(filename));
1108 ++mpctx->set_of_sub_size;
1109 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1110 mpctx->set_of_sub_size, filename_recode(filename));
1113 void init_vo_spudec(struct MPContext *mpctx)
1115 unsigned width, height;
1116 spudec_free(vo_spudec);
1117 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1118 vo_spudec = NULL;
1120 // we currently can't work without video stream
1121 if (!mpctx->sh_video)
1122 return;
1124 if (spudec_ifo) {
1125 unsigned int palette[16];
1126 current_module = "spudec_init_vobsub";
1127 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1128 1, -1, NULL) >= 0)
1129 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1132 width = mpctx->sh_video->disp_w;
1133 height = mpctx->sh_video->disp_h;
1135 #ifdef CONFIG_DVDREAD
1136 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1137 current_module = "spudec_init_dvdread";
1138 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1139 cur_pgc->palette, width, height, NULL, 0);
1141 #endif
1143 #ifdef CONFIG_DVDNAV
1144 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1145 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1146 current_module = "spudec_init_dvdnav";
1147 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1149 #endif
1151 if (vo_spudec == NULL) {
1152 sh_sub_t *sh = mpctx->d_sub->sh;
1153 current_module = "spudec_init_normal";
1154 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1155 sh->extradata_len);
1156 spudec_set_font_factor(vo_spudec, font_factor);
1159 if (vo_spudec != NULL) {
1160 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1161 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1162 mpctx);
1167 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1168 * make it all work is to use the builtin SDL-bootstrap code, which
1169 * will be done automatically by replacing our main() if we include SDL.h.
1171 #if defined(__APPLE__) && defined(CONFIG_SDL)
1172 #ifdef CONFIG_SDL_SDL_H
1173 #include <SDL/SDL.h>
1174 #else
1175 #include <SDL.h>
1176 #endif
1177 #endif
1180 * \brief append a formatted string
1181 * \param buf buffer to print into
1182 * \param pos position of terminating 0 in buf
1183 * \param len maximum number of characters in buf, not including terminating 0
1184 * \param format printf format string
1186 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1188 va_list va;
1189 va_start(va, format);
1190 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1191 va_end(va);
1192 if (*pos >= len) {
1193 buf[len] = 0;
1194 *pos = len;
1199 * \brief append time in the hh:mm:ss.f format
1200 * \param buf buffer to print into
1201 * \param pos position of terminating 0 in buf
1202 * \param len maximum number of characters in buf, not including terminating 0
1203 * \param time time value to convert/append
1205 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1207 int64_t tenths = 10 * time;
1208 int f1 = tenths % 10;
1209 int ss = (tenths / 10) % 60;
1210 int mm = (tenths / 600) % 60;
1211 int hh = tenths / 36000;
1212 if (time < 0) {
1213 saddf(buf, pos, len, "unknown");
1214 return;
1216 if (hh > 0)
1217 saddf(buf, pos, len, "%2d:", hh);
1218 if (hh > 0 || mm > 0)
1219 saddf(buf, pos, len, "%02d:", mm);
1220 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1223 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1225 struct MPOpts *opts = &mpctx->opts;
1226 sh_video_t * const sh_video = mpctx->sh_video;
1228 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1229 a_pos = playing_audio_pts(mpctx);
1230 if (mpctx->sh_audio && sh_video && at_frame) {
1231 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1232 if (mpctx->time_frame > 0)
1233 mpctx->last_av_difference +=
1234 mpctx->time_frame * opts->playback_speed;
1235 if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
1236 mpctx->last_av_difference = MP_NOPTS_VALUE;
1237 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1238 && !mpctx->drop_message_shown) {
1239 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1240 mpctx->drop_message_shown = true;
1243 if (opts->quiet)
1244 return;
1246 int width;
1247 char *line;
1248 unsigned pos = 0;
1249 get_screen_size();
1250 if (screen_width > 0)
1251 width = screen_width;
1252 else
1253 width = 80;
1254 #if defined(__MINGW32__) || defined(__CYGWIN__)
1255 /* Windows command line is broken (MinGW's rxvt works, but we
1256 * should not depend on that). */
1257 width--;
1258 #endif
1259 line = malloc(width + 1); // one additional char for the terminating null
1261 // Audio time
1262 if (mpctx->sh_audio) {
1263 if (a_pos != MP_NOPTS_VALUE)
1264 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1265 else
1266 saddf(line, &pos, width, "A: ??? ");
1267 if (!sh_video && a_pos != MP_NOPTS_VALUE) {
1268 float len = get_time_length(mpctx);
1269 saddf(line, &pos, width, "(");
1270 sadd_hhmmssf(line, &pos, width, a_pos);
1271 saddf(line, &pos, width, ") of %.1f (", len);
1272 sadd_hhmmssf(line, &pos, width, len);
1273 saddf(line, &pos, width, ") ");
1277 // Video time
1278 if (sh_video) {
1279 if (mpctx->video_pts != MP_NOPTS_VALUE)
1280 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1281 else
1282 saddf(line, &pos, width, "V: ??? ", mpctx->video_pts);
1285 // A-V sync
1286 if (mpctx->sh_audio && sh_video) {
1287 if (mpctx->last_av_difference != MP_NOPTS_VALUE)
1288 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1289 mpctx->last_av_difference, mpctx->total_avsync_change);
1290 else
1291 saddf(line, &pos, width, "A-V: ??? ct:%7.3f ",
1292 mpctx->total_avsync_change);
1295 // Video stats
1296 if (sh_video)
1297 saddf(line, &pos, width, "%3d/%3d ",
1298 (int)sh_video->num_frames,
1299 (int)sh_video->num_frames_decoded);
1301 // CPU usage
1302 if (sh_video) {
1303 if (sh_video->timer > 0.5)
1304 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1305 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1306 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1307 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1308 else
1309 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1310 } else if (mpctx->sh_audio) {
1311 if (mpctx->delay > 0.5)
1312 saddf(line, &pos, width, "%4.1f%% ",
1313 100.0 * audio_time_usage / (double)mpctx->delay);
1314 else
1315 saddf(line, &pos, width, "??,?%% ");
1318 // VO stats
1319 if (sh_video)
1320 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1322 #ifdef CONFIG_STREAM_CACHE
1323 // cache stats
1324 if (stream_cache_size > 0)
1325 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1326 #endif
1328 // other
1329 if (opts->playback_speed != 1)
1330 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1332 // end
1333 if (erase_to_end_of_line) {
1334 line[pos] = 0;
1335 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1336 "%s%s\r", line, erase_to_end_of_line);
1337 } else {
1338 memset(&line[pos], ' ', width - pos);
1339 line[width] = 0;
1340 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1342 free(line);
1344 mpctx->status_printed = true;
1347 struct stream_dump_progress {
1348 uint64_t count;
1349 unsigned start_time;
1350 unsigned last_print_time;
1353 static void stream_dump_progress_start(struct stream_dump_progress *p)
1355 p->start_time = p->last_print_time = GetTimerMS();
1356 p->count = 0;
1359 static void stream_dump_progress(struct stream_dump_progress *p,
1360 uint64_t len, stream_t *stream)
1362 p->count += len;
1363 unsigned t = GetTimerMS();
1364 if (t - p->last_print_time < 1000)
1365 return;
1367 uint64_t start = stream->start_pos;
1368 uint64_t end = stream->end_pos;
1369 uint64_t pos = stream->pos;
1371 p->last_print_time = t;
1372 /* TODO: pretty print sizes; ETA */
1373 if (end > start && pos >= start && pos <= end) {
1374 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1375 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1376 p->count, 100.0 * (pos - start) / (end - start));
1377 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1378 } else {
1379 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1380 "dump: %"PRIu64 " bytes written", p->count);
1381 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1385 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1387 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1388 p->count, name);
1392 * \brief build a chain of audio filters that converts the input format
1393 * to the ao's format, taking into account the current playback_speed.
1394 * sh_audio describes the requested input format of the chain.
1395 * ao describes the requested output format of the chain.
1397 static int build_afilter_chain(struct MPContext *mpctx)
1399 struct sh_audio *sh_audio = mpctx->sh_audio;
1400 struct ao *ao = mpctx->ao;
1401 struct MPOpts *opts = &mpctx->opts;
1402 int new_srate;
1403 int result;
1404 if (!sh_audio) {
1405 mpctx->mixer.afilter = NULL;
1406 return 0;
1408 if (af_control_any_rev(sh_audio->afilter,
1409 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1410 &opts->playback_speed))
1411 new_srate = sh_audio->samplerate;
1412 else {
1413 new_srate = sh_audio->samplerate * opts->playback_speed;
1414 if (new_srate != ao->samplerate) {
1415 // limits are taken from libaf/af_resample.c
1416 if (new_srate < 8000)
1417 new_srate = 8000;
1418 if (new_srate > 192000)
1419 new_srate = 192000;
1420 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1423 result = init_audio_filters(sh_audio, new_srate,
1424 &ao->samplerate, &ao->channels, &ao->format);
1425 mpctx->mixer.afilter = sh_audio->afilter;
1426 return result;
1430 typedef struct mp_osd_msg mp_osd_msg_t;
1431 struct mp_osd_msg {
1432 /// Previous message on the stack.
1433 mp_osd_msg_t *prev;
1434 /// Message text.
1435 char *msg;
1436 int id, level, started;
1437 /// Display duration in ms.
1438 unsigned time;
1439 // Show full OSD for duration of message instead of static text ('P' key)
1440 bool show_position;
1443 /// OSD message stack.
1444 static mp_osd_msg_t *osd_msg_stack = NULL;
1447 * \brief Add a message on the OSD message stack
1449 * If a message with the same id is already present in the stack
1450 * it is pulled on top of the stack, otherwise a new message is created.
1453 static void set_osd_msg_va(int id, int level, int time, bool show_position,
1454 const char *fmt, va_list ap)
1456 mp_osd_msg_t *msg, *last = NULL;
1458 // look if the id is already in the stack
1459 for (msg = osd_msg_stack; msg && msg->id != id;
1460 last = msg, msg = msg->prev) ;
1461 // not found: alloc it
1462 if (!msg) {
1463 msg = talloc_zero(NULL, mp_osd_msg_t);
1464 msg->prev = osd_msg_stack;
1465 osd_msg_stack = msg;
1466 } else if (last) { // found, but it's not on top of the stack
1467 last->prev = msg->prev;
1468 msg->prev = osd_msg_stack;
1469 osd_msg_stack = msg;
1471 talloc_free(msg->msg);
1472 // write the msg
1473 msg->msg = talloc_vasprintf(msg, fmt, ap);
1474 // set id and time
1475 msg->id = id;
1476 msg->level = level;
1477 msg->time = time;
1478 msg->show_position = show_position;
1481 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1483 va_list ap;
1484 va_start(ap, fmt);
1485 set_osd_msg_va(id, level, time, false, fmt, ap);
1486 va_end(ap);
1489 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1491 va_list ap;
1492 va_start(ap, fmt);
1493 set_osd_msg_va(id, level, time, false, mp_gtext(fmt), ap);
1494 va_end(ap);
1497 void set_osd_progressmsg(int id, int level, int time, ...)
1499 va_list ap;
1500 va_start(ap, time);
1501 set_osd_msg_va(id, level, time, true, "", ap);
1502 va_end(ap);
1506 * \brief Remove a message from the OSD stack
1508 * This function can be used to get rid of a message right away.
1512 void rm_osd_msg(int id)
1514 mp_osd_msg_t *msg, *last = NULL;
1516 // Search for the msg
1517 for (msg = osd_msg_stack; msg && msg->id != id;
1518 last = msg, msg = msg->prev) ;
1519 if (!msg)
1520 return;
1522 // Detach it from the stack and free it
1523 if (last)
1524 last->prev = msg->prev;
1525 else
1526 osd_msg_stack = msg->prev;
1527 talloc_free(msg);
1531 * \brief Remove all messages from the OSD stack
1535 static void clear_osd_msgs(void)
1537 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1538 while (msg) {
1539 prev = msg->prev;
1540 talloc_free(msg);
1541 msg = prev;
1543 osd_msg_stack = NULL;
1547 * \brief Get the current message from the OSD stack.
1549 * This function decrements the message timer and destroys the old ones.
1550 * The message that should be displayed is returned (if any).
1554 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1556 struct MPOpts *opts = &mpctx->opts;
1557 mp_osd_msg_t *msg, *prev, *last = NULL;
1558 static unsigned last_update = 0;
1559 unsigned now = GetTimerMS();
1560 unsigned diff;
1561 char hidden_dec_done = 0;
1563 if (mpctx->osd_visible) {
1564 // 36000000 means max timed visibility is 1 hour into the future, if
1565 // the difference is greater assume it's wrapped around from below 0
1566 if (mpctx->osd_visible - now > 36000000) {
1567 mpctx->osd_visible = 0;
1568 vo_osd_progbar_type = -1; // disable
1569 vo_osd_changed(OSDTYPE_PROGBAR);
1570 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1573 if (mpctx->osd_show_percentage_until - now > 36000000)
1574 mpctx->osd_show_percentage_until = 0;
1576 if (!last_update)
1577 last_update = now;
1578 diff = now >= last_update ? now - last_update : 0;
1580 last_update = now;
1582 // Look for the first message in the stack with high enough level.
1583 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1584 prev = msg->prev;
1585 if (msg->level > opts->osd_level && hidden_dec_done)
1586 continue;
1587 // The message has a high enough level or it is the first hidden one
1588 // in both cases we decrement the timer or kill it.
1589 if (!msg->started || msg->time > diff) {
1590 if (msg->started)
1591 msg->time -= diff;
1592 else
1593 msg->started = 1;
1594 // display it
1595 if (msg->level <= opts->osd_level)
1596 return msg;
1597 hidden_dec_done = 1;
1598 continue;
1600 // kill the message
1601 talloc_free(msg);
1602 if (last) {
1603 last->prev = prev;
1604 msg = last;
1605 } else {
1606 osd_msg_stack = prev;
1607 msg = NULL;
1610 // Nothing found
1611 return NULL;
1615 * \brief Display the OSD bar.
1617 * Display the OSD bar or fall back on a simple message.
1621 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1622 double min, double max, double val)
1624 struct MPOpts *opts = &mpctx->opts;
1625 if (opts->osd_level < 1)
1626 return;
1628 if (mpctx->sh_video) {
1629 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1630 vo_osd_progbar_type = type;
1631 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1632 vo_osd_changed(OSDTYPE_PROGBAR);
1633 return;
1636 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1637 name, ROUND(100 * (val - min) / (max - min)));
1641 * \brief Display text subtitles on the OSD
1643 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1645 int i;
1646 vo_sub = subs;
1647 vo_osd_changed(OSDTYPE_SUBTITLE);
1648 if (!mpctx->sh_video) {
1649 // reverse order, since newest set_osd_msg is displayed first
1650 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1651 if (!subs || i >= subs->lines || !subs->text[i])
1652 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1653 else {
1654 // HACK: currently display time for each sub line
1655 // except the last is set to 2 seconds.
1656 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1657 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1658 "%s", subs->text[i]);
1665 * \brief Update the OSD message line.
1667 * This function displays the current message on the vo OSD or on the term.
1668 * If the stack is empty and the OSD level is high enough the timer
1669 * is displayed (only on the vo OSD).
1673 static void update_osd_msg(struct MPContext *mpctx)
1675 struct MPOpts *opts = &mpctx->opts;
1676 mp_osd_msg_t *msg;
1677 struct osd_state *osd = mpctx->osd;
1678 char osd_text_timer[128];
1680 if (mpctx->add_osd_seek_info) {
1681 double percentage = get_percent_pos(mpctx);
1682 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1683 if (mpctx->sh_video)
1684 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1685 mpctx->add_osd_seek_info = false;
1688 // Look if we have a msg
1689 if ((msg = get_osd_msg(mpctx)) && !msg->show_position) {
1690 if (strcmp(osd->osd_text, msg->msg)) {
1691 osd_set_text(osd, msg->msg);
1692 if (mpctx->sh_video)
1693 vo_osd_changed(OSDTYPE_OSD);
1694 else if (opts->term_osd)
1695 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1696 msg->msg);
1698 return;
1701 int osdlevel = opts->osd_level;
1702 if (msg && msg->show_position)
1703 osdlevel = 3;
1705 if (mpctx->sh_video) {
1706 // fallback on the timer
1707 if (osdlevel >= 2) {
1708 int len = get_time_length(mpctx);
1709 int percentage = -1;
1710 char percentage_text[10];
1711 char fractions_text[4];
1712 double fpts = get_current_time(mpctx);
1713 int pts = fpts;
1715 if (mpctx->osd_show_percentage_until)
1716 percentage = get_percent_pos(mpctx);
1718 if (percentage >= 0)
1719 snprintf(percentage_text, 9, " (%d%%)", percentage);
1720 else
1721 percentage_text[0] = 0;
1723 if (opts->osd_fractions == 1) {
1724 //print fractions as sub-second timestamp
1725 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1726 (int)((fpts - pts) * 100));
1727 } else if (opts->osd_fractions == 2) {
1728 /* Print fractions by estimating the frame count within the
1729 * second.
1731 * Rounding or cutting off numbers after the decimal point
1732 * causes problems because of float's precision and movies
1733 * whose first frame is not exactly at timestamp 0. Therefore,
1734 * we add 0.2 and cut off at the decimal point, which proved
1735 * to be good heuristic.
1737 double fps = mpctx->sh_video->fps;
1738 if (fps <= 1 || fps > 99)
1739 strcpy(fractions_text, ".??");
1740 else
1741 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1742 (int) ((fpts - pts) * fps + 0.2));
1743 } else {
1744 //do not print fractions
1745 fractions_text[0] = 0;
1748 if (osdlevel == 3)
1749 snprintf(osd_text_timer, sizeof(osd_text_timer),
1750 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1751 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1752 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1753 percentage_text);
1754 else
1755 snprintf(osd_text_timer, sizeof(osd_text_timer),
1756 "%c %02d:%02d:%02d%s%s",
1757 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1758 pts % 60, fractions_text, percentage_text);
1759 } else
1760 osd_text_timer[0] = 0;
1762 if (strcmp(osd->osd_text, osd_text_timer)) {
1763 osd_set_text(osd, osd_text_timer);
1764 vo_osd_changed(OSDTYPE_OSD);
1766 return;
1769 // Clear the term osd line
1770 if (opts->term_osd && osd->osd_text[0]) {
1771 osd->osd_text[0] = 0;
1772 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1777 void reinit_audio_chain(struct MPContext *mpctx)
1779 struct MPOpts *opts = &mpctx->opts;
1780 struct ao *ao;
1781 if (!mpctx->sh_audio) {
1782 uninit_player(mpctx, INITIALIZED_AO);
1783 return;
1785 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1786 current_module = "init_audio_codec";
1787 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1788 goto init_error;
1789 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1792 current_module = "af_preinit";
1793 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1794 mpctx->initialized_flags |= INITIALIZED_AO;
1795 mpctx->ao = ao_create(opts, mpctx->input);
1796 mpctx->ao->samplerate = force_srate;
1797 mpctx->ao->format = opts->audio_output_format;
1799 ao = mpctx->ao;
1801 // first init to detect best values
1802 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1803 // input:
1804 mpctx->sh_audio->samplerate,
1805 // output:
1806 &ao->samplerate, &ao->channels, &ao->format)) {
1807 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1808 "pre-init!\n");
1809 exit_player(mpctx, EXIT_ERROR);
1811 if (!ao->initialized) {
1812 current_module = "ao2_init";
1813 ao->buffersize = opts->ao_buffersize;
1814 ao_init(ao, opts->audio_driver_list);
1815 if (!ao->initialized) {
1816 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1817 "Could not open/initialize audio device -> no sound.\n");
1818 goto init_error;
1820 ao->buffer.start = talloc_new(ao);
1821 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1822 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1823 ao->driver->info->short_name,
1824 ao->samplerate, ao->channels,
1825 af_fmt2str_short(ao->format),
1826 af_fmt2bits(ao->format) / 8);
1827 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1828 ao->driver->info->name, ao->driver->info->author);
1829 if (strlen(ao->driver->info->comment) > 0)
1830 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1831 ao->driver->info->comment);
1834 // init audio filters:
1835 current_module = "af_init";
1836 if (!build_afilter_chain(mpctx)) {
1837 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1838 "Couldn't find matching filter/ao format!\n");
1839 goto init_error;
1841 mpctx->mixer.volstep = volstep;
1842 mpctx->mixer.softvol = opts->softvol;
1843 mpctx->mixer.softvol_max = opts->softvol_max;
1844 mixer_reinit(&mpctx->mixer, ao);
1845 mpctx->syncing_audio = true;
1846 return;
1848 init_error:
1849 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1850 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1851 mpctx->d_audio->id = -2;
1855 // Return pts value corresponding to the end point of audio written to the
1856 // ao so far.
1857 static double written_audio_pts(struct MPContext *mpctx)
1859 sh_audio_t *sh_audio = mpctx->sh_audio;
1860 if (!sh_audio)
1861 return MP_NOPTS_VALUE;
1862 demux_stream_t *d_audio = mpctx->d_audio;
1863 // first calculate the end pts of audio that has been output by decoder
1864 double a_pts = sh_audio->pts;
1865 if (a_pts != MP_NOPTS_VALUE)
1866 // Good, decoder supports new way of calculating audio pts.
1867 // sh_audio->pts is the timestamp of the latest input packet with
1868 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1869 // the amount of bytes the decoder has written after that timestamp.
1870 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1871 else {
1872 // Decoder doesn't support new way of calculating pts (or we're
1873 // being called before it has decoded anything with known timestamp).
1874 // Use the old method of audio pts calculation: take the timestamp
1875 // of last packet with known pts the decoder has read data from,
1876 // and add amount of bytes read after the beginning of that packet
1877 // divided by input bps. This will be inaccurate if the input/output
1878 // ratio is not constant for every audio packet or if it is constant
1879 // but not accurately known in sh_audio->i_bps.
1881 a_pts = d_audio->pts;
1882 if (a_pts == MP_NOPTS_VALUE)
1883 return a_pts;
1885 // ds_tell_pts returns bytes read after last timestamp from
1886 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1887 // it has read but not decoded
1888 if (sh_audio->i_bps)
1889 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1890 (double)sh_audio->i_bps;
1892 // Now a_pts hopefully holds the pts for end of audio from decoder.
1893 // Substract data in buffers between decoder and audio out.
1895 // Decoded but not filtered
1896 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1898 // Data buffered in audio filters, measured in bytes of "missing" output
1899 double buffered_output = af_calc_delay(sh_audio->afilter);
1901 // Data that was ready for ao but was buffered because ao didn't fully
1902 // accept everything to internal buffers yet
1903 buffered_output += mpctx->ao->buffer.len;
1905 // Filters divide audio length by playback_speed, so multiply by it
1906 // to get the length in original units without speedup or slowdown
1907 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1909 return a_pts + mpctx->video_offset;
1912 // Return pts value corresponding to currently playing audio.
1913 double playing_audio_pts(struct MPContext *mpctx)
1915 double pts = written_audio_pts(mpctx);
1916 if (pts == MP_NOPTS_VALUE)
1917 return pts;
1918 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1921 static bool is_av_sub(int type)
1923 return type == 'b' || type == 'p' || type == 'x';
1926 void update_subtitles(struct MPContext *mpctx, double refpts_tl, bool reset)
1928 mpctx->osd->sub_offset = mpctx->video_offset;
1929 struct MPOpts *opts = &mpctx->opts;
1930 struct sh_video *sh_video = mpctx->sh_video;
1931 struct demux_stream *d_sub = mpctx->d_sub;
1932 double refpts_s = refpts_tl - mpctx->osd->sub_offset;
1933 double curpts_s = refpts_s + sub_delay;
1934 unsigned char *packet = NULL;
1935 int len;
1936 struct sh_sub *sh_sub = d_sub->sh;
1937 int type = sh_sub ? sh_sub->type : 'v';
1938 static subtitle subs;
1939 if (reset) {
1940 if (sh_sub)
1941 sub_reset(sh_sub, mpctx->osd);
1942 sub_clear_text(&subs, MP_NOPTS_VALUE);
1943 if (vo_sub)
1944 set_osd_subtitle(mpctx, NULL);
1945 if (vo_spudec) {
1946 spudec_reset(vo_spudec);
1947 vo_osd_changed(OSDTYPE_SPU);
1949 if (is_av_sub(type))
1950 reset_avsub(sh_sub);
1951 return;
1953 // find sub
1954 if (mpctx->subdata) {
1955 if (sub_fps == 0)
1956 sub_fps = sh_video ? sh_video->fps : 25;
1957 current_module = "find_sub";
1958 find_sub(mpctx, mpctx->subdata, curpts_s *
1959 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1960 if (vo_sub)
1961 mpctx->vo_sub_last = vo_sub;
1964 // DVD sub:
1965 if (vobsub_id >= 0 || type == 'v') {
1966 int timestamp;
1967 current_module = "spudec";
1968 /* Get a sub packet from the DVD or a vobsub */
1969 while (1) {
1970 // Vobsub
1971 len = 0;
1972 if (vo_vobsub) {
1973 if (curpts_s >= 0) {
1974 len = vobsub_get_packet(vo_vobsub, curpts_s,
1975 (void **)&packet, &timestamp);
1976 if (len > 0)
1977 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1978 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1979 len, refpts_s, sh_video->timer,
1980 timestamp / 90000.0, timestamp);
1982 } else {
1983 // DVD sub
1984 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1985 if (len > 0) {
1986 // XXX This is wrong, sh_video->pts can be arbitrarily
1987 // much behind demuxing position. Unfortunately using
1988 // d_video->pts which would have been the simplest
1989 // improvement doesn't work because mpeg specific hacks
1990 // in video.c set d_video->pts to 0.
1991 float x = d_sub->pts - refpts_s;
1992 if (x > -20 && x < 20) // prevent missing subs on pts reset
1993 timestamp = 90000 * d_sub->pts;
1994 else
1995 timestamp = 90000 * curpts_s;
1996 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1997 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1998 refpts_s, d_sub->pts, timestamp);
2001 if (len <= 0 || !packet)
2002 break;
2003 // create it only here, since with some broken demuxers we might
2004 // type = v but no DVD sub and we currently do not change the
2005 // "original frame size" ever after init, leading to wrong-sized
2006 // PGS subtitles.
2007 if (!vo_spudec)
2008 vo_spudec = spudec_new(NULL);
2009 if (vo_vobsub || timestamp >= 0)
2010 spudec_assemble(vo_spudec, packet, len, timestamp);
2012 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
2013 if (type == 'd' && !d_sub->demuxer->teletext) {
2014 tt_stream_props tsp = { 0 };
2015 void *ptr = &tsp;
2016 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
2017 VBI_CONTROL_TRUE)
2018 d_sub->demuxer->teletext = ptr;
2020 if (d_sub->non_interleaved)
2021 ds_get_next_pts(d_sub);
2023 while (d_sub->first) {
2024 double subpts_s = ds_get_next_pts(d_sub);
2025 if (subpts_s > curpts_s) {
2026 // Libass handled subs can be fed to it in advance
2027 if (!opts->ass_enabled || !is_text_sub(type))
2028 break;
2029 // Try to avoid demuxing whole file at once
2030 if (d_sub->non_interleaved && subpts_s > curpts_s + 1)
2031 break;
2033 double duration = d_sub->first->duration;
2034 len = ds_get_packet_sub(d_sub, &packet);
2035 if (is_av_sub(type)) {
2036 int ret = decode_avsub(sh_sub, packet, len, subpts_s, duration);
2037 if (ret < 0)
2038 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2039 "subtitle\n");
2040 continue;
2042 if (type == 'm') {
2043 if (len < 2)
2044 continue;
2045 len = FFMIN(len - 2, AV_RB16(packet));
2046 packet += 2;
2048 if (type == 'd') {
2049 if (d_sub->demuxer->teletext) {
2050 uint8_t *p = packet;
2051 p++;
2052 len--;
2053 while (len >= 46) {
2054 int sublen = p[1];
2055 if (p[0] == 2 || p[0] == 3)
2056 teletext_control(d_sub->demuxer->teletext,
2057 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2058 p += sublen + 2;
2059 len -= sublen + 2;
2062 continue;
2064 if (sh_sub && sh_sub->active) {
2065 sub_decode(sh_sub, mpctx->osd, packet, len, subpts_s, duration);
2066 continue;
2068 if (subpts_s != MP_NOPTS_VALUE) {
2069 if (duration < 0)
2070 sub_clear_text(&subs, MP_NOPTS_VALUE);
2071 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2072 int i;
2073 unsigned char *p = packet;
2074 for (i = 0; i < 8 && *p != '\0'; p++)
2075 if (*p == ',')
2076 i++;
2077 if (*p == '\0') /* Broken line? */
2078 continue;
2079 len -= p - packet;
2080 packet = p;
2082 double endpts_s = MP_NOPTS_VALUE;
2083 if (subpts_s != MP_NOPTS_VALUE && duration >= 0)
2084 endpts_s = subpts_s + duration;
2085 sub_add_text(&subs, packet, len, endpts_s);
2086 set_osd_subtitle(mpctx, &subs);
2088 if (d_sub->non_interleaved)
2089 ds_get_next_pts(d_sub);
2091 if (!opts->ass_enabled)
2092 if (sub_clear_text(&subs, curpts_s))
2093 set_osd_subtitle(mpctx, &subs);
2095 if (vo_spudec) {
2096 spudec_heartbeat(vo_spudec, 90000 * curpts_s);
2097 if (spudec_changed(vo_spudec))
2098 vo_osd_changed(OSDTYPE_SPU);
2101 current_module = NULL;
2104 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2106 int page_changed;
2108 if (!demuxer->teletext)
2109 return;
2111 //Also forcing page update when such ioctl is not supported or call error occured
2112 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2113 &page_changed) != VBI_CONTROL_TRUE)
2114 page_changed = 1;
2116 if (!page_changed)
2117 return;
2119 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2120 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2121 vo_osd_teletext_page = NULL;
2122 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2123 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2124 vo_osd_teletext_half = 0;
2125 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2126 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2127 vo_osd_teletext_mode = 0;
2128 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2129 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2130 vo_osd_teletext_format = 0;
2131 vo_osd_changed(OSDTYPE_TELETEXT);
2133 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2136 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2138 struct MPOpts *opts = &mpctx->opts;
2139 // check for frame-drop:
2140 current_module = "check_framedrop";
2141 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2142 static int dropped_frames;
2143 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2144 float d = delay - mpctx->delay;
2145 ++total_frame_cnt;
2146 // we should avoid dropping too many frames in sequence unless we
2147 // are too late. and we allow 100ms A-V delay here:
2148 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2149 && !mpctx->restart_playback) {
2150 ++drop_frame_cnt;
2151 ++dropped_frames;
2152 return frame_dropping;
2153 } else
2154 dropped_frames = 0;
2156 return 0;
2160 #ifdef HAVE_RTC
2161 int rtc_fd = -1;
2162 #endif
2164 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2166 #ifdef HAVE_RTC
2167 if (rtc_fd >= 0) {
2168 // -------- RTC -----------
2169 current_module = "sleep_rtc";
2170 while (time_frame > 0.000) {
2171 unsigned long rtc_ts;
2172 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2173 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2174 "Linux RTC read error: %s\n", strerror(errno));
2175 time_frame -= get_relative_time(mpctx);
2177 } else
2178 #endif
2180 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2181 // unnecessarily high CPU usage
2182 struct MPOpts *opts = &mpctx->opts;
2183 float margin = opts->softsleep ? 0.011 : 0;
2184 current_module = "sleep_timer";
2185 while (time_frame > margin) {
2186 usec_sleep(1000000 * (time_frame - margin));
2187 time_frame -= get_relative_time(mpctx);
2189 if (opts->softsleep) {
2190 current_module = "sleep_soft";
2191 if (time_frame < 0)
2192 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2193 "Warning! Softsleep underflow!\n");
2194 while (time_frame > 0)
2195 time_frame -= get_relative_time(mpctx); // burn the CPU
2198 return time_frame;
2201 static int select_subtitle(MPContext *mpctx)
2203 struct MPOpts *opts = &mpctx->opts;
2204 // find the best sub to use
2205 int id;
2206 int found = 0;
2207 mpctx->global_sub_pos = -1; // no subs by default
2208 if (vobsub_id >= 0) {
2209 // if user asks for a vobsub id, use that first.
2210 id = vobsub_id;
2211 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2212 M_PROPERTY_OK;
2215 if (!found && opts->sub_id >= 0) {
2216 // if user asks for a dvd sub id, use that next.
2217 id = opts->sub_id;
2218 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2219 M_PROPERTY_OK;
2222 if (!found) {
2223 // if there are text subs to use, use those. (autosubs come last here)
2224 id = 0;
2225 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2226 M_PROPERTY_OK;
2229 if (!found && opts->sub_id == -1) {
2230 // finally select subs by language and container hints
2231 if (opts->sub_id == -1)
2232 opts->sub_id =
2233 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2234 opts->sub_lang);
2235 if (opts->sub_id >= 0) {
2236 id = opts->sub_id;
2237 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2238 M_PROPERTY_OK;
2241 return found;
2244 #ifdef CONFIG_DVDNAV
2245 #ifndef FF_B_TYPE
2246 #define FF_B_TYPE 3
2247 #endif
2248 /// store decoded video image
2249 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2250 mp_image_t *from_mpi)
2252 mp_image_t *mpi;
2254 /// Do not store B-frames
2255 if (from_mpi->pict_type == FF_B_TYPE)
2256 return to_mpi;
2258 if (to_mpi &&
2259 to_mpi->w == from_mpi->w &&
2260 to_mpi->h == from_mpi->h &&
2261 to_mpi->imgfmt == from_mpi->imgfmt)
2262 mpi = to_mpi;
2263 else {
2264 if (to_mpi)
2265 free_mp_image(to_mpi);
2266 if (from_mpi->w == 0 || from_mpi->h == 0)
2267 return NULL;
2268 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2271 copy_mpi(mpi, from_mpi);
2272 return mpi;
2275 static void mp_dvdnav_reset_stream(MPContext *ctx)
2277 struct MPOpts *opts = &ctx->opts;
2278 if (ctx->sh_video) {
2279 /// clear video pts
2280 ctx->d_video->pts = 0.0f;
2281 ctx->sh_video->pts = 0.0f;
2282 ctx->sh_video->i_pts = 0.0f;
2283 ctx->sh_video->last_pts = 0.0f;
2284 ctx->sh_video->num_buffered_pts = 0;
2285 ctx->sh_video->num_frames = 0;
2286 ctx->sh_video->num_frames_decoded = 0;
2287 ctx->sh_video->timer = 0.0f;
2288 ctx->sh_video->stream_delay = 0.0f;
2289 ctx->sh_video->timer = 0;
2290 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2293 if (ctx->sh_audio) {
2294 /// free audio packets and reset
2295 ds_free_packs(ctx->d_audio);
2296 audio_delay -= ctx->sh_audio->stream_delay;
2297 ctx->delay = -audio_delay;
2298 ao_reset(ctx->ao);
2299 resync_audio_stream(ctx->sh_audio);
2302 audio_delay = 0.0f;
2303 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2304 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2305 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2306 if (dvdsub_lang_id != opts->sub_id) {
2307 opts->sub_id = dvdsub_lang_id;
2308 select_subtitle(ctx);
2312 /// clear all EOF related flags
2313 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2316 /// Restore last decoded DVDNAV (still frame)
2317 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2318 int *in_size,
2319 unsigned char **start,
2320 mp_image_t *decoded_frame)
2322 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2323 return decoded_frame;
2325 /// a change occurred in dvdnav stream
2326 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2327 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2328 mp_dvdnav_context_free(mpctx);
2329 mp_dvdnav_reset_stream(mpctx);
2330 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2331 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2334 if (*in_size < 0) {
2335 float len;
2337 /// Display still frame, if any
2338 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2339 decoded_frame = mpctx->nav_smpi;
2341 /// increment video frame : continue playing after still frame
2342 len = get_time_length(mpctx);
2343 if (mpctx->sh_video->pts >= len &&
2344 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2345 mp_dvdnav_skip_still(mpctx->stream);
2346 mp_dvdnav_skip_wait(mpctx->stream);
2348 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2350 if (mpctx->nav_buffer) {
2351 *start = mpctx->nav_start;
2352 *in_size = mpctx->nav_in_size;
2353 if (mpctx->nav_start)
2354 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2358 return decoded_frame;
2361 /// Save last decoded DVDNAV (still frame)
2362 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2363 unsigned char *start,
2364 mp_image_t *decoded_frame)
2366 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2367 return;
2369 free(mpctx->nav_buffer);
2370 mpctx->nav_buffer = NULL;
2371 mpctx->nav_start = NULL;
2372 mpctx->nav_in_size = -1;
2374 if (in_size > 0)
2375 mpctx->nav_buffer = malloc(in_size);
2376 if (mpctx->nav_buffer) {
2377 mpctx->nav_start = start;
2378 mpctx->nav_in_size = in_size;
2379 memcpy(mpctx->nav_buffer, start, in_size);
2382 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2383 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2385 #endif /* CONFIG_DVDNAV */
2387 /* Modify video timing to match the audio timeline. There are two main
2388 * reasons this is needed. First, video and audio can start from different
2389 * positions at beginning of file or after a seek (MPlayer starts both
2390 * immediately even if they have different pts). Second, the file can have
2391 * audio timestamps that are inconsistent with the duration of the audio
2392 * packets, for example two consecutive timestamp values differing by
2393 * one second but only a packet with enough samples for half a second
2394 * of playback between them.
2396 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2398 current_module = "av_sync";
2400 if (!mpctx->sh_audio || mpctx->syncing_audio)
2401 return;
2403 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2404 double v_pts = mpctx->sh_video->pts;
2405 double av_delay = a_pts - v_pts;
2406 // Try to sync vo_flip() so it will *finish* at given time
2407 av_delay += mpctx->last_vo_flip_duration;
2408 av_delay -= audio_delay; // This much pts difference is desired
2410 double change = av_delay * 0.1;
2411 double max_change = default_max_pts_correction >= 0 ?
2412 default_max_pts_correction : frame_time * 0.1;
2413 if (change < -max_change)
2414 change = -max_change;
2415 else if (change > max_change)
2416 change = max_change;
2417 mpctx->delay += change;
2418 mpctx->total_avsync_change += change;
2421 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2422 double pts)
2424 if (mpctx->paused)
2425 return 0;
2426 struct ao *ao = mpctx->ao;
2427 double bps = ao->bps / mpctx->opts.playback_speed;
2428 ao->pts = pts;
2429 // hack used by some mpeg-writing AOs
2430 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2431 mpctx->delay) * 90000.0;
2432 int played = ao_play(mpctx->ao, data, len, flags);
2433 if (played > 0) {
2434 mpctx->delay += played / bps;
2435 // Keep correct pts for remaining data - could be used to flush
2436 // remaining buffer when closing ao.
2437 ao->pts += played / bps;
2439 return played;
2442 #define ASYNC_PLAY_DONE -3
2443 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2445 struct ao *ao = mpctx->ao;
2446 struct MPOpts *opts = &mpctx->opts;
2447 sh_audio_t * const sh_audio = mpctx->sh_audio;
2448 int res;
2450 // Timing info may not be set without
2451 res = decode_audio(sh_audio, &ao->buffer, 1);
2452 if (res < 0)
2453 return res;
2455 int bytes;
2456 bool did_retry = false;
2457 double written_pts;
2458 double bps = ao->bps / opts->playback_speed;
2459 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2460 mpctx->hrseek_active = false;
2461 while (1) {
2462 written_pts = written_audio_pts(mpctx);
2463 double ptsdiff;
2464 if (hrseek)
2465 ptsdiff = written_pts - mpctx->hrseek_pts;
2466 else
2467 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2468 - audio_delay;
2469 bytes = ptsdiff * bps;
2470 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2472 // ogg demuxers give packets without timing
2473 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2474 if (!did_retry) {
2475 // Try to read more data to see packets that have pts
2476 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2477 if (res < 0)
2478 return res;
2479 did_retry = true;
2480 continue;
2482 bytes = 0;
2485 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2486 bytes = 0;
2488 if (bytes > 0)
2489 break;
2491 mpctx->syncing_audio = false;
2492 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2493 int res = decode_audio(sh_audio, &ao->buffer, a);
2494 bytes += ao->buffer.len;
2495 if (bytes >= 0) {
2496 memmove(ao->buffer.start,
2497 ao->buffer.start + ao->buffer.len - bytes, bytes);
2498 ao->buffer.len = bytes;
2499 if (res < 0)
2500 return res;
2501 return decode_audio(sh_audio, &ao->buffer, playsize);
2503 ao->buffer.len = 0;
2504 if (res < 0)
2505 return res;
2507 if (hrseek)
2508 // Don't add silence in audio-only case even if position is too late
2509 return 0;
2510 int fillbyte = 0;
2511 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2512 fillbyte = 0x80;
2513 if (bytes >= playsize) {
2514 /* This case could fall back to the one below with
2515 * bytes = playsize, but then silence would keep accumulating
2516 * in a_out_buffer if the AO accepts less data than it asks for
2517 * in playsize. */
2518 char *p = malloc(playsize);
2519 memset(p, fillbyte, playsize);
2520 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2521 free(p);
2522 return ASYNC_PLAY_DONE;
2524 mpctx->syncing_audio = false;
2525 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2526 return decode_audio(sh_audio, &ao->buffer, playsize);
2529 static int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
2531 struct MPOpts *opts = &mpctx->opts;
2532 struct ao *ao = mpctx->ao;
2533 unsigned int t;
2534 double tt;
2535 int playsize;
2536 int playflags = 0;
2537 bool audio_eof = false;
2538 bool partial_fill = false;
2539 sh_audio_t * const sh_audio = mpctx->sh_audio;
2540 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2541 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2543 current_module = "play_audio";
2545 // hack used by some mpeg-writing AOs
2546 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2547 mpctx->delay) * 90000.0;
2549 if (mpctx->paused)
2550 playsize = 1; // just initialize things (audio pts at least)
2551 else
2552 playsize = ao_get_space(ao);
2554 // Fill buffer if needed:
2555 current_module = "decode_audio";
2556 t = GetTimer();
2558 // Coming here with hrseek_active still set means audio-only
2559 if (!mpctx->sh_video)
2560 mpctx->syncing_audio = false;
2561 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2562 mpctx->syncing_audio = false;
2563 mpctx->hrseek_active = false;
2566 int res;
2567 if (mpctx->syncing_audio || mpctx->hrseek_active)
2568 res = audio_start_sync(mpctx, playsize);
2569 else
2570 res = decode_audio(sh_audio, &ao->buffer, playsize);
2571 if (res < 0) { // EOF, error or format change
2572 if (res == -2) {
2573 /* The format change isn't handled too gracefully. A more precise
2574 * implementation would require draining buffered old-format audio
2575 * while displaying video, then doing the output format switch.
2577 uninit_player(mpctx, INITIALIZED_AO);
2578 reinit_audio_chain(mpctx);
2579 return -1;
2580 } else if (res == ASYNC_PLAY_DONE)
2581 return 0;
2582 else if (mpctx->d_audio->eof)
2583 audio_eof = true;
2585 t = GetTimer() - t;
2586 tt = t * 0.000001f;
2587 audio_time_usage += tt;
2588 if (endpts != MP_NOPTS_VALUE && modifiable_audio_format) {
2589 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2590 * ao->bps / opts->playback_speed;
2591 if (playsize > bytes) {
2592 playsize = FFMAX(bytes, 0);
2593 playflags |= AOPLAY_FINAL_CHUNK;
2594 audio_eof = true;
2595 partial_fill = true;
2599 assert(ao->buffer.len % unitsize == 0);
2600 if (playsize > ao->buffer.len) {
2601 partial_fill = true;
2602 playsize = ao->buffer.len;
2603 if (audio_eof)
2604 playflags |= AOPLAY_FINAL_CHUNK;
2606 playsize -= playsize % unitsize;
2607 if (!playsize)
2608 return partial_fill && audio_eof ? -2 : -partial_fill;
2610 // play audio:
2611 current_module = "play_audio";
2613 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2614 written_audio_pts(mpctx));
2615 assert(played % unitsize == 0);
2616 ao->buffer_playable_size = playsize - played;
2618 if (played > 0) {
2619 ao->buffer.len -= played;
2620 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2621 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2622 // Sanity check to avoid hanging in case current ao doesn't output
2623 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2624 return -2;
2627 return -partial_fill;
2630 int reinit_video_chain(struct MPContext *mpctx)
2632 struct MPOpts *opts = &mpctx->opts;
2633 sh_video_t * const sh_video = mpctx->sh_video;
2634 if (!sh_video) {
2635 uninit_player(mpctx, INITIALIZED_VO);
2636 return 0;
2638 double ar = -1.0;
2639 //================== Init VIDEO (codec & libvo) ==========================
2640 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2641 current_module = "preinit_libvo";
2643 //shouldn't we set dvideo->id=-2 when we fail?
2644 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2645 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2646 mpctx->key_fifo,
2647 mpctx->input))) {
2648 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2649 "the selected video_out (-vo) device.\n");
2650 goto err_out;
2652 mpctx->initialized_flags |= INITIALIZED_VO;
2655 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2656 &ar) != STREAM_UNSUPPORTED)
2657 mpctx->sh_video->stream_aspect = ar;
2658 current_module = "init_video_filters";
2660 char *vf_arg[] = {
2661 "_oldargs_", (char *)mpctx->video_out, NULL
2663 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2666 #ifdef CONFIG_ASS
2667 if (opts->ass_enabled) {
2668 int i;
2669 int insert = 1;
2670 if (opts->vf_settings)
2671 for (i = 0; opts->vf_settings[i].name; ++i)
2672 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2673 insert = 0;
2674 break;
2676 if (insert) {
2677 extern vf_info_t vf_info_ass;
2678 const vf_info_t *libass_vfs[] = {
2679 &vf_info_ass, NULL
2681 char *vf_arg[] = {
2682 "auto", "1", NULL
2684 int retcode = 0;
2685 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2686 sh_video->vfilter,
2687 "ass", vf_arg,
2688 &retcode);
2689 if (vf_ass)
2690 sh_video->vfilter = vf_ass;
2691 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2692 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2693 else
2694 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2695 "ASS: cannot add video filter\n");
2698 #endif
2700 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2702 #ifdef CONFIG_ASS
2703 if (opts->ass_enabled)
2704 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2705 mpctx->ass_library);
2706 #endif
2708 current_module = "init_video_codec";
2710 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2712 if (!sh_video->initialized) {
2713 if (!opts->fixed_vo)
2714 uninit_player(mpctx, INITIALIZED_VO);
2715 goto err_out;
2718 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2720 if (sh_video->codec)
2721 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2722 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2724 sh_video->last_pts = MP_NOPTS_VALUE;
2725 sh_video->num_buffered_pts = 0;
2726 sh_video->next_frame_time = 0;
2727 mpctx->restart_playback = true;
2728 mpctx->delay = 0;
2730 if (opts->auto_quality > 0) {
2731 // Auto quality option enabled
2732 output_quality = get_video_quality_max(sh_video);
2733 if (opts->auto_quality > output_quality)
2734 opts->auto_quality = output_quality;
2735 else
2736 output_quality = opts->auto_quality;
2737 mp_msg(MSGT_CPLAYER, MSGL_V,
2738 "AutoQ: setting quality to %d.\n", output_quality);
2739 set_video_quality(sh_video, output_quality);
2742 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2744 current_module = "init_vo";
2746 return 1;
2748 err_out:
2749 mpctx->sh_video = mpctx->d_video->sh = NULL;
2750 return 0;
2753 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2755 struct sh_video *sh_video = mpctx->sh_video;
2756 double frame_time = 0;
2757 struct vo *video_out = mpctx->video_out;
2758 while (1) {
2759 current_module = "filter_video";
2760 // In nocorrect-pts mode there is no way to properly time these frames
2761 if (vo_get_buffered_frame(video_out, 0) >= 0)
2762 break;
2763 if (vf_output_queued_frame(sh_video->vfilter))
2764 break;
2765 unsigned char *packet = NULL;
2766 frame_time = sh_video->next_frame_time;
2767 if (mpctx->restart_playback)
2768 frame_time = 0;
2769 int in_size = 0;
2770 while (!in_size)
2771 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2772 &packet, force_fps);
2773 if (in_size < 0) {
2774 #ifdef CONFIG_DVDNAV
2775 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2776 if (mp_dvdnav_is_eof(mpctx->stream))
2777 return -1;
2778 if (mpctx->d_video)
2779 mpctx->d_video->eof = 0;
2780 if (mpctx->d_audio)
2781 mpctx->d_audio->eof = 0;
2782 mpctx->stream->eof = 0;
2783 } else
2784 #endif
2785 return -1;
2787 if (in_size > max_framesize)
2788 max_framesize = in_size;
2789 sh_video->timer += frame_time;
2790 if (mpctx->sh_audio)
2791 mpctx->delay -= frame_time;
2792 // video_read_frame can change fps (e.g. for ASF video)
2793 vo_fps = sh_video->fps;
2794 int framedrop_type = check_framedrop(mpctx, frame_time);
2795 current_module = "decode video";
2797 void *decoded_frame;
2798 #ifdef CONFIG_DVDNAV
2799 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2800 if (in_size >= 0 && !decoded_frame)
2801 #endif
2802 decoded_frame = decode_video(sh_video, sh_video->ds->current, packet,
2803 in_size, framedrop_type, sh_video->pts);
2804 #ifdef CONFIG_DVDNAV
2805 // Save last still frame for future display
2806 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2807 #endif
2808 if (decoded_frame) {
2809 current_module = "filter video";
2810 filter_video(sh_video, decoded_frame, sh_video->pts);
2812 break;
2814 return frame_time;
2817 static void determine_frame_pts(struct MPContext *mpctx)
2819 struct sh_video *sh_video = mpctx->sh_video;
2820 struct MPOpts *opts = &mpctx->opts;
2822 if (opts->user_pts_assoc_mode)
2823 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2824 else if (sh_video->pts_assoc_mode == 0) {
2825 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2826 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2827 sh_video->pts_assoc_mode = 1;
2828 else
2829 sh_video->pts_assoc_mode = 2;
2830 } else {
2831 int probcount1 = sh_video->num_reordered_pts_problems;
2832 int probcount2 = sh_video->num_sorted_pts_problems;
2833 if (sh_video->pts_assoc_mode == 2) {
2834 int tmp = probcount1;
2835 probcount1 = probcount2;
2836 probcount2 = tmp;
2838 if (probcount1 >= probcount2 * 1.5 + 2) {
2839 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2840 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2841 "%d.\n", sh_video->pts_assoc_mode);
2844 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2845 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2848 static double update_video(struct MPContext *mpctx)
2850 struct sh_video *sh_video = mpctx->sh_video;
2851 struct vo *video_out = mpctx->video_out;
2852 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2853 mpctx->osd); // hack for vf_expand
2854 if (!mpctx->opts.correct_pts)
2855 return update_video_nocorrect_pts(mpctx);
2857 double pts;
2859 while (1) {
2860 current_module = "filter_video";
2861 if (vo_get_buffered_frame(video_out, false) >= 0)
2862 break;
2863 // XXX Time used in this call is not counted in any performance
2864 // timer now
2865 if (vf_output_queued_frame(sh_video->vfilter))
2866 break;
2867 int in_size = 0;
2868 unsigned char *buf = NULL;
2869 pts = MP_NOPTS_VALUE;
2870 struct demux_packet *pkt;
2871 while (1) {
2872 pkt = ds_get_packet2(mpctx->d_video, false);
2873 if (!pkt || pkt->len)
2874 break;
2875 /* Packets with size 0 are assumed to not correspond to frames,
2876 * but to indicate the absence of a frame in formats like AVI
2877 * that must have packets at fixed timecode intervals. */
2879 if (pkt) {
2880 in_size = pkt->len;
2881 buf = pkt->buffer;
2882 pts = pkt->pts;
2884 if (pts != MP_NOPTS_VALUE)
2885 pts += mpctx->video_offset;
2886 if (in_size > max_framesize)
2887 max_framesize = in_size;
2888 current_module = "decode video";
2889 if (pts >= mpctx->hrseek_pts - .005)
2890 mpctx->hrseek_framedrop = false;
2891 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2892 check_framedrop(mpctx, sh_video->frametime);
2893 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2894 framedrop_type, pts);
2895 if (decoded_frame) {
2896 determine_frame_pts(mpctx);
2897 current_module = "filter video";
2898 filter_video(sh_video, decoded_frame, sh_video->pts);
2899 } else if (!pkt) {
2900 if (vo_get_buffered_frame(video_out, true) < 0)
2901 return -1;
2903 break;
2906 if (!video_out->frame_loaded)
2907 return 0;
2909 pts = video_out->next_pts;
2910 if (pts == MP_NOPTS_VALUE) {
2911 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2912 // Try to use decoder pts from before filters
2913 pts = sh_video->pts;
2914 if (pts == MP_NOPTS_VALUE)
2915 pts = sh_video->last_pts;
2917 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2918 vo_skip_frame(video_out);
2919 return 0;
2921 mpctx->hrseek_active = false;
2922 sh_video->pts = pts;
2923 if (sh_video->last_pts == MP_NOPTS_VALUE)
2924 sh_video->last_pts = sh_video->pts;
2925 else if (sh_video->last_pts > sh_video->pts) {
2926 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2927 sh_video->pts, sh_video->last_pts);
2928 /* If the difference in pts is small treat it as jitter around the
2929 * right value (possibly caused by incorrect timestamp ordering) and
2930 * just show this frame immediately after the last one.
2931 * Treat bigger differences as timestamp resets and start counting
2932 * timing of later frames from the position of this one. */
2933 if (sh_video->last_pts - sh_video->pts > 0.5)
2934 sh_video->last_pts = sh_video->pts;
2935 else
2936 sh_video->pts = sh_video->last_pts;
2938 double frame_time = sh_video->pts - sh_video->last_pts;
2939 sh_video->last_pts = sh_video->pts;
2940 sh_video->timer += frame_time;
2941 if (mpctx->sh_audio)
2942 mpctx->delay -= frame_time;
2943 return frame_time;
2946 static int get_cache_fill(struct MPContext *mpctx)
2948 #ifdef CONFIG_STREAM_CACHE
2949 if (stream_cache_size > 0)
2950 return cache_fill_status(mpctx->stream);
2951 #endif
2952 return -1;
2955 static void update_pause_message(struct MPContext *mpctx)
2957 struct MPOpts *opts = &mpctx->opts;
2959 if (opts->quiet)
2960 return;
2962 int cache_fill = get_cache_fill(mpctx);
2963 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2965 if (!mpctx->status_printed && !cache_changed)
2966 return;
2968 char *msg = mp_gtext(" ===== PAUSE =====");
2969 char *tmpmem = NULL;
2970 if (cache_fill >= 0)
2971 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
2973 if (opts->term_osd && !mpctx->sh_video) {
2974 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
2975 update_osd_msg(mpctx);
2976 } else {
2977 if (mpctx->status_printed)
2978 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
2979 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
2982 mpctx->paused_cache_fill = cache_fill;
2983 mpctx->status_printed = false;
2985 talloc_free(tmpmem);
2988 void pause_player(struct MPContext *mpctx)
2990 if (mpctx->paused)
2991 return;
2992 mpctx->paused = 1;
2993 mpctx->step_frames = 0;
2994 mpctx->time_frame -= get_relative_time(mpctx);
2995 mpctx->osd_function = OSD_PAUSE;
2997 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2998 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3000 if (mpctx->ao && mpctx->sh_audio)
3001 ao_pause(mpctx->ao); // pause audio, keep data if possible
3003 mpctx->paused_cache_fill = get_cache_fill(mpctx);
3004 mpctx->status_printed = true;
3005 update_pause_message(mpctx);
3007 if (!mpctx->opts.quiet)
3008 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
3011 void unpause_player(struct MPContext *mpctx)
3013 if (!mpctx->paused)
3014 return;
3015 mpctx->paused = 0;
3016 if (!mpctx->step_frames)
3017 mpctx->osd_function = OSD_PLAY;
3019 if (mpctx->ao && mpctx->sh_audio)
3020 ao_resume(mpctx->ao);
3021 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3022 && !mpctx->step_frames)
3023 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3024 (void)get_relative_time(mpctx); // ignore time that passed during pause
3027 static int redraw_osd(struct MPContext *mpctx)
3029 struct sh_video *sh_video = mpctx->sh_video;
3030 struct vf_instance *vf = sh_video->vfilter;
3031 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3032 return -1;
3033 if (vo_redraw_frame(mpctx->video_out) < 0)
3034 return -1;
3035 mpctx->osd->pts = mpctx->video_pts - mpctx->osd->sub_offset;
3036 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3037 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3038 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3039 vo_flip_page(mpctx->video_out, 0, -1);
3040 return 0;
3043 void add_step_frame(struct MPContext *mpctx)
3045 mpctx->step_frames++;
3046 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3047 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3048 unpause_player(mpctx);
3051 static void seek_reset(struct MPContext *mpctx, bool reset_ao, bool reset_ac)
3053 if (mpctx->sh_video) {
3054 current_module = "seek_video_reset";
3055 resync_video_stream(mpctx->sh_video);
3056 mpctx->sh_video->timer = 0;
3057 vo_seek_reset(mpctx->video_out);
3058 mpctx->sh_video->timer = 0;
3059 mpctx->sh_video->num_buffered_pts = 0;
3060 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3061 mpctx->delay = 0;
3062 mpctx->time_frame = 0;
3063 // Not all demuxers set d_video->pts during seek, so this value
3064 // (which is used by at least vobsub code below) may be completely
3065 // wrong (probably 0).
3066 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3067 mpctx->video_pts = mpctx->sh_video->pts;
3068 update_subtitles(mpctx, mpctx->sh_video->pts, true);
3069 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3072 if (mpctx->sh_audio && reset_ac) {
3073 current_module = "seek_audio_reset";
3074 resync_audio_stream(mpctx->sh_audio);
3075 if (reset_ao)
3076 ao_reset(mpctx->ao);
3077 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3078 mpctx->sh_audio->a_buffer_len = 0;
3079 if (!mpctx->sh_video)
3080 update_subtitles(mpctx, mpctx->sh_audio->pts, true);
3083 if (vo_vobsub && mpctx->sh_video) {
3084 current_module = "seek_vobsub_reset";
3085 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3088 mpctx->restart_playback = true;
3089 mpctx->hrseek_active = false;
3090 mpctx->hrseek_framedrop = false;
3091 mpctx->total_avsync_change = 0;
3092 audio_time_usage = 0;
3093 video_time_usage = 0;
3094 vout_time_usage = 0;
3095 drop_frame_cnt = 0;
3097 current_module = NULL;
3100 static bool timeline_set_part(struct MPContext *mpctx, int i)
3102 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3103 struct timeline_part *n = mpctx->timeline + i;
3104 mpctx->timeline_part = i;
3105 mpctx->video_offset = n->start - n->source_start;
3106 if (n->source == p->source)
3107 return false;
3108 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3109 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3110 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3111 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3112 mpctx->stop_play = orig_stop_play;
3113 mpctx->demuxer = n->source->demuxer;
3114 mpctx->d_video = mpctx->demuxer->video;
3115 mpctx->d_audio = mpctx->demuxer->audio;
3116 mpctx->d_sub = mpctx->demuxer->sub;
3117 mpctx->sh_video = mpctx->d_video->sh;
3118 mpctx->sh_audio = mpctx->d_audio->sh;
3119 return true;
3122 // Given pts, switch playback to the corresponding part.
3123 // Return offset within that part.
3124 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3125 bool *need_reset)
3127 if (pts < 0)
3128 pts = 0;
3129 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3130 struct timeline_part *p = mpctx->timeline + i;
3131 if (pts < (p + 1)->start) {
3132 *need_reset = timeline_set_part(mpctx, i);
3133 return pts - p->start + p->source_start;
3136 return -1;
3140 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3141 static int seek(MPContext *mpctx, struct seek_params seek,
3142 bool timeline_fallthrough)
3144 struct MPOpts *opts = &mpctx->opts;
3146 current_module = "seek";
3147 if (mpctx->stop_play == AT_END_OF_FILE)
3148 mpctx->stop_play = KEEP_PLAYING;
3149 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3150 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3151 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3152 || opts->hr_seek > 0 || seek.exact > 0;
3153 if (seek.type == MPSEEK_FACTOR
3154 || seek.type == MPSEEK_ABSOLUTE
3155 && seek.amount < mpctx->last_chapter_pts
3156 || seek.amount < 0)
3157 mpctx->last_chapter_seek = -2;
3158 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3159 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3160 seek.type = MPSEEK_ABSOLUTE;
3162 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3163 && seek.type == MPSEEK_RELATIVE) {
3164 seek.type = MPSEEK_ABSOLUTE;
3165 seek.direction = seek.amount > 0 ? 1 : -1;
3166 seek.amount += get_current_time(mpctx);
3169 /* At least the liba52 decoder wants to read from the input stream
3170 * during initialization, so reinit must be done after the demux_seek()
3171 * call that clears possible stream EOF. */
3172 bool need_reset = false;
3173 double demuxer_amount = seek.amount;
3174 if (mpctx->timeline) {
3175 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3176 &need_reset);
3177 if (demuxer_amount == -1) {
3178 mpctx->stop_play = AT_END_OF_FILE;
3179 // Clear audio from current position
3180 if (mpctx->sh_audio && !timeline_fallthrough) {
3181 ao_reset(mpctx->ao);
3182 mpctx->sh_audio->a_buffer_len = 0;
3184 return -1;
3187 if (need_reset) {
3188 reinit_video_chain(mpctx);
3189 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos},
3190 mpctx);
3193 int demuxer_style = 0;
3194 switch (seek.type) {
3195 case MPSEEK_FACTOR:
3196 demuxer_style |= SEEK_FACTOR; // fallthrough
3197 case MPSEEK_ABSOLUTE:
3198 demuxer_style |= SEEK_ABSOLUTE;
3200 if (hr_seek || seek.direction < 0)
3201 demuxer_style |= SEEK_BACKWARD;
3202 else if (seek.direction > 0)
3203 demuxer_style |= SEEK_FORWARD;
3205 if (hr_seek)
3206 demuxer_amount -= opts->hr_seek_demuxer_offset;
3207 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3208 demuxer_style);
3209 if (seekresult == 0) {
3210 if (need_reset) {
3211 reinit_audio_chain(mpctx);
3212 seek_reset(mpctx, !timeline_fallthrough, false);
3214 return -1;
3217 if (need_reset)
3218 reinit_audio_chain(mpctx);
3219 /* If we just reinitialized audio it doesn't need to be reset,
3220 * and resetting could lose audio some decoders produce during init. */
3221 seek_reset(mpctx, !timeline_fallthrough, !need_reset);
3223 /* Use the target time as "current position" for further relative
3224 * seeks etc until a new video frame has been decoded */
3225 if (seek.type == MPSEEK_ABSOLUTE) {
3226 mpctx->video_pts = seek.amount;
3227 mpctx->last_seek_pts = seek.amount;
3228 } else
3229 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3231 if (hr_seek) {
3232 mpctx->hrseek_active = true;
3233 mpctx->hrseek_framedrop = true;
3234 mpctx->hrseek_pts = seek.amount;
3237 mpctx->start_timestamp = GetTimerMS();
3239 return 0;
3242 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3243 int exact)
3245 struct seek_params *seek = &mpctx->seek;
3246 switch (type) {
3247 case MPSEEK_RELATIVE:
3248 if (seek->type == MPSEEK_FACTOR)
3249 return; // Well... not common enough to bother doing better
3250 seek->amount += amount;
3251 seek->exact = FFMAX(seek->exact, exact);
3252 if (seek->type == MPSEEK_NONE)
3253 seek->exact = exact;
3254 if (seek->type == MPSEEK_ABSOLUTE)
3255 return;
3256 if (seek->amount == 0) {
3257 *seek = (struct seek_params){ 0 };
3258 return;
3260 seek->type = MPSEEK_RELATIVE;
3261 return;
3262 case MPSEEK_ABSOLUTE:
3263 case MPSEEK_FACTOR:
3264 *seek = (struct seek_params) {
3265 .type = type,
3266 .amount = amount,
3267 .exact = exact,
3269 return;
3270 case MPSEEK_NONE:
3271 *seek = (struct seek_params){ 0 };
3272 return;
3274 abort();
3278 double get_time_length(struct MPContext *mpctx)
3280 if (mpctx->timeline)
3281 return mpctx->timeline[mpctx->num_timeline_parts].start;
3283 struct demuxer *demuxer = mpctx->demuxer;
3284 double get_time_ans;
3285 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3286 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3287 (void *) &get_time_ans) > 0)
3288 return get_time_ans;
3290 struct sh_video *sh_video = mpctx->d_video->sh;
3291 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3292 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3293 return (double) (demuxer->movi_end - demuxer->movi_start) /
3294 (sh_video->i_bps + sh_audio->i_bps);
3295 if (sh_video && sh_video->i_bps)
3296 return (double) (demuxer->movi_end - demuxer->movi_start) /
3297 sh_video->i_bps;
3298 if (sh_audio && sh_audio->i_bps)
3299 return (double) (demuxer->movi_end - demuxer->movi_start) /
3300 sh_audio->i_bps;
3301 return 0;
3304 /* If there are timestamps from stream level then use those (for example
3305 * DVDs can have consistent times there while the MPEG-level timestamps
3306 * reset). */
3307 double get_current_time(struct MPContext *mpctx)
3309 struct demuxer *demuxer = mpctx->demuxer;
3310 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3311 return demuxer->stream_pts;
3312 if (mpctx->sh_video) {
3313 double pts = mpctx->video_pts;
3314 if (pts != MP_NOPTS_VALUE)
3315 return pts;
3317 double apts = playing_audio_pts(mpctx);
3318 if (apts != MP_NOPTS_VALUE)
3319 return apts;
3320 return mpctx->last_seek_pts;
3323 int get_percent_pos(struct MPContext *mpctx)
3325 struct demuxer *demuxer = mpctx->demuxer;
3326 int ans = 0;
3327 if (mpctx->timeline)
3328 ans = get_current_time(mpctx) * 100 /
3329 mpctx->timeline[mpctx->num_timeline_parts].start;
3330 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3332 else {
3333 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3334 off_t pos = demuxer->filepos > 0 ?
3335 demuxer->filepos : stream_tell(demuxer->stream);
3336 if (len > 0)
3337 ans = (pos - demuxer->movi_start) / len;
3338 else
3339 ans = 0;
3341 if (ans < 0)
3342 ans = 0;
3343 if (ans > 100)
3344 ans = 100;
3345 return ans;
3348 // -2 is no chapters, -1 is before first chapter
3349 int get_current_chapter(struct MPContext *mpctx)
3351 double current_pts = get_current_time(mpctx);
3352 if (!mpctx->chapters)
3353 return FFMAX(mpctx->last_chapter_seek,
3354 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3356 int i;
3357 for (i = 1; i < mpctx->num_chapters; i++)
3358 if (current_pts < mpctx->chapters[i].start)
3359 break;
3360 return FFMAX(mpctx->last_chapter_seek, i - 1);
3363 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3365 char *name = chapter_name(mpctx, chapter);
3366 if (name) {
3367 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3368 } else {
3369 int chapter_count = get_chapter_count(mpctx);
3370 if (chapter_count <= 0)
3371 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3372 else
3373 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3374 chapter_count);
3376 return name;
3379 // returns NULL if chapter name unavailable
3380 char *chapter_name(struct MPContext *mpctx, int chapter)
3382 if (!mpctx->chapters)
3383 return demuxer_chapter_name(mpctx->demuxer, chapter);
3384 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3387 // returns the start of the chapter in seconds
3388 double chapter_start_time(struct MPContext *mpctx, int chapter)
3390 if (!mpctx->chapters)
3391 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3392 return mpctx->chapters[chapter].start;
3395 int get_chapter_count(struct MPContext *mpctx)
3397 if (!mpctx->chapters)
3398 return demuxer_chapter_count(mpctx->demuxer);
3399 return mpctx->num_chapters;
3402 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3404 mpctx->last_chapter_seek = -2;
3405 if (!mpctx->chapters) {
3406 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3407 if (res >= 0) {
3408 if (*seek_pts == -1)
3409 seek_reset(mpctx, true, true);
3410 else {
3411 mpctx->last_chapter_seek = res;
3412 mpctx->last_chapter_pts = *seek_pts;
3415 return res;
3418 if (chapter >= mpctx->num_chapters)
3419 return -1;
3420 if (chapter < 0)
3421 chapter = 0;
3422 *seek_pts = mpctx->chapters[chapter].start;
3423 mpctx->last_chapter_seek = chapter;
3424 mpctx->last_chapter_pts = *seek_pts;
3425 return chapter;
3429 static void run_playloop(struct MPContext *mpctx)
3431 struct MPOpts *opts = &mpctx->opts;
3432 bool full_audio_buffers = false;
3433 bool audio_left = false, video_left = false;
3434 double endpts = end_at.type == END_AT_TIME ? end_at.pos : MP_NOPTS_VALUE;
3435 bool end_is_chapter = false;
3436 double sleeptime = WAKEUP_PERIOD;
3437 bool was_restart = mpctx->restart_playback;
3439 if (mpctx->timeline) {
3440 double end = mpctx->timeline[mpctx->timeline_part + 1].start;
3441 if (endpts == MP_NOPTS_VALUE || end < endpts) {
3442 endpts = end;
3443 end_is_chapter = true;
3447 if (opts->chapterrange[1] > 0) {
3448 int cur_chapter = get_current_chapter(mpctx);
3449 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3450 mpctx->stop_play = PT_NEXT_ENTRY;
3453 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3454 mpctx->sh_audio = mpctx->d_audio->sh;
3455 mpctx->sh_audio->ds = mpctx->d_audio;
3456 reinit_audio_chain(mpctx);
3459 if (mpctx->step_frames && !mpctx->sh_video) {
3460 mpctx->step_frames = 0;
3461 pause_player(mpctx);
3464 if (mpctx->sh_audio && !mpctx->restart_playback && !mpctx->ao->untimed) {
3465 int status = fill_audio_out_buffers(mpctx, endpts);
3466 full_audio_buffers = status >= 0;
3467 // Not at audio stream EOF yet
3468 audio_left = status > -2;
3471 double buffered_audio = -1;
3472 while (mpctx->sh_video) { // never loops, for "break;" only
3473 struct vo *vo = mpctx->video_out;
3474 vo_pts = mpctx->sh_video->timer * 90000.0;
3475 vo_fps = mpctx->sh_video->fps;
3477 video_left = vo->hasframe || vo->frame_loaded;
3478 if (!vo->frame_loaded && (!mpctx->paused || mpctx->restart_playback)) {
3479 double frame_time = update_video(mpctx);
3480 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3481 if (mpctx->sh_video->vf_initialized < 0) {
3482 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3483 "\nFATAL: Could not initialize video filters (-vf) "
3484 "or video output (-vo).\n");
3485 mpctx->stop_play = PT_NEXT_ENTRY;
3486 return;
3488 video_left = frame_time >= 0;
3489 if (video_left && !mpctx->restart_playback) {
3490 mpctx->time_frame += frame_time / opts->playback_speed;
3491 adjust_sync(mpctx, frame_time);
3495 if (endpts != MP_NOPTS_VALUE)
3496 video_left &= mpctx->sh_video->pts < endpts;
3498 // ================================================================
3500 current_module = "vo_check_events";
3501 vo_check_events(vo);
3503 #ifdef CONFIG_X11
3504 if (stop_xscreensaver) {
3505 current_module = "stop_xscreensaver";
3506 xscreensaver_heartbeat(mpctx->x11_state);
3508 #endif
3509 if (heartbeat_cmd) {
3510 static unsigned last_heartbeat;
3511 unsigned now = GetTimerMS();
3512 if (now - last_heartbeat > 30000) {
3513 last_heartbeat = now;
3514 system(heartbeat_cmd);
3518 if (!video_left || (mpctx->paused && !mpctx->restart_playback))
3519 break;
3520 if (!vo->frame_loaded) {
3521 sleeptime = 0;
3522 break;
3525 mpctx->time_frame -= get_relative_time(mpctx);
3526 if (full_audio_buffers && !mpctx->restart_playback) {
3527 buffered_audio = ao_get_delay(mpctx->ao);
3528 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", buffered_audio);
3530 if (opts->autosync) {
3531 /* Smooth reported playback position from AO by averaging
3532 * it with the value expected based on previus value and
3533 * time elapsed since then. May help smooth video timing
3534 * with audio output that have inaccurate position reporting.
3535 * This is badly implemented; the behavior of the smoothing
3536 * now undesirably depends on how often this code runs
3537 * (mainly depends on video frame rate). */
3538 float predicted = (mpctx->delay / opts->playback_speed +
3539 mpctx->time_frame);
3540 float difference = buffered_audio - predicted;
3541 buffered_audio = predicted + difference / opts->autosync;
3544 mpctx->time_frame = (buffered_audio -
3545 mpctx->delay / opts->playback_speed);
3546 } else {
3547 /* If we're more than 200 ms behind the right playback
3548 * position, don't try to speed up display of following
3549 * frames to catch up; continue with default speed from
3550 * the current frame instead.
3551 * If benchmark is set always output frames immediately
3552 * without sleeping.
3554 if (mpctx->time_frame < -0.2 || opts->benchmark)
3555 mpctx->time_frame = 0;
3558 double vsleep = mpctx->time_frame - vo->flip_queue_offset;
3559 if (vsleep > 0.050) {
3560 sleeptime = FFMIN(sleeptime, vsleep - 0.040);
3561 break;
3563 sleeptime = 0;
3565 //=================== FLIP PAGE (VIDEO BLT): ======================
3567 current_module = "flip_page";
3568 vo_new_frame_imminent(vo);
3569 struct sh_video *sh_video = mpctx->sh_video;
3570 mpctx->video_pts = sh_video->pts;
3571 update_subtitles(mpctx, sh_video->pts, false);
3572 update_teletext(sh_video, mpctx->demuxer, 0);
3573 update_osd_msg(mpctx);
3574 struct vf_instance *vf = sh_video->vfilter;
3575 mpctx->osd->pts = mpctx->video_pts - mpctx->osd->sub_offset;
3576 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3577 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3578 vo_osd_changed(0);
3580 mpctx->time_frame -= get_relative_time(mpctx);
3581 mpctx->time_frame -= vo->flip_queue_offset;
3582 float aq_sleep_time = mpctx->time_frame;
3583 if (mpctx->time_frame > 0.001
3584 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3585 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3586 mpctx->time_frame += vo->flip_queue_offset;
3588 unsigned int t2 = GetTimer();
3589 /* Playing with playback speed it's possible to get pathological
3590 * cases with mpctx->time_frame negative enough to cause an
3591 * overflow in pts_us calculation, thus the FFMAX. */
3592 double time_frame = FFMAX(mpctx->time_frame, -1);
3593 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3594 int duration = -1;
3595 double pts2 = vo->next_pts2;
3596 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts &&
3597 !mpctx->restart_playback) {
3598 // expected A/V sync correction is ignored
3599 double diff = (pts2 - mpctx->video_pts);
3600 diff /= opts->playback_speed;
3601 if (mpctx->time_frame < 0)
3602 diff += mpctx->time_frame;
3603 if (diff < 0)
3604 diff = 0;
3605 if (diff > 10)
3606 diff = 10;
3607 duration = diff * 1e6;
3609 vo_flip_page(vo, pts_us | 1, duration);
3611 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3612 vout_time_usage += mpctx->last_vo_flip_duration;
3613 if (vo->driver->flip_page_timed) {
3614 // No need to adjust sync based on flip speed
3615 mpctx->last_vo_flip_duration = 0;
3616 // For print_status - VO call finishing early is OK for sync
3617 mpctx->time_frame -= get_relative_time(mpctx);
3619 if (mpctx->restart_playback) {
3620 mpctx->syncing_audio = true;
3621 if (mpctx->sh_audio)
3622 fill_audio_out_buffers(mpctx, endpts);
3623 mpctx->restart_playback = false;
3624 mpctx->time_frame = 0;
3625 get_relative_time(mpctx);
3627 print_status(mpctx, MP_NOPTS_VALUE, true);
3628 screenshot_flip(mpctx);
3630 if (opts->auto_quality > 0) {
3631 current_module = "autoq";
3632 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3633 ++output_quality;
3634 else if (output_quality > 1 && aq_sleep_time < 0)
3635 --output_quality;
3636 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3637 output_quality = 0;
3638 set_video_quality(mpctx->sh_video, output_quality);
3641 if (play_n_frames >= 0) {
3642 --play_n_frames;
3643 if (play_n_frames <= 0)
3644 mpctx->stop_play = PT_NEXT_ENTRY;
3646 if (mpctx->step_frames > 0) {
3647 mpctx->step_frames--;
3648 if (mpctx->step_frames == 0)
3649 pause_player(mpctx);
3651 break;
3652 } // video
3654 #ifdef CONFIG_DVDNAV
3655 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3656 nav_highlight_t hl;
3657 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3658 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3659 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3660 vo_osd_changed(OSDTYPE_DVDNAV);
3661 } else {
3662 osd_set_nav_box(0, 0, 0, 0);
3663 vo_osd_changed(OSDTYPE_DVDNAV);
3664 vo_osd_changed(OSDTYPE_SPU);
3667 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3668 double ar = -1.0;
3669 if (mpctx->sh_video &&
3670 stream_control(mpctx->demuxer->stream,
3671 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3672 != STREAM_UNSUPPORTED)
3673 mpctx->sh_video->stream_aspect = ar;
3676 #endif
3678 if (mpctx->sh_audio && (mpctx->restart_playback ? !video_left :
3679 mpctx->ao->untimed && (mpctx->delay <= 0 ||
3680 !video_left))) {
3681 int status = fill_audio_out_buffers(mpctx, endpts);
3682 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3683 // Not at audio stream EOF yet
3684 audio_left = status > -2;
3686 if (!video_left)
3687 mpctx->restart_playback = false;
3688 if (mpctx->sh_audio && buffered_audio == -1)
3689 buffered_audio = mpctx->paused ? 0 : ao_get_delay(mpctx->ao);
3691 update_osd_msg(mpctx);
3692 if (mpctx->paused)
3693 update_pause_message(mpctx);
3694 if (!video_left && (!mpctx->paused || was_restart)) {
3695 double a_pos = 0;
3696 if (mpctx->sh_audio) {
3697 a_pos = (written_audio_pts(mpctx) -
3698 mpctx->opts.playback_speed * buffered_audio);
3700 print_status(mpctx, a_pos, false);
3702 if (!mpctx->sh_video)
3703 update_subtitles(mpctx, a_pos, false);
3706 /* It's possible for the user to simultaneously switch both audio
3707 * and video streams to "disabled" at runtime. Handle this by waiting
3708 * rather than immediately stopping playback due to EOF.
3710 * When all audio has been written to output driver, stay in the
3711 * main loop handling commands until it has been mostly consumed,
3712 * except in the gapless case, where the next file will be started
3713 * while audio from the current one still remains to be played.
3715 * We want this check to trigger if we seeked to this position,
3716 * but not if we paused at it with audio possibly still buffered in
3717 * the AO. There's currently no working way to check buffered audio
3718 * inside AO while paused. Thus the "was_restart" check below, which
3719 * should trigger after seek only, when we know there's no audio
3720 * buffered.
3722 if ((mpctx->sh_audio || mpctx->sh_video) && !audio_left && !video_left
3723 && (opts->gapless_audio || buffered_audio < 0.05)
3724 && (!mpctx->paused || was_restart)) {
3725 if (end_is_chapter) {
3726 seek(mpctx, (struct seek_params){
3727 .type = MPSEEK_ABSOLUTE,
3728 .amount = mpctx->timeline[mpctx->timeline_part+1].start
3729 }, true);
3730 } else
3731 mpctx->stop_play = AT_END_OF_FILE;
3732 } else if (!mpctx->stop_play) {
3733 double audio_sleep = 9;
3734 if (mpctx->sh_audio && !mpctx->paused) {
3735 if (mpctx->ao->untimed) {
3736 if (!video_left)
3737 audio_sleep = 0;
3738 } else if (full_audio_buffers) {
3739 audio_sleep = buffered_audio - 0.050;
3740 // Keep extra safety margin if the buffers are large
3741 if (audio_sleep > 0.100)
3742 audio_sleep = FFMAX(audio_sleep - 0.200, 0.100);
3743 else
3744 audio_sleep = FFMAX(audio_sleep, 0.020);
3745 } else
3746 audio_sleep = 0.020;
3748 sleeptime = FFMIN(sleeptime, audio_sleep);
3749 if (sleeptime > 0) {
3750 if (!mpctx->sh_video)
3751 goto novideo;
3752 int hack = vo_osd_changed(0);
3753 vo_osd_changed(hack);
3754 if (hack || mpctx->video_out->want_redraw) {
3755 if (redraw_osd(mpctx) < 0) {
3756 if (mpctx->paused && video_left)
3757 add_step_frame(mpctx);
3758 else
3759 goto novideo;
3760 } else
3761 vo_osd_changed(0);
3762 } else {
3763 novideo:
3764 mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
3769 //================= Keyboard events, SEEKing ====================
3771 current_module = "key_events";
3773 mp_cmd_t *cmd;
3774 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3775 /* Allow running consecutive seek commands to combine them,
3776 * but execute the seek before running other commands.
3777 * If the user seeks continuously (keeps arrow key down)
3778 * try to finish showing a frame from one location before doing
3779 * another seek (which could lead to unchanging display). */
3780 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3781 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3782 && GetTimerMS() - mpctx->start_timestamp < 300)
3783 break;
3784 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3785 run_command(mpctx, cmd);
3786 mp_cmd_free(cmd);
3787 if (mpctx->stop_play)
3788 break;
3791 // handle -sstep
3792 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3793 mpctx->osd_function = OSD_FFW;
3794 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3797 /* Looping. */
3798 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3799 mpctx->stop_play == PT_NEXT_ENTRY)) {
3800 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3802 if (opts->loop_times > 1)
3803 opts->loop_times--;
3804 else if (opts->loop_times == 1)
3805 opts->loop_times = -1;
3806 play_n_frames = play_n_frames_mf;
3807 mpctx->stop_play = 0;
3808 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3811 if (mpctx->seek.type) {
3812 seek(mpctx, mpctx->seek, false);
3813 mpctx->seek = (struct seek_params){ 0 };
3818 static int read_keys(void *ctx, int fd)
3820 if (getch2(ctx))
3821 return MP_INPUT_NOTHING;
3822 return MP_INPUT_DEAD;
3825 static bool attachment_is_font(struct demux_attachment *att)
3827 if (!att->name || !att->type || !att->data || !att->data_size)
3828 return false;
3829 // match against MIME types
3830 if (strcmp(att->type, "application/x-truetype-font") == 0
3831 || strcmp(att->type, "application/x-font") == 0)
3832 return true;
3833 // fallback: match against file extension
3834 if (strlen(att->name) > 4) {
3835 char *ext = att->name + strlen(att->name) - 4;
3836 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3837 || strcasecmp(ext, ".otf") == 0)
3838 return true;
3840 return false;
3843 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3845 if (audio_id == -1)
3846 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3847 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3848 demuxer_switch_audio(demuxer, audio_id);
3849 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3850 demuxer->audio->id = -2;
3851 demuxer->audio->sh = NULL;
3853 return demuxer->audio->id;
3856 static void print_version(const char *name)
3858 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3860 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3861 GetCpuCaps(&gCpuCaps);
3862 #if ARCH_X86
3863 mp_msg(MSGT_CPLAYER, MSGL_V,
3864 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3865 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3866 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3867 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3868 #if CONFIG_RUNTIME_CPUDETECT
3869 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3870 #else
3871 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3872 if (HAVE_MMX)
3873 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3874 if (HAVE_MMX2)
3875 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3876 if (HAVE_AMD3DNOW)
3877 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3878 if (HAVE_AMD3DNOWEXT)
3879 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3880 if (HAVE_SSE)
3881 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3882 if (HAVE_SSE2)
3883 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3884 if (HAVE_SSSE3)
3885 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3886 if (HAVE_CMOV)
3887 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3888 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3889 #endif /* CONFIG_RUNTIME_CPUDETECT */
3890 #endif /* ARCH_X86 */
3891 print_libav_versions();
3894 #ifdef PTW32_STATIC_LIB
3895 static void detach_ptw32(void)
3897 pthread_win32_thread_detach_np();
3898 pthread_win32_process_detach_np();
3900 #endif
3902 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3903 * file for some tools to link against. */
3904 #ifndef DISABLE_MAIN
3905 int main(int argc, char *argv[])
3907 #ifdef PTW32_STATIC_LIB
3908 pthread_win32_process_attach_np();
3909 pthread_win32_thread_attach_np();
3910 atexit(detach_ptw32);
3911 #endif
3912 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3913 || !strcmp(argv[1], "--leak-report")))
3914 talloc_enable_leak_report();
3916 #ifdef __MINGW32__
3917 mp_get_converted_argv(&argc, &argv);
3918 #endif
3920 char *mem_ptr;
3922 // movie info:
3924 /* Flag indicating whether MPlayer should exit without playing anything. */
3925 int opt_exit = 0;
3926 int i;
3928 struct MPContext *mpctx = talloc(NULL, MPContext);
3929 *mpctx = (struct MPContext){
3930 .osd_function = OSD_PLAY,
3931 .begin_skip = MP_NOPTS_VALUE,
3932 .play_tree_step = 1,
3933 .global_sub_pos = -1,
3934 .set_of_sub_pos = -1,
3935 .file_format = DEMUXER_TYPE_UNKNOWN,
3936 .last_dvb_step = 1,
3937 .paused_cache_fill = -1,
3940 InitTimer();
3941 srand(GetTimerMS());
3943 mp_msg_init();
3944 init_libav();
3946 #ifdef CONFIG_X11
3947 mpctx->x11_state = vo_x11_init_state();
3948 #endif
3949 struct MPOpts *opts = &mpctx->opts;
3950 set_default_mplayer_options(opts);
3951 // Create the config context and register the options
3952 mpctx->mconfig = m_config_new(opts, cfg_include);
3953 m_config_register_options(mpctx->mconfig, mplayer_opts);
3954 m_config_register_options(mpctx->mconfig, common_opts);
3955 mp_input_register_options(mpctx->mconfig);
3956 m_config_initialize(mpctx->mconfig, opts);
3958 // Preparse the command line
3959 m_config_preparse_command_line(mpctx->mconfig, argc, argv, &verbose);
3961 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3962 set_path_env();
3963 #endif
3965 #ifdef CONFIG_TV
3966 stream_tv_defaults.immediate = 1;
3967 #endif
3969 parse_cfgfiles(mpctx, mpctx->mconfig);
3971 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3972 if (mpctx->playtree == NULL)
3973 opt_exit = 1;
3974 else {
3975 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3976 if (mpctx->playtree) {
3977 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3978 mpctx->mconfig);
3979 if (mpctx->playtree_iter) {
3980 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3981 PLAY_TREE_ITER_ENTRY) {
3982 play_tree_iter_free(mpctx->playtree_iter);
3983 mpctx->playtree_iter = NULL;
3985 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3991 print_version("MPlayer2");
3993 #if defined(__MINGW32__) || defined(__CYGWIN__)
3995 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3996 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3997 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3998 if (kernel32) {
3999 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
4000 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
4002 if (setDEP)
4003 setDEP(3);
4004 if (setDllDir)
4005 setDllDir("");
4007 // stop Windows from showing all kinds of annoying error dialogs
4008 SetErrorMode(0x8003);
4009 // request 1ms timer resolution
4010 timeBeginPeriod(1);
4011 #endif
4013 #ifdef CONFIG_PRIORITY
4014 set_priority();
4015 #endif
4017 if (opts->video_driver_list &&
4018 strcmp(opts->video_driver_list[0], "help") == 0) {
4019 list_video_out();
4020 opt_exit = 1;
4023 if (opts->audio_driver_list &&
4024 strcmp(opts->audio_driver_list[0], "help") == 0) {
4025 list_audio_out();
4026 opt_exit = 1;
4029 /* Check codecs.conf. */
4030 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4031 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4032 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4033 if (!parse_codec_cfg(NULL))
4034 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4035 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4036 "Using built-in default codecs.conf.\n");
4039 free(mem_ptr); // release the buffer created by get_path()
4042 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4043 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4044 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4045 list_codecs(1);
4046 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4047 opt_exit = 1;
4049 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4050 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4051 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4052 list_codecs(0);
4053 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4054 opt_exit = 1;
4056 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4057 vfm_help();
4058 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4059 opt_exit = 1;
4061 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4062 afm_help();
4063 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4064 opt_exit = 1;
4066 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4067 af_help();
4068 printf("\n");
4069 opt_exit = 1;
4071 #ifdef CONFIG_X11
4072 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4073 fstype_help();
4074 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4075 opt_exit = 1;
4077 #endif
4078 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4079 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4080 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4081 demuxer_help();
4082 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4083 opt_exit = 1;
4085 if (opts->list_properties) {
4086 property_print_help();
4087 opt_exit = 1;
4090 if (opt_exit)
4091 exit_player(mpctx, EXIT_NONE);
4093 if (!mpctx->filename && !opts->player_idle_mode) {
4094 // no file/vcd/dvd -> show HELP:
4095 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4096 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4099 /* Display what configure line was used */
4100 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4102 // Many users forget to include command line in bugreports...
4103 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4104 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4105 for (i = 1; i < argc; i++)
4106 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4107 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4110 //------ load global data first ------
4112 mpctx->osd = osd_create();
4114 // check font
4115 #ifdef CONFIG_FREETYPE
4116 init_freetype();
4117 #endif
4118 #ifdef CONFIG_FONTCONFIG
4119 if (font_fontconfig <= 0) {
4120 #endif
4121 #ifdef CONFIG_BITMAP_FONT
4122 if (font_name) {
4123 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4124 if (!vo_font)
4125 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4126 filename_recode(font_name));
4127 } else {
4128 // try default:
4129 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4130 font_factor, verbose > 1);
4131 free(mem_ptr); // release the buffer created by get_path()
4132 if (!vo_font)
4133 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4134 font_factor, verbose > 1);
4136 if (sub_font_name)
4137 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4138 verbose > 1);
4139 else
4140 mpctx->osd->sub_font = vo_font;
4141 #endif
4142 #ifdef CONFIG_FONTCONFIG
4144 #endif
4146 #ifdef CONFIG_ASS
4147 mpctx->ass_library = mp_ass_init(opts);
4148 mpctx->osd->ass_library = mpctx->ass_library;
4149 #endif
4151 #ifdef HAVE_RTC
4152 if (opts->rtc) {
4153 char *rtc_device = opts->rtc_device;
4154 // seteuid(0); /* Can't hurt to try to get root here */
4155 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4156 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4157 "(it should be readable by the user.)\n",
4158 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4159 else {
4160 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4162 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4163 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4164 "ioctl (rtc_irqp_set %lu): %s\n",
4165 irqp, strerror(errno));
4166 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4167 close(rtc_fd);
4168 rtc_fd = -1;
4169 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4170 /* variable only by the root */
4171 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4172 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4173 close(rtc_fd);
4174 rtc_fd = -1;
4175 } else
4176 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4177 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4180 if (rtc_fd < 0)
4181 #endif /* HAVE_RTC */
4182 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4183 opts->softsleep ? "software" : timer_name);
4185 #ifdef HAVE_TERMCAP
4186 load_termcap(NULL); // load key-codes
4187 #endif
4189 // ========== Init keyboard FIFO (connection to libvo) ============
4191 // Init input system
4192 current_module = "init_input";
4193 mpctx->input = mp_input_init(&opts->input);
4194 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4195 if (slave_mode)
4196 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4197 else if (opts->consolecontrols)
4198 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4199 // Set the libstream interrupt callback
4200 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4202 current_module = NULL;
4204 /// Catch signals
4205 #ifndef __MINGW32__
4206 signal(SIGCHLD, child_sighandler);
4207 #endif
4209 #ifdef CONFIG_CRASH_DEBUG
4210 prog_path = argv[0];
4211 #endif
4212 //========= Catch terminate signals: ================
4213 // terminate requests:
4214 signal(SIGTERM, exit_sighandler); // kill
4215 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4217 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4219 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4220 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4221 #ifdef CONFIG_SIGHANDLER
4222 // fatal errors:
4223 signal(SIGBUS, exit_sighandler); // bus error
4224 signal(SIGSEGV, exit_sighandler); // segfault
4225 signal(SIGILL, exit_sighandler); // illegal instruction
4226 signal(SIGFPE, exit_sighandler); // floating point exc.
4227 signal(SIGABRT, exit_sighandler); // abort()
4228 #ifdef CONFIG_CRASH_DEBUG
4229 if (crash_debug)
4230 signal(SIGTRAP, exit_sighandler);
4231 #endif
4232 #endif
4234 // ***************** Now, let's see the per-file stuff ******************
4236 play_next_file:
4238 // init global sub numbers
4239 mpctx->global_sub_size = 0;
4240 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4242 if (mpctx->filename) {
4243 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4244 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4245 load_per_file_config(mpctx->mconfig, mpctx->filename);
4248 if (opts->video_driver_list)
4249 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4250 opts->video_driver_list[0]);
4251 if (opts->audio_driver_list)
4252 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4253 opts->audio_driver_list[0]);
4255 // We must enable getch2 here to be able to interrupt network connection
4256 // or cache filling
4257 if (opts->consolecontrols && !slave_mode) {
4258 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4259 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4260 "WARNING: getch2_init called twice!\n");
4261 else
4262 getch2_enable(); // prepare stdin for hotkeys...
4263 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4264 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4267 // ================= idle loop (STOP state) =========================
4268 while (opts->player_idle_mode && !mpctx->filename) {
4269 uninit_player(mpctx, INITIALIZED_AO | INITIALIZED_VO);
4270 play_tree_t *entry = NULL;
4271 mp_cmd_t *cmd;
4272 while (!(cmd = mp_input_get_cmd(mpctx->input, WAKEUP_PERIOD * 1000,
4273 false)));
4274 switch (cmd->id) {
4275 case MP_CMD_LOADFILE:
4276 // prepare a tree entry with the new filename
4277 entry = play_tree_new();
4278 play_tree_add_file(entry, cmd->args[0].v.s);
4279 // The entry is added to the main playtree after the switch().
4280 break;
4281 case MP_CMD_LOADLIST:
4282 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4283 break;
4284 case MP_CMD_QUIT:
4285 exit_player_with_rc(mpctx, EXIT_QUIT,
4286 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4287 break;
4288 case MP_CMD_VO_FULLSCREEN:
4289 case MP_CMD_GET_PROPERTY:
4290 case MP_CMD_SET_PROPERTY:
4291 case MP_CMD_STEP_PROPERTY:
4292 run_command(mpctx, cmd);
4293 break;
4296 mp_cmd_free(cmd);
4298 if (entry) { // user entered a command that gave a valid entry
4299 if (mpctx->playtree)
4300 // the playtree is always a node with one child. let's clear it
4301 play_tree_free_list(mpctx->playtree->child, 1);
4302 else
4303 // .. or make a brand new playtree
4304 mpctx->playtree = play_tree_new();
4306 if (!mpctx->playtree)
4307 continue; // couldn't make playtree! wait for next command
4309 play_tree_set_child(mpctx->playtree, entry);
4311 /* Make iterator start at the top the of tree. */
4312 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4313 mpctx->mconfig);
4314 if (!mpctx->playtree_iter)
4315 continue;
4317 // find the first real item in the tree
4318 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4319 PLAY_TREE_ITER_ENTRY) {
4320 // no items!
4321 play_tree_iter_free(mpctx->playtree_iter);
4322 mpctx->playtree_iter = NULL;
4323 continue; // wait for next command
4325 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4329 #ifdef CONFIG_ASS
4330 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4331 #endif
4332 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4333 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4335 if (mpctx->filename) {
4336 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4337 filename_recode(mpctx->filename));
4338 if (use_filename_title && opts->vo_wintitle == NULL)
4339 opts->vo_wintitle = talloc_strdup(NULL,
4340 mp_basename(mpctx->filename));
4343 if (edl_output_filename) {
4344 if (edl_fd)
4345 fclose(edl_fd);
4346 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4347 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4348 "Can't open EDL file [%s] for writing.\n",
4349 filename_recode(edl_output_filename));
4353 //==================== Open VOB-Sub ============================
4355 current_module = "vobsub";
4356 if (opts->vobsub_name) {
4357 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4358 if (vo_vobsub == NULL)
4359 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4360 filename_recode(opts->vobsub_name));
4361 } else if (opts->sub_auto && mpctx->filename) {
4362 char **vob = find_vob_subtitles(opts, mpctx->filename);
4363 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4364 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4365 if (vo_vobsub)
4366 break;
4368 talloc_free(vob);
4370 if (vo_vobsub) {
4371 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4372 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4373 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4374 mpctx);
4376 // setup global sub numbering
4377 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4378 vobsub_get_indexes_count(vo_vobsub);
4381 //============ Open & Sync STREAM --- fork cache2 ====================
4383 mpctx->stream = NULL;
4384 mpctx->demuxer = NULL;
4385 mpctx->d_audio = NULL;
4386 mpctx->d_video = NULL;
4387 mpctx->d_sub = NULL;
4388 mpctx->sh_audio = NULL;
4389 mpctx->sh_video = NULL;
4391 current_module = "open_stream";
4392 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4393 if (!mpctx->stream) { // error...
4394 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4395 goto goto_next_file;
4397 mpctx->initialized_flags |= INITIALIZED_STREAM;
4399 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4400 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4401 "playlist support will not be used automatically.\n"
4402 "MPlayer's playlist code is unsafe and should only be used with "
4403 "trusted sources.\nPlayback will probably fail.\n\n");
4404 #if 0
4405 play_tree_t *entry;
4406 // Handle playlist
4407 current_module = "handle_playlist";
4408 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4409 filename_recode(mpctx->filename));
4410 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4411 mpctx->eof = playtree_add_playlist(mpctx, entry);
4412 goto goto_next_file;
4413 #endif
4415 mpctx->stream->start_pos += seek_to_byte;
4417 if (stream_dump_type == 5) {
4418 unsigned char buf[4096];
4419 int len;
4420 FILE *f;
4421 current_module = "dumpstream";
4422 stream_reset(mpctx->stream);
4423 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4424 f = fopen(opts->stream_dump_name, "wb");
4425 if (!f) {
4426 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4427 exit_player(mpctx, EXIT_ERROR);
4429 if (opts->chapterrange[0] > 1) {
4430 int chapter = opts->chapterrange[0] - 1;
4431 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4433 struct stream_dump_progress info;
4434 stream_dump_progress_start(&info);
4435 while (!mpctx->stream->eof && !async_quit_request) {
4436 len = stream_read(mpctx->stream, buf, 4096);
4437 if (len > 0) {
4438 if (fwrite(buf, len, 1, f) != 1) {
4439 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4440 exit_player(mpctx, EXIT_ERROR);
4443 stream_dump_progress(&info, len, mpctx->stream);
4444 if (opts->chapterrange[1] > 0) {
4445 int chapter = -1;
4446 if (stream_control(mpctx->stream,
4447 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4448 && chapter + 1 > opts->chapterrange[1])
4449 break;
4452 if (fclose(f)) {
4453 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4454 opts->stream_dump_name);
4455 exit_player(mpctx, EXIT_ERROR);
4457 stream_dump_progress_end(&info, opts->stream_dump_name);
4458 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4459 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4462 #ifdef CONFIG_DVDREAD
4463 if (mpctx->stream->type == STREAMTYPE_DVD) {
4464 current_module = "dvd lang->id";
4465 if (opts->audio_lang && opts->audio_id == -1)
4466 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4467 if (opts->sub_lang && opts->sub_id == -1)
4468 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4469 // setup global sub numbering
4470 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4471 current_module = NULL;
4473 #endif
4475 #ifdef CONFIG_DVDNAV
4476 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4477 current_module = "dvdnav lang->id";
4478 if (opts->audio_lang && opts->audio_id == -1)
4479 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4480 opts->audio_lang);
4481 dvdsub_lang_id = -3;
4482 if (opts->sub_lang && opts->sub_id == -1)
4483 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4484 mpctx->stream, opts->sub_lang);
4485 // setup global sub numbering
4486 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4487 mpctx->stream);
4488 current_module = NULL;
4490 #endif
4492 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4493 goto_enable_cache:
4494 if (stream_cache_size > 0) {
4495 int res;
4496 float stream_cache_min_percent = opts->stream_cache_min_percent;
4497 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4498 current_module = "enable_cache";
4499 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4500 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4501 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4502 if (res == 0)
4503 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4504 goto goto_next_file;
4507 //============ Open DEMUXERS --- DETECT file type =======================
4508 current_module = "demux_open";
4510 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4511 opts->audio_id, opts->video_id, opts->sub_id,
4512 mpctx->filename);
4514 // HACK to get MOV Reference Files working
4516 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4517 unsigned char *playlist_entry;
4518 play_tree_t *list = NULL, *entry = NULL;
4520 current_module = "handle_demux_playlist";
4521 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4522 char *temp;
4523 const char *bname;
4525 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4526 filename_recode(playlist_entry));
4528 bname = mp_basename(playlist_entry);
4529 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4530 !strncmp(bname + 3, "gateQT", 6))
4531 continue;
4533 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4534 continue;
4536 entry = play_tree_new();
4538 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4539 playlist_entry)) { // add reference path of current file
4540 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4541 mpctx->filename)) + strlen(playlist_entry) + 1));
4542 if (temp) {
4543 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4544 strlen(mp_basename(mpctx->filename)));
4545 temp[strlen(mpctx->filename) - strlen(mp_basename(
4546 mpctx->filename))] = '\0';
4547 strcat(temp, playlist_entry);
4548 if (!strcmp(temp, mpctx->filename)) {
4549 free(temp);
4550 continue;
4552 play_tree_add_file(entry, temp);
4553 mp_msg(MSGT_CPLAYER, MSGL_V,
4554 "Resolving reference to %s.\n", temp);
4555 free(temp);
4557 } else
4558 play_tree_add_file(entry, playlist_entry);
4560 if (!list)
4561 list = entry;
4562 else
4563 play_tree_append_entry(list, entry);
4565 free_demuxer(mpctx->demuxer);
4566 mpctx->demuxer = NULL;
4568 if (list) {
4569 entry = play_tree_new();
4570 play_tree_set_child(entry, list);
4571 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4572 goto goto_next_file;
4576 if (!mpctx->demuxer) {
4577 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4578 goto goto_next_file;
4581 if (mpctx->demuxer->matroska_data.ordered_chapters)
4582 build_ordered_chapter_timeline(mpctx);
4584 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4585 build_edl_timeline(mpctx);
4587 if (mpctx->timeline) {
4588 mpctx->timeline_part = 0;
4589 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4591 int part_count = mpctx->num_timeline_parts;
4592 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4593 "sources. Total length %.3f seconds.\n", part_count,
4594 mpctx->num_sources, mpctx->timeline[part_count].start);
4595 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4596 for (int i = 0; i < mpctx->num_sources; i++)
4597 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4598 filename_recode(mpctx->sources[i].demuxer->filename));
4599 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4600 "source_start, source):\n");
4601 for (int i = 0; i < part_count; i++) {
4602 struct timeline_part *p = mpctx->timeline + i;
4603 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4604 p->source_start, p->source - mpctx->sources);
4606 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4607 mpctx->timeline[part_count].start);
4610 if (!mpctx->sources) {
4611 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4612 *mpctx->sources = (struct content_source){
4613 .stream = mpctx->stream,
4614 .demuxer = mpctx->demuxer
4616 mpctx->num_sources = 1;
4619 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4621 #ifdef CONFIG_ASS
4622 if (opts->ass_enabled && mpctx->ass_library) {
4623 for (int j = 0; j < mpctx->num_sources; j++) {
4624 struct demuxer *d = mpctx->sources[j].demuxer;
4625 for (int i = 0; i < d->num_attachments; i++) {
4626 struct demux_attachment *att = d->attachments + i;
4627 if (opts->use_embedded_fonts && attachment_is_font(att))
4628 ass_add_font(mpctx->ass_library, att->name, att->data,
4629 att->data_size);
4633 #endif
4635 current_module = "demux_open2";
4637 mpctx->d_audio = mpctx->demuxer->audio;
4638 mpctx->d_video = mpctx->demuxer->video;
4639 mpctx->d_sub = mpctx->demuxer->sub;
4641 if (ts_prog) {
4642 int tmp = ts_prog;
4643 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4645 // select audio stream
4646 for (int i = 0; i < mpctx->num_sources; i++)
4647 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4648 opts->audio_lang);
4650 // DUMP STREAMS:
4651 if ((stream_dump_type) && (stream_dump_type < 4)) {
4652 FILE *f;
4653 demux_stream_t *ds = NULL;
4654 current_module = "dump";
4655 // select stream to dump
4656 switch (stream_dump_type) {
4657 case 1: ds = mpctx->d_audio;
4658 break;
4659 case 2: ds = mpctx->d_video;
4660 break;
4661 case 3: ds = mpctx->d_sub;
4662 break;
4664 if (!ds) {
4665 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4666 "dump: FATAL: Selected stream missing!\n");
4667 exit_player(mpctx, EXIT_ERROR);
4669 // disable other streams:
4670 if (mpctx->d_audio && mpctx->d_audio != ds) {
4671 ds_free_packs(mpctx->d_audio);
4672 mpctx->d_audio->id = -2;
4674 if (mpctx->d_video && mpctx->d_video != ds) {
4675 ds_free_packs(mpctx->d_video);
4676 mpctx->d_video->id = -2;
4678 if (mpctx->d_sub && mpctx->d_sub != ds) {
4679 ds_free_packs(mpctx->d_sub);
4680 mpctx->d_sub->id = -2;
4682 // let's dump it!
4683 f = fopen(opts->stream_dump_name, "wb");
4684 if (!f) {
4685 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4686 exit_player(mpctx, EXIT_ERROR);
4688 struct stream_dump_progress info;
4689 stream_dump_progress_start(&info);
4690 while (!ds->eof) {
4691 unsigned char *start;
4692 int in_size = ds_get_packet(ds, &start);
4693 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4694 && stream_dump_type == 2)
4695 fwrite(&in_size, 1, 4, f);
4696 if (in_size > 0) {
4697 fwrite(start, in_size, 1, f);
4698 stream_dump_progress(&info, in_size, mpctx->stream);
4700 if (opts->chapterrange[1] > 0) {
4701 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4702 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4703 break;
4706 fclose(f);
4707 stream_dump_progress_end(&info, opts->stream_dump_name);
4708 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4709 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4712 mpctx->sh_audio = mpctx->d_audio->sh;
4713 mpctx->sh_video = mpctx->d_video->sh;
4715 if (mpctx->sh_video) {
4716 current_module = "video_read_properties";
4717 if (!video_read_properties(mpctx->sh_video)) {
4718 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4719 mpctx->sh_video = mpctx->d_video->sh = NULL;
4720 } else {
4721 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4722 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4723 mpctx->demuxer->file_format, mpctx->sh_video->format,
4724 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4725 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4726 if (force_fps) {
4727 mpctx->sh_video->fps = force_fps;
4728 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4730 vo_fps = mpctx->sh_video->fps;
4732 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4733 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4734 "header or invalid, use the -fps option.\n");
4740 if (!mpctx->sh_video && !mpctx->sh_audio) {
4741 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4742 #ifdef CONFIG_DVBIN
4743 if (mpctx->stream->type == STREAMTYPE_DVB) {
4744 int dir;
4745 int v = mpctx->last_dvb_step;
4746 if (v > 0)
4747 dir = DVB_CHANNEL_HIGHER;
4748 else
4749 dir = DVB_CHANNEL_LOWER;
4751 if (dvb_step_channel(mpctx->stream, dir)) {
4752 mpctx->stop_play = PT_NEXT_ENTRY;
4753 mpctx->dvbin_reopen = 1;
4756 #endif
4757 goto goto_next_file; // exit_player(_("Fatal error"));
4760 /* display clip info */
4761 demux_info_print(mpctx->demuxer);
4763 //================= Read SUBTITLES (DVD & TEXT) =========================
4764 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4765 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4766 init_vo_spudec(mpctx);
4768 // after reading video params we should load subtitles because
4769 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4770 // check .sub
4771 current_module = "read_subtitles_file";
4772 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4773 if (opts->sub_name) {
4774 for (i = 0; opts->sub_name[i] != NULL; ++i)
4775 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4777 if (opts->sub_auto) { // auto load sub file ...
4778 char **tmp = find_text_subtitles(opts, mpctx->filename);
4779 int nsub = MP_TALLOC_ELEMS(tmp);
4780 for (int i = 0; i < nsub; i++)
4781 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4782 talloc_free(tmp);
4784 if (mpctx->set_of_sub_size > 0)
4785 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4787 if (select_subtitle(mpctx)) {
4788 if (mpctx->subdata)
4789 switch (stream_dump_type) {
4790 case 3: list_sub_file(mpctx->subdata);
4791 break;
4792 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4793 break;
4794 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4795 break;
4796 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4797 break;
4798 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4799 break;
4800 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4801 break;
4805 print_file_properties(mpctx, mpctx->filename);
4807 reinit_video_chain(mpctx);
4808 if (mpctx->sh_video) {
4809 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4810 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4811 #ifdef CONFIG_FREETYPE
4812 force_load_font = 1;
4813 #endif
4814 } else if (!mpctx->sh_audio)
4815 goto goto_next_file;
4817 //================== MAIN: ==========================
4818 current_module = "main";
4820 if (opts->playing_msg) {
4821 char *msg = property_expand_string(mpctx, opts->playing_msg);
4822 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4823 free(msg);
4827 // Disable the term OSD in verbose mode
4828 if (verbose)
4829 opts->term_osd = 0;
4831 // Make sure old OSD does not stay around
4832 clear_osd_msgs();
4834 //================ SETUP AUDIO ==========================
4836 if (mpctx->sh_audio) {
4837 reinit_audio_chain(mpctx);
4838 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4839 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4840 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4843 current_module = "av_init";
4845 if (mpctx->sh_video) {
4846 mpctx->sh_video->timer = 0;
4847 if (!ignore_start)
4848 audio_delay += mpctx->sh_video->stream_delay;
4850 if (mpctx->sh_audio) {
4851 if (start_volume >= 0)
4852 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4853 if (!ignore_start)
4854 audio_delay -= mpctx->sh_audio->stream_delay;
4857 if (!mpctx->sh_audio) {
4858 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4859 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4860 mpctx->d_audio->packs);
4861 ds_free_packs(mpctx->d_audio); // free buffered chunks
4863 if (!mpctx->sh_video) {
4864 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4865 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4866 mpctx->d_video->packs);
4867 ds_free_packs(mpctx->d_video);
4868 mpctx->d_video->id = -2;
4871 if (!mpctx->sh_video && !mpctx->sh_audio)
4872 goto goto_next_file;
4874 if (force_fps && mpctx->sh_video) {
4875 vo_fps = mpctx->sh_video->fps = force_fps;
4876 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4877 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4878 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4879 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4882 mp_input_set_section(mpctx->input, NULL);
4883 //TODO: add desired (stream-based) sections here
4884 if (mpctx->stream->type == STREAMTYPE_TV)
4885 mp_input_set_section(mpctx->input, "tv");
4886 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4887 mp_input_set_section(mpctx->input, "dvdnav");
4889 //==================== START PLAYING =======================
4891 if (opts->loop_times > 1)
4892 opts->loop_times--;
4893 else if (opts->loop_times == 1)
4894 opts->loop_times = -1;
4896 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4898 total_time_usage_start = GetTimer();
4899 audio_time_usage = 0;
4900 video_time_usage = 0;
4901 vout_time_usage = 0;
4902 total_frame_cnt = 0;
4903 drop_frame_cnt = 0; // fix for multifile fps benchmark
4904 play_n_frames = play_n_frames_mf;
4906 if (play_n_frames == 0) {
4907 mpctx->stop_play = PT_NEXT_ENTRY;
4908 goto goto_next_file;
4911 mpctx->time_frame = 0;
4912 mpctx->drop_message_shown = 0;
4913 mpctx->restart_playback = true;
4914 mpctx->video_pts = 0;
4915 mpctx->last_seek_pts = 0;
4916 mpctx->hrseek_active = false;
4917 mpctx->hrseek_framedrop = false;
4918 mpctx->step_frames = 0;
4919 mpctx->total_avsync_change = 0;
4920 mpctx->last_chapter_seek = -2;
4922 // If there's a timeline force an absolute seek to initialize state
4923 if (opts->seek_to_sec || mpctx->timeline) {
4924 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4925 seek(mpctx, mpctx->seek, false);
4926 end_at.pos += opts->seek_to_sec;
4928 if (opts->chapterrange[0] > 0) {
4929 double pts;
4930 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4931 && pts > -1.0) {
4932 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4933 seek(mpctx, mpctx->seek, false);
4937 if (end_at.type == END_AT_SIZE) {
4938 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4939 "Option -endpos in MPlayer does not yet support size units.\n");
4940 end_at.type = END_AT_NONE;
4943 #ifdef CONFIG_DVDNAV
4944 mp_dvdnav_context_free(mpctx);
4945 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4946 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4947 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4949 #endif
4951 mpctx->seek = (struct seek_params){ 0 };
4952 get_relative_time(mpctx); // reset current delta
4953 // Make sure VO knows current pause state
4954 if (mpctx->sh_video)
4955 vo_control(mpctx->video_out,
4956 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4958 while (!mpctx->stop_play)
4959 run_playloop(mpctx);
4961 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4963 #ifdef CONFIG_DVBIN
4964 if (mpctx->dvbin_reopen) {
4965 mpctx->stop_play = 0;
4966 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4967 cache_uninit(mpctx->stream);
4968 mpctx->dvbin_reopen = 0;
4969 goto goto_enable_cache;
4971 #endif
4973 goto_next_file: // don't jump here after ao/vo/getch initialization!
4975 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4977 if (opts->benchmark) {
4978 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4979 double total_time_usage;
4980 total_time_usage_start = GetTimer() - total_time_usage_start;
4981 total_time_usage = (float)total_time_usage_start * 0.000001;
4982 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4983 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4984 video_time_usage, vout_time_usage, audio_time_usage,
4985 total_time_usage - tot, total_time_usage);
4986 if (total_time_usage > 0.0)
4987 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4988 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4989 100.0 * video_time_usage / total_time_usage,
4990 100.0 * vout_time_usage / total_time_usage,
4991 100.0 * audio_time_usage / total_time_usage,
4992 100.0 * (total_time_usage - tot) / total_time_usage,
4993 100.0);
4994 if (total_frame_cnt && frame_dropping)
4995 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4996 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4997 total_frame_cnt - drop_frame_cnt,
4998 (total_time_usage > 0.5) ? ((total_frame_cnt -
4999 drop_frame_cnt) / total_time_usage) : 0,
5000 drop_frame_cnt,
5001 100 * drop_frame_cnt / total_frame_cnt,
5002 total_frame_cnt,
5003 (total_time_usage > 0.5) ?
5004 (total_frame_cnt / total_time_usage) : 0);
5007 // time to uninit all, except global stuff:
5008 int uninitialize_parts = INITIALIZED_ALL;
5009 if (opts->fixed_vo)
5010 uninitialize_parts -= INITIALIZED_VO;
5011 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
5012 uninitialize_parts -= INITIALIZED_AO;
5013 uninit_player(mpctx, uninitialize_parts);
5015 if (mpctx->set_of_sub_size > 0) {
5016 current_module = "sub_free";
5017 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5018 sub_free(mpctx->set_of_subtitles[i]);
5019 #ifdef CONFIG_ASS
5020 if (mpctx->set_of_ass_tracks[i])
5021 ass_free_track(mpctx->set_of_ass_tracks[i]);
5022 #endif
5024 mpctx->set_of_sub_size = 0;
5026 mpctx->vo_sub_last = vo_sub = NULL;
5027 mpctx->subdata = NULL;
5028 #ifdef CONFIG_ASS
5029 mpctx->osd->ass_track = NULL;
5030 if (mpctx->ass_library)
5031 ass_clear_fonts(mpctx->ass_library);
5032 #endif
5034 if (!mpctx->stop_play) // In case some goto jumped here...
5035 mpctx->stop_play = PT_NEXT_ENTRY;
5037 int playtree_direction = 1;
5039 if (mpctx->stop_play == PT_NEXT_ENTRY
5040 || mpctx->stop_play == PT_PREV_ENTRY) {
5041 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5042 != PLAY_TREE_ITER_ENTRY) {
5043 play_tree_iter_free(mpctx->playtree_iter);
5044 mpctx->playtree_iter = NULL;
5046 mpctx->play_tree_step = 1;
5047 } else if (mpctx->stop_play == PT_UP_NEXT ||
5048 mpctx->stop_play == PT_UP_PREV) {
5049 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5050 if (mpctx->playtree_iter) {
5051 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5052 PLAY_TREE_ITER_ENTRY) {
5053 play_tree_iter_free(mpctx->playtree_iter);
5054 mpctx->playtree_iter = NULL;
5057 } else if (mpctx->stop_play == PT_STOP) {
5058 play_tree_iter_free(mpctx->playtree_iter);
5059 mpctx->playtree_iter = NULL;
5060 } else // NEXT PREV SRC
5061 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5063 while (mpctx->playtree_iter != NULL) {
5064 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5065 playtree_direction);
5066 if (mpctx->filename == NULL) {
5067 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5068 0) != PLAY_TREE_ITER_ENTRY) {
5069 play_tree_iter_free(mpctx->playtree_iter);
5070 mpctx->playtree_iter = NULL;
5073 } else
5074 break;
5077 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5078 if (!mpctx->playtree_iter)
5079 mpctx->filename = NULL;
5080 mpctx->stop_play = 0;
5081 goto play_next_file;
5084 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5086 return 1;
5088 #endif /* DISABLE_MAIN */