cocoa_common.m: add missing config.h include
[mplayer.git] / mplayer.c
blobfe2e509fb49b06565d3b0bc14a33236f52f3ec05
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;
1441 /// OSD message stack.
1442 static mp_osd_msg_t *osd_msg_stack = NULL;
1445 * \brief Add a message on the OSD message stack
1447 * If a message with the same id is already present in the stack
1448 * it is pulled on top of the stack, otherwise a new message is created.
1451 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1452 va_list ap)
1454 mp_osd_msg_t *msg, *last = NULL;
1456 // look if the id is already in the stack
1457 for (msg = osd_msg_stack; msg && msg->id != id;
1458 last = msg, msg = msg->prev) ;
1459 // not found: alloc it
1460 if (!msg) {
1461 msg = talloc_zero(NULL, mp_osd_msg_t);
1462 msg->prev = osd_msg_stack;
1463 osd_msg_stack = msg;
1464 } else if (last) { // found, but it's not on top of the stack
1465 last->prev = msg->prev;
1466 msg->prev = osd_msg_stack;
1467 osd_msg_stack = msg;
1469 talloc_free(msg->msg);
1470 // write the msg
1471 msg->msg = talloc_vasprintf(msg, fmt, ap);
1472 // set id and time
1473 msg->id = id;
1474 msg->level = level;
1475 msg->time = time;
1479 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1481 va_list ap;
1482 va_start(ap, fmt);
1483 set_osd_msg_va(id, level, time, fmt, ap);
1484 va_end(ap);
1487 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1489 va_list ap;
1490 va_start(ap, fmt);
1491 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1492 va_end(ap);
1496 * \brief Remove a message from the OSD stack
1498 * This function can be used to get rid of a message right away.
1502 void rm_osd_msg(int id)
1504 mp_osd_msg_t *msg, *last = NULL;
1506 // Search for the msg
1507 for (msg = osd_msg_stack; msg && msg->id != id;
1508 last = msg, msg = msg->prev) ;
1509 if (!msg)
1510 return;
1512 // Detach it from the stack and free it
1513 if (last)
1514 last->prev = msg->prev;
1515 else
1516 osd_msg_stack = msg->prev;
1517 talloc_free(msg);
1521 * \brief Remove all messages from the OSD stack
1525 static void clear_osd_msgs(void)
1527 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1528 while (msg) {
1529 prev = msg->prev;
1530 talloc_free(msg);
1531 msg = prev;
1533 osd_msg_stack = NULL;
1537 * \brief Get the current message from the OSD stack.
1539 * This function decrements the message timer and destroys the old ones.
1540 * The message that should be displayed is returned (if any).
1544 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1546 struct MPOpts *opts = &mpctx->opts;
1547 mp_osd_msg_t *msg, *prev, *last = NULL;
1548 static unsigned last_update = 0;
1549 unsigned now = GetTimerMS();
1550 unsigned diff;
1551 char hidden_dec_done = 0;
1553 if (mpctx->osd_visible) {
1554 // 36000000 means max timed visibility is 1 hour into the future, if
1555 // the difference is greater assume it's wrapped around from below 0
1556 if (mpctx->osd_visible - now > 36000000) {
1557 mpctx->osd_visible = 0;
1558 vo_osd_progbar_type = -1; // disable
1559 vo_osd_changed(OSDTYPE_PROGBAR);
1560 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1563 if (mpctx->osd_show_percentage_until - now > 36000000)
1564 mpctx->osd_show_percentage_until = 0;
1566 if (!last_update)
1567 last_update = now;
1568 diff = now >= last_update ? now - last_update : 0;
1570 last_update = now;
1572 // Look for the first message in the stack with high enough level.
1573 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1574 prev = msg->prev;
1575 if (msg->level > opts->osd_level && hidden_dec_done)
1576 continue;
1577 // The message has a high enough level or it is the first hidden one
1578 // in both cases we decrement the timer or kill it.
1579 if (!msg->started || msg->time > diff) {
1580 if (msg->started)
1581 msg->time -= diff;
1582 else
1583 msg->started = 1;
1584 // display it
1585 if (msg->level <= opts->osd_level)
1586 return msg;
1587 hidden_dec_done = 1;
1588 continue;
1590 // kill the message
1591 talloc_free(msg);
1592 if (last) {
1593 last->prev = prev;
1594 msg = last;
1595 } else {
1596 osd_msg_stack = prev;
1597 msg = NULL;
1600 // Nothing found
1601 return NULL;
1605 * \brief Display the OSD bar.
1607 * Display the OSD bar or fall back on a simple message.
1611 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1612 double min, double max, double val)
1614 struct MPOpts *opts = &mpctx->opts;
1615 if (opts->osd_level < 1)
1616 return;
1618 if (mpctx->sh_video) {
1619 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1620 vo_osd_progbar_type = type;
1621 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1622 vo_osd_changed(OSDTYPE_PROGBAR);
1623 return;
1626 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1627 name, ROUND(100 * (val - min) / (max - min)));
1631 * \brief Display text subtitles on the OSD
1633 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1635 int i;
1636 vo_sub = subs;
1637 vo_osd_changed(OSDTYPE_SUBTITLE);
1638 if (!mpctx->sh_video) {
1639 // reverse order, since newest set_osd_msg is displayed first
1640 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1641 if (!subs || i >= subs->lines || !subs->text[i])
1642 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1643 else {
1644 // HACK: currently display time for each sub line
1645 // except the last is set to 2 seconds.
1646 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1647 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1648 "%s", subs->text[i]);
1655 * \brief Update the OSD message line.
1657 * This function displays the current message on the vo OSD or on the term.
1658 * If the stack is empty and the OSD level is high enough the timer
1659 * is displayed (only on the vo OSD).
1663 static void update_osd_msg(struct MPContext *mpctx)
1665 struct MPOpts *opts = &mpctx->opts;
1666 mp_osd_msg_t *msg;
1667 struct osd_state *osd = mpctx->osd;
1668 char osd_text_timer[128];
1670 if (mpctx->add_osd_seek_info) {
1671 double percentage = get_percent_pos(mpctx);
1672 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1673 if (mpctx->sh_video)
1674 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1675 mpctx->add_osd_seek_info = false;
1678 // Look if we have a msg
1679 if ((msg = get_osd_msg(mpctx))) {
1680 if (strcmp(osd->osd_text, msg->msg)) {
1681 osd_set_text(osd, msg->msg);
1682 if (mpctx->sh_video)
1683 vo_osd_changed(OSDTYPE_OSD);
1684 else if (opts->term_osd)
1685 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1686 msg->msg);
1688 return;
1691 if (mpctx->sh_video) {
1692 // fallback on the timer
1693 if (opts->osd_level >= 2) {
1694 int len = get_time_length(mpctx);
1695 int percentage = -1;
1696 char percentage_text[10];
1697 char fractions_text[4];
1698 double fpts = get_current_time(mpctx);
1699 int pts = fpts;
1701 if (mpctx->osd_show_percentage_until)
1702 percentage = get_percent_pos(mpctx);
1704 if (percentage >= 0)
1705 snprintf(percentage_text, 9, " (%d%%)", percentage);
1706 else
1707 percentage_text[0] = 0;
1709 if (opts->osd_fractions == 1) {
1710 //print fractions as sub-second timestamp
1711 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1712 (int)((fpts - pts) * 100));
1713 } else if (opts->osd_fractions == 2) {
1714 /* Print fractions by estimating the frame count within the
1715 * second.
1717 * Rounding or cutting off numbers after the decimal point
1718 * causes problems because of float's precision and movies
1719 * whose first frame is not exactly at timestamp 0. Therefore,
1720 * we add 0.2 and cut off at the decimal point, which proved
1721 * to be good heuristic.
1723 double fps = mpctx->sh_video->fps;
1724 if (fps <= 1 || fps > 99)
1725 strcpy(fractions_text, ".??");
1726 else
1727 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1728 (int) ((fpts - pts) * fps + 0.2));
1729 } else {
1730 //do not print fractions
1731 fractions_text[0] = 0;
1734 if (opts->osd_level == 3)
1735 snprintf(osd_text_timer, sizeof(osd_text_timer),
1736 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1737 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1738 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1739 percentage_text);
1740 else
1741 snprintf(osd_text_timer, sizeof(osd_text_timer),
1742 "%c %02d:%02d:%02d%s%s",
1743 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1744 pts % 60, fractions_text, percentage_text);
1745 } else
1746 osd_text_timer[0] = 0;
1748 if (strcmp(osd->osd_text, osd_text_timer)) {
1749 osd_set_text(osd, osd_text_timer);
1750 vo_osd_changed(OSDTYPE_OSD);
1752 return;
1755 // Clear the term osd line
1756 if (opts->term_osd && osd->osd_text[0]) {
1757 osd->osd_text[0] = 0;
1758 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1763 void reinit_audio_chain(struct MPContext *mpctx)
1765 struct MPOpts *opts = &mpctx->opts;
1766 struct ao *ao;
1767 if (!mpctx->sh_audio) {
1768 uninit_player(mpctx, INITIALIZED_AO);
1769 return;
1771 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1772 current_module = "init_audio_codec";
1773 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1774 goto init_error;
1775 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1778 current_module = "af_preinit";
1779 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1780 mpctx->initialized_flags |= INITIALIZED_AO;
1781 mpctx->ao = ao_create(opts, mpctx->input);
1782 mpctx->ao->samplerate = force_srate;
1783 mpctx->ao->format = opts->audio_output_format;
1785 ao = mpctx->ao;
1787 // first init to detect best values
1788 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1789 // input:
1790 mpctx->sh_audio->samplerate,
1791 // output:
1792 &ao->samplerate, &ao->channels, &ao->format)) {
1793 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1794 "pre-init!\n");
1795 exit_player(mpctx, EXIT_ERROR);
1797 if (!ao->initialized) {
1798 current_module = "ao2_init";
1799 ao->buffersize = opts->ao_buffersize;
1800 ao_init(ao, opts->audio_driver_list);
1801 if (!ao->initialized) {
1802 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1803 "Could not open/initialize audio device -> no sound.\n");
1804 goto init_error;
1806 ao->buffer.start = talloc_new(ao);
1807 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1808 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1809 ao->driver->info->short_name,
1810 ao->samplerate, ao->channels,
1811 af_fmt2str_short(ao->format),
1812 af_fmt2bits(ao->format) / 8);
1813 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1814 ao->driver->info->name, ao->driver->info->author);
1815 if (strlen(ao->driver->info->comment) > 0)
1816 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1817 ao->driver->info->comment);
1820 // init audio filters:
1821 current_module = "af_init";
1822 if (!build_afilter_chain(mpctx)) {
1823 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1824 "Couldn't find matching filter/ao format!\n");
1825 goto init_error;
1827 mpctx->mixer.volstep = volstep;
1828 mpctx->mixer.softvol = opts->softvol;
1829 mpctx->mixer.softvol_max = opts->softvol_max;
1830 mixer_reinit(&mpctx->mixer, ao);
1831 mpctx->syncing_audio = true;
1832 return;
1834 init_error:
1835 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1836 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1837 mpctx->d_audio->id = -2;
1841 // Return pts value corresponding to the end point of audio written to the
1842 // ao so far.
1843 static double written_audio_pts(struct MPContext *mpctx)
1845 sh_audio_t *sh_audio = mpctx->sh_audio;
1846 if (!sh_audio)
1847 return MP_NOPTS_VALUE;
1848 demux_stream_t *d_audio = mpctx->d_audio;
1849 // first calculate the end pts of audio that has been output by decoder
1850 double a_pts = sh_audio->pts;
1851 if (a_pts != MP_NOPTS_VALUE)
1852 // Good, decoder supports new way of calculating audio pts.
1853 // sh_audio->pts is the timestamp of the latest input packet with
1854 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1855 // the amount of bytes the decoder has written after that timestamp.
1856 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1857 else {
1858 // Decoder doesn't support new way of calculating pts (or we're
1859 // being called before it has decoded anything with known timestamp).
1860 // Use the old method of audio pts calculation: take the timestamp
1861 // of last packet with known pts the decoder has read data from,
1862 // and add amount of bytes read after the beginning of that packet
1863 // divided by input bps. This will be inaccurate if the input/output
1864 // ratio is not constant for every audio packet or if it is constant
1865 // but not accurately known in sh_audio->i_bps.
1867 a_pts = d_audio->pts;
1868 if (a_pts == MP_NOPTS_VALUE)
1869 return a_pts;
1871 // ds_tell_pts returns bytes read after last timestamp from
1872 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1873 // it has read but not decoded
1874 if (sh_audio->i_bps)
1875 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1876 (double)sh_audio->i_bps;
1878 // Now a_pts hopefully holds the pts for end of audio from decoder.
1879 // Substract data in buffers between decoder and audio out.
1881 // Decoded but not filtered
1882 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1884 // Data buffered in audio filters, measured in bytes of "missing" output
1885 double buffered_output = af_calc_delay(sh_audio->afilter);
1887 // Data that was ready for ao but was buffered because ao didn't fully
1888 // accept everything to internal buffers yet
1889 buffered_output += mpctx->ao->buffer.len;
1891 // Filters divide audio length by playback_speed, so multiply by it
1892 // to get the length in original units without speedup or slowdown
1893 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1895 return a_pts + mpctx->video_offset;
1898 // Return pts value corresponding to currently playing audio.
1899 double playing_audio_pts(struct MPContext *mpctx)
1901 double pts = written_audio_pts(mpctx);
1902 if (pts == MP_NOPTS_VALUE)
1903 return pts;
1904 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1907 static bool is_av_sub(int type)
1909 return type == 'b' || type == 'p' || type == 'x';
1912 void update_subtitles(struct MPContext *mpctx, double refpts_tl, bool reset)
1914 mpctx->osd->sub_offset = mpctx->video_offset;
1915 struct MPOpts *opts = &mpctx->opts;
1916 struct sh_video *sh_video = mpctx->sh_video;
1917 struct demux_stream *d_sub = mpctx->d_sub;
1918 double refpts_s = refpts_tl - mpctx->osd->sub_offset;
1919 double curpts_s = refpts_s + sub_delay;
1920 unsigned char *packet = NULL;
1921 int len;
1922 struct sh_sub *sh_sub = d_sub->sh;
1923 int type = sh_sub ? sh_sub->type : 'v';
1924 static subtitle subs;
1925 if (reset) {
1926 if (sh_sub)
1927 sub_reset(sh_sub, mpctx->osd);
1928 sub_clear_text(&subs, MP_NOPTS_VALUE);
1929 if (vo_sub)
1930 set_osd_subtitle(mpctx, NULL);
1931 if (vo_spudec) {
1932 spudec_reset(vo_spudec);
1933 vo_osd_changed(OSDTYPE_SPU);
1935 if (is_av_sub(type))
1936 reset_avsub(sh_sub);
1937 return;
1939 // find sub
1940 if (mpctx->subdata) {
1941 if (sub_fps == 0)
1942 sub_fps = sh_video ? sh_video->fps : 25;
1943 current_module = "find_sub";
1944 find_sub(mpctx, mpctx->subdata, curpts_s *
1945 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1946 if (vo_sub)
1947 mpctx->vo_sub_last = vo_sub;
1950 // DVD sub:
1951 if (vobsub_id >= 0 || type == 'v') {
1952 int timestamp;
1953 current_module = "spudec";
1954 /* Get a sub packet from the DVD or a vobsub */
1955 while (1) {
1956 // Vobsub
1957 len = 0;
1958 if (vo_vobsub) {
1959 if (curpts_s >= 0) {
1960 len = vobsub_get_packet(vo_vobsub, curpts_s,
1961 (void **)&packet, &timestamp);
1962 if (len > 0)
1963 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1964 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1965 len, refpts_s, sh_video->timer,
1966 timestamp / 90000.0, timestamp);
1968 } else {
1969 // DVD sub
1970 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1971 if (len > 0) {
1972 // XXX This is wrong, sh_video->pts can be arbitrarily
1973 // much behind demuxing position. Unfortunately using
1974 // d_video->pts which would have been the simplest
1975 // improvement doesn't work because mpeg specific hacks
1976 // in video.c set d_video->pts to 0.
1977 float x = d_sub->pts - refpts_s;
1978 if (x > -20 && x < 20) // prevent missing subs on pts reset
1979 timestamp = 90000 * d_sub->pts;
1980 else
1981 timestamp = 90000 * curpts_s;
1982 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1983 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1984 refpts_s, d_sub->pts, timestamp);
1987 if (len <= 0 || !packet)
1988 break;
1989 // create it only here, since with some broken demuxers we might
1990 // type = v but no DVD sub and we currently do not change the
1991 // "original frame size" ever after init, leading to wrong-sized
1992 // PGS subtitles.
1993 if (!vo_spudec)
1994 vo_spudec = spudec_new(NULL);
1995 if (vo_vobsub || timestamp >= 0)
1996 spudec_assemble(vo_spudec, packet, len, timestamp);
1998 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1999 if (type == 'd' && !d_sub->demuxer->teletext) {
2000 tt_stream_props tsp = { 0 };
2001 void *ptr = &tsp;
2002 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
2003 VBI_CONTROL_TRUE)
2004 d_sub->demuxer->teletext = ptr;
2006 if (d_sub->non_interleaved)
2007 ds_get_next_pts(d_sub);
2009 while (d_sub->first) {
2010 double subpts_s = ds_get_next_pts(d_sub);
2011 if (subpts_s > curpts_s) {
2012 // Libass handled subs can be fed to it in advance
2013 if (!opts->ass_enabled || !is_text_sub(type))
2014 break;
2015 // Try to avoid demuxing whole file at once
2016 if (d_sub->non_interleaved && subpts_s > curpts_s + 1)
2017 break;
2019 double duration = d_sub->first->duration;
2020 len = ds_get_packet_sub(d_sub, &packet);
2021 if (is_av_sub(type)) {
2022 int ret = decode_avsub(sh_sub, packet, len, subpts_s, duration);
2023 if (ret < 0)
2024 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2025 "subtitle\n");
2026 continue;
2028 if (type == 'm') {
2029 if (len < 2)
2030 continue;
2031 len = FFMIN(len - 2, AV_RB16(packet));
2032 packet += 2;
2034 if (type == 'd') {
2035 if (d_sub->demuxer->teletext) {
2036 uint8_t *p = packet;
2037 p++;
2038 len--;
2039 while (len >= 46) {
2040 int sublen = p[1];
2041 if (p[0] == 2 || p[0] == 3)
2042 teletext_control(d_sub->demuxer->teletext,
2043 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2044 p += sublen + 2;
2045 len -= sublen + 2;
2048 continue;
2050 if (sh_sub && sh_sub->active) {
2051 sub_decode(sh_sub, mpctx->osd, packet, len, subpts_s, duration);
2052 continue;
2054 if (subpts_s != MP_NOPTS_VALUE) {
2055 if (duration < 0)
2056 sub_clear_text(&subs, MP_NOPTS_VALUE);
2057 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2058 int i;
2059 unsigned char *p = packet;
2060 for (i = 0; i < 8 && *p != '\0'; p++)
2061 if (*p == ',')
2062 i++;
2063 if (*p == '\0') /* Broken line? */
2064 continue;
2065 len -= p - packet;
2066 packet = p;
2068 double endpts_s = MP_NOPTS_VALUE;
2069 if (subpts_s != MP_NOPTS_VALUE && duration >= 0)
2070 endpts_s = subpts_s + duration;
2071 sub_add_text(&subs, packet, len, endpts_s);
2072 set_osd_subtitle(mpctx, &subs);
2074 if (d_sub->non_interleaved)
2075 ds_get_next_pts(d_sub);
2077 if (!opts->ass_enabled)
2078 if (sub_clear_text(&subs, curpts_s))
2079 set_osd_subtitle(mpctx, &subs);
2081 if (vo_spudec) {
2082 spudec_heartbeat(vo_spudec, 90000 * curpts_s);
2083 if (spudec_changed(vo_spudec))
2084 vo_osd_changed(OSDTYPE_SPU);
2087 current_module = NULL;
2090 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2092 int page_changed;
2094 if (!demuxer->teletext)
2095 return;
2097 //Also forcing page update when such ioctl is not supported or call error occured
2098 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2099 &page_changed) != VBI_CONTROL_TRUE)
2100 page_changed = 1;
2102 if (!page_changed)
2103 return;
2105 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2106 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2107 vo_osd_teletext_page = NULL;
2108 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2109 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2110 vo_osd_teletext_half = 0;
2111 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2112 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2113 vo_osd_teletext_mode = 0;
2114 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2115 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2116 vo_osd_teletext_format = 0;
2117 vo_osd_changed(OSDTYPE_TELETEXT);
2119 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2122 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2124 struct MPOpts *opts = &mpctx->opts;
2125 // check for frame-drop:
2126 current_module = "check_framedrop";
2127 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2128 static int dropped_frames;
2129 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2130 float d = delay - mpctx->delay;
2131 ++total_frame_cnt;
2132 // we should avoid dropping too many frames in sequence unless we
2133 // are too late. and we allow 100ms A-V delay here:
2134 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2135 && !mpctx->restart_playback) {
2136 ++drop_frame_cnt;
2137 ++dropped_frames;
2138 return frame_dropping;
2139 } else
2140 dropped_frames = 0;
2142 return 0;
2146 #ifdef HAVE_RTC
2147 int rtc_fd = -1;
2148 #endif
2150 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2152 #ifdef HAVE_RTC
2153 if (rtc_fd >= 0) {
2154 // -------- RTC -----------
2155 current_module = "sleep_rtc";
2156 while (time_frame > 0.000) {
2157 unsigned long rtc_ts;
2158 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2159 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2160 "Linux RTC read error: %s\n", strerror(errno));
2161 time_frame -= get_relative_time(mpctx);
2163 } else
2164 #endif
2166 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2167 // unnecessarily high CPU usage
2168 struct MPOpts *opts = &mpctx->opts;
2169 float margin = opts->softsleep ? 0.011 : 0;
2170 current_module = "sleep_timer";
2171 while (time_frame > margin) {
2172 usec_sleep(1000000 * (time_frame - margin));
2173 time_frame -= get_relative_time(mpctx);
2175 if (opts->softsleep) {
2176 current_module = "sleep_soft";
2177 if (time_frame < 0)
2178 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2179 "Warning! Softsleep underflow!\n");
2180 while (time_frame > 0)
2181 time_frame -= get_relative_time(mpctx); // burn the CPU
2184 return time_frame;
2187 static int select_subtitle(MPContext *mpctx)
2189 struct MPOpts *opts = &mpctx->opts;
2190 // find the best sub to use
2191 int id;
2192 int found = 0;
2193 mpctx->global_sub_pos = -1; // no subs by default
2194 if (vobsub_id >= 0) {
2195 // if user asks for a vobsub id, use that first.
2196 id = vobsub_id;
2197 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2198 M_PROPERTY_OK;
2201 if (!found && opts->sub_id >= 0) {
2202 // if user asks for a dvd sub id, use that next.
2203 id = opts->sub_id;
2204 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2205 M_PROPERTY_OK;
2208 if (!found) {
2209 // if there are text subs to use, use those. (autosubs come last here)
2210 id = 0;
2211 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2212 M_PROPERTY_OK;
2215 if (!found && opts->sub_id == -1) {
2216 // finally select subs by language and container hints
2217 if (opts->sub_id == -1)
2218 opts->sub_id =
2219 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2220 opts->sub_lang);
2221 if (opts->sub_id >= 0) {
2222 id = opts->sub_id;
2223 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2224 M_PROPERTY_OK;
2227 return found;
2230 #ifdef CONFIG_DVDNAV
2231 #ifndef FF_B_TYPE
2232 #define FF_B_TYPE 3
2233 #endif
2234 /// store decoded video image
2235 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2236 mp_image_t *from_mpi)
2238 mp_image_t *mpi;
2240 /// Do not store B-frames
2241 if (from_mpi->pict_type == FF_B_TYPE)
2242 return to_mpi;
2244 if (to_mpi &&
2245 to_mpi->w == from_mpi->w &&
2246 to_mpi->h == from_mpi->h &&
2247 to_mpi->imgfmt == from_mpi->imgfmt)
2248 mpi = to_mpi;
2249 else {
2250 if (to_mpi)
2251 free_mp_image(to_mpi);
2252 if (from_mpi->w == 0 || from_mpi->h == 0)
2253 return NULL;
2254 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2257 copy_mpi(mpi, from_mpi);
2258 return mpi;
2261 static void mp_dvdnav_reset_stream(MPContext *ctx)
2263 struct MPOpts *opts = &ctx->opts;
2264 if (ctx->sh_video) {
2265 /// clear video pts
2266 ctx->d_video->pts = 0.0f;
2267 ctx->sh_video->pts = 0.0f;
2268 ctx->sh_video->i_pts = 0.0f;
2269 ctx->sh_video->last_pts = 0.0f;
2270 ctx->sh_video->num_buffered_pts = 0;
2271 ctx->sh_video->num_frames = 0;
2272 ctx->sh_video->num_frames_decoded = 0;
2273 ctx->sh_video->timer = 0.0f;
2274 ctx->sh_video->stream_delay = 0.0f;
2275 ctx->sh_video->timer = 0;
2276 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2279 if (ctx->sh_audio) {
2280 /// free audio packets and reset
2281 ds_free_packs(ctx->d_audio);
2282 audio_delay -= ctx->sh_audio->stream_delay;
2283 ctx->delay = -audio_delay;
2284 ao_reset(ctx->ao);
2285 resync_audio_stream(ctx->sh_audio);
2288 audio_delay = 0.0f;
2289 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2290 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2291 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2292 if (dvdsub_lang_id != opts->sub_id) {
2293 opts->sub_id = dvdsub_lang_id;
2294 select_subtitle(ctx);
2298 /// clear all EOF related flags
2299 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2302 /// Restore last decoded DVDNAV (still frame)
2303 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2304 int *in_size,
2305 unsigned char **start,
2306 mp_image_t *decoded_frame)
2308 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2309 return decoded_frame;
2311 /// a change occurred in dvdnav stream
2312 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2313 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2314 mp_dvdnav_context_free(mpctx);
2315 mp_dvdnav_reset_stream(mpctx);
2316 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2317 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2320 if (*in_size < 0) {
2321 float len;
2323 /// Display still frame, if any
2324 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2325 decoded_frame = mpctx->nav_smpi;
2327 /// increment video frame : continue playing after still frame
2328 len = get_time_length(mpctx);
2329 if (mpctx->sh_video->pts >= len &&
2330 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2331 mp_dvdnav_skip_still(mpctx->stream);
2332 mp_dvdnav_skip_wait(mpctx->stream);
2334 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2336 if (mpctx->nav_buffer) {
2337 *start = mpctx->nav_start;
2338 *in_size = mpctx->nav_in_size;
2339 if (mpctx->nav_start)
2340 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2344 return decoded_frame;
2347 /// Save last decoded DVDNAV (still frame)
2348 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2349 unsigned char *start,
2350 mp_image_t *decoded_frame)
2352 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2353 return;
2355 free(mpctx->nav_buffer);
2356 mpctx->nav_buffer = NULL;
2357 mpctx->nav_start = NULL;
2358 mpctx->nav_in_size = -1;
2360 if (in_size > 0)
2361 mpctx->nav_buffer = malloc(in_size);
2362 if (mpctx->nav_buffer) {
2363 mpctx->nav_start = start;
2364 mpctx->nav_in_size = in_size;
2365 memcpy(mpctx->nav_buffer, start, in_size);
2368 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2369 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2371 #endif /* CONFIG_DVDNAV */
2373 /* Modify video timing to match the audio timeline. There are two main
2374 * reasons this is needed. First, video and audio can start from different
2375 * positions at beginning of file or after a seek (MPlayer starts both
2376 * immediately even if they have different pts). Second, the file can have
2377 * audio timestamps that are inconsistent with the duration of the audio
2378 * packets, for example two consecutive timestamp values differing by
2379 * one second but only a packet with enough samples for half a second
2380 * of playback between them.
2382 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2384 current_module = "av_sync";
2386 if (!mpctx->sh_audio || mpctx->syncing_audio)
2387 return;
2389 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2390 double v_pts = mpctx->sh_video->pts;
2391 double av_delay = a_pts - v_pts;
2392 // Try to sync vo_flip() so it will *finish* at given time
2393 av_delay += mpctx->last_vo_flip_duration;
2394 av_delay -= audio_delay; // This much pts difference is desired
2396 double change = av_delay * 0.1;
2397 double max_change = default_max_pts_correction >= 0 ?
2398 default_max_pts_correction : frame_time * 0.1;
2399 if (change < -max_change)
2400 change = -max_change;
2401 else if (change > max_change)
2402 change = max_change;
2403 mpctx->delay += change;
2404 mpctx->total_avsync_change += change;
2407 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2408 double pts)
2410 if (mpctx->paused)
2411 return 0;
2412 struct ao *ao = mpctx->ao;
2413 double bps = ao->bps / mpctx->opts.playback_speed;
2414 ao->pts = pts;
2415 // hack used by some mpeg-writing AOs
2416 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2417 mpctx->delay) * 90000.0;
2418 int played = ao_play(mpctx->ao, data, len, flags);
2419 if (played > 0) {
2420 mpctx->delay += played / bps;
2421 // Keep correct pts for remaining data - could be used to flush
2422 // remaining buffer when closing ao.
2423 ao->pts += played / bps;
2425 return played;
2428 #define ASYNC_PLAY_DONE -3
2429 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2431 struct ao *ao = mpctx->ao;
2432 struct MPOpts *opts = &mpctx->opts;
2433 sh_audio_t * const sh_audio = mpctx->sh_audio;
2434 int res;
2436 // Timing info may not be set without
2437 res = decode_audio(sh_audio, &ao->buffer, 1);
2438 if (res < 0)
2439 return res;
2441 int bytes;
2442 bool did_retry = false;
2443 double written_pts;
2444 double bps = ao->bps / opts->playback_speed;
2445 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2446 mpctx->hrseek_active = false;
2447 while (1) {
2448 written_pts = written_audio_pts(mpctx);
2449 double ptsdiff;
2450 if (hrseek)
2451 ptsdiff = written_pts - mpctx->hrseek_pts;
2452 else
2453 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2454 - audio_delay;
2455 bytes = ptsdiff * bps;
2456 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2458 // ogg demuxers give packets without timing
2459 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2460 if (!did_retry) {
2461 // Try to read more data to see packets that have pts
2462 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2463 if (res < 0)
2464 return res;
2465 did_retry = true;
2466 continue;
2468 bytes = 0;
2471 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2472 bytes = 0;
2474 if (bytes > 0)
2475 break;
2477 mpctx->syncing_audio = false;
2478 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2479 int res = decode_audio(sh_audio, &ao->buffer, a);
2480 bytes += ao->buffer.len;
2481 if (bytes >= 0) {
2482 memmove(ao->buffer.start,
2483 ao->buffer.start + ao->buffer.len - bytes, bytes);
2484 ao->buffer.len = bytes;
2485 if (res < 0)
2486 return res;
2487 return decode_audio(sh_audio, &ao->buffer, playsize);
2489 ao->buffer.len = 0;
2490 if (res < 0)
2491 return res;
2493 if (hrseek)
2494 // Don't add silence in audio-only case even if position is too late
2495 return 0;
2496 int fillbyte = 0;
2497 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2498 fillbyte = 0x80;
2499 if (bytes >= playsize) {
2500 /* This case could fall back to the one below with
2501 * bytes = playsize, but then silence would keep accumulating
2502 * in a_out_buffer if the AO accepts less data than it asks for
2503 * in playsize. */
2504 char *p = malloc(playsize);
2505 memset(p, fillbyte, playsize);
2506 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2507 free(p);
2508 return ASYNC_PLAY_DONE;
2510 mpctx->syncing_audio = false;
2511 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2512 return decode_audio(sh_audio, &ao->buffer, playsize);
2515 static int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
2517 struct MPOpts *opts = &mpctx->opts;
2518 struct ao *ao = mpctx->ao;
2519 unsigned int t;
2520 double tt;
2521 int playsize;
2522 int playflags = 0;
2523 bool audio_eof = false;
2524 bool partial_fill = false;
2525 sh_audio_t * const sh_audio = mpctx->sh_audio;
2526 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2527 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2529 current_module = "play_audio";
2531 // hack used by some mpeg-writing AOs
2532 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2533 mpctx->delay) * 90000.0;
2535 if (mpctx->paused)
2536 playsize = 1; // just initialize things (audio pts at least)
2537 else
2538 playsize = ao_get_space(ao);
2540 // Fill buffer if needed:
2541 current_module = "decode_audio";
2542 t = GetTimer();
2544 // Coming here with hrseek_active still set means audio-only
2545 if (!mpctx->sh_video)
2546 mpctx->syncing_audio = false;
2547 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2548 mpctx->syncing_audio = false;
2549 mpctx->hrseek_active = false;
2552 int res;
2553 if (mpctx->syncing_audio || mpctx->hrseek_active)
2554 res = audio_start_sync(mpctx, playsize);
2555 else
2556 res = decode_audio(sh_audio, &ao->buffer, playsize);
2557 if (res < 0) { // EOF, error or format change
2558 if (res == -2) {
2559 /* The format change isn't handled too gracefully. A more precise
2560 * implementation would require draining buffered old-format audio
2561 * while displaying video, then doing the output format switch.
2563 uninit_player(mpctx, INITIALIZED_AO);
2564 reinit_audio_chain(mpctx);
2565 return -1;
2566 } else if (res == ASYNC_PLAY_DONE)
2567 return 0;
2568 else if (mpctx->d_audio->eof)
2569 audio_eof = true;
2571 t = GetTimer() - t;
2572 tt = t * 0.000001f;
2573 audio_time_usage += tt;
2574 if (endpts != MP_NOPTS_VALUE && modifiable_audio_format) {
2575 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2576 * ao->bps / opts->playback_speed;
2577 if (playsize > bytes) {
2578 playsize = FFMAX(bytes, 0);
2579 playflags |= AOPLAY_FINAL_CHUNK;
2580 audio_eof = true;
2581 partial_fill = true;
2585 assert(ao->buffer.len % unitsize == 0);
2586 if (playsize > ao->buffer.len) {
2587 partial_fill = true;
2588 playsize = ao->buffer.len;
2589 if (audio_eof)
2590 playflags |= AOPLAY_FINAL_CHUNK;
2592 playsize -= playsize % unitsize;
2593 if (!playsize)
2594 return partial_fill && audio_eof ? -2 : -partial_fill;
2596 // play audio:
2597 current_module = "play_audio";
2599 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2600 written_audio_pts(mpctx));
2601 assert(played % unitsize == 0);
2602 ao->buffer_playable_size = playsize - played;
2604 if (played > 0) {
2605 ao->buffer.len -= played;
2606 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2607 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2608 // Sanity check to avoid hanging in case current ao doesn't output
2609 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2610 return -2;
2613 return -partial_fill;
2616 int reinit_video_chain(struct MPContext *mpctx)
2618 struct MPOpts *opts = &mpctx->opts;
2619 sh_video_t * const sh_video = mpctx->sh_video;
2620 if (!sh_video) {
2621 uninit_player(mpctx, INITIALIZED_VO);
2622 return 0;
2624 double ar = -1.0;
2625 //================== Init VIDEO (codec & libvo) ==========================
2626 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2627 current_module = "preinit_libvo";
2629 //shouldn't we set dvideo->id=-2 when we fail?
2630 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2631 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2632 mpctx->key_fifo,
2633 mpctx->input))) {
2634 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2635 "the selected video_out (-vo) device.\n");
2636 goto err_out;
2638 mpctx->initialized_flags |= INITIALIZED_VO;
2641 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2642 &ar) != STREAM_UNSUPPORTED)
2643 mpctx->sh_video->stream_aspect = ar;
2644 current_module = "init_video_filters";
2646 char *vf_arg[] = {
2647 "_oldargs_", (char *)mpctx->video_out, NULL
2649 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2652 #ifdef CONFIG_ASS
2653 if (opts->ass_enabled) {
2654 int i;
2655 int insert = 1;
2656 if (opts->vf_settings)
2657 for (i = 0; opts->vf_settings[i].name; ++i)
2658 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2659 insert = 0;
2660 break;
2662 if (insert) {
2663 extern vf_info_t vf_info_ass;
2664 const vf_info_t *libass_vfs[] = {
2665 &vf_info_ass, NULL
2667 char *vf_arg[] = {
2668 "auto", "1", NULL
2670 int retcode = 0;
2671 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2672 sh_video->vfilter,
2673 "ass", vf_arg,
2674 &retcode);
2675 if (vf_ass)
2676 sh_video->vfilter = vf_ass;
2677 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2678 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2679 else
2680 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2681 "ASS: cannot add video filter\n");
2684 #endif
2686 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2688 #ifdef CONFIG_ASS
2689 if (opts->ass_enabled)
2690 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2691 mpctx->ass_library);
2692 #endif
2694 current_module = "init_video_codec";
2696 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2698 if (!sh_video->initialized) {
2699 if (!opts->fixed_vo)
2700 uninit_player(mpctx, INITIALIZED_VO);
2701 goto err_out;
2704 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2706 if (sh_video->codec)
2707 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2708 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2710 sh_video->last_pts = MP_NOPTS_VALUE;
2711 sh_video->num_buffered_pts = 0;
2712 sh_video->next_frame_time = 0;
2713 mpctx->restart_playback = true;
2714 mpctx->delay = 0;
2716 if (opts->auto_quality > 0) {
2717 // Auto quality option enabled
2718 output_quality = get_video_quality_max(sh_video);
2719 if (opts->auto_quality > output_quality)
2720 opts->auto_quality = output_quality;
2721 else
2722 output_quality = opts->auto_quality;
2723 mp_msg(MSGT_CPLAYER, MSGL_V,
2724 "AutoQ: setting quality to %d.\n", output_quality);
2725 set_video_quality(sh_video, output_quality);
2728 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2730 current_module = "init_vo";
2732 return 1;
2734 err_out:
2735 mpctx->sh_video = mpctx->d_video->sh = NULL;
2736 return 0;
2739 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2741 struct sh_video *sh_video = mpctx->sh_video;
2742 double frame_time = 0;
2743 struct vo *video_out = mpctx->video_out;
2744 while (1) {
2745 current_module = "filter_video";
2746 // In nocorrect-pts mode there is no way to properly time these frames
2747 if (vo_get_buffered_frame(video_out, 0) >= 0)
2748 break;
2749 if (vf_output_queued_frame(sh_video->vfilter))
2750 break;
2751 unsigned char *packet = NULL;
2752 frame_time = sh_video->next_frame_time;
2753 if (mpctx->restart_playback)
2754 frame_time = 0;
2755 int in_size = 0;
2756 while (!in_size)
2757 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2758 &packet, force_fps);
2759 if (in_size < 0) {
2760 #ifdef CONFIG_DVDNAV
2761 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2762 if (mp_dvdnav_is_eof(mpctx->stream))
2763 return -1;
2764 if (mpctx->d_video)
2765 mpctx->d_video->eof = 0;
2766 if (mpctx->d_audio)
2767 mpctx->d_audio->eof = 0;
2768 mpctx->stream->eof = 0;
2769 } else
2770 #endif
2771 return -1;
2773 if (in_size > max_framesize)
2774 max_framesize = in_size;
2775 sh_video->timer += frame_time;
2776 if (mpctx->sh_audio)
2777 mpctx->delay -= frame_time;
2778 // video_read_frame can change fps (e.g. for ASF video)
2779 vo_fps = sh_video->fps;
2780 int framedrop_type = check_framedrop(mpctx, frame_time);
2781 current_module = "decode video";
2783 void *decoded_frame;
2784 #ifdef CONFIG_DVDNAV
2785 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2786 if (in_size >= 0 && !decoded_frame)
2787 #endif
2788 decoded_frame = decode_video(sh_video, sh_video->ds->current, packet,
2789 in_size, framedrop_type, sh_video->pts);
2790 #ifdef CONFIG_DVDNAV
2791 // Save last still frame for future display
2792 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2793 #endif
2794 if (decoded_frame) {
2795 current_module = "filter video";
2796 filter_video(sh_video, decoded_frame, sh_video->pts);
2798 break;
2800 return frame_time;
2803 static void determine_frame_pts(struct MPContext *mpctx)
2805 struct sh_video *sh_video = mpctx->sh_video;
2806 struct MPOpts *opts = &mpctx->opts;
2808 if (opts->user_pts_assoc_mode)
2809 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2810 else if (sh_video->pts_assoc_mode == 0) {
2811 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2812 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2813 sh_video->pts_assoc_mode = 1;
2814 else
2815 sh_video->pts_assoc_mode = 2;
2816 } else {
2817 int probcount1 = sh_video->num_reordered_pts_problems;
2818 int probcount2 = sh_video->num_sorted_pts_problems;
2819 if (sh_video->pts_assoc_mode == 2) {
2820 int tmp = probcount1;
2821 probcount1 = probcount2;
2822 probcount2 = tmp;
2824 if (probcount1 >= probcount2 * 1.5 + 2) {
2825 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2826 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2827 "%d.\n", sh_video->pts_assoc_mode);
2830 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2831 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2834 static double update_video(struct MPContext *mpctx)
2836 struct sh_video *sh_video = mpctx->sh_video;
2837 struct vo *video_out = mpctx->video_out;
2838 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2839 mpctx->osd); // hack for vf_expand
2840 if (!mpctx->opts.correct_pts)
2841 return update_video_nocorrect_pts(mpctx);
2843 double pts;
2845 while (1) {
2846 current_module = "filter_video";
2847 if (vo_get_buffered_frame(video_out, false) >= 0)
2848 break;
2849 // XXX Time used in this call is not counted in any performance
2850 // timer now
2851 if (vf_output_queued_frame(sh_video->vfilter))
2852 break;
2853 int in_size = 0;
2854 unsigned char *buf = NULL;
2855 pts = MP_NOPTS_VALUE;
2856 struct demux_packet *pkt;
2857 while (1) {
2858 pkt = ds_get_packet2(mpctx->d_video, false);
2859 if (!pkt || pkt->len)
2860 break;
2861 /* Packets with size 0 are assumed to not correspond to frames,
2862 * but to indicate the absence of a frame in formats like AVI
2863 * that must have packets at fixed timecode intervals. */
2865 if (pkt) {
2866 in_size = pkt->len;
2867 buf = pkt->buffer;
2868 pts = pkt->pts;
2870 if (pts != MP_NOPTS_VALUE)
2871 pts += mpctx->video_offset;
2872 if (in_size > max_framesize)
2873 max_framesize = in_size;
2874 current_module = "decode video";
2875 if (pts >= mpctx->hrseek_pts - .005)
2876 mpctx->hrseek_framedrop = false;
2877 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2878 check_framedrop(mpctx, sh_video->frametime);
2879 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2880 framedrop_type, pts);
2881 if (decoded_frame) {
2882 determine_frame_pts(mpctx);
2883 current_module = "filter video";
2884 filter_video(sh_video, decoded_frame, sh_video->pts);
2885 } else if (!pkt) {
2886 if (vo_get_buffered_frame(video_out, true) < 0)
2887 return -1;
2889 break;
2892 if (!video_out->frame_loaded)
2893 return 0;
2895 pts = video_out->next_pts;
2896 if (pts == MP_NOPTS_VALUE) {
2897 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2898 // Try to use decoder pts from before filters
2899 pts = sh_video->pts;
2900 if (pts == MP_NOPTS_VALUE)
2901 pts = sh_video->last_pts;
2903 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2904 vo_skip_frame(video_out);
2905 return 0;
2907 mpctx->hrseek_active = false;
2908 sh_video->pts = pts;
2909 if (sh_video->last_pts == MP_NOPTS_VALUE)
2910 sh_video->last_pts = sh_video->pts;
2911 else if (sh_video->last_pts > sh_video->pts) {
2912 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2913 sh_video->pts, sh_video->last_pts);
2914 /* If the difference in pts is small treat it as jitter around the
2915 * right value (possibly caused by incorrect timestamp ordering) and
2916 * just show this frame immediately after the last one.
2917 * Treat bigger differences as timestamp resets and start counting
2918 * timing of later frames from the position of this one. */
2919 if (sh_video->last_pts - sh_video->pts > 0.5)
2920 sh_video->last_pts = sh_video->pts;
2921 else
2922 sh_video->pts = sh_video->last_pts;
2924 double frame_time = sh_video->pts - sh_video->last_pts;
2925 sh_video->last_pts = sh_video->pts;
2926 sh_video->timer += frame_time;
2927 if (mpctx->sh_audio)
2928 mpctx->delay -= frame_time;
2929 return frame_time;
2932 static int get_cache_fill(struct MPContext *mpctx)
2934 #ifdef CONFIG_STREAM_CACHE
2935 if (stream_cache_size > 0)
2936 return cache_fill_status(mpctx->stream);
2937 #endif
2938 return -1;
2941 static void update_pause_message(struct MPContext *mpctx)
2943 struct MPOpts *opts = &mpctx->opts;
2945 if (opts->quiet)
2946 return;
2948 int cache_fill = get_cache_fill(mpctx);
2949 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2951 if (!mpctx->status_printed && !cache_changed)
2952 return;
2954 char *msg = mp_gtext(" ===== PAUSE =====");
2955 char *tmpmem = NULL;
2956 if (cache_fill >= 0)
2957 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
2959 if (opts->term_osd && !mpctx->sh_video) {
2960 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
2961 update_osd_msg(mpctx);
2962 } else {
2963 if (mpctx->status_printed)
2964 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
2965 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
2968 mpctx->paused_cache_fill = cache_fill;
2969 mpctx->status_printed = false;
2971 talloc_free(tmpmem);
2974 void pause_player(struct MPContext *mpctx)
2976 if (mpctx->paused)
2977 return;
2978 mpctx->paused = 1;
2979 mpctx->step_frames = 0;
2980 mpctx->time_frame -= get_relative_time(mpctx);
2981 mpctx->osd_function = OSD_PAUSE;
2983 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2984 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2986 if (mpctx->ao && mpctx->sh_audio)
2987 ao_pause(mpctx->ao); // pause audio, keep data if possible
2989 mpctx->paused_cache_fill = get_cache_fill(mpctx);
2990 mpctx->status_printed = true;
2991 update_pause_message(mpctx);
2993 if (!mpctx->opts.quiet)
2994 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2997 void unpause_player(struct MPContext *mpctx)
2999 if (!mpctx->paused)
3000 return;
3001 mpctx->paused = 0;
3002 if (!mpctx->step_frames)
3003 mpctx->osd_function = OSD_PLAY;
3005 if (mpctx->ao && mpctx->sh_audio)
3006 ao_resume(mpctx->ao);
3007 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3008 && !mpctx->step_frames)
3009 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3010 (void)get_relative_time(mpctx); // ignore time that passed during pause
3013 static int redraw_osd(struct MPContext *mpctx)
3015 struct sh_video *sh_video = mpctx->sh_video;
3016 struct vf_instance *vf = sh_video->vfilter;
3017 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3018 return -1;
3019 if (vo_redraw_frame(mpctx->video_out) < 0)
3020 return -1;
3021 mpctx->osd->pts = mpctx->video_pts - mpctx->osd->sub_offset;
3022 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3023 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3024 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3025 vo_flip_page(mpctx->video_out, 0, -1);
3026 return 0;
3029 void add_step_frame(struct MPContext *mpctx)
3031 mpctx->step_frames++;
3032 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3033 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3034 unpause_player(mpctx);
3037 static void seek_reset(struct MPContext *mpctx, bool reset_ao, bool reset_ac)
3039 if (mpctx->sh_video) {
3040 current_module = "seek_video_reset";
3041 resync_video_stream(mpctx->sh_video);
3042 mpctx->sh_video->timer = 0;
3043 vo_seek_reset(mpctx->video_out);
3044 mpctx->sh_video->timer = 0;
3045 mpctx->sh_video->num_buffered_pts = 0;
3046 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3047 mpctx->delay = 0;
3048 mpctx->time_frame = 0;
3049 // Not all demuxers set d_video->pts during seek, so this value
3050 // (which is used by at least vobsub code below) may be completely
3051 // wrong (probably 0).
3052 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3053 mpctx->video_pts = mpctx->sh_video->pts;
3054 update_subtitles(mpctx, mpctx->sh_video->pts, true);
3055 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3058 if (mpctx->sh_audio && reset_ac) {
3059 current_module = "seek_audio_reset";
3060 resync_audio_stream(mpctx->sh_audio);
3061 if (reset_ao)
3062 ao_reset(mpctx->ao);
3063 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3064 mpctx->sh_audio->a_buffer_len = 0;
3065 if (!mpctx->sh_video)
3066 update_subtitles(mpctx, mpctx->sh_audio->pts, true);
3069 if (vo_vobsub && mpctx->sh_video) {
3070 current_module = "seek_vobsub_reset";
3071 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3074 mpctx->restart_playback = true;
3075 mpctx->hrseek_active = false;
3076 mpctx->hrseek_framedrop = false;
3077 mpctx->total_avsync_change = 0;
3078 audio_time_usage = 0;
3079 video_time_usage = 0;
3080 vout_time_usage = 0;
3081 drop_frame_cnt = 0;
3083 current_module = NULL;
3086 static bool timeline_set_part(struct MPContext *mpctx, int i)
3088 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3089 struct timeline_part *n = mpctx->timeline + i;
3090 mpctx->timeline_part = i;
3091 mpctx->video_offset = n->start - n->source_start;
3092 if (n->source == p->source)
3093 return false;
3094 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3095 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3096 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3097 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3098 mpctx->stop_play = orig_stop_play;
3099 mpctx->demuxer = n->source->demuxer;
3100 mpctx->d_video = mpctx->demuxer->video;
3101 mpctx->d_audio = mpctx->demuxer->audio;
3102 mpctx->d_sub = mpctx->demuxer->sub;
3103 mpctx->sh_video = mpctx->d_video->sh;
3104 mpctx->sh_audio = mpctx->d_audio->sh;
3105 return true;
3108 // Given pts, switch playback to the corresponding part.
3109 // Return offset within that part.
3110 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3111 bool *need_reset)
3113 if (pts < 0)
3114 pts = 0;
3115 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3116 struct timeline_part *p = mpctx->timeline + i;
3117 if (pts < (p + 1)->start) {
3118 *need_reset = timeline_set_part(mpctx, i);
3119 return pts - p->start + p->source_start;
3122 return -1;
3126 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3127 static int seek(MPContext *mpctx, struct seek_params seek,
3128 bool timeline_fallthrough)
3130 struct MPOpts *opts = &mpctx->opts;
3132 current_module = "seek";
3133 if (mpctx->stop_play == AT_END_OF_FILE)
3134 mpctx->stop_play = KEEP_PLAYING;
3135 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3136 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3137 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3138 || opts->hr_seek > 0 || seek.exact > 0;
3139 if (seek.type == MPSEEK_FACTOR
3140 || seek.type == MPSEEK_ABSOLUTE
3141 && seek.amount < mpctx->last_chapter_pts
3142 || seek.amount < 0)
3143 mpctx->last_chapter_seek = -2;
3144 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3145 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3146 seek.type = MPSEEK_ABSOLUTE;
3148 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3149 && seek.type == MPSEEK_RELATIVE) {
3150 seek.type = MPSEEK_ABSOLUTE;
3151 seek.direction = seek.amount > 0 ? 1 : -1;
3152 seek.amount += get_current_time(mpctx);
3155 /* At least the liba52 decoder wants to read from the input stream
3156 * during initialization, so reinit must be done after the demux_seek()
3157 * call that clears possible stream EOF. */
3158 bool need_reset = false;
3159 double demuxer_amount = seek.amount;
3160 if (mpctx->timeline) {
3161 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3162 &need_reset);
3163 if (demuxer_amount == -1) {
3164 mpctx->stop_play = AT_END_OF_FILE;
3165 // Clear audio from current position
3166 if (mpctx->sh_audio && !timeline_fallthrough) {
3167 ao_reset(mpctx->ao);
3168 mpctx->sh_audio->a_buffer_len = 0;
3170 return -1;
3173 if (need_reset) {
3174 reinit_video_chain(mpctx);
3175 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos},
3176 mpctx);
3179 int demuxer_style = 0;
3180 switch (seek.type) {
3181 case MPSEEK_FACTOR:
3182 demuxer_style |= SEEK_FACTOR; // fallthrough
3183 case MPSEEK_ABSOLUTE:
3184 demuxer_style |= SEEK_ABSOLUTE;
3186 if (hr_seek || seek.direction < 0)
3187 demuxer_style |= SEEK_BACKWARD;
3188 else if (seek.direction > 0)
3189 demuxer_style |= SEEK_FORWARD;
3191 if (hr_seek)
3192 demuxer_amount -= opts->hr_seek_demuxer_offset;
3193 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3194 demuxer_style);
3195 if (seekresult == 0) {
3196 if (need_reset) {
3197 reinit_audio_chain(mpctx);
3198 seek_reset(mpctx, !timeline_fallthrough, false);
3200 return -1;
3203 if (need_reset)
3204 reinit_audio_chain(mpctx);
3205 /* If we just reinitialized audio it doesn't need to be reset,
3206 * and resetting could lose audio some decoders produce during init. */
3207 seek_reset(mpctx, !timeline_fallthrough, !need_reset);
3209 /* Use the target time as "current position" for further relative
3210 * seeks etc until a new video frame has been decoded */
3211 if (seek.type == MPSEEK_ABSOLUTE) {
3212 mpctx->video_pts = seek.amount;
3213 mpctx->last_seek_pts = seek.amount;
3214 } else
3215 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3217 if (hr_seek) {
3218 mpctx->hrseek_active = true;
3219 mpctx->hrseek_framedrop = true;
3220 mpctx->hrseek_pts = seek.amount;
3223 mpctx->start_timestamp = GetTimerMS();
3225 return 0;
3228 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3229 int exact)
3231 struct seek_params *seek = &mpctx->seek;
3232 switch (type) {
3233 case MPSEEK_RELATIVE:
3234 if (seek->type == MPSEEK_FACTOR)
3235 return; // Well... not common enough to bother doing better
3236 seek->amount += amount;
3237 seek->exact = FFMAX(seek->exact, exact);
3238 if (seek->type == MPSEEK_NONE)
3239 seek->exact = exact;
3240 if (seek->type == MPSEEK_ABSOLUTE)
3241 return;
3242 if (seek->amount == 0) {
3243 *seek = (struct seek_params){ 0 };
3244 return;
3246 seek->type = MPSEEK_RELATIVE;
3247 return;
3248 case MPSEEK_ABSOLUTE:
3249 case MPSEEK_FACTOR:
3250 *seek = (struct seek_params) {
3251 .type = type,
3252 .amount = amount,
3253 .exact = exact,
3255 return;
3256 case MPSEEK_NONE:
3257 *seek = (struct seek_params){ 0 };
3258 return;
3260 abort();
3264 double get_time_length(struct MPContext *mpctx)
3266 if (mpctx->timeline)
3267 return mpctx->timeline[mpctx->num_timeline_parts].start;
3269 struct demuxer *demuxer = mpctx->demuxer;
3270 double get_time_ans;
3271 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3272 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3273 (void *) &get_time_ans) > 0)
3274 return get_time_ans;
3276 struct sh_video *sh_video = mpctx->d_video->sh;
3277 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3278 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3279 return (double) (demuxer->movi_end - demuxer->movi_start) /
3280 (sh_video->i_bps + sh_audio->i_bps);
3281 if (sh_video && sh_video->i_bps)
3282 return (double) (demuxer->movi_end - demuxer->movi_start) /
3283 sh_video->i_bps;
3284 if (sh_audio && sh_audio->i_bps)
3285 return (double) (demuxer->movi_end - demuxer->movi_start) /
3286 sh_audio->i_bps;
3287 return 0;
3290 /* If there are timestamps from stream level then use those (for example
3291 * DVDs can have consistent times there while the MPEG-level timestamps
3292 * reset). */
3293 double get_current_time(struct MPContext *mpctx)
3295 struct demuxer *demuxer = mpctx->demuxer;
3296 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3297 return demuxer->stream_pts;
3298 if (mpctx->sh_video) {
3299 double pts = mpctx->video_pts;
3300 if (pts != MP_NOPTS_VALUE)
3301 return pts;
3303 double apts = playing_audio_pts(mpctx);
3304 if (apts != MP_NOPTS_VALUE)
3305 return apts;
3306 return mpctx->last_seek_pts;
3309 int get_percent_pos(struct MPContext *mpctx)
3311 struct demuxer *demuxer = mpctx->demuxer;
3312 int ans = 0;
3313 if (mpctx->timeline)
3314 ans = get_current_time(mpctx) * 100 /
3315 mpctx->timeline[mpctx->num_timeline_parts].start;
3316 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3318 else {
3319 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3320 off_t pos = demuxer->filepos > 0 ?
3321 demuxer->filepos : stream_tell(demuxer->stream);
3322 if (len > 0)
3323 ans = (pos - demuxer->movi_start) / len;
3324 else
3325 ans = 0;
3327 if (ans < 0)
3328 ans = 0;
3329 if (ans > 100)
3330 ans = 100;
3331 return ans;
3334 // -2 is no chapters, -1 is before first chapter
3335 int get_current_chapter(struct MPContext *mpctx)
3337 double current_pts = get_current_time(mpctx);
3338 if (!mpctx->chapters)
3339 return FFMAX(mpctx->last_chapter_seek,
3340 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3342 int i;
3343 for (i = 1; i < mpctx->num_chapters; i++)
3344 if (current_pts < mpctx->chapters[i].start)
3345 break;
3346 return FFMAX(mpctx->last_chapter_seek, i - 1);
3349 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3351 char *name = chapter_name(mpctx, chapter);
3352 if (name) {
3353 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3354 } else {
3355 int chapter_count = get_chapter_count(mpctx);
3356 if (chapter_count <= 0)
3357 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3358 else
3359 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3360 chapter_count);
3362 return name;
3365 // returns NULL if chapter name unavailable
3366 char *chapter_name(struct MPContext *mpctx, int chapter)
3368 if (!mpctx->chapters)
3369 return demuxer_chapter_name(mpctx->demuxer, chapter);
3370 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3373 // returns the start of the chapter in seconds
3374 double chapter_start_time(struct MPContext *mpctx, int chapter)
3376 if (!mpctx->chapters)
3377 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3378 return mpctx->chapters[chapter].start;
3381 int get_chapter_count(struct MPContext *mpctx)
3383 if (!mpctx->chapters)
3384 return demuxer_chapter_count(mpctx->demuxer);
3385 return mpctx->num_chapters;
3388 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3390 mpctx->last_chapter_seek = -2;
3391 if (!mpctx->chapters) {
3392 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3393 if (res >= 0) {
3394 if (*seek_pts == -1)
3395 seek_reset(mpctx, true, true);
3396 else {
3397 mpctx->last_chapter_seek = res;
3398 mpctx->last_chapter_pts = *seek_pts;
3401 return res;
3404 if (chapter >= mpctx->num_chapters)
3405 return -1;
3406 if (chapter < 0)
3407 chapter = 0;
3408 *seek_pts = mpctx->chapters[chapter].start;
3409 mpctx->last_chapter_seek = chapter;
3410 mpctx->last_chapter_pts = *seek_pts;
3411 return chapter;
3415 static void run_playloop(struct MPContext *mpctx)
3417 struct MPOpts *opts = &mpctx->opts;
3418 bool full_audio_buffers = false;
3419 bool audio_left = false, video_left = false;
3420 double endpts = end_at.type == END_AT_TIME ? end_at.pos : MP_NOPTS_VALUE;
3421 bool end_is_chapter = false;
3422 double sleeptime = WAKEUP_PERIOD;
3423 bool was_restart = mpctx->restart_playback;
3425 if (mpctx->timeline) {
3426 double end = mpctx->timeline[mpctx->timeline_part + 1].start;
3427 if (endpts == MP_NOPTS_VALUE || end < endpts) {
3428 endpts = end;
3429 end_is_chapter = true;
3433 if (opts->chapterrange[1] > 0) {
3434 int cur_chapter = get_current_chapter(mpctx);
3435 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3436 mpctx->stop_play = PT_NEXT_ENTRY;
3439 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3440 mpctx->sh_audio = mpctx->d_audio->sh;
3441 mpctx->sh_audio->ds = mpctx->d_audio;
3442 reinit_audio_chain(mpctx);
3445 if (mpctx->step_frames && !mpctx->sh_video) {
3446 mpctx->step_frames = 0;
3447 pause_player(mpctx);
3450 if (mpctx->sh_audio && !mpctx->restart_playback && !mpctx->ao->untimed) {
3451 int status = fill_audio_out_buffers(mpctx, endpts);
3452 full_audio_buffers = status >= 0;
3453 // Not at audio stream EOF yet
3454 audio_left = status > -2;
3457 double buffered_audio = -1;
3458 while (mpctx->sh_video) { // never loops, for "break;" only
3459 struct vo *vo = mpctx->video_out;
3460 vo_pts = mpctx->sh_video->timer * 90000.0;
3461 vo_fps = mpctx->sh_video->fps;
3463 video_left = vo->hasframe || vo->frame_loaded;
3464 if (!vo->frame_loaded && (!mpctx->paused || mpctx->restart_playback)) {
3465 double frame_time = update_video(mpctx);
3466 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3467 if (mpctx->sh_video->vf_initialized < 0) {
3468 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3469 "\nFATAL: Could not initialize video filters (-vf) "
3470 "or video output (-vo).\n");
3471 mpctx->stop_play = PT_NEXT_ENTRY;
3472 return;
3474 video_left = frame_time >= 0;
3475 if (video_left && !mpctx->restart_playback) {
3476 mpctx->time_frame += frame_time / opts->playback_speed;
3477 adjust_sync(mpctx, frame_time);
3481 if (endpts != MP_NOPTS_VALUE)
3482 video_left &= mpctx->sh_video->pts < endpts;
3484 // ================================================================
3486 current_module = "vo_check_events";
3487 vo_check_events(vo);
3489 #ifdef CONFIG_X11
3490 if (stop_xscreensaver) {
3491 current_module = "stop_xscreensaver";
3492 xscreensaver_heartbeat(mpctx->x11_state);
3494 #endif
3495 if (heartbeat_cmd) {
3496 static unsigned last_heartbeat;
3497 unsigned now = GetTimerMS();
3498 if (now - last_heartbeat > 30000) {
3499 last_heartbeat = now;
3500 system(heartbeat_cmd);
3504 if (!video_left || (mpctx->paused && !mpctx->restart_playback))
3505 break;
3506 if (!vo->frame_loaded) {
3507 sleeptime = 0;
3508 break;
3511 mpctx->time_frame -= get_relative_time(mpctx);
3512 if (full_audio_buffers && !mpctx->restart_playback) {
3513 buffered_audio = ao_get_delay(mpctx->ao);
3514 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", buffered_audio);
3516 if (opts->autosync) {
3517 /* Smooth reported playback position from AO by averaging
3518 * it with the value expected based on previus value and
3519 * time elapsed since then. May help smooth video timing
3520 * with audio output that have inaccurate position reporting.
3521 * This is badly implemented; the behavior of the smoothing
3522 * now undesirably depends on how often this code runs
3523 * (mainly depends on video frame rate). */
3524 float predicted = (mpctx->delay / opts->playback_speed +
3525 mpctx->time_frame);
3526 float difference = buffered_audio - predicted;
3527 buffered_audio = predicted + difference / opts->autosync;
3530 mpctx->time_frame = (buffered_audio -
3531 mpctx->delay / opts->playback_speed);
3532 } else {
3533 /* If we're more than 200 ms behind the right playback
3534 * position, don't try to speed up display of following
3535 * frames to catch up; continue with default speed from
3536 * the current frame instead.
3537 * If benchmark is set always output frames immediately
3538 * without sleeping.
3540 if (mpctx->time_frame < -0.2 || opts->benchmark)
3541 mpctx->time_frame = 0;
3544 double vsleep = mpctx->time_frame - vo->flip_queue_offset;
3545 if (vsleep > 0.050) {
3546 sleeptime = FFMIN(sleeptime, vsleep - 0.040);
3547 break;
3549 sleeptime = 0;
3551 //=================== FLIP PAGE (VIDEO BLT): ======================
3553 current_module = "flip_page";
3554 vo_new_frame_imminent(vo);
3555 struct sh_video *sh_video = mpctx->sh_video;
3556 mpctx->video_pts = sh_video->pts;
3557 update_subtitles(mpctx, sh_video->pts, false);
3558 update_teletext(sh_video, mpctx->demuxer, 0);
3559 update_osd_msg(mpctx);
3560 struct vf_instance *vf = sh_video->vfilter;
3561 mpctx->osd->pts = mpctx->video_pts - mpctx->osd->sub_offset;
3562 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3563 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3564 vo_osd_changed(0);
3566 mpctx->time_frame -= get_relative_time(mpctx);
3567 mpctx->time_frame -= vo->flip_queue_offset;
3568 float aq_sleep_time = mpctx->time_frame;
3569 if (mpctx->time_frame > 0.001
3570 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3571 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3572 mpctx->time_frame += vo->flip_queue_offset;
3574 unsigned int t2 = GetTimer();
3575 /* Playing with playback speed it's possible to get pathological
3576 * cases with mpctx->time_frame negative enough to cause an
3577 * overflow in pts_us calculation, thus the FFMAX. */
3578 double time_frame = FFMAX(mpctx->time_frame, -1);
3579 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3580 int duration = -1;
3581 double pts2 = vo->next_pts2;
3582 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts &&
3583 !mpctx->restart_playback) {
3584 // expected A/V sync correction is ignored
3585 double diff = (pts2 - mpctx->video_pts);
3586 diff /= opts->playback_speed;
3587 if (mpctx->time_frame < 0)
3588 diff += mpctx->time_frame;
3589 if (diff < 0)
3590 diff = 0;
3591 if (diff > 10)
3592 diff = 10;
3593 duration = diff * 1e6;
3595 vo_flip_page(vo, pts_us | 1, duration);
3597 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3598 vout_time_usage += mpctx->last_vo_flip_duration;
3599 if (vo->driver->flip_page_timed) {
3600 // No need to adjust sync based on flip speed
3601 mpctx->last_vo_flip_duration = 0;
3602 // For print_status - VO call finishing early is OK for sync
3603 mpctx->time_frame -= get_relative_time(mpctx);
3605 if (mpctx->restart_playback) {
3606 mpctx->syncing_audio = true;
3607 if (mpctx->sh_audio)
3608 fill_audio_out_buffers(mpctx, endpts);
3609 mpctx->restart_playback = false;
3610 mpctx->time_frame = 0;
3611 get_relative_time(mpctx);
3613 print_status(mpctx, MP_NOPTS_VALUE, true);
3614 screenshot_flip(mpctx);
3616 if (opts->auto_quality > 0) {
3617 current_module = "autoq";
3618 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3619 ++output_quality;
3620 else if (output_quality > 1 && aq_sleep_time < 0)
3621 --output_quality;
3622 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3623 output_quality = 0;
3624 set_video_quality(mpctx->sh_video, output_quality);
3627 if (play_n_frames >= 0) {
3628 --play_n_frames;
3629 if (play_n_frames <= 0)
3630 mpctx->stop_play = PT_NEXT_ENTRY;
3632 if (mpctx->step_frames > 0) {
3633 mpctx->step_frames--;
3634 if (mpctx->step_frames == 0)
3635 pause_player(mpctx);
3637 break;
3638 } // video
3640 #ifdef CONFIG_DVDNAV
3641 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3642 nav_highlight_t hl;
3643 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3644 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3645 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3646 vo_osd_changed(OSDTYPE_DVDNAV);
3647 } else {
3648 osd_set_nav_box(0, 0, 0, 0);
3649 vo_osd_changed(OSDTYPE_DVDNAV);
3650 vo_osd_changed(OSDTYPE_SPU);
3653 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3654 double ar = -1.0;
3655 if (mpctx->sh_video &&
3656 stream_control(mpctx->demuxer->stream,
3657 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3658 != STREAM_UNSUPPORTED)
3659 mpctx->sh_video->stream_aspect = ar;
3662 #endif
3664 if (mpctx->sh_audio && (mpctx->restart_playback ? !video_left :
3665 mpctx->ao->untimed && (mpctx->delay <= 0 ||
3666 !video_left))) {
3667 int status = fill_audio_out_buffers(mpctx, endpts);
3668 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3669 // Not at audio stream EOF yet
3670 audio_left = status > -2;
3672 if (!video_left)
3673 mpctx->restart_playback = false;
3674 if (mpctx->sh_audio && buffered_audio == -1)
3675 buffered_audio = mpctx->paused ? 0 : ao_get_delay(mpctx->ao);
3677 update_osd_msg(mpctx);
3678 if (mpctx->paused)
3679 update_pause_message(mpctx);
3680 if (!video_left && (!mpctx->paused || was_restart)) {
3681 double a_pos = 0;
3682 if (mpctx->sh_audio) {
3683 a_pos = (written_audio_pts(mpctx) -
3684 mpctx->opts.playback_speed * buffered_audio);
3686 print_status(mpctx, a_pos, false);
3688 if (!mpctx->sh_video)
3689 update_subtitles(mpctx, a_pos, false);
3692 /* It's possible for the user to simultaneously switch both audio
3693 * and video streams to "disabled" at runtime. Handle this by waiting
3694 * rather than immediately stopping playback due to EOF.
3696 * When all audio has been written to output driver, stay in the
3697 * main loop handling commands until it has been mostly consumed,
3698 * except in the gapless case, where the next file will be started
3699 * while audio from the current one still remains to be played.
3701 * We want this check to trigger if we seeked to this position,
3702 * but not if we paused at it with audio possibly still buffered in
3703 * the AO. There's currently no working way to check buffered audio
3704 * inside AO while paused. Thus the "was_restart" check below, which
3705 * should trigger after seek only, when we know there's no audio
3706 * buffered.
3708 if ((mpctx->sh_audio || mpctx->sh_video) && !audio_left && !video_left
3709 && (opts->gapless_audio || buffered_audio < 0.05)
3710 && (!mpctx->paused || was_restart)) {
3711 if (end_is_chapter) {
3712 seek(mpctx, (struct seek_params){
3713 .type = MPSEEK_ABSOLUTE,
3714 .amount = mpctx->timeline[mpctx->timeline_part+1].start
3715 }, true);
3716 } else
3717 mpctx->stop_play = AT_END_OF_FILE;
3718 } else if (!mpctx->stop_play) {
3719 double audio_sleep = 9;
3720 if (mpctx->sh_audio && !mpctx->paused) {
3721 if (mpctx->ao->untimed) {
3722 if (!video_left)
3723 audio_sleep = 0;
3724 } else if (full_audio_buffers) {
3725 audio_sleep = buffered_audio - 0.050;
3726 // Keep extra safety margin if the buffers are large
3727 if (audio_sleep > 0.100)
3728 audio_sleep = FFMAX(audio_sleep - 0.200, 0.100);
3729 else
3730 audio_sleep = FFMAX(audio_sleep, 0.020);
3731 } else
3732 audio_sleep = 0.020;
3734 sleeptime = FFMIN(sleeptime, audio_sleep);
3735 if (sleeptime > 0) {
3736 if (!mpctx->sh_video)
3737 goto novideo;
3738 int hack = vo_osd_changed(0);
3739 vo_osd_changed(hack);
3740 if (hack || mpctx->video_out->want_redraw) {
3741 if (redraw_osd(mpctx) < 0) {
3742 if (mpctx->paused && video_left)
3743 add_step_frame(mpctx);
3744 else
3745 goto novideo;
3746 } else
3747 vo_osd_changed(0);
3748 } else {
3749 novideo:
3750 mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
3755 //================= Keyboard events, SEEKing ====================
3757 current_module = "key_events";
3759 mp_cmd_t *cmd;
3760 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3761 /* Allow running consecutive seek commands to combine them,
3762 * but execute the seek before running other commands.
3763 * If the user seeks continuously (keeps arrow key down)
3764 * try to finish showing a frame from one location before doing
3765 * another seek (which could lead to unchanging display). */
3766 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3767 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3768 && GetTimerMS() - mpctx->start_timestamp < 300)
3769 break;
3770 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3771 run_command(mpctx, cmd);
3772 mp_cmd_free(cmd);
3773 if (mpctx->stop_play)
3774 break;
3777 // handle -sstep
3778 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3779 mpctx->osd_function = OSD_FFW;
3780 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3783 /* Looping. */
3784 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3785 mpctx->stop_play == PT_NEXT_ENTRY)) {
3786 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3788 if (opts->loop_times > 1)
3789 opts->loop_times--;
3790 else if (opts->loop_times == 1)
3791 opts->loop_times = -1;
3792 play_n_frames = play_n_frames_mf;
3793 mpctx->stop_play = 0;
3794 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3797 if (mpctx->seek.type) {
3798 seek(mpctx, mpctx->seek, false);
3799 mpctx->seek = (struct seek_params){ 0 };
3804 static int read_keys(void *ctx, int fd)
3806 if (getch2(ctx))
3807 return MP_INPUT_NOTHING;
3808 return MP_INPUT_DEAD;
3811 static bool attachment_is_font(struct demux_attachment *att)
3813 if (!att->name || !att->type || !att->data || !att->data_size)
3814 return false;
3815 // match against MIME types
3816 if (strcmp(att->type, "application/x-truetype-font") == 0
3817 || strcmp(att->type, "application/x-font") == 0)
3818 return true;
3819 // fallback: match against file extension
3820 if (strlen(att->name) > 4) {
3821 char *ext = att->name + strlen(att->name) - 4;
3822 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3823 || strcasecmp(ext, ".otf") == 0)
3824 return true;
3826 return false;
3829 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3831 if (audio_id == -1)
3832 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3833 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3834 demuxer_switch_audio(demuxer, audio_id);
3835 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3836 demuxer->audio->id = -2;
3837 demuxer->audio->sh = NULL;
3839 return demuxer->audio->id;
3842 static void print_version(const char *name)
3844 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3846 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3847 GetCpuCaps(&gCpuCaps);
3848 #if ARCH_X86
3849 mp_msg(MSGT_CPLAYER, MSGL_V,
3850 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3851 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3852 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3853 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3854 #if CONFIG_RUNTIME_CPUDETECT
3855 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3856 #else
3857 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3858 if (HAVE_MMX)
3859 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3860 if (HAVE_MMX2)
3861 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3862 if (HAVE_AMD3DNOW)
3863 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3864 if (HAVE_AMD3DNOWEXT)
3865 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3866 if (HAVE_SSE)
3867 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3868 if (HAVE_SSE2)
3869 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3870 if (HAVE_SSSE3)
3871 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3872 if (HAVE_CMOV)
3873 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3874 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3875 #endif /* CONFIG_RUNTIME_CPUDETECT */
3876 #endif /* ARCH_X86 */
3877 print_libav_versions();
3880 #ifdef PTW32_STATIC_LIB
3881 static void detach_ptw32(void)
3883 pthread_win32_thread_detach_np();
3884 pthread_win32_process_detach_np();
3886 #endif
3888 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3889 * file for some tools to link against. */
3890 #ifndef DISABLE_MAIN
3891 int main(int argc, char *argv[])
3893 #ifdef PTW32_STATIC_LIB
3894 pthread_win32_process_attach_np();
3895 pthread_win32_thread_attach_np();
3896 atexit(detach_ptw32);
3897 #endif
3898 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3899 || !strcmp(argv[1], "--leak-report")))
3900 talloc_enable_leak_report();
3902 #ifdef __MINGW32__
3903 mp_get_converted_argv(&argc, &argv);
3904 #endif
3906 char *mem_ptr;
3908 // movie info:
3910 /* Flag indicating whether MPlayer should exit without playing anything. */
3911 int opt_exit = 0;
3912 int i;
3914 struct MPContext *mpctx = talloc(NULL, MPContext);
3915 *mpctx = (struct MPContext){
3916 .osd_function = OSD_PLAY,
3917 .begin_skip = MP_NOPTS_VALUE,
3918 .play_tree_step = 1,
3919 .global_sub_pos = -1,
3920 .set_of_sub_pos = -1,
3921 .file_format = DEMUXER_TYPE_UNKNOWN,
3922 .last_dvb_step = 1,
3923 .paused_cache_fill = -1,
3926 InitTimer();
3927 srand(GetTimerMS());
3929 mp_msg_init();
3930 init_libav();
3932 #ifdef CONFIG_X11
3933 mpctx->x11_state = vo_x11_init_state();
3934 #endif
3935 struct MPOpts *opts = &mpctx->opts;
3936 set_default_mplayer_options(opts);
3937 // Create the config context and register the options
3938 mpctx->mconfig = m_config_new(opts, cfg_include);
3939 m_config_register_options(mpctx->mconfig, mplayer_opts);
3940 m_config_register_options(mpctx->mconfig, common_opts);
3941 mp_input_register_options(mpctx->mconfig);
3942 m_config_initialize(mpctx->mconfig, opts);
3944 // Preparse the command line
3945 m_config_preparse_command_line(mpctx->mconfig, argc, argv, &verbose);
3947 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3948 set_path_env();
3949 #endif
3951 #ifdef CONFIG_TV
3952 stream_tv_defaults.immediate = 1;
3953 #endif
3955 parse_cfgfiles(mpctx, mpctx->mconfig);
3957 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3958 if (mpctx->playtree == NULL)
3959 opt_exit = 1;
3960 else {
3961 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3962 if (mpctx->playtree) {
3963 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3964 mpctx->mconfig);
3965 if (mpctx->playtree_iter) {
3966 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3967 PLAY_TREE_ITER_ENTRY) {
3968 play_tree_iter_free(mpctx->playtree_iter);
3969 mpctx->playtree_iter = NULL;
3971 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3977 print_version("MPlayer2");
3979 #if defined(__MINGW32__) || defined(__CYGWIN__)
3981 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3982 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3983 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3984 if (kernel32) {
3985 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3986 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3988 if (setDEP)
3989 setDEP(3);
3990 if (setDllDir)
3991 setDllDir("");
3993 // stop Windows from showing all kinds of annoying error dialogs
3994 SetErrorMode(0x8003);
3995 // request 1ms timer resolution
3996 timeBeginPeriod(1);
3997 #endif
3999 #ifdef CONFIG_PRIORITY
4000 set_priority();
4001 #endif
4003 if (opts->video_driver_list &&
4004 strcmp(opts->video_driver_list[0], "help") == 0) {
4005 list_video_out();
4006 opt_exit = 1;
4009 if (opts->audio_driver_list &&
4010 strcmp(opts->audio_driver_list[0], "help") == 0) {
4011 list_audio_out();
4012 opt_exit = 1;
4015 /* Check codecs.conf. */
4016 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4017 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4018 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4019 if (!parse_codec_cfg(NULL))
4020 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4021 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4022 "Using built-in default codecs.conf.\n");
4025 free(mem_ptr); // release the buffer created by get_path()
4028 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4029 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4030 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4031 list_codecs(1);
4032 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4033 opt_exit = 1;
4035 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4036 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4037 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4038 list_codecs(0);
4039 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4040 opt_exit = 1;
4042 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4043 vfm_help();
4044 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4045 opt_exit = 1;
4047 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4048 afm_help();
4049 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4050 opt_exit = 1;
4052 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4053 af_help();
4054 printf("\n");
4055 opt_exit = 1;
4057 #ifdef CONFIG_X11
4058 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4059 fstype_help();
4060 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4061 opt_exit = 1;
4063 #endif
4064 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4065 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4066 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4067 demuxer_help();
4068 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4069 opt_exit = 1;
4071 if (opts->list_properties) {
4072 property_print_help();
4073 opt_exit = 1;
4076 if (opt_exit)
4077 exit_player(mpctx, EXIT_NONE);
4079 if (!mpctx->filename && !opts->player_idle_mode) {
4080 // no file/vcd/dvd -> show HELP:
4081 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4082 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4085 /* Display what configure line was used */
4086 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4088 // Many users forget to include command line in bugreports...
4089 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4090 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4091 for (i = 1; i < argc; i++)
4092 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4093 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4096 //------ load global data first ------
4098 mpctx->osd = osd_create();
4100 // check font
4101 #ifdef CONFIG_FREETYPE
4102 init_freetype();
4103 #endif
4104 #ifdef CONFIG_FONTCONFIG
4105 if (font_fontconfig <= 0) {
4106 #endif
4107 #ifdef CONFIG_BITMAP_FONT
4108 if (font_name) {
4109 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4110 if (!vo_font)
4111 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4112 filename_recode(font_name));
4113 } else {
4114 // try default:
4115 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4116 font_factor, verbose > 1);
4117 free(mem_ptr); // release the buffer created by get_path()
4118 if (!vo_font)
4119 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4120 font_factor, verbose > 1);
4122 if (sub_font_name)
4123 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4124 verbose > 1);
4125 else
4126 mpctx->osd->sub_font = vo_font;
4127 #endif
4128 #ifdef CONFIG_FONTCONFIG
4130 #endif
4132 #ifdef CONFIG_ASS
4133 mpctx->ass_library = mp_ass_init(opts);
4134 mpctx->osd->ass_library = mpctx->ass_library;
4135 #endif
4137 #ifdef HAVE_RTC
4138 if (opts->rtc) {
4139 char *rtc_device = opts->rtc_device;
4140 // seteuid(0); /* Can't hurt to try to get root here */
4141 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4142 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4143 "(it should be readable by the user.)\n",
4144 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4145 else {
4146 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4148 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4149 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4150 "ioctl (rtc_irqp_set %lu): %s\n",
4151 irqp, strerror(errno));
4152 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4153 close(rtc_fd);
4154 rtc_fd = -1;
4155 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4156 /* variable only by the root */
4157 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4158 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4159 close(rtc_fd);
4160 rtc_fd = -1;
4161 } else
4162 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4163 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4166 if (rtc_fd < 0)
4167 #endif /* HAVE_RTC */
4168 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4169 opts->softsleep ? "software" : timer_name);
4171 #ifdef HAVE_TERMCAP
4172 load_termcap(NULL); // load key-codes
4173 #endif
4175 // ========== Init keyboard FIFO (connection to libvo) ============
4177 // Init input system
4178 current_module = "init_input";
4179 mpctx->input = mp_input_init(&opts->input);
4180 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4181 if (slave_mode)
4182 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4183 else if (opts->consolecontrols)
4184 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4185 // Set the libstream interrupt callback
4186 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4188 current_module = NULL;
4190 /// Catch signals
4191 #ifndef __MINGW32__
4192 signal(SIGCHLD, child_sighandler);
4193 #endif
4195 #ifdef CONFIG_CRASH_DEBUG
4196 prog_path = argv[0];
4197 #endif
4198 //========= Catch terminate signals: ================
4199 // terminate requests:
4200 signal(SIGTERM, exit_sighandler); // kill
4201 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4203 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4205 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4206 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4207 #ifdef CONFIG_SIGHANDLER
4208 // fatal errors:
4209 signal(SIGBUS, exit_sighandler); // bus error
4210 signal(SIGSEGV, exit_sighandler); // segfault
4211 signal(SIGILL, exit_sighandler); // illegal instruction
4212 signal(SIGFPE, exit_sighandler); // floating point exc.
4213 signal(SIGABRT, exit_sighandler); // abort()
4214 #ifdef CONFIG_CRASH_DEBUG
4215 if (crash_debug)
4216 signal(SIGTRAP, exit_sighandler);
4217 #endif
4218 #endif
4220 // ***************** Now, let's see the per-file stuff ******************
4222 play_next_file:
4224 // init global sub numbers
4225 mpctx->global_sub_size = 0;
4226 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4228 if (mpctx->filename) {
4229 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4230 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4231 load_per_file_config(mpctx->mconfig, mpctx->filename);
4234 if (opts->video_driver_list)
4235 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4236 opts->video_driver_list[0]);
4237 if (opts->audio_driver_list)
4238 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4239 opts->audio_driver_list[0]);
4241 // We must enable getch2 here to be able to interrupt network connection
4242 // or cache filling
4243 if (opts->consolecontrols && !slave_mode) {
4244 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4245 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4246 "WARNING: getch2_init called twice!\n");
4247 else
4248 getch2_enable(); // prepare stdin for hotkeys...
4249 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4250 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4253 // ================= idle loop (STOP state) =========================
4254 while (opts->player_idle_mode && !mpctx->filename) {
4255 uninit_player(mpctx, INITIALIZED_AO | INITIALIZED_VO);
4256 play_tree_t *entry = NULL;
4257 mp_cmd_t *cmd;
4258 while (!(cmd = mp_input_get_cmd(mpctx->input, WAKEUP_PERIOD * 1000,
4259 false)));
4260 switch (cmd->id) {
4261 case MP_CMD_LOADFILE:
4262 // prepare a tree entry with the new filename
4263 entry = play_tree_new();
4264 play_tree_add_file(entry, cmd->args[0].v.s);
4265 // The entry is added to the main playtree after the switch().
4266 break;
4267 case MP_CMD_LOADLIST:
4268 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4269 break;
4270 case MP_CMD_QUIT:
4271 exit_player_with_rc(mpctx, EXIT_QUIT,
4272 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4273 break;
4274 case MP_CMD_VO_FULLSCREEN:
4275 case MP_CMD_GET_PROPERTY:
4276 case MP_CMD_SET_PROPERTY:
4277 case MP_CMD_STEP_PROPERTY:
4278 run_command(mpctx, cmd);
4279 break;
4282 mp_cmd_free(cmd);
4284 if (entry) { // user entered a command that gave a valid entry
4285 if (mpctx->playtree)
4286 // the playtree is always a node with one child. let's clear it
4287 play_tree_free_list(mpctx->playtree->child, 1);
4288 else
4289 // .. or make a brand new playtree
4290 mpctx->playtree = play_tree_new();
4292 if (!mpctx->playtree)
4293 continue; // couldn't make playtree! wait for next command
4295 play_tree_set_child(mpctx->playtree, entry);
4297 /* Make iterator start at the top the of tree. */
4298 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4299 mpctx->mconfig);
4300 if (!mpctx->playtree_iter)
4301 continue;
4303 // find the first real item in the tree
4304 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4305 PLAY_TREE_ITER_ENTRY) {
4306 // no items!
4307 play_tree_iter_free(mpctx->playtree_iter);
4308 mpctx->playtree_iter = NULL;
4309 continue; // wait for next command
4311 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4315 #ifdef CONFIG_ASS
4316 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4317 #endif
4318 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4319 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4321 if (mpctx->filename) {
4322 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4323 filename_recode(mpctx->filename));
4324 if (use_filename_title && opts->vo_wintitle == NULL)
4325 opts->vo_wintitle = talloc_strdup(NULL,
4326 mp_basename(mpctx->filename));
4329 if (edl_output_filename) {
4330 if (edl_fd)
4331 fclose(edl_fd);
4332 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4333 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4334 "Can't open EDL file [%s] for writing.\n",
4335 filename_recode(edl_output_filename));
4339 //==================== Open VOB-Sub ============================
4341 current_module = "vobsub";
4342 if (opts->vobsub_name) {
4343 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4344 if (vo_vobsub == NULL)
4345 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4346 filename_recode(opts->vobsub_name));
4347 } else if (opts->sub_auto && mpctx->filename) {
4348 char **vob = find_vob_subtitles(opts, mpctx->filename);
4349 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4350 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4351 if (vo_vobsub)
4352 break;
4354 talloc_free(vob);
4356 if (vo_vobsub) {
4357 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4358 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4359 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4360 mpctx);
4362 // setup global sub numbering
4363 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4364 vobsub_get_indexes_count(vo_vobsub);
4367 //============ Open & Sync STREAM --- fork cache2 ====================
4369 mpctx->stream = NULL;
4370 mpctx->demuxer = NULL;
4371 mpctx->d_audio = NULL;
4372 mpctx->d_video = NULL;
4373 mpctx->d_sub = NULL;
4374 mpctx->sh_audio = NULL;
4375 mpctx->sh_video = NULL;
4377 current_module = "open_stream";
4378 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4379 if (!mpctx->stream) { // error...
4380 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4381 goto goto_next_file;
4383 mpctx->initialized_flags |= INITIALIZED_STREAM;
4385 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4386 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4387 "playlist support will not be used automatically.\n"
4388 "MPlayer's playlist code is unsafe and should only be used with "
4389 "trusted sources.\nPlayback will probably fail.\n\n");
4390 #if 0
4391 play_tree_t *entry;
4392 // Handle playlist
4393 current_module = "handle_playlist";
4394 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4395 filename_recode(mpctx->filename));
4396 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4397 mpctx->eof = playtree_add_playlist(mpctx, entry);
4398 goto goto_next_file;
4399 #endif
4401 mpctx->stream->start_pos += seek_to_byte;
4403 if (stream_dump_type == 5) {
4404 unsigned char buf[4096];
4405 int len;
4406 FILE *f;
4407 current_module = "dumpstream";
4408 stream_reset(mpctx->stream);
4409 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4410 f = fopen(opts->stream_dump_name, "wb");
4411 if (!f) {
4412 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4413 exit_player(mpctx, EXIT_ERROR);
4415 if (opts->chapterrange[0] > 1) {
4416 int chapter = opts->chapterrange[0] - 1;
4417 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4419 struct stream_dump_progress info;
4420 stream_dump_progress_start(&info);
4421 while (!mpctx->stream->eof && !async_quit_request) {
4422 len = stream_read(mpctx->stream, buf, 4096);
4423 if (len > 0) {
4424 if (fwrite(buf, len, 1, f) != 1) {
4425 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4426 exit_player(mpctx, EXIT_ERROR);
4429 stream_dump_progress(&info, len, mpctx->stream);
4430 if (opts->chapterrange[1] > 0) {
4431 int chapter = -1;
4432 if (stream_control(mpctx->stream,
4433 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4434 && chapter + 1 > opts->chapterrange[1])
4435 break;
4438 if (fclose(f)) {
4439 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4440 opts->stream_dump_name);
4441 exit_player(mpctx, EXIT_ERROR);
4443 stream_dump_progress_end(&info, opts->stream_dump_name);
4444 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4445 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4448 #ifdef CONFIG_DVDREAD
4449 if (mpctx->stream->type == STREAMTYPE_DVD) {
4450 current_module = "dvd lang->id";
4451 if (opts->audio_lang && opts->audio_id == -1)
4452 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4453 if (opts->sub_lang && opts->sub_id == -1)
4454 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4455 // setup global sub numbering
4456 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4457 current_module = NULL;
4459 #endif
4461 #ifdef CONFIG_DVDNAV
4462 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4463 current_module = "dvdnav lang->id";
4464 if (opts->audio_lang && opts->audio_id == -1)
4465 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4466 opts->audio_lang);
4467 dvdsub_lang_id = -3;
4468 if (opts->sub_lang && opts->sub_id == -1)
4469 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4470 mpctx->stream, opts->sub_lang);
4471 // setup global sub numbering
4472 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4473 mpctx->stream);
4474 current_module = NULL;
4476 #endif
4478 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4479 goto_enable_cache:
4480 if (stream_cache_size > 0) {
4481 int res;
4482 float stream_cache_min_percent = opts->stream_cache_min_percent;
4483 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4484 current_module = "enable_cache";
4485 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4486 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4487 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4488 if (res == 0)
4489 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4490 goto goto_next_file;
4493 //============ Open DEMUXERS --- DETECT file type =======================
4494 current_module = "demux_open";
4496 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4497 opts->audio_id, opts->video_id, opts->sub_id,
4498 mpctx->filename);
4500 // HACK to get MOV Reference Files working
4502 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4503 unsigned char *playlist_entry;
4504 play_tree_t *list = NULL, *entry = NULL;
4506 current_module = "handle_demux_playlist";
4507 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4508 char *temp;
4509 const char *bname;
4511 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4512 filename_recode(playlist_entry));
4514 bname = mp_basename(playlist_entry);
4515 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4516 !strncmp(bname + 3, "gateQT", 6))
4517 continue;
4519 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4520 continue;
4522 entry = play_tree_new();
4524 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4525 playlist_entry)) { // add reference path of current file
4526 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4527 mpctx->filename)) + strlen(playlist_entry) + 1));
4528 if (temp) {
4529 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4530 strlen(mp_basename(mpctx->filename)));
4531 temp[strlen(mpctx->filename) - strlen(mp_basename(
4532 mpctx->filename))] = '\0';
4533 strcat(temp, playlist_entry);
4534 if (!strcmp(temp, mpctx->filename)) {
4535 free(temp);
4536 continue;
4538 play_tree_add_file(entry, temp);
4539 mp_msg(MSGT_CPLAYER, MSGL_V,
4540 "Resolving reference to %s.\n", temp);
4541 free(temp);
4543 } else
4544 play_tree_add_file(entry, playlist_entry);
4546 if (!list)
4547 list = entry;
4548 else
4549 play_tree_append_entry(list, entry);
4551 free_demuxer(mpctx->demuxer);
4552 mpctx->demuxer = NULL;
4554 if (list) {
4555 entry = play_tree_new();
4556 play_tree_set_child(entry, list);
4557 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4558 goto goto_next_file;
4562 if (!mpctx->demuxer) {
4563 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4564 goto goto_next_file;
4567 if (mpctx->demuxer->matroska_data.ordered_chapters)
4568 build_ordered_chapter_timeline(mpctx);
4570 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4571 build_edl_timeline(mpctx);
4573 if (mpctx->timeline) {
4574 mpctx->timeline_part = 0;
4575 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4577 int part_count = mpctx->num_timeline_parts;
4578 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4579 "sources. Total length %.3f seconds.\n", part_count,
4580 mpctx->num_sources, mpctx->timeline[part_count].start);
4581 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4582 for (int i = 0; i < mpctx->num_sources; i++)
4583 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4584 filename_recode(mpctx->sources[i].demuxer->filename));
4585 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4586 "source_start, source):\n");
4587 for (int i = 0; i < part_count; i++) {
4588 struct timeline_part *p = mpctx->timeline + i;
4589 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4590 p->source_start, p->source - mpctx->sources);
4592 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4593 mpctx->timeline[part_count].start);
4596 if (!mpctx->sources) {
4597 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4598 *mpctx->sources = (struct content_source){
4599 .stream = mpctx->stream,
4600 .demuxer = mpctx->demuxer
4602 mpctx->num_sources = 1;
4605 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4607 #ifdef CONFIG_ASS
4608 if (opts->ass_enabled && mpctx->ass_library) {
4609 for (int j = 0; j < mpctx->num_sources; j++) {
4610 struct demuxer *d = mpctx->sources[j].demuxer;
4611 for (int i = 0; i < d->num_attachments; i++) {
4612 struct demux_attachment *att = d->attachments + i;
4613 if (opts->use_embedded_fonts && attachment_is_font(att))
4614 ass_add_font(mpctx->ass_library, att->name, att->data,
4615 att->data_size);
4619 #endif
4621 current_module = "demux_open2";
4623 mpctx->d_audio = mpctx->demuxer->audio;
4624 mpctx->d_video = mpctx->demuxer->video;
4625 mpctx->d_sub = mpctx->demuxer->sub;
4627 if (ts_prog) {
4628 int tmp = ts_prog;
4629 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4631 // select audio stream
4632 for (int i = 0; i < mpctx->num_sources; i++)
4633 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4634 opts->audio_lang);
4636 // DUMP STREAMS:
4637 if ((stream_dump_type) && (stream_dump_type < 4)) {
4638 FILE *f;
4639 demux_stream_t *ds = NULL;
4640 current_module = "dump";
4641 // select stream to dump
4642 switch (stream_dump_type) {
4643 case 1: ds = mpctx->d_audio;
4644 break;
4645 case 2: ds = mpctx->d_video;
4646 break;
4647 case 3: ds = mpctx->d_sub;
4648 break;
4650 if (!ds) {
4651 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4652 "dump: FATAL: Selected stream missing!\n");
4653 exit_player(mpctx, EXIT_ERROR);
4655 // disable other streams:
4656 if (mpctx->d_audio && mpctx->d_audio != ds) {
4657 ds_free_packs(mpctx->d_audio);
4658 mpctx->d_audio->id = -2;
4660 if (mpctx->d_video && mpctx->d_video != ds) {
4661 ds_free_packs(mpctx->d_video);
4662 mpctx->d_video->id = -2;
4664 if (mpctx->d_sub && mpctx->d_sub != ds) {
4665 ds_free_packs(mpctx->d_sub);
4666 mpctx->d_sub->id = -2;
4668 // let's dump it!
4669 f = fopen(opts->stream_dump_name, "wb");
4670 if (!f) {
4671 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4672 exit_player(mpctx, EXIT_ERROR);
4674 struct stream_dump_progress info;
4675 stream_dump_progress_start(&info);
4676 while (!ds->eof) {
4677 unsigned char *start;
4678 int in_size = ds_get_packet(ds, &start);
4679 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4680 && stream_dump_type == 2)
4681 fwrite(&in_size, 1, 4, f);
4682 if (in_size > 0) {
4683 fwrite(start, in_size, 1, f);
4684 stream_dump_progress(&info, in_size, mpctx->stream);
4686 if (opts->chapterrange[1] > 0) {
4687 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4688 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4689 break;
4692 fclose(f);
4693 stream_dump_progress_end(&info, opts->stream_dump_name);
4694 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4695 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4698 mpctx->sh_audio = mpctx->d_audio->sh;
4699 mpctx->sh_video = mpctx->d_video->sh;
4701 if (mpctx->sh_video) {
4702 current_module = "video_read_properties";
4703 if (!video_read_properties(mpctx->sh_video)) {
4704 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4705 mpctx->sh_video = mpctx->d_video->sh = NULL;
4706 } else {
4707 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4708 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4709 mpctx->demuxer->file_format, mpctx->sh_video->format,
4710 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4711 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4712 if (force_fps) {
4713 mpctx->sh_video->fps = force_fps;
4714 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4716 vo_fps = mpctx->sh_video->fps;
4718 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4719 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4720 "header or invalid, use the -fps option.\n");
4726 if (!mpctx->sh_video && !mpctx->sh_audio) {
4727 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4728 #ifdef CONFIG_DVBIN
4729 if (mpctx->stream->type == STREAMTYPE_DVB) {
4730 int dir;
4731 int v = mpctx->last_dvb_step;
4732 if (v > 0)
4733 dir = DVB_CHANNEL_HIGHER;
4734 else
4735 dir = DVB_CHANNEL_LOWER;
4737 if (dvb_step_channel(mpctx->stream, dir)) {
4738 mpctx->stop_play = PT_NEXT_ENTRY;
4739 mpctx->dvbin_reopen = 1;
4742 #endif
4743 goto goto_next_file; // exit_player(_("Fatal error"));
4746 /* display clip info */
4747 demux_info_print(mpctx->demuxer);
4749 //================= Read SUBTITLES (DVD & TEXT) =========================
4750 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4751 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4752 init_vo_spudec(mpctx);
4754 // after reading video params we should load subtitles because
4755 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4756 // check .sub
4757 current_module = "read_subtitles_file";
4758 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4759 if (opts->sub_name) {
4760 for (i = 0; opts->sub_name[i] != NULL; ++i)
4761 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4763 if (opts->sub_auto) { // auto load sub file ...
4764 char **tmp = find_text_subtitles(opts, mpctx->filename);
4765 int nsub = MP_TALLOC_ELEMS(tmp);
4766 for (int i = 0; i < nsub; i++)
4767 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4768 talloc_free(tmp);
4770 if (mpctx->set_of_sub_size > 0)
4771 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4773 if (select_subtitle(mpctx)) {
4774 if (mpctx->subdata)
4775 switch (stream_dump_type) {
4776 case 3: list_sub_file(mpctx->subdata);
4777 break;
4778 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4779 break;
4780 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4781 break;
4782 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4783 break;
4784 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4785 break;
4786 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4787 break;
4791 print_file_properties(mpctx, mpctx->filename);
4793 reinit_video_chain(mpctx);
4794 if (mpctx->sh_video) {
4795 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4796 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4797 #ifdef CONFIG_FREETYPE
4798 force_load_font = 1;
4799 #endif
4800 } else if (!mpctx->sh_audio)
4801 goto goto_next_file;
4803 //================== MAIN: ==========================
4804 current_module = "main";
4806 if (opts->playing_msg) {
4807 char *msg = property_expand_string(mpctx, opts->playing_msg);
4808 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4809 free(msg);
4813 // Disable the term OSD in verbose mode
4814 if (verbose)
4815 opts->term_osd = 0;
4817 // Make sure old OSD does not stay around
4818 clear_osd_msgs();
4820 //================ SETUP AUDIO ==========================
4822 if (mpctx->sh_audio) {
4823 reinit_audio_chain(mpctx);
4824 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4825 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4826 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4829 current_module = "av_init";
4831 if (mpctx->sh_video) {
4832 mpctx->sh_video->timer = 0;
4833 if (!ignore_start)
4834 audio_delay += mpctx->sh_video->stream_delay;
4836 if (mpctx->sh_audio) {
4837 if (start_volume >= 0)
4838 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4839 if (!ignore_start)
4840 audio_delay -= mpctx->sh_audio->stream_delay;
4843 if (!mpctx->sh_audio) {
4844 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4845 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4846 mpctx->d_audio->packs);
4847 ds_free_packs(mpctx->d_audio); // free buffered chunks
4849 if (!mpctx->sh_video) {
4850 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4851 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4852 mpctx->d_video->packs);
4853 ds_free_packs(mpctx->d_video);
4854 mpctx->d_video->id = -2;
4857 if (!mpctx->sh_video && !mpctx->sh_audio)
4858 goto goto_next_file;
4860 if (force_fps && mpctx->sh_video) {
4861 vo_fps = mpctx->sh_video->fps = force_fps;
4862 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4863 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4864 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4865 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4868 mp_input_set_section(mpctx->input, NULL);
4869 //TODO: add desired (stream-based) sections here
4870 if (mpctx->stream->type == STREAMTYPE_TV)
4871 mp_input_set_section(mpctx->input, "tv");
4872 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4873 mp_input_set_section(mpctx->input, "dvdnav");
4875 //==================== START PLAYING =======================
4877 if (opts->loop_times > 1)
4878 opts->loop_times--;
4879 else if (opts->loop_times == 1)
4880 opts->loop_times = -1;
4882 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4884 total_time_usage_start = GetTimer();
4885 audio_time_usage = 0;
4886 video_time_usage = 0;
4887 vout_time_usage = 0;
4888 total_frame_cnt = 0;
4889 drop_frame_cnt = 0; // fix for multifile fps benchmark
4890 play_n_frames = play_n_frames_mf;
4892 if (play_n_frames == 0) {
4893 mpctx->stop_play = PT_NEXT_ENTRY;
4894 goto goto_next_file;
4897 mpctx->time_frame = 0;
4898 mpctx->drop_message_shown = 0;
4899 mpctx->restart_playback = true;
4900 mpctx->video_pts = 0;
4901 mpctx->last_seek_pts = 0;
4902 mpctx->hrseek_active = false;
4903 mpctx->hrseek_framedrop = false;
4904 mpctx->step_frames = 0;
4905 mpctx->total_avsync_change = 0;
4906 mpctx->last_chapter_seek = -2;
4908 // If there's a timeline force an absolute seek to initialize state
4909 if (opts->seek_to_sec || mpctx->timeline) {
4910 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4911 seek(mpctx, mpctx->seek, false);
4912 end_at.pos += opts->seek_to_sec;
4914 if (opts->chapterrange[0] > 0) {
4915 double pts;
4916 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4917 && pts > -1.0) {
4918 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4919 seek(mpctx, mpctx->seek, false);
4923 if (end_at.type == END_AT_SIZE) {
4924 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4925 "Option -endpos in MPlayer does not yet support size units.\n");
4926 end_at.type = END_AT_NONE;
4929 #ifdef CONFIG_DVDNAV
4930 mp_dvdnav_context_free(mpctx);
4931 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4932 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4933 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4935 #endif
4937 mpctx->seek = (struct seek_params){ 0 };
4938 get_relative_time(mpctx); // reset current delta
4939 // Make sure VO knows current pause state
4940 if (mpctx->sh_video)
4941 vo_control(mpctx->video_out,
4942 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4944 while (!mpctx->stop_play)
4945 run_playloop(mpctx);
4947 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4949 #ifdef CONFIG_DVBIN
4950 if (mpctx->dvbin_reopen) {
4951 mpctx->stop_play = 0;
4952 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4953 cache_uninit(mpctx->stream);
4954 mpctx->dvbin_reopen = 0;
4955 goto goto_enable_cache;
4957 #endif
4959 goto_next_file: // don't jump here after ao/vo/getch initialization!
4961 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4963 if (opts->benchmark) {
4964 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4965 double total_time_usage;
4966 total_time_usage_start = GetTimer() - total_time_usage_start;
4967 total_time_usage = (float)total_time_usage_start * 0.000001;
4968 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4969 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4970 video_time_usage, vout_time_usage, audio_time_usage,
4971 total_time_usage - tot, total_time_usage);
4972 if (total_time_usage > 0.0)
4973 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4974 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4975 100.0 * video_time_usage / total_time_usage,
4976 100.0 * vout_time_usage / total_time_usage,
4977 100.0 * audio_time_usage / total_time_usage,
4978 100.0 * (total_time_usage - tot) / total_time_usage,
4979 100.0);
4980 if (total_frame_cnt && frame_dropping)
4981 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4982 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4983 total_frame_cnt - drop_frame_cnt,
4984 (total_time_usage > 0.5) ? ((total_frame_cnt -
4985 drop_frame_cnt) / total_time_usage) : 0,
4986 drop_frame_cnt,
4987 100 * drop_frame_cnt / total_frame_cnt,
4988 total_frame_cnt,
4989 (total_time_usage > 0.5) ?
4990 (total_frame_cnt / total_time_usage) : 0);
4993 // time to uninit all, except global stuff:
4994 int uninitialize_parts = INITIALIZED_ALL;
4995 if (opts->fixed_vo)
4996 uninitialize_parts -= INITIALIZED_VO;
4997 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4998 uninitialize_parts -= INITIALIZED_AO;
4999 uninit_player(mpctx, uninitialize_parts);
5001 if (mpctx->set_of_sub_size > 0) {
5002 current_module = "sub_free";
5003 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5004 sub_free(mpctx->set_of_subtitles[i]);
5005 #ifdef CONFIG_ASS
5006 if (mpctx->set_of_ass_tracks[i])
5007 ass_free_track(mpctx->set_of_ass_tracks[i]);
5008 #endif
5010 mpctx->set_of_sub_size = 0;
5012 mpctx->vo_sub_last = vo_sub = NULL;
5013 mpctx->subdata = NULL;
5014 #ifdef CONFIG_ASS
5015 mpctx->osd->ass_track = NULL;
5016 if (mpctx->ass_library)
5017 ass_clear_fonts(mpctx->ass_library);
5018 #endif
5020 if (!mpctx->stop_play) // In case some goto jumped here...
5021 mpctx->stop_play = PT_NEXT_ENTRY;
5023 int playtree_direction = 1;
5025 if (mpctx->stop_play == PT_NEXT_ENTRY
5026 || mpctx->stop_play == PT_PREV_ENTRY) {
5027 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5028 != PLAY_TREE_ITER_ENTRY) {
5029 play_tree_iter_free(mpctx->playtree_iter);
5030 mpctx->playtree_iter = NULL;
5032 mpctx->play_tree_step = 1;
5033 } else if (mpctx->stop_play == PT_UP_NEXT ||
5034 mpctx->stop_play == PT_UP_PREV) {
5035 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5036 if (mpctx->playtree_iter) {
5037 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5038 PLAY_TREE_ITER_ENTRY) {
5039 play_tree_iter_free(mpctx->playtree_iter);
5040 mpctx->playtree_iter = NULL;
5043 } else if (mpctx->stop_play == PT_STOP) {
5044 play_tree_iter_free(mpctx->playtree_iter);
5045 mpctx->playtree_iter = NULL;
5046 } else // NEXT PREV SRC
5047 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5049 while (mpctx->playtree_iter != NULL) {
5050 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5051 playtree_direction);
5052 if (mpctx->filename == NULL) {
5053 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5054 0) != PLAY_TREE_ITER_ENTRY) {
5055 play_tree_iter_free(mpctx->playtree_iter);
5056 mpctx->playtree_iter = NULL;
5059 } else
5060 break;
5063 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5064 if (!mpctx->playtree_iter)
5065 mpctx->filename = NULL;
5066 mpctx->stop_play = 0;
5067 goto play_next_file;
5070 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5072 return 1;
5074 #endif /* DISABLE_MAIN */