gl_common: minor cleanup/refactor
[mplayer.git] / mplayer.c
blob3076d784c3142b698f1432c594772232736a71b8
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stdbool.h>
22 #include <math.h>
23 #include <assert.h>
25 #include <libavutil/intreadwrite.h>
27 #include "config.h"
28 #include "talloc.h"
30 #include "osdep/io.h"
32 #if defined(__MINGW32__) || defined(__CYGWIN__)
33 #include <windows.h>
34 // No proper file descriptor event handling; keep waking up to poll input
35 #define WAKEUP_PERIOD 0.02
36 #else
37 /* Even if we can immediately wake up in response to most input events,
38 * there are some timers which are not registered to the event loop
39 * and need to be checked periodically (like automatic mouse cursor hiding).
40 * OSD content updates behave similarly. Also some uncommon input devices
41 * may not have proper FD event support.
43 #define WAKEUP_PERIOD 0.5
44 #endif
45 #include <string.h>
46 #include <unistd.h>
48 // #include <sys/mman.h>
49 #include <sys/types.h>
50 #ifndef __MINGW32__
51 #include <sys/ioctl.h>
52 #include <sys/wait.h>
53 #else
54 #define SIGHUP 1 /* hangup */
55 #define SIGQUIT 3 /* quit */
56 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
57 #define SIGBUS 10 /* bus error */
58 #define SIGPIPE 13 /* broken pipe */
59 #endif
61 #include <sys/time.h>
62 #include <sys/stat.h>
64 #include <signal.h>
65 #include <time.h>
66 #include <fcntl.h>
67 #include <limits.h>
69 #include <errno.h>
71 #include "mp_msg.h"
72 #include "av_log.h"
75 #include "m_option.h"
76 #include "m_config.h"
77 #include "mplayer.h"
78 #include "m_property.h"
80 #include "sub/subreader.h"
81 #include "sub/find_subfiles.h"
82 #include "sub/dec_sub.h"
83 #include "sub/sub_cc.h"
85 #include "mp_osd.h"
86 #include "libvo/video_out.h"
87 #include "screenshot.h"
89 #include "sub/sub.h"
90 #include "libmpcodecs/dec_teletext.h"
91 #include "cpudetect.h"
92 #include "version.h"
94 #ifdef CONFIG_X11
95 #include "libvo/x11_common.h"
96 #endif
98 #include "libao2/audio_out.h"
100 #include "codec-cfg.h"
102 #include "sub/spudec.h"
103 #include "sub/vobsub.h"
105 #include "osdep/getch2.h"
106 #include "osdep/timer.h"
108 #include "input/input.h"
110 int slave_mode = 0;
111 int enable_mouse_movements = 0;
112 float start_volume = -1;
114 #include "osdep/priority.h"
116 char *heartbeat_cmd;
118 #ifdef HAVE_RTC
119 #ifdef __linux__
120 #include <linux/rtc.h>
121 #else
122 #include <rtc.h>
123 #define RTC_IRQP_SET RTCIO_IRQP_SET
124 #define RTC_PIE_ON RTCIO_PIE_ON
125 #endif /* __linux__ */
126 #endif /* HAVE_RTC */
128 #include "stream/tv.h"
129 #include "stream/stream_radio.h"
130 #ifdef CONFIG_DVBIN
131 #include "stream/dvbin.h"
132 #endif
133 #include "stream/cache2.h"
135 //**************************************************************************//
136 // Playtree
137 //**************************************************************************//
138 #include "playtree.h"
139 #include "playtreeparser.h"
141 //**************************************************************************//
142 // Config
143 //**************************************************************************//
144 #include "parser-cfg.h"
145 #include "parser-mpcmd.h"
147 //**************************************************************************//
148 // Config file
149 //**************************************************************************//
151 #include "path.h"
153 //**************************************************************************//
154 //**************************************************************************//
155 // Input media streaming & demultiplexer:
156 //**************************************************************************//
158 static int max_framesize = 0;
160 #include "stream/stream.h"
161 #include "libmpdemux/demuxer.h"
162 #include "libmpdemux/stheader.h"
164 #ifdef CONFIG_DVDREAD
165 #include "stream/stream_dvd.h"
166 #endif
167 #include "stream/stream_dvdnav.h"
169 #include "libmpcodecs/dec_audio.h"
170 #include "libmpcodecs/dec_video.h"
171 #include "libmpcodecs/mp_image.h"
172 #include "libmpcodecs/vf.h"
173 #include "libmpcodecs/vd.h"
175 #include "mixer.h"
177 #include "mp_core.h"
178 #include "options.h"
179 #include "defaultopts.h"
181 static const char help_text[] = _(
182 "Usage: mplayer [options] [url|path/]filename\n"
183 "\n"
184 "Basic options: (complete list in the man page)\n"
185 " -vo <drv> select video output driver ('-vo help' for a list)\n"
186 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
187 #ifdef CONFIG_VCD
188 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
189 #endif
190 #ifdef CONFIG_DVDREAD
191 " dvd://<titleno> play DVD title from device instead of plain file\n"
192 #endif
193 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
194 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
195 " -nosound do not play sound\n"
196 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
197 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
198 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
199 " -playlist <file> specify playlist file\n"
200 " -vid x -aid y select video (x) and audio (y) stream to play\n"
201 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
202 " -pp <quality> enable postprocessing filter (details in the man page)\n"
203 " -framedrop enable frame dropping (for slow machines)\n"
204 "\n"
205 "Basic keys: (complete list in the man page, also check input.conf)\n"
206 " <- or -> seek backward/forward 10 seconds\n"
207 " down or up seek backward/forward 1 minute\n"
208 " pgdown or pgup seek backward/forward 10 minutes\n"
209 " < or > step backward/forward in playlist\n"
210 " p or SPACE pause movie (press any key to continue)\n"
211 " q or ESC stop playing and quit program\n"
212 " + or - adjust audio delay by +/- 0.1 second\n"
213 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
214 " * or / increase or decrease PCM volume\n"
215 " x or z adjust subtitle delay by +/- 0.1 second\n"
216 " r or t adjust subtitle position up/down, also see -vf expand\n"
217 " double click toggle fullscreen\n"
218 " right click pause (press again to continue)\n"
219 "\n"
220 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
221 "\n");
224 #define Exit_SIGILL_RTCpuSel _(\
225 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
226 " It may be a bug in our new runtime CPU-detection code...\n"\
227 " Please read DOCS/HTML/en/bugreports.html.\n")
229 #define Exit_SIGILL _(\
230 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
231 " It usually happens when you run it on a CPU different than the one it was\n"\
232 " compiled/optimized for.\n"\
233 " Verify this!\n")
235 #define Exit_SIGSEGV_SIGFPE _(\
236 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
237 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
238 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
240 #define Exit_SIGCRASH _(\
241 "- MPlayer crashed. This shouldn't happen.\n"\
242 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
243 " gcc version. If you think it's MPlayer's fault, please read\n"\
244 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
245 " won't help unless you provide this information when reporting a possible bug.\n")
247 #define SystemTooSlow _("\n\n"\
248 " ************************************************\n"\
249 " **** Your system is too SLOW to play this! ****\n"\
250 " ************************************************\n\n"\
251 "Possible reasons, problems, workarounds:\n"\
252 "- Most common: broken/buggy _audio_ driver\n"\
253 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
254 " - Experiment with different values for -autosync, 30 is a good start.\n"\
255 "- Slow video output\n"\
256 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
257 "- Slow CPU\n"\
258 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
259 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
260 "- Broken file\n"\
261 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
262 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
263 " - Try -cache 8192.\n"\
264 "- Are you using -cache to play a non-interleaved AVI file?\n"\
265 " - Try -nocache.\n"\
266 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
267 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
270 //**************************************************************************//
271 //**************************************************************************//
273 #include "mp_fifo.h"
275 // benchmark:
276 double video_time_usage;
277 double vout_time_usage;
278 static double audio_time_usage;
279 static int total_time_usage_start;
280 static int total_frame_cnt;
281 static int drop_frame_cnt; // total number of dropped frames
283 // options:
284 static int output_quality;
286 // seek:
287 static off_t seek_to_byte;
288 static off_t step_sec;
290 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
292 // codecs:
293 char **audio_codec_list; // override audio codec
294 char **video_codec_list; // override video codec
295 char **audio_fm_list; // override audio codec family
296 char **video_fm_list; // override video codec family
298 // this dvdsub_id was selected via slang
299 // use this to allow dvdnav to follow -slang across stream resets,
300 // in particular the subtitle ID for a language changes
301 int dvdsub_lang_id;
302 int vobsub_id = -1;
303 static char *spudec_ifo = NULL;
304 int forced_subs_only = 0;
306 // dump:
307 int stream_dump_type = 0;
309 // A-V sync:
310 static float default_max_pts_correction = -1;
311 float audio_delay = 0;
312 static int ignore_start = 0;
314 double force_fps = 0;
315 static int force_srate = 0;
316 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
317 static int play_n_frames = -1;
318 static int play_n_frames_mf = -1;
320 #include "sub/ass_mp.h"
322 char *current_module; // for debugging
325 // ---
327 FILE *edl_fd; // file to write to when in -edlout mode.
328 char *edl_output_filename; // file to put EDL entries in (-edlout)
330 int use_filedir_conf;
331 int use_filename_title;
333 #include "mpcommon.h"
334 #include "command.h"
336 #include "metadata.h"
338 static float get_relative_time(struct MPContext *mpctx)
340 unsigned int new_time = GetTimer();
341 unsigned int delta = new_time - mpctx->last_time;
342 mpctx->last_time = new_time;
343 return delta * 0.000001;
346 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
348 switch (type) {
349 /* check for valid video stream */
350 case META_VIDEO_CODEC:
351 case META_VIDEO_BITRATE:
352 case META_VIDEO_RESOLUTION:
353 if (!mpctx->sh_video)
354 return 0;
355 break;
357 /* check for valid audio stream */
358 case META_AUDIO_CODEC:
359 case META_AUDIO_BITRATE:
360 case META_AUDIO_SAMPLES:
361 if (!mpctx->sh_audio)
362 return 0;
363 break;
365 /* check for valid demuxer */
366 case META_INFO_TITLE:
367 case META_INFO_ARTIST:
368 case META_INFO_ALBUM:
369 case META_INFO_YEAR:
370 case META_INFO_COMMENT:
371 case META_INFO_TRACK:
372 case META_INFO_GENRE:
373 if (!mpctx->demuxer)
374 return 0;
375 break;
377 default:
378 break;
381 return 1;
384 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
386 char **info = mpctx->demuxer->info;
387 int n;
389 if (!info || !tag)
390 return talloc_strdup(NULL, "");
392 for (n = 0; info[2 * n] != NULL; n++)
393 if (!strcasecmp(info[2 * n], tag))
394 break;
396 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
399 char *get_metadata(struct MPContext *mpctx, metadata_t type)
401 sh_audio_t * const sh_audio = mpctx->sh_audio;
402 sh_video_t * const sh_video = mpctx->sh_video;
404 if (!is_valid_metadata_type(mpctx, type))
405 return NULL;
407 switch (type) {
408 case META_NAME:
409 return talloc_strdup(NULL, mp_basename(mpctx->filename));
410 case META_VIDEO_CODEC:
411 if (sh_video->format == 0x10000001)
412 return talloc_strdup(NULL, "mpeg1");
413 else if (sh_video->format == 0x10000002)
414 return talloc_strdup(NULL, "mpeg2");
415 else if (sh_video->format == 0x10000004)
416 return talloc_strdup(NULL, "mpeg4");
417 else if (sh_video->format == 0x10000005)
418 return talloc_strdup(NULL, "h264");
419 else if (sh_video->format >= 0x20202020)
420 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
421 else
422 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
423 case META_VIDEO_BITRATE:
424 return talloc_asprintf(NULL, "%d kbps",
425 (int) (sh_video->i_bps * 8 / 1024));
426 case META_VIDEO_RESOLUTION:
427 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
428 sh_video->disp_h);
429 case META_AUDIO_CODEC:
430 if (sh_audio->codec && sh_audio->codec->name)
431 return talloc_strdup(NULL, sh_audio->codec->name);
432 return talloc_strdup(NULL, "");
433 case META_AUDIO_BITRATE:
434 return talloc_asprintf(NULL, "%d kbps",
435 (int) (sh_audio->i_bps * 8 / 1000));
436 case META_AUDIO_SAMPLES:
437 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
438 sh_audio->channels);
440 /* check for valid demuxer */
441 case META_INFO_TITLE:
442 return get_demuxer_info(mpctx, "Title");
444 case META_INFO_ARTIST:
445 return get_demuxer_info(mpctx, "Artist");
447 case META_INFO_ALBUM:
448 return get_demuxer_info(mpctx, "Album");
450 case META_INFO_YEAR:
451 return get_demuxer_info(mpctx, "Year");
453 case META_INFO_COMMENT:
454 return get_demuxer_info(mpctx, "Comment");
456 case META_INFO_TRACK:
457 return get_demuxer_info(mpctx, "Track");
459 case META_INFO_GENRE:
460 return get_demuxer_info(mpctx, "Genre");
462 default:
463 break;
466 return talloc_strdup(NULL, "");
469 static void print_file_properties(struct MPContext *mpctx, const char *filename)
471 double start_pts = MP_NOPTS_VALUE;
472 double video_start_pts = MP_NOPTS_VALUE;
473 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
474 filename_recode(filename));
475 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
476 mpctx->demuxer->desc->name);
477 if (mpctx->sh_video) {
478 /* Assume FOURCC if all bytes >= 0x20 (' ') */
479 if (mpctx->sh_video->format >= 0x20202020)
480 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
481 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
482 else
483 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
484 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
485 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
486 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
487 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
488 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
489 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
490 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
491 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
492 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
493 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
494 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
495 video_start_pts = ds_get_next_pts(mpctx->d_video);
497 if (mpctx->sh_audio) {
498 /* Assume FOURCC if all bytes >= 0x20 (' ') */
499 if (mpctx->sh_audio->format >= 0x20202020)
500 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
501 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
502 else
503 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
504 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
505 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
506 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
507 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
508 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
509 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
510 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
511 start_pts = ds_get_next_pts(mpctx->d_audio);
513 if (video_start_pts != MP_NOPTS_VALUE) {
514 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
515 (mpctx->sh_video && video_start_pts < start_pts))
516 start_pts = video_start_pts;
518 if (start_pts != MP_NOPTS_VALUE)
519 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
520 else
521 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
522 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
523 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
524 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
525 mpctx->stream->seek
526 && (!mpctx->demuxer || mpctx->demuxer->seekable));
527 if (mpctx->demuxer) {
528 int chapter_count = get_chapter_count(mpctx);
529 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
530 for (int i = 0; i < chapter_count; i++) {
531 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
532 // in milliseconds
533 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
534 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
535 char *name = chapter_name(mpctx, i);
536 if (name) {
537 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
538 name);
539 talloc_free(name);
545 /// step size of mixer changes
546 int volstep = 3;
548 #ifdef CONFIG_DVDNAV
549 static void mp_dvdnav_context_free(MPContext *ctx)
551 if (ctx->nav_smpi)
552 free_mp_image(ctx->nav_smpi);
553 ctx->nav_smpi = NULL;
554 free(ctx->nav_buffer);
555 ctx->nav_buffer = NULL;
556 ctx->nav_start = NULL;
557 ctx->nav_in_size = 0;
559 #endif
561 static void uninit_subs(struct demuxer *demuxer)
563 for (int i = 0; i < MAX_S_STREAMS; i++) {
564 struct sh_sub *sh = demuxer->s_streams[i];
565 if (sh && sh->initialized)
566 sub_uninit(sh);
570 void uninit_player(struct MPContext *mpctx, unsigned int mask)
572 mask &= mpctx->initialized_flags;
574 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
576 if (mask & INITIALIZED_ACODEC) {
577 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
578 current_module = "uninit_acodec";
579 if (mpctx->sh_audio)
580 uninit_audio(mpctx->sh_audio);
581 mpctx->sh_audio = NULL;
582 mpctx->mixer.afilter = NULL;
585 if (mask & INITIALIZED_SUB) {
586 mpctx->initialized_flags &= ~INITIALIZED_SUB;
587 if (mpctx->osd->sh_sub)
588 sub_switchoff(mpctx->osd->sh_sub, mpctx->osd);
591 if (mask & INITIALIZED_VCODEC) {
592 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
593 current_module = "uninit_vcodec";
594 if (mpctx->sh_video)
595 uninit_video(mpctx->sh_video);
596 mpctx->sh_video = NULL;
599 if (mask & INITIALIZED_DEMUXER) {
600 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
601 current_module = "free_demuxer";
602 if (mpctx->num_sources) {
603 mpctx->demuxer = mpctx->sources[0].demuxer;
604 for (int i = 1; i < mpctx->num_sources; i++) {
605 uninit_subs(mpctx->sources[i].demuxer);
606 free_stream(mpctx->sources[i].stream);
607 free_demuxer(mpctx->sources[i].demuxer);
610 talloc_free(mpctx->sources);
611 mpctx->sources = NULL;
612 mpctx->num_sources = 0;
613 talloc_free(mpctx->timeline);
614 mpctx->timeline = NULL;
615 mpctx->num_timeline_parts = 0;
616 talloc_free(mpctx->chapters);
617 mpctx->chapters = NULL;
618 mpctx->num_chapters = 0;
619 mpctx->video_offset = 0;
620 if (mpctx->demuxer) {
621 mpctx->stream = mpctx->demuxer->stream;
622 uninit_subs(mpctx->demuxer);
623 free_demuxer(mpctx->demuxer);
625 mpctx->demuxer = NULL;
628 // kill the cache process:
629 if (mask & INITIALIZED_STREAM) {
630 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
631 current_module = "uninit_stream";
632 if (mpctx->stream)
633 free_stream(mpctx->stream);
634 mpctx->stream = NULL;
637 if (mask & INITIALIZED_VO) {
638 mpctx->initialized_flags &= ~INITIALIZED_VO;
639 current_module = "uninit_vo";
640 vo_destroy(mpctx->video_out);
641 mpctx->video_out = NULL;
642 #ifdef CONFIG_DVDNAV
643 mp_dvdnav_context_free(mpctx);
644 #endif
647 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
648 if (mask & INITIALIZED_GETCH2) {
649 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
650 current_module = "uninit_getch2";
651 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
652 // restore terminal:
653 getch2_disable();
656 if (mask & INITIALIZED_VOBSUB) {
657 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
658 current_module = "uninit_vobsub";
659 if (vo_vobsub)
660 vobsub_close(vo_vobsub);
661 vo_vobsub = NULL;
664 if (mask & INITIALIZED_SPUDEC) {
665 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
666 current_module = "uninit_spudec";
667 spudec_free(vo_spudec);
668 vo_spudec = NULL;
671 if (mask & INITIALIZED_AO) {
672 mpctx->initialized_flags &= ~INITIALIZED_AO;
673 current_module = "uninit_ao";
674 if (mpctx->ao) {
675 mixer_uninit(&mpctx->mixer);
676 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
678 mpctx->ao = NULL;
681 current_module = NULL;
684 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
686 uninit_player(mpctx, INITIALIZED_ALL);
687 #if defined(__MINGW32__) || defined(__CYGWIN__)
688 timeEndPeriod(1);
689 #endif
691 current_module = "uninit_input";
692 mp_input_uninit(mpctx->input);
694 osd_free(mpctx->osd);
696 #ifdef CONFIG_ASS
697 ass_library_done(mpctx->ass_library);
698 mpctx->ass_library = NULL;
699 #endif
701 current_module = "exit_player";
703 if (mpctx->playtree_iter)
704 play_tree_iter_free(mpctx->playtree_iter);
705 mpctx->playtree_iter = NULL;
706 if (mpctx->playtree)
707 play_tree_free(mpctx->playtree, 1);
708 mpctx->playtree = NULL;
710 talloc_free(mpctx->key_fifo);
712 switch (how) {
713 case EXIT_QUIT:
714 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
715 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
716 break;
717 case EXIT_EOF:
718 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
719 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
720 break;
721 case EXIT_ERROR:
722 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
723 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
724 break;
725 default:
726 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
728 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
729 "max framesize was %d bytes\n", max_framesize);
731 // must be last since e.g. mp_msg uses option values
732 // that will be freed by this.
733 if (mpctx->mconfig)
734 m_config_free(mpctx->mconfig);
735 mpctx->mconfig = NULL;
737 talloc_free(mpctx);
739 exit(rc);
742 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
744 exit_player_with_rc(mpctx, how, 1);
747 #ifndef __MINGW32__
748 static void child_sighandler(int x)
750 pid_t pid;
751 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
753 #endif
755 #ifdef CONFIG_CRASH_DEBUG
756 static char *prog_path;
757 static int crash_debug = 0;
758 #endif
760 static void exit_sighandler(int x)
762 static int sig_count = 0;
763 #ifdef CONFIG_CRASH_DEBUG
764 if (!crash_debug || x != SIGTRAP)
765 #endif
766 ++sig_count;
767 if (sig_count == 5) {
768 /* We're crashing bad and can't uninit cleanly :(
769 * by popular request, we make one last (dirty)
770 * effort to restore the user's
771 * terminal. */
772 getch2_disable();
773 exit(1);
775 if (sig_count == 6)
776 exit(1);
777 if (sig_count > 6) {
778 // can't stop :(
779 #ifndef __MINGW32__
780 kill(getpid(), SIGKILL);
781 #endif
783 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
784 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
785 "\nMPlayer interrupted by signal %d in module: %s\n", x,
786 current_module ? current_module : "unknown");
787 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
788 if (sig_count <= 1)
789 switch (x) {
790 case SIGINT:
791 case SIGPIPE:
792 case SIGQUIT:
793 case SIGTERM:
794 case SIGKILL:
795 async_quit_request = 1;
796 return; // killed from keyboard (^C) or killed [-9]
797 case SIGILL:
798 #if CONFIG_RUNTIME_CPUDETECT
799 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
800 #else
801 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
802 #endif
803 case SIGFPE:
804 case SIGSEGV:
805 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
806 default:
807 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
808 #ifdef CONFIG_CRASH_DEBUG
809 if (crash_debug) {
810 int gdb_pid;
811 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
812 gdb_pid = fork();
813 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
814 if (gdb_pid == 0) { // We are the child
815 char spid[20];
816 snprintf(spid, sizeof(spid), "%i", getppid());
817 getch2_disable(); // allow terminal to work properly with gdb
818 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
819 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
820 } else if (gdb_pid < 0)
821 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
822 else
823 waitpid(gdb_pid, NULL, 0);
824 if (x == SIGTRAP)
825 return;
827 #endif
829 getch2_disable();
830 exit(1);
833 #include "cfg-mplayer.h"
835 static int cfg_include(struct m_config *conf, char *filename)
837 return m_config_parse_config_file(conf, filename);
840 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
842 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
844 struct MPOpts *opts = &mpctx->opts;
845 char *conffile;
846 int conffile_fd;
847 if (!(opts->noconfig & 2) &&
848 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
849 exit_player(mpctx, EXIT_NONE);
850 if ((conffile = get_path("")) == NULL)
851 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
852 else {
853 mkdir(conffile, 0777);
854 free(conffile);
855 if ((conffile = get_path("config")) == NULL)
856 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
857 else {
858 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
859 0666)) != -1) {
860 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
861 "Creating config file: %s\n", conffile);
862 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
863 close(conffile_fd);
865 if (!(opts->noconfig & 1) &&
866 m_config_parse_config_file(conf, conffile) < 0)
867 exit_player(mpctx, EXIT_NONE);
868 free(conffile);
873 #define PROFILE_CFG_PROTOCOL "protocol."
875 static void load_per_protocol_config(m_config_t *conf, const char * const file)
877 char *str;
878 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
879 m_profile_t *p;
881 /* does filename actually uses a protocol ? */
882 str = strstr(file, "://");
883 if (!str)
884 return;
886 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
887 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
888 p = m_config_get_profile(conf, protocol);
889 if (p) {
890 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
891 "Loading protocol-related profile '%s'\n", protocol);
892 m_config_set_profile(conf, p);
896 #define PROFILE_CFG_EXTENSION "extension."
898 static void load_per_extension_config(m_config_t *conf, const char * const file)
900 char *str;
901 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
902 m_profile_t *p;
904 /* does filename actually have an extension ? */
905 str = strrchr(file, '.');
906 if (!str)
907 return;
909 sprintf(extension, PROFILE_CFG_EXTENSION);
910 strncat(extension, ++str, 7);
911 p = m_config_get_profile(conf, extension);
912 if (p) {
913 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
914 "Loading extension-related profile '%s'\n", extension);
915 m_config_set_profile(conf, p);
919 #define PROFILE_CFG_VO "vo."
920 #define PROFILE_CFG_AO "ao."
922 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
924 char profile[strlen(cfg) + strlen(out) + 1];
925 m_profile_t *p;
927 sprintf(profile, "%s%s", cfg, out);
928 p = m_config_get_profile(conf, profile);
929 if (p) {
930 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
931 "Loading extension-related profile '%s'\n", profile);
932 m_config_set_profile(conf, p);
937 * Tries to load a config file
938 * @return 0 if file was not found, 1 otherwise
940 static int try_load_config(m_config_t *conf, const char *file)
942 if (!mp_path_exists(file))
943 return 0;
944 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
945 m_config_parse_config_file(conf, file);
946 return 1;
949 static void load_per_file_config(m_config_t *conf, const char * const file)
951 char *confpath;
952 char cfg[MP_PATH_MAX];
953 const char *name;
955 if (strlen(file) > MP_PATH_MAX - 14) {
956 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
957 "can not load file or directory specific config files\n");
958 return;
960 sprintf(cfg, "%s.conf", file);
962 name = mp_basename(cfg);
963 if (use_filedir_conf) {
964 char dircfg[MP_PATH_MAX];
965 strcpy(dircfg, cfg);
966 strcpy(dircfg + (name - cfg), "mplayer.conf");
967 try_load_config(conf, dircfg);
969 if (try_load_config(conf, cfg))
970 return;
973 if ((confpath = get_path(name)) != NULL) {
974 try_load_config(conf, confpath);
976 free(confpath);
980 /* When libmpdemux performs a blocking operation (network connection or
981 * cache filling) if the operation fails we use this function to check
982 * if it was interrupted by the user.
983 * The function returns a new value for eof. */
984 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
986 mp_cmd_t *cmd;
987 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
988 switch (cmd->id) {
989 case MP_CMD_QUIT:
990 exit_player_with_rc(mpctx, EXIT_QUIT,
991 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
992 case MP_CMD_PLAY_TREE_STEP: {
993 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
994 mpctx->play_tree_step =
995 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
996 } break;
997 case MP_CMD_PLAY_TREE_UP_STEP: {
998 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
999 } break;
1000 case MP_CMD_PLAY_ALT_SRC_STEP: {
1001 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1002 } break;
1004 mp_cmd_free(cmd);
1006 return stop_play;
1009 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1011 play_tree_add_bpf(entry, bstr(mpctx->filename));
1014 if (!entry) {
1015 entry = mpctx->playtree_iter->tree;
1016 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1017 != PLAY_TREE_ITER_ENTRY)
1018 return PT_NEXT_ENTRY;
1019 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1020 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1021 != PLAY_TREE_ITER_ENTRY)
1022 return PT_NEXT_ENTRY;
1024 play_tree_remove(entry, 1, 1);
1025 return PT_NEXT_SRC;
1027 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1028 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1029 entry = mpctx->playtree_iter->tree;
1030 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1031 != PLAY_TREE_ITER_ENTRY)
1032 return PT_NEXT_ENTRY;
1033 play_tree_remove(entry, 1, 1);
1035 return PT_NEXT_SRC;
1038 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1039 int noerr)
1041 struct MPOpts *opts = &mpctx->opts;
1042 sub_data *subd = NULL;
1043 struct sh_sub *sh = NULL;
1045 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1046 return;
1048 if (opts->ass_enabled) {
1049 #ifdef CONFIG_ASS
1050 struct ass_track *asst;
1051 #ifdef CONFIG_ICONV
1052 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1053 #else
1054 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1055 #endif
1056 bool is_native_ass = asst;
1057 if (!asst) {
1058 subd = sub_read_file(filename, fps, &mpctx->opts);
1059 if (subd) {
1060 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1061 sub_free(subd);
1062 subd = NULL;
1065 if (asst)
1066 sh = sd_ass_create_from_track(asst, is_native_ass, opts);
1067 #endif
1068 } else
1069 subd = sub_read_file(filename, fps, &mpctx->opts);
1072 if (!sh && !subd) {
1073 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1074 "Cannot load subtitles: %s\n", filename_recode(filename));
1075 return;
1078 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = sh;
1079 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1080 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1081 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1082 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1083 filename_recode(filename));
1084 ++mpctx->set_of_sub_size;
1085 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1086 mpctx->set_of_sub_size, filename_recode(filename));
1089 void init_vo_spudec(struct MPContext *mpctx)
1091 unsigned width, height;
1092 spudec_free(vo_spudec);
1093 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1094 vo_spudec = NULL;
1096 // we currently can't work without video stream
1097 if (!mpctx->sh_video)
1098 return;
1100 if (spudec_ifo) {
1101 unsigned int palette[16];
1102 current_module = "spudec_init_vobsub";
1103 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1104 1, -1, NULL) >= 0)
1105 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1108 width = mpctx->sh_video->disp_w;
1109 height = mpctx->sh_video->disp_h;
1111 #ifdef CONFIG_DVDREAD
1112 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1113 current_module = "spudec_init_dvdread";
1114 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1115 cur_pgc->palette, width, height, NULL, 0);
1117 #endif
1119 #ifdef CONFIG_DVDNAV
1120 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1121 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1122 current_module = "spudec_init_dvdnav";
1123 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1125 #endif
1127 if (vo_spudec == NULL) {
1128 sh_sub_t *sh = mpctx->d_sub->sh;
1129 current_module = "spudec_init_normal";
1130 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1131 sh->extradata_len);
1132 spudec_set_font_factor(vo_spudec, font_factor);
1135 if (vo_spudec != NULL) {
1136 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1137 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1138 mpctx);
1143 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1144 * make it all work is to use the builtin SDL-bootstrap code, which
1145 * will be done automatically by replacing our main() if we include SDL.h.
1147 #if defined(__APPLE__) && defined(CONFIG_SDL)
1148 #ifdef CONFIG_SDL_SDL_H
1149 #include <SDL/SDL.h>
1150 #else
1151 #include <SDL.h>
1152 #endif
1153 #endif
1156 * \brief append a formatted string
1157 * \param buf buffer to print into
1158 * \param pos position of terminating 0 in buf
1159 * \param len maximum number of characters in buf, not including terminating 0
1160 * \param format printf format string
1162 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1164 va_list va;
1165 va_start(va, format);
1166 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1167 va_end(va);
1168 if (*pos >= len) {
1169 buf[len] = 0;
1170 *pos = len;
1175 * \brief append time in the hh:mm:ss.f format
1176 * \param buf buffer to print into
1177 * \param pos position of terminating 0 in buf
1178 * \param len maximum number of characters in buf, not including terminating 0
1179 * \param time time value to convert/append
1181 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1183 int64_t tenths = 10 * time;
1184 int f1 = tenths % 10;
1185 int ss = (tenths / 10) % 60;
1186 int mm = (tenths / 600) % 60;
1187 int hh = tenths / 36000;
1188 if (time < 0) {
1189 saddf(buf, pos, len, "unknown");
1190 return;
1192 if (hh > 0)
1193 saddf(buf, pos, len, "%2d:", hh);
1194 if (hh > 0 || mm > 0)
1195 saddf(buf, pos, len, "%02d:", mm);
1196 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1199 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1201 struct MPOpts *opts = &mpctx->opts;
1202 sh_video_t * const sh_video = mpctx->sh_video;
1204 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1205 a_pos = playing_audio_pts(mpctx);
1206 if (mpctx->sh_audio && sh_video && at_frame) {
1207 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1208 if (mpctx->time_frame > 0)
1209 mpctx->last_av_difference +=
1210 mpctx->time_frame * opts->playback_speed;
1211 if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
1212 mpctx->last_av_difference = MP_NOPTS_VALUE;
1213 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1214 && !mpctx->drop_message_shown) {
1215 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1216 mpctx->drop_message_shown = true;
1219 if (opts->quiet)
1220 return;
1222 int width;
1223 char *line;
1224 unsigned pos = 0;
1225 get_screen_size();
1226 if (screen_width > 0)
1227 width = screen_width;
1228 else
1229 width = 80;
1230 #if defined(__MINGW32__) || defined(__CYGWIN__)
1231 /* Windows command line is broken (MinGW's rxvt works, but we
1232 * should not depend on that). */
1233 width--;
1234 #endif
1235 line = malloc(width + 1); // one additional char for the terminating null
1237 // Audio time
1238 if (mpctx->sh_audio) {
1239 if (a_pos != MP_NOPTS_VALUE)
1240 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1241 else
1242 saddf(line, &pos, width, "A: ??? ");
1243 if (!sh_video && a_pos != MP_NOPTS_VALUE) {
1244 float len = get_time_length(mpctx);
1245 saddf(line, &pos, width, "(");
1246 sadd_hhmmssf(line, &pos, width, a_pos);
1247 saddf(line, &pos, width, ") of %.1f (", len);
1248 sadd_hhmmssf(line, &pos, width, len);
1249 saddf(line, &pos, width, ") ");
1253 // Video time
1254 if (sh_video) {
1255 if (mpctx->video_pts != MP_NOPTS_VALUE)
1256 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1257 else
1258 saddf(line, &pos, width, "V: ??? ", mpctx->video_pts);
1261 // A-V sync
1262 if (mpctx->sh_audio && sh_video) {
1263 if (mpctx->last_av_difference != MP_NOPTS_VALUE)
1264 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1265 mpctx->last_av_difference, mpctx->total_avsync_change);
1266 else
1267 saddf(line, &pos, width, "A-V: ??? ct:%7.3f ",
1268 mpctx->total_avsync_change);
1271 // Video stats
1272 if (sh_video)
1273 saddf(line, &pos, width, "%3d/%3d ",
1274 (int)sh_video->num_frames,
1275 (int)sh_video->num_frames_decoded);
1277 // CPU usage
1278 if (sh_video) {
1279 if (sh_video->timer > 0.5)
1280 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1281 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1282 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1283 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1284 else
1285 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1286 } else if (mpctx->sh_audio) {
1287 if (mpctx->delay > 0.5)
1288 saddf(line, &pos, width, "%4.1f%% ",
1289 100.0 * audio_time_usage / (double)mpctx->delay);
1290 else
1291 saddf(line, &pos, width, "??,?%% ");
1294 // VO stats
1295 if (sh_video)
1296 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1298 #ifdef CONFIG_STREAM_CACHE
1299 // cache stats
1300 if (opts->stream_cache_size > 0)
1301 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1302 #endif
1304 // other
1305 if (opts->playback_speed != 1)
1306 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1308 // end
1309 if (erase_to_end_of_line) {
1310 line[pos] = 0;
1311 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1312 "%s%s\r", line, erase_to_end_of_line);
1313 } else {
1314 memset(&line[pos], ' ', width - pos);
1315 line[width] = 0;
1316 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1318 free(line);
1320 mpctx->status_printed = true;
1323 struct stream_dump_progress {
1324 uint64_t count;
1325 unsigned start_time;
1326 unsigned last_print_time;
1329 static void stream_dump_progress_start(struct stream_dump_progress *p)
1331 p->start_time = p->last_print_time = GetTimerMS();
1332 p->count = 0;
1335 static void stream_dump_progress(struct stream_dump_progress *p,
1336 uint64_t len, stream_t *stream)
1338 p->count += len;
1339 unsigned t = GetTimerMS();
1340 if (t - p->last_print_time < 1000)
1341 return;
1343 uint64_t start = stream->start_pos;
1344 uint64_t end = stream->end_pos;
1345 uint64_t pos = stream->pos;
1347 p->last_print_time = t;
1348 /* TODO: pretty print sizes; ETA */
1349 if (end > start && pos >= start && pos <= end) {
1350 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1351 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1352 p->count, 100.0 * (pos - start) / (end - start));
1353 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1354 } else {
1355 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1356 "dump: %"PRIu64 " bytes written", p->count);
1357 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1361 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1363 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1364 p->count, name);
1368 * \brief build a chain of audio filters that converts the input format
1369 * to the ao's format, taking into account the current playback_speed.
1370 * sh_audio describes the requested input format of the chain.
1371 * ao describes the requested output format of the chain.
1373 static int build_afilter_chain(struct MPContext *mpctx)
1375 struct sh_audio *sh_audio = mpctx->sh_audio;
1376 struct ao *ao = mpctx->ao;
1377 struct MPOpts *opts = &mpctx->opts;
1378 int new_srate;
1379 int result;
1380 if (!sh_audio) {
1381 mpctx->mixer.afilter = NULL;
1382 return 0;
1384 if (af_control_any_rev(sh_audio->afilter,
1385 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1386 &opts->playback_speed))
1387 new_srate = sh_audio->samplerate;
1388 else {
1389 new_srate = sh_audio->samplerate * opts->playback_speed;
1390 if (new_srate != ao->samplerate) {
1391 // limits are taken from libaf/af_resample.c
1392 if (new_srate < 8000)
1393 new_srate = 8000;
1394 if (new_srate > 192000)
1395 new_srate = 192000;
1396 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1399 result = init_audio_filters(sh_audio, new_srate,
1400 &ao->samplerate, &ao->channels, &ao->format);
1401 mpctx->mixer.afilter = sh_audio->afilter;
1402 return result;
1406 typedef struct mp_osd_msg mp_osd_msg_t;
1407 struct mp_osd_msg {
1408 /// Previous message on the stack.
1409 mp_osd_msg_t *prev;
1410 /// Message text.
1411 char *msg;
1412 int id, level, started;
1413 /// Display duration in ms.
1414 unsigned time;
1415 // Show full OSD for duration of message instead of static text ('P' key)
1416 bool show_position;
1419 /// OSD message stack.
1420 static mp_osd_msg_t *osd_msg_stack = NULL;
1423 * \brief Add a message on the OSD message stack
1425 * If a message with the same id is already present in the stack
1426 * it is pulled on top of the stack, otherwise a new message is created.
1429 static void set_osd_msg_va(int id, int level, int time, bool show_position,
1430 const char *fmt, va_list ap)
1432 mp_osd_msg_t *msg, *last = NULL;
1434 // look if the id is already in the stack
1435 for (msg = osd_msg_stack; msg && msg->id != id;
1436 last = msg, msg = msg->prev) ;
1437 // not found: alloc it
1438 if (!msg) {
1439 msg = talloc_zero(NULL, mp_osd_msg_t);
1440 msg->prev = osd_msg_stack;
1441 osd_msg_stack = msg;
1442 } else if (last) { // found, but it's not on top of the stack
1443 last->prev = msg->prev;
1444 msg->prev = osd_msg_stack;
1445 osd_msg_stack = msg;
1447 talloc_free(msg->msg);
1448 // write the msg
1449 msg->msg = talloc_vasprintf(msg, fmt, ap);
1450 // set id and time
1451 msg->id = id;
1452 msg->level = level;
1453 msg->time = time;
1454 msg->show_position = show_position;
1457 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1459 va_list ap;
1460 va_start(ap, fmt);
1461 set_osd_msg_va(id, level, time, false, fmt, ap);
1462 va_end(ap);
1465 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1467 va_list ap;
1468 va_start(ap, fmt);
1469 set_osd_msg_va(id, level, time, false, mp_gtext(fmt), ap);
1470 va_end(ap);
1473 void set_osd_progressmsg(int id, int level, int time, ...)
1475 va_list ap;
1476 va_start(ap, time);
1477 set_osd_msg_va(id, level, time, true, "", ap);
1478 va_end(ap);
1482 * \brief Remove a message from the OSD stack
1484 * This function can be used to get rid of a message right away.
1488 void rm_osd_msg(int id)
1490 mp_osd_msg_t *msg, *last = NULL;
1492 // Search for the msg
1493 for (msg = osd_msg_stack; msg && msg->id != id;
1494 last = msg, msg = msg->prev) ;
1495 if (!msg)
1496 return;
1498 // Detach it from the stack and free it
1499 if (last)
1500 last->prev = msg->prev;
1501 else
1502 osd_msg_stack = msg->prev;
1503 talloc_free(msg);
1507 * \brief Remove all messages from the OSD stack
1511 static void clear_osd_msgs(void)
1513 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1514 while (msg) {
1515 prev = msg->prev;
1516 talloc_free(msg);
1517 msg = prev;
1519 osd_msg_stack = NULL;
1523 * \brief Get the current message from the OSD stack.
1525 * This function decrements the message timer and destroys the old ones.
1526 * The message that should be displayed is returned (if any).
1530 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1532 struct MPOpts *opts = &mpctx->opts;
1533 mp_osd_msg_t *msg, *prev, *last = NULL;
1534 static unsigned last_update = 0;
1535 unsigned now = GetTimerMS();
1536 unsigned diff;
1537 char hidden_dec_done = 0;
1539 if (mpctx->osd_visible) {
1540 // 36000000 means max timed visibility is 1 hour into the future, if
1541 // the difference is greater assume it's wrapped around from below 0
1542 if (mpctx->osd_visible - now > 36000000) {
1543 mpctx->osd_visible = 0;
1544 vo_osd_progbar_type = -1; // disable
1545 vo_osd_changed(OSDTYPE_PROGBAR);
1546 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1549 if (mpctx->osd_show_percentage_until - now > 36000000)
1550 mpctx->osd_show_percentage_until = 0;
1552 if (!last_update)
1553 last_update = now;
1554 diff = now >= last_update ? now - last_update : 0;
1556 last_update = now;
1558 // Look for the first message in the stack with high enough level.
1559 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1560 prev = msg->prev;
1561 if (msg->level > opts->osd_level && hidden_dec_done)
1562 continue;
1563 // The message has a high enough level or it is the first hidden one
1564 // in both cases we decrement the timer or kill it.
1565 if (!msg->started || msg->time > diff) {
1566 if (msg->started)
1567 msg->time -= diff;
1568 else
1569 msg->started = 1;
1570 // display it
1571 if (msg->level <= opts->osd_level)
1572 return msg;
1573 hidden_dec_done = 1;
1574 continue;
1576 // kill the message
1577 talloc_free(msg);
1578 if (last) {
1579 last->prev = prev;
1580 msg = last;
1581 } else {
1582 osd_msg_stack = prev;
1583 msg = NULL;
1586 // Nothing found
1587 return NULL;
1591 * \brief Display the OSD bar.
1593 * Display the OSD bar or fall back on a simple message.
1597 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1598 double min, double max, double val)
1600 struct MPOpts *opts = &mpctx->opts;
1601 if (opts->osd_level < 1)
1602 return;
1604 if (mpctx->sh_video) {
1605 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1606 vo_osd_progbar_type = type;
1607 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1608 vo_osd_changed(OSDTYPE_PROGBAR);
1609 return;
1612 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1613 name, ROUND(100 * (val - min) / (max - min)));
1617 * \brief Display text subtitles on the OSD
1619 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1621 int i;
1622 vo_sub = subs;
1623 vo_osd_changed(OSDTYPE_SUBTITLE);
1624 if (!mpctx->sh_video) {
1625 // reverse order, since newest set_osd_msg is displayed first
1626 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1627 if (!subs || i >= subs->lines || !subs->text[i])
1628 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1629 else {
1630 // HACK: currently display time for each sub line
1631 // except the last is set to 2 seconds.
1632 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1633 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1634 "%s", subs->text[i]);
1641 * \brief Update the OSD message line.
1643 * This function displays the current message on the vo OSD or on the term.
1644 * If the stack is empty and the OSD level is high enough the timer
1645 * is displayed (only on the vo OSD).
1649 static void update_osd_msg(struct MPContext *mpctx)
1651 struct MPOpts *opts = &mpctx->opts;
1652 mp_osd_msg_t *msg;
1653 struct osd_state *osd = mpctx->osd;
1655 if (mpctx->add_osd_seek_info) {
1656 double percentage = get_percent_pos(mpctx);
1657 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1658 if (mpctx->sh_video)
1659 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1660 mpctx->add_osd_seek_info = false;
1663 // Look if we have a msg
1664 if ((msg = get_osd_msg(mpctx)) && !msg->show_position) {
1665 if (strcmp(osd->osd_text, msg->msg)) {
1666 osd_set_text(osd, msg->msg);
1667 if (mpctx->sh_video)
1668 vo_osd_changed(OSDTYPE_OSD);
1669 else if (opts->term_osd)
1670 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1671 msg->msg);
1673 return;
1676 int osdlevel = opts->osd_level;
1677 if (msg && msg->show_position)
1678 osdlevel = 3;
1680 if (mpctx->sh_video) {
1681 // fallback on the timer
1682 char osd_text_timer[128] = {0};
1683 if (osdlevel >= 2) {
1684 int len = get_time_length(mpctx);
1685 int percentage = -1;
1686 char percentage_text[10];
1687 char fractions_text[4];
1688 double fpts = get_current_time(mpctx);
1689 int pts = fpts;
1691 if (mpctx->osd_show_percentage_until)
1692 percentage = get_percent_pos(mpctx);
1694 if (percentage >= 0)
1695 snprintf(percentage_text, 9, " (%d%%)", percentage);
1696 else
1697 percentage_text[0] = 0;
1699 if (opts->osd_fractions == 1) {
1700 //print fractions as sub-second timestamp
1701 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1702 (int)((fpts - pts) * 100));
1703 } else if (opts->osd_fractions == 2) {
1704 /* Print fractions by estimating the frame count within the
1705 * second.
1707 * Rounding or cutting off numbers after the decimal point
1708 * causes problems because of float's precision and movies
1709 * whose first frame is not exactly at timestamp 0. Therefore,
1710 * we add 0.2 and cut off at the decimal point, which proved
1711 * to be good heuristic.
1713 double fps = mpctx->sh_video->fps;
1714 if (fps <= 1 || fps > 99)
1715 strcpy(fractions_text, ".??");
1716 else
1717 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1718 (int) ((fpts - pts) * fps + 0.2));
1719 } else {
1720 //do not print fractions
1721 fractions_text[0] = 0;
1724 osd_get_function_sym(osd_text_timer, sizeof(osd_text_timer),
1725 mpctx->osd_function);
1726 size_t blen = strlen(osd_text_timer);
1728 if (osdlevel == 3)
1729 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1730 " %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1731 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1732 len / 3600, (len / 60) % 60, len % 60,
1733 percentage_text);
1734 else
1735 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1736 " %02d:%02d:%02d%s%s",
1737 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1738 percentage_text);
1741 if (strcmp(osd->osd_text, osd_text_timer)) {
1742 osd_set_text(osd, osd_text_timer);
1743 vo_osd_changed(OSDTYPE_OSD);
1745 return;
1748 // Clear the term osd line
1749 if (opts->term_osd && osd->osd_text[0]) {
1750 osd->osd_text[0] = 0;
1751 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1756 void reinit_audio_chain(struct MPContext *mpctx)
1758 struct MPOpts *opts = &mpctx->opts;
1759 struct ao *ao;
1760 if (!mpctx->sh_audio) {
1761 uninit_player(mpctx, INITIALIZED_AO);
1762 return;
1764 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1765 current_module = "init_audio_codec";
1766 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1767 goto init_error;
1768 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1771 current_module = "af_preinit";
1772 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1773 mpctx->initialized_flags |= INITIALIZED_AO;
1774 mpctx->ao = ao_create(opts, mpctx->input);
1775 mpctx->ao->samplerate = force_srate;
1776 mpctx->ao->format = opts->audio_output_format;
1778 ao = mpctx->ao;
1780 // first init to detect best values
1781 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1782 // input:
1783 mpctx->sh_audio->samplerate,
1784 // output:
1785 &ao->samplerate, &ao->channels, &ao->format)) {
1786 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1787 "pre-init!\n");
1788 exit_player(mpctx, EXIT_ERROR);
1790 if (!ao->initialized) {
1791 current_module = "ao2_init";
1792 ao->buffersize = opts->ao_buffersize;
1793 ao_init(ao, opts->audio_driver_list);
1794 if (!ao->initialized) {
1795 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1796 "Could not open/initialize audio device -> no sound.\n");
1797 goto init_error;
1799 ao->buffer.start = talloc_new(ao);
1800 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1801 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1802 ao->driver->info->short_name,
1803 ao->samplerate, ao->channels,
1804 af_fmt2str_short(ao->format),
1805 af_fmt2bits(ao->format) / 8);
1806 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1807 ao->driver->info->name, ao->driver->info->author);
1808 if (strlen(ao->driver->info->comment) > 0)
1809 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1810 ao->driver->info->comment);
1813 // init audio filters:
1814 current_module = "af_init";
1815 if (!build_afilter_chain(mpctx)) {
1816 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1817 "Couldn't find matching filter/ao format!\n");
1818 goto init_error;
1820 mpctx->mixer.volstep = volstep;
1821 mpctx->mixer.softvol = opts->softvol;
1822 mpctx->mixer.softvol_max = opts->softvol_max;
1823 mixer_reinit(&mpctx->mixer, ao);
1824 mpctx->syncing_audio = true;
1825 return;
1827 init_error:
1828 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1829 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1830 mpctx->d_audio->id = -2;
1834 // Return pts value corresponding to the end point of audio written to the
1835 // ao so far.
1836 static double written_audio_pts(struct MPContext *mpctx)
1838 sh_audio_t *sh_audio = mpctx->sh_audio;
1839 if (!sh_audio)
1840 return MP_NOPTS_VALUE;
1841 demux_stream_t *d_audio = mpctx->d_audio;
1842 // first calculate the end pts of audio that has been output by decoder
1843 double a_pts = sh_audio->pts;
1844 if (a_pts != MP_NOPTS_VALUE)
1845 // Good, decoder supports new way of calculating audio pts.
1846 // sh_audio->pts is the timestamp of the latest input packet with
1847 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1848 // the amount of bytes the decoder has written after that timestamp.
1849 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1850 else {
1851 // Decoder doesn't support new way of calculating pts (or we're
1852 // being called before it has decoded anything with known timestamp).
1853 // Use the old method of audio pts calculation: take the timestamp
1854 // of last packet with known pts the decoder has read data from,
1855 // and add amount of bytes read after the beginning of that packet
1856 // divided by input bps. This will be inaccurate if the input/output
1857 // ratio is not constant for every audio packet or if it is constant
1858 // but not accurately known in sh_audio->i_bps.
1860 a_pts = d_audio->pts;
1861 if (a_pts == MP_NOPTS_VALUE)
1862 return a_pts;
1864 // ds_tell_pts returns bytes read after last timestamp from
1865 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1866 // it has read but not decoded
1867 if (sh_audio->i_bps)
1868 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1869 (double)sh_audio->i_bps;
1871 // Now a_pts hopefully holds the pts for end of audio from decoder.
1872 // Substract data in buffers between decoder and audio out.
1874 // Decoded but not filtered
1875 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1877 // Data buffered in audio filters, measured in bytes of "missing" output
1878 double buffered_output = af_calc_delay(sh_audio->afilter);
1880 // Data that was ready for ao but was buffered because ao didn't fully
1881 // accept everything to internal buffers yet
1882 buffered_output += mpctx->ao->buffer.len;
1884 // Filters divide audio length by playback_speed, so multiply by it
1885 // to get the length in original units without speedup or slowdown
1886 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1888 return a_pts + mpctx->video_offset;
1891 // Return pts value corresponding to currently playing audio.
1892 double playing_audio_pts(struct MPContext *mpctx)
1894 double pts = written_audio_pts(mpctx);
1895 if (pts == MP_NOPTS_VALUE)
1896 return pts;
1897 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1900 static bool is_av_sub(int type)
1902 return type == 'b' || type == 'p' || type == 'x';
1905 void update_subtitles(struct MPContext *mpctx, double refpts_tl, bool reset)
1907 mpctx->osd->sub_offset = mpctx->video_offset;
1908 struct MPOpts *opts = &mpctx->opts;
1909 struct sh_video *sh_video = mpctx->sh_video;
1910 struct demux_stream *d_sub = mpctx->d_sub;
1911 double refpts_s = refpts_tl - mpctx->osd->sub_offset;
1912 double curpts_s = refpts_s + sub_delay;
1913 unsigned char *packet = NULL;
1914 int len;
1915 struct sh_sub *sh_sub = d_sub->sh;
1916 int type = sh_sub ? sh_sub->type : 'v';
1917 static subtitle subs;
1918 if (reset) {
1919 if (sh_sub)
1920 sub_reset(sh_sub, mpctx->osd);
1921 sub_clear_text(&subs, MP_NOPTS_VALUE);
1922 if (vo_sub)
1923 set_osd_subtitle(mpctx, NULL);
1924 if (vo_spudec) {
1925 spudec_reset(vo_spudec);
1926 vo_osd_changed(OSDTYPE_SPU);
1928 return;
1930 // find sub
1931 if (mpctx->subdata) {
1932 if (sub_fps == 0)
1933 sub_fps = sh_video ? sh_video->fps : 25;
1934 current_module = "find_sub";
1935 find_sub(mpctx, mpctx->subdata, curpts_s *
1936 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1937 if (vo_sub)
1938 mpctx->vo_sub_last = vo_sub;
1941 // DVD sub:
1942 if (vobsub_id >= 0 || type == 'v') {
1943 int timestamp;
1944 current_module = "spudec";
1945 /* Get a sub packet from the DVD or a vobsub */
1946 while (1) {
1947 // Vobsub
1948 len = 0;
1949 if (vo_vobsub) {
1950 if (curpts_s >= 0) {
1951 len = vobsub_get_packet(vo_vobsub, curpts_s,
1952 (void **)&packet, &timestamp);
1953 if (len > 0)
1954 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1955 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1956 len, refpts_s, sh_video->timer,
1957 timestamp / 90000.0, timestamp);
1959 } else {
1960 // DVD sub
1961 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1962 if (len > 0) {
1963 // XXX This is wrong, sh_video->pts can be arbitrarily
1964 // much behind demuxing position. Unfortunately using
1965 // d_video->pts which would have been the simplest
1966 // improvement doesn't work because mpeg specific hacks
1967 // in video.c set d_video->pts to 0.
1968 float x = d_sub->pts - refpts_s;
1969 if (x > -20 && x < 20) // prevent missing subs on pts reset
1970 timestamp = 90000 * d_sub->pts;
1971 else
1972 timestamp = 90000 * curpts_s;
1973 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1974 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1975 refpts_s, d_sub->pts, timestamp);
1978 if (len <= 0 || !packet)
1979 break;
1980 // create it only here, since with some broken demuxers we might
1981 // type = v but no DVD sub and we currently do not change the
1982 // "original frame size" ever after init, leading to wrong-sized
1983 // PGS subtitles.
1984 if (!vo_spudec)
1985 vo_spudec = spudec_new(NULL);
1986 if (vo_vobsub || timestamp >= 0)
1987 spudec_assemble(vo_spudec, packet, len, timestamp);
1989 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1990 if (type == 'd' && !d_sub->demuxer->teletext) {
1991 tt_stream_props tsp = { 0 };
1992 void *ptr = &tsp;
1993 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
1994 VBI_CONTROL_TRUE)
1995 d_sub->demuxer->teletext = ptr;
1997 if (d_sub->non_interleaved)
1998 ds_get_next_pts(d_sub);
2000 while (d_sub->first) {
2001 double subpts_s = ds_get_next_pts(d_sub);
2002 if (subpts_s > curpts_s) {
2003 // Libass handled subs can be fed to it in advance
2004 if (!opts->ass_enabled || !is_text_sub(type))
2005 break;
2006 // Try to avoid demuxing whole file at once
2007 if (d_sub->non_interleaved && subpts_s > curpts_s + 1)
2008 break;
2010 double duration = d_sub->first->duration;
2011 len = ds_get_packet_sub(d_sub, &packet);
2012 if (type == 'm') {
2013 if (len < 2)
2014 continue;
2015 len = FFMIN(len - 2, AV_RB16(packet));
2016 packet += 2;
2018 if (type == 'd') {
2019 if (d_sub->demuxer->teletext) {
2020 uint8_t *p = packet;
2021 p++;
2022 len--;
2023 while (len >= 46) {
2024 int sublen = p[1];
2025 if (p[0] == 2 || p[0] == 3)
2026 teletext_control(d_sub->demuxer->teletext,
2027 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2028 p += sublen + 2;
2029 len -= sublen + 2;
2032 continue;
2034 if (sh_sub && sh_sub->active) {
2035 sub_decode(sh_sub, mpctx->osd, packet, len, subpts_s, duration);
2036 continue;
2038 if (subpts_s != MP_NOPTS_VALUE) {
2039 if (duration < 0)
2040 sub_clear_text(&subs, MP_NOPTS_VALUE);
2041 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2042 int i;
2043 unsigned char *p = packet;
2044 for (i = 0; i < 8 && *p != '\0'; p++)
2045 if (*p == ',')
2046 i++;
2047 if (*p == '\0') /* Broken line? */
2048 continue;
2049 len -= p - packet;
2050 packet = p;
2052 double endpts_s = MP_NOPTS_VALUE;
2053 if (subpts_s != MP_NOPTS_VALUE && duration >= 0)
2054 endpts_s = subpts_s + duration;
2055 sub_add_text(&subs, packet, len, endpts_s);
2056 set_osd_subtitle(mpctx, &subs);
2058 if (d_sub->non_interleaved)
2059 ds_get_next_pts(d_sub);
2061 if (!opts->ass_enabled)
2062 if (sub_clear_text(&subs, curpts_s))
2063 set_osd_subtitle(mpctx, &subs);
2065 if (vo_spudec) {
2066 spudec_heartbeat(vo_spudec, 90000 * curpts_s);
2067 if (spudec_changed(vo_spudec))
2068 vo_osd_changed(OSDTYPE_SPU);
2071 current_module = NULL;
2074 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2076 int page_changed;
2078 if (!demuxer->teletext)
2079 return;
2081 //Also forcing page update when such ioctl is not supported or call error occured
2082 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2083 &page_changed) != VBI_CONTROL_TRUE)
2084 page_changed = 1;
2086 if (!page_changed)
2087 return;
2089 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2090 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2091 vo_osd_teletext_page = NULL;
2092 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2093 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2094 vo_osd_teletext_half = 0;
2095 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2096 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2097 vo_osd_teletext_mode = 0;
2098 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2099 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2100 vo_osd_teletext_format = 0;
2101 vo_osd_changed(OSDTYPE_TELETEXT);
2103 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2106 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2108 struct MPOpts *opts = &mpctx->opts;
2109 // check for frame-drop:
2110 current_module = "check_framedrop";
2111 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2112 static int dropped_frames;
2113 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2114 float d = delay - mpctx->delay;
2115 ++total_frame_cnt;
2116 // we should avoid dropping too many frames in sequence unless we
2117 // are too late. and we allow 100ms A-V delay here:
2118 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2119 && !mpctx->restart_playback) {
2120 ++drop_frame_cnt;
2121 ++dropped_frames;
2122 return frame_dropping;
2123 } else
2124 dropped_frames = 0;
2126 return 0;
2130 #ifdef HAVE_RTC
2131 int rtc_fd = -1;
2132 #endif
2134 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2136 #ifdef HAVE_RTC
2137 if (rtc_fd >= 0) {
2138 // -------- RTC -----------
2139 current_module = "sleep_rtc";
2140 while (time_frame > 0.000) {
2141 unsigned long rtc_ts;
2142 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2143 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2144 "Linux RTC read error: %s\n", strerror(errno));
2145 time_frame -= get_relative_time(mpctx);
2147 } else
2148 #endif
2150 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2151 // unnecessarily high CPU usage
2152 struct MPOpts *opts = &mpctx->opts;
2153 float margin = opts->softsleep ? 0.011 : 0;
2154 current_module = "sleep_timer";
2155 while (time_frame > margin) {
2156 usec_sleep(1000000 * (time_frame - margin));
2157 time_frame -= get_relative_time(mpctx);
2159 if (opts->softsleep) {
2160 current_module = "sleep_soft";
2161 if (time_frame < 0)
2162 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2163 "Warning! Softsleep underflow!\n");
2164 while (time_frame > 0)
2165 time_frame -= get_relative_time(mpctx); // burn the CPU
2168 return time_frame;
2171 static int select_subtitle(MPContext *mpctx)
2173 struct MPOpts *opts = &mpctx->opts;
2174 // find the best sub to use
2175 int id;
2176 int found = 0;
2177 mpctx->global_sub_pos = -1; // no subs by default
2178 if (vobsub_id >= 0) {
2179 // if user asks for a vobsub id, use that first.
2180 id = vobsub_id;
2181 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2182 M_PROPERTY_OK;
2185 if (!found && opts->sub_id >= 0) {
2186 // if user asks for a dvd sub id, use that next.
2187 id = opts->sub_id;
2188 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2189 M_PROPERTY_OK;
2192 if (!found) {
2193 // if there are text subs to use, use those. (autosubs come last here)
2194 id = 0;
2195 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2196 M_PROPERTY_OK;
2199 if (!found && opts->sub_id == -1) {
2200 // finally select subs by language and container hints
2201 if (opts->sub_id == -1)
2202 opts->sub_id =
2203 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2204 opts->sub_lang);
2205 if (opts->sub_id >= 0) {
2206 id = opts->sub_id;
2207 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2208 M_PROPERTY_OK;
2211 return found;
2214 #ifdef CONFIG_DVDNAV
2215 #ifndef FF_B_TYPE
2216 #define FF_B_TYPE 3
2217 #endif
2218 /// store decoded video image
2219 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2220 mp_image_t *from_mpi)
2222 mp_image_t *mpi;
2224 /// Do not store B-frames
2225 if (from_mpi->pict_type == FF_B_TYPE)
2226 return to_mpi;
2228 if (to_mpi &&
2229 to_mpi->w == from_mpi->w &&
2230 to_mpi->h == from_mpi->h &&
2231 to_mpi->imgfmt == from_mpi->imgfmt)
2232 mpi = to_mpi;
2233 else {
2234 if (to_mpi)
2235 free_mp_image(to_mpi);
2236 if (from_mpi->w == 0 || from_mpi->h == 0)
2237 return NULL;
2238 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2241 copy_mpi(mpi, from_mpi);
2242 return mpi;
2245 static void mp_dvdnav_reset_stream(MPContext *ctx)
2247 struct MPOpts *opts = &ctx->opts;
2248 if (ctx->sh_video) {
2249 /// clear video pts
2250 ctx->d_video->pts = 0.0f;
2251 ctx->sh_video->pts = 0.0f;
2252 ctx->sh_video->i_pts = 0.0f;
2253 ctx->sh_video->last_pts = 0.0f;
2254 ctx->sh_video->num_buffered_pts = 0;
2255 ctx->sh_video->num_frames = 0;
2256 ctx->sh_video->num_frames_decoded = 0;
2257 ctx->sh_video->timer = 0.0f;
2258 ctx->sh_video->stream_delay = 0.0f;
2259 ctx->sh_video->timer = 0;
2260 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2263 if (ctx->sh_audio) {
2264 /// free audio packets and reset
2265 ds_free_packs(ctx->d_audio);
2266 audio_delay -= ctx->sh_audio->stream_delay;
2267 ctx->delay = -audio_delay;
2268 ao_reset(ctx->ao);
2269 resync_audio_stream(ctx->sh_audio);
2272 audio_delay = 0.0f;
2273 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2274 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2275 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2276 if (dvdsub_lang_id != opts->sub_id) {
2277 opts->sub_id = dvdsub_lang_id;
2278 select_subtitle(ctx);
2282 /// clear all EOF related flags
2283 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2286 /// Restore last decoded DVDNAV (still frame)
2287 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2288 int *in_size,
2289 unsigned char **start,
2290 mp_image_t *decoded_frame)
2292 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2293 return decoded_frame;
2295 /// a change occurred in dvdnav stream
2296 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2297 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2298 mp_dvdnav_context_free(mpctx);
2299 mp_dvdnav_reset_stream(mpctx);
2300 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2301 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2304 if (*in_size < 0) {
2305 float len;
2307 /// Display still frame, if any
2308 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2309 decoded_frame = mpctx->nav_smpi;
2311 /// increment video frame : continue playing after still frame
2312 len = get_time_length(mpctx);
2313 if (mpctx->sh_video->pts >= len &&
2314 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2315 mp_dvdnav_skip_still(mpctx->stream);
2316 mp_dvdnav_skip_wait(mpctx->stream);
2318 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2320 if (mpctx->nav_buffer) {
2321 *start = mpctx->nav_start;
2322 *in_size = mpctx->nav_in_size;
2323 if (mpctx->nav_start)
2324 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2328 return decoded_frame;
2331 /// Save last decoded DVDNAV (still frame)
2332 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2333 unsigned char *start,
2334 mp_image_t *decoded_frame)
2336 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2337 return;
2339 free(mpctx->nav_buffer);
2340 mpctx->nav_buffer = NULL;
2341 mpctx->nav_start = NULL;
2342 mpctx->nav_in_size = -1;
2344 if (in_size > 0)
2345 mpctx->nav_buffer = malloc(in_size);
2346 if (mpctx->nav_buffer) {
2347 mpctx->nav_start = start;
2348 mpctx->nav_in_size = in_size;
2349 memcpy(mpctx->nav_buffer, start, in_size);
2352 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2353 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2355 #endif /* CONFIG_DVDNAV */
2357 /* Modify video timing to match the audio timeline. There are two main
2358 * reasons this is needed. First, video and audio can start from different
2359 * positions at beginning of file or after a seek (MPlayer starts both
2360 * immediately even if they have different pts). Second, the file can have
2361 * audio timestamps that are inconsistent with the duration of the audio
2362 * packets, for example two consecutive timestamp values differing by
2363 * one second but only a packet with enough samples for half a second
2364 * of playback between them.
2366 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2368 current_module = "av_sync";
2370 if (!mpctx->sh_audio || mpctx->syncing_audio)
2371 return;
2373 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2374 double v_pts = mpctx->sh_video->pts;
2375 double av_delay = a_pts - v_pts;
2376 // Try to sync vo_flip() so it will *finish* at given time
2377 av_delay += mpctx->last_vo_flip_duration;
2378 av_delay -= audio_delay; // This much pts difference is desired
2380 double change = av_delay * 0.1;
2381 double max_change = default_max_pts_correction >= 0 ?
2382 default_max_pts_correction : frame_time * 0.1;
2383 if (change < -max_change)
2384 change = -max_change;
2385 else if (change > max_change)
2386 change = max_change;
2387 mpctx->delay += change;
2388 mpctx->total_avsync_change += change;
2391 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2392 double pts)
2394 if (mpctx->paused)
2395 return 0;
2396 struct ao *ao = mpctx->ao;
2397 double bps = ao->bps / mpctx->opts.playback_speed;
2398 ao->pts = pts;
2399 // hack used by some mpeg-writing AOs
2400 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2401 mpctx->delay) * 90000.0;
2402 int played = ao_play(mpctx->ao, data, len, flags);
2403 if (played > 0) {
2404 mpctx->delay += played / bps;
2405 // Keep correct pts for remaining data - could be used to flush
2406 // remaining buffer when closing ao.
2407 ao->pts += played / bps;
2409 return played;
2412 #define ASYNC_PLAY_DONE -3
2413 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2415 struct ao *ao = mpctx->ao;
2416 struct MPOpts *opts = &mpctx->opts;
2417 sh_audio_t * const sh_audio = mpctx->sh_audio;
2418 int res;
2420 // Timing info may not be set without
2421 res = decode_audio(sh_audio, &ao->buffer, 1);
2422 if (res < 0)
2423 return res;
2425 int bytes;
2426 bool did_retry = false;
2427 double written_pts;
2428 double bps = ao->bps / opts->playback_speed;
2429 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2430 mpctx->hrseek_active = false;
2431 while (1) {
2432 written_pts = written_audio_pts(mpctx);
2433 double ptsdiff;
2434 if (hrseek)
2435 ptsdiff = written_pts - mpctx->hrseek_pts;
2436 else
2437 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2438 - audio_delay;
2439 bytes = ptsdiff * bps;
2440 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2442 // ogg demuxers give packets without timing
2443 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2444 if (!did_retry) {
2445 // Try to read more data to see packets that have pts
2446 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2447 if (res < 0)
2448 return res;
2449 did_retry = true;
2450 continue;
2452 bytes = 0;
2455 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2456 bytes = 0;
2458 if (bytes > 0)
2459 break;
2461 mpctx->syncing_audio = false;
2462 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2463 int res = decode_audio(sh_audio, &ao->buffer, a);
2464 bytes += ao->buffer.len;
2465 if (bytes >= 0) {
2466 memmove(ao->buffer.start,
2467 ao->buffer.start + ao->buffer.len - bytes, bytes);
2468 ao->buffer.len = bytes;
2469 if (res < 0)
2470 return res;
2471 return decode_audio(sh_audio, &ao->buffer, playsize);
2473 ao->buffer.len = 0;
2474 if (res < 0)
2475 return res;
2477 if (hrseek)
2478 // Don't add silence in audio-only case even if position is too late
2479 return 0;
2480 int fillbyte = 0;
2481 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2482 fillbyte = 0x80;
2483 if (bytes >= playsize) {
2484 /* This case could fall back to the one below with
2485 * bytes = playsize, but then silence would keep accumulating
2486 * in a_out_buffer if the AO accepts less data than it asks for
2487 * in playsize. */
2488 char *p = malloc(playsize);
2489 memset(p, fillbyte, playsize);
2490 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2491 free(p);
2492 return ASYNC_PLAY_DONE;
2494 mpctx->syncing_audio = false;
2495 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2496 return decode_audio(sh_audio, &ao->buffer, playsize);
2499 static int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
2501 struct MPOpts *opts = &mpctx->opts;
2502 struct ao *ao = mpctx->ao;
2503 unsigned int t;
2504 double tt;
2505 int playsize;
2506 int playflags = 0;
2507 bool audio_eof = false;
2508 bool partial_fill = false;
2509 sh_audio_t * const sh_audio = mpctx->sh_audio;
2510 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2511 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2513 current_module = "play_audio";
2515 // hack used by some mpeg-writing AOs
2516 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2517 mpctx->delay) * 90000.0;
2519 if (mpctx->paused)
2520 playsize = 1; // just initialize things (audio pts at least)
2521 else
2522 playsize = ao_get_space(ao);
2524 // Fill buffer if needed:
2525 current_module = "decode_audio";
2526 t = GetTimer();
2528 // Coming here with hrseek_active still set means audio-only
2529 if (!mpctx->sh_video)
2530 mpctx->syncing_audio = false;
2531 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2532 mpctx->syncing_audio = false;
2533 mpctx->hrseek_active = false;
2536 int res;
2537 if (mpctx->syncing_audio || mpctx->hrseek_active)
2538 res = audio_start_sync(mpctx, playsize);
2539 else
2540 res = decode_audio(sh_audio, &ao->buffer, playsize);
2541 if (res < 0) { // EOF, error or format change
2542 if (res == -2) {
2543 /* The format change isn't handled too gracefully. A more precise
2544 * implementation would require draining buffered old-format audio
2545 * while displaying video, then doing the output format switch.
2547 uninit_player(mpctx, INITIALIZED_AO);
2548 reinit_audio_chain(mpctx);
2549 return -1;
2550 } else if (res == ASYNC_PLAY_DONE)
2551 return 0;
2552 else if (mpctx->d_audio->eof)
2553 audio_eof = true;
2555 t = GetTimer() - t;
2556 tt = t * 0.000001f;
2557 audio_time_usage += tt;
2558 if (endpts != MP_NOPTS_VALUE && modifiable_audio_format) {
2559 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2560 * ao->bps / opts->playback_speed;
2561 if (playsize > bytes) {
2562 playsize = FFMAX(bytes, 0);
2563 playflags |= AOPLAY_FINAL_CHUNK;
2564 audio_eof = true;
2565 partial_fill = true;
2569 assert(ao->buffer.len % unitsize == 0);
2570 if (playsize > ao->buffer.len) {
2571 partial_fill = true;
2572 playsize = ao->buffer.len;
2573 if (audio_eof)
2574 playflags |= AOPLAY_FINAL_CHUNK;
2576 playsize -= playsize % unitsize;
2577 if (!playsize)
2578 return partial_fill && audio_eof ? -2 : -partial_fill;
2580 // play audio:
2581 current_module = "play_audio";
2583 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2584 written_audio_pts(mpctx));
2585 assert(played % unitsize == 0);
2586 ao->buffer_playable_size = playsize - played;
2588 if (played > 0) {
2589 ao->buffer.len -= played;
2590 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2591 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2592 // Sanity check to avoid hanging in case current ao doesn't output
2593 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2594 return -2;
2597 return -partial_fill;
2600 int reinit_video_chain(struct MPContext *mpctx)
2602 struct MPOpts *opts = &mpctx->opts;
2603 sh_video_t * const sh_video = mpctx->sh_video;
2604 if (!sh_video) {
2605 uninit_player(mpctx, INITIALIZED_VO);
2606 return 0;
2608 double ar = -1.0;
2609 //================== Init VIDEO (codec & libvo) ==========================
2610 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2611 current_module = "preinit_libvo";
2613 //shouldn't we set dvideo->id=-2 when we fail?
2614 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2615 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->key_fifo,
2616 mpctx->input))) {
2617 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2618 "the selected video_out (-vo) device.\n");
2619 goto err_out;
2621 mpctx->initialized_flags |= INITIALIZED_VO;
2624 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2625 &ar) != STREAM_UNSUPPORTED)
2626 mpctx->sh_video->stream_aspect = ar;
2627 current_module = "init_video_filters";
2629 char *vf_arg[] = {
2630 "_oldargs_", (char *)mpctx->video_out, NULL
2632 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2635 #ifdef CONFIG_ASS
2636 if (opts->ass_enabled) {
2637 int i;
2638 int insert = 1;
2639 if (opts->vf_settings)
2640 for (i = 0; opts->vf_settings[i].name; ++i)
2641 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2642 insert = 0;
2643 break;
2645 if (insert) {
2646 extern vf_info_t vf_info_ass;
2647 const vf_info_t *libass_vfs[] = {
2648 &vf_info_ass, NULL
2650 char *vf_arg[] = {
2651 "auto", "1", NULL
2653 int retcode = 0;
2654 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2655 sh_video->vfilter,
2656 "ass", vf_arg,
2657 &retcode);
2658 if (vf_ass)
2659 sh_video->vfilter = vf_ass;
2660 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2661 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2662 else
2663 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2664 "ASS: cannot add video filter\n");
2667 #endif
2669 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2671 if (opts->ass_enabled)
2672 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2673 mpctx->ass_library);
2675 current_module = "init_video_codec";
2677 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2679 if (!sh_video->initialized) {
2680 if (!opts->fixed_vo)
2681 uninit_player(mpctx, INITIALIZED_VO);
2682 goto err_out;
2685 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2687 if (sh_video->codec)
2688 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2689 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2691 sh_video->last_pts = MP_NOPTS_VALUE;
2692 sh_video->num_buffered_pts = 0;
2693 sh_video->next_frame_time = 0;
2694 mpctx->restart_playback = true;
2695 mpctx->delay = 0;
2697 if (opts->auto_quality > 0) {
2698 // Auto quality option enabled
2699 output_quality = get_video_quality_max(sh_video);
2700 if (opts->auto_quality > output_quality)
2701 opts->auto_quality = output_quality;
2702 else
2703 output_quality = opts->auto_quality;
2704 mp_msg(MSGT_CPLAYER, MSGL_V,
2705 "AutoQ: setting quality to %d.\n", output_quality);
2706 set_video_quality(sh_video, output_quality);
2709 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2711 current_module = "init_vo";
2713 return 1;
2715 err_out:
2716 mpctx->sh_video = mpctx->d_video->sh = NULL;
2717 return 0;
2720 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2722 struct sh_video *sh_video = mpctx->sh_video;
2723 double frame_time = 0;
2724 struct vo *video_out = mpctx->video_out;
2725 while (1) {
2726 current_module = "filter_video";
2727 // In nocorrect-pts mode there is no way to properly time these frames
2728 if (vo_get_buffered_frame(video_out, 0) >= 0)
2729 break;
2730 if (vf_output_queued_frame(sh_video->vfilter))
2731 break;
2732 unsigned char *packet = NULL;
2733 frame_time = sh_video->next_frame_time;
2734 if (mpctx->restart_playback)
2735 frame_time = 0;
2736 int in_size = 0;
2737 while (!in_size)
2738 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2739 &packet, force_fps);
2740 if (in_size < 0) {
2741 #ifdef CONFIG_DVDNAV
2742 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2743 if (mp_dvdnav_is_eof(mpctx->stream))
2744 return -1;
2745 if (mpctx->d_video)
2746 mpctx->d_video->eof = 0;
2747 if (mpctx->d_audio)
2748 mpctx->d_audio->eof = 0;
2749 mpctx->stream->eof = 0;
2750 } else
2751 #endif
2752 return -1;
2754 if (in_size > max_framesize)
2755 max_framesize = in_size;
2756 sh_video->timer += frame_time;
2757 if (mpctx->sh_audio)
2758 mpctx->delay -= frame_time;
2759 // video_read_frame can change fps (e.g. for ASF video)
2760 vo_fps = sh_video->fps;
2761 int framedrop_type = check_framedrop(mpctx, frame_time);
2762 current_module = "decode video";
2764 void *decoded_frame;
2765 #ifdef CONFIG_DVDNAV
2766 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2767 if (in_size >= 0 && !decoded_frame)
2768 #endif
2769 decoded_frame = decode_video(sh_video, sh_video->ds->current, packet,
2770 in_size, framedrop_type, sh_video->pts);
2771 #ifdef CONFIG_DVDNAV
2772 // Save last still frame for future display
2773 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2774 #endif
2775 if (decoded_frame) {
2776 current_module = "filter video";
2777 filter_video(sh_video, decoded_frame, sh_video->pts);
2779 break;
2781 return frame_time;
2784 static void determine_frame_pts(struct MPContext *mpctx)
2786 struct sh_video *sh_video = mpctx->sh_video;
2787 struct MPOpts *opts = &mpctx->opts;
2789 if (opts->user_pts_assoc_mode)
2790 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2791 else if (sh_video->pts_assoc_mode == 0) {
2792 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2793 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2794 sh_video->pts_assoc_mode = 1;
2795 else
2796 sh_video->pts_assoc_mode = 2;
2797 } else {
2798 int probcount1 = sh_video->num_reordered_pts_problems;
2799 int probcount2 = sh_video->num_sorted_pts_problems;
2800 if (sh_video->pts_assoc_mode == 2) {
2801 int tmp = probcount1;
2802 probcount1 = probcount2;
2803 probcount2 = tmp;
2805 if (probcount1 >= probcount2 * 1.5 + 2) {
2806 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2807 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2808 "%d.\n", sh_video->pts_assoc_mode);
2811 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2812 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2815 static double update_video(struct MPContext *mpctx)
2817 struct sh_video *sh_video = mpctx->sh_video;
2818 struct vo *video_out = mpctx->video_out;
2819 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2820 mpctx->osd); // hack for vf_expand
2821 if (!mpctx->opts.correct_pts)
2822 return update_video_nocorrect_pts(mpctx);
2824 double pts;
2826 while (1) {
2827 current_module = "filter_video";
2828 if (vo_get_buffered_frame(video_out, false) >= 0)
2829 break;
2830 // XXX Time used in this call is not counted in any performance
2831 // timer now
2832 if (vf_output_queued_frame(sh_video->vfilter))
2833 break;
2834 int in_size = 0;
2835 unsigned char *buf = NULL;
2836 pts = MP_NOPTS_VALUE;
2837 struct demux_packet *pkt;
2838 while (1) {
2839 pkt = ds_get_packet2(mpctx->d_video, false);
2840 if (!pkt || pkt->len)
2841 break;
2842 /* Packets with size 0 are assumed to not correspond to frames,
2843 * but to indicate the absence of a frame in formats like AVI
2844 * that must have packets at fixed timecode intervals. */
2846 if (pkt) {
2847 in_size = pkt->len;
2848 buf = pkt->buffer;
2849 pts = pkt->pts;
2851 if (pts != MP_NOPTS_VALUE)
2852 pts += mpctx->video_offset;
2853 if (in_size > max_framesize)
2854 max_framesize = in_size;
2855 current_module = "decode video";
2856 if (pts >= mpctx->hrseek_pts - .005)
2857 mpctx->hrseek_framedrop = false;
2858 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2859 check_framedrop(mpctx, sh_video->frametime);
2860 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2861 framedrop_type, pts);
2862 if (decoded_frame) {
2863 determine_frame_pts(mpctx);
2864 current_module = "filter video";
2865 filter_video(sh_video, decoded_frame, sh_video->pts);
2866 } else if (!pkt) {
2867 if (vo_get_buffered_frame(video_out, true) < 0)
2868 return -1;
2870 break;
2873 if (!video_out->frame_loaded)
2874 return 0;
2876 pts = video_out->next_pts;
2877 if (pts == MP_NOPTS_VALUE) {
2878 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2879 // Try to use decoder pts from before filters
2880 pts = sh_video->pts;
2881 if (pts == MP_NOPTS_VALUE)
2882 pts = sh_video->last_pts;
2884 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2885 vo_skip_frame(video_out);
2886 return 0;
2888 mpctx->hrseek_active = false;
2889 sh_video->pts = pts;
2890 if (sh_video->last_pts == MP_NOPTS_VALUE)
2891 sh_video->last_pts = sh_video->pts;
2892 else if (sh_video->last_pts > sh_video->pts) {
2893 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2894 sh_video->pts, sh_video->last_pts);
2895 /* If the difference in pts is small treat it as jitter around the
2896 * right value (possibly caused by incorrect timestamp ordering) and
2897 * just show this frame immediately after the last one.
2898 * Treat bigger differences as timestamp resets and start counting
2899 * timing of later frames from the position of this one. */
2900 if (sh_video->last_pts - sh_video->pts > 0.5)
2901 sh_video->last_pts = sh_video->pts;
2902 else
2903 sh_video->pts = sh_video->last_pts;
2905 double frame_time = sh_video->pts - sh_video->last_pts;
2906 sh_video->last_pts = sh_video->pts;
2907 sh_video->timer += frame_time;
2908 if (mpctx->sh_audio)
2909 mpctx->delay -= frame_time;
2910 return frame_time;
2913 static int get_cache_fill(struct MPContext *mpctx)
2915 #ifdef CONFIG_STREAM_CACHE
2916 struct MPOpts *opts = &mpctx->opts;
2917 if (opts->stream_cache_size > 0)
2918 return cache_fill_status(mpctx->stream);
2919 #endif
2920 return -1;
2923 static void update_pause_message(struct MPContext *mpctx)
2925 struct MPOpts *opts = &mpctx->opts;
2927 if (opts->quiet)
2928 return;
2930 int cache_fill = get_cache_fill(mpctx);
2931 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2933 if (!mpctx->status_printed && !cache_changed)
2934 return;
2936 char *msg = mp_gtext(" ===== PAUSE =====");
2937 char *tmpmem = NULL;
2938 if (cache_fill >= 0)
2939 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
2941 if (opts->term_osd && !mpctx->sh_video) {
2942 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
2943 update_osd_msg(mpctx);
2944 } else {
2945 if (mpctx->status_printed)
2946 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
2947 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
2950 mpctx->paused_cache_fill = cache_fill;
2951 mpctx->status_printed = false;
2953 talloc_free(tmpmem);
2956 void pause_player(struct MPContext *mpctx)
2958 if (mpctx->paused)
2959 return;
2960 mpctx->paused = 1;
2961 mpctx->step_frames = 0;
2962 mpctx->time_frame -= get_relative_time(mpctx);
2963 mpctx->osd_function = OSD_PAUSE;
2965 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2966 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2968 if (mpctx->ao && mpctx->sh_audio)
2969 ao_pause(mpctx->ao); // pause audio, keep data if possible
2971 mpctx->paused_cache_fill = get_cache_fill(mpctx);
2972 mpctx->status_printed = true;
2973 update_pause_message(mpctx);
2975 if (!mpctx->opts.quiet)
2976 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2979 void unpause_player(struct MPContext *mpctx)
2981 if (!mpctx->paused)
2982 return;
2983 mpctx->paused = 0;
2984 if (!mpctx->step_frames)
2985 mpctx->osd_function = OSD_PLAY;
2987 if (mpctx->ao && mpctx->sh_audio)
2988 ao_resume(mpctx->ao);
2989 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2990 && !mpctx->step_frames)
2991 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2992 (void)get_relative_time(mpctx); // ignore time that passed during pause
2995 static int redraw_osd(struct MPContext *mpctx)
2997 struct sh_video *sh_video = mpctx->sh_video;
2998 struct vf_instance *vf = sh_video->vfilter;
2999 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3000 return -1;
3001 if (vo_redraw_frame(mpctx->video_out) < 0)
3002 return -1;
3003 mpctx->osd->sub_pts = mpctx->video_pts;
3004 if (mpctx->osd->sub_pts != MP_NOPTS_VALUE)
3005 mpctx->osd->sub_pts += sub_delay - mpctx->osd->sub_offset;
3007 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3008 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3009 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3010 vo_flip_page(mpctx->video_out, 0, -1);
3011 return 0;
3014 void add_step_frame(struct MPContext *mpctx)
3016 mpctx->step_frames++;
3017 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3018 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3019 unpause_player(mpctx);
3022 static void seek_reset(struct MPContext *mpctx, bool reset_ao, bool reset_ac)
3024 if (mpctx->sh_video) {
3025 current_module = "seek_video_reset";
3026 resync_video_stream(mpctx->sh_video);
3027 mpctx->sh_video->timer = 0;
3028 vo_seek_reset(mpctx->video_out);
3029 mpctx->sh_video->timer = 0;
3030 mpctx->sh_video->num_buffered_pts = 0;
3031 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3032 mpctx->delay = 0;
3033 mpctx->time_frame = 0;
3034 // Not all demuxers set d_video->pts during seek, so this value
3035 // (which is used by at least vobsub code below) may be completely
3036 // wrong (probably 0).
3037 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3038 mpctx->video_pts = mpctx->sh_video->pts;
3039 update_subtitles(mpctx, mpctx->sh_video->pts, true);
3040 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3043 if (mpctx->sh_audio && reset_ac) {
3044 current_module = "seek_audio_reset";
3045 resync_audio_stream(mpctx->sh_audio);
3046 if (reset_ao)
3047 ao_reset(mpctx->ao);
3048 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3049 mpctx->sh_audio->a_buffer_len = 0;
3050 if (!mpctx->sh_video)
3051 update_subtitles(mpctx, mpctx->sh_audio->pts, true);
3054 if (vo_vobsub && mpctx->sh_video) {
3055 current_module = "seek_vobsub_reset";
3056 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3059 mpctx->restart_playback = true;
3060 mpctx->hrseek_active = false;
3061 mpctx->hrseek_framedrop = false;
3062 mpctx->total_avsync_change = 0;
3063 audio_time_usage = 0;
3064 video_time_usage = 0;
3065 vout_time_usage = 0;
3066 drop_frame_cnt = 0;
3068 current_module = NULL;
3071 static bool timeline_set_part(struct MPContext *mpctx, int i)
3073 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3074 struct timeline_part *n = mpctx->timeline + i;
3075 mpctx->timeline_part = i;
3076 mpctx->video_offset = n->start - n->source_start;
3077 if (n->source == p->source)
3078 return false;
3079 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3080 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3081 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3082 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3083 mpctx->stop_play = orig_stop_play;
3084 mpctx->demuxer = n->source->demuxer;
3085 mpctx->d_video = mpctx->demuxer->video;
3086 mpctx->d_audio = mpctx->demuxer->audio;
3087 mpctx->d_sub = mpctx->demuxer->sub;
3088 mpctx->sh_video = mpctx->d_video->sh;
3089 mpctx->sh_audio = mpctx->d_audio->sh;
3090 return true;
3093 // Given pts, switch playback to the corresponding part.
3094 // Return offset within that part.
3095 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3096 bool *need_reset)
3098 if (pts < 0)
3099 pts = 0;
3100 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3101 struct timeline_part *p = mpctx->timeline + i;
3102 if (pts < (p + 1)->start) {
3103 *need_reset = timeline_set_part(mpctx, i);
3104 return pts - p->start + p->source_start;
3107 return -1;
3111 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3112 static int seek(MPContext *mpctx, struct seek_params seek,
3113 bool timeline_fallthrough)
3115 struct MPOpts *opts = &mpctx->opts;
3117 current_module = "seek";
3118 if (mpctx->stop_play == AT_END_OF_FILE)
3119 mpctx->stop_play = KEEP_PLAYING;
3120 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3121 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3122 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3123 || opts->hr_seek > 0 || seek.exact > 0;
3124 if (seek.type == MPSEEK_FACTOR
3125 || seek.type == MPSEEK_ABSOLUTE
3126 && seek.amount < mpctx->last_chapter_pts
3127 || seek.amount < 0)
3128 mpctx->last_chapter_seek = -2;
3129 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3130 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3131 seek.type = MPSEEK_ABSOLUTE;
3133 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3134 && seek.type == MPSEEK_RELATIVE) {
3135 seek.type = MPSEEK_ABSOLUTE;
3136 seek.direction = seek.amount > 0 ? 1 : -1;
3137 seek.amount += get_current_time(mpctx);
3140 /* At least the liba52 decoder wants to read from the input stream
3141 * during initialization, so reinit must be done after the demux_seek()
3142 * call that clears possible stream EOF. */
3143 bool need_reset = false;
3144 double demuxer_amount = seek.amount;
3145 if (mpctx->timeline) {
3146 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3147 &need_reset);
3148 if (demuxer_amount == -1) {
3149 mpctx->stop_play = AT_END_OF_FILE;
3150 // Clear audio from current position
3151 if (mpctx->sh_audio && !timeline_fallthrough) {
3152 ao_reset(mpctx->ao);
3153 mpctx->sh_audio->a_buffer_len = 0;
3155 return -1;
3158 if (need_reset) {
3159 reinit_video_chain(mpctx);
3160 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos},
3161 mpctx);
3164 int demuxer_style = 0;
3165 switch (seek.type) {
3166 case MPSEEK_FACTOR:
3167 demuxer_style |= SEEK_FACTOR; // fallthrough
3168 case MPSEEK_ABSOLUTE:
3169 demuxer_style |= SEEK_ABSOLUTE;
3171 if (hr_seek || seek.direction < 0)
3172 demuxer_style |= SEEK_BACKWARD;
3173 else if (seek.direction > 0)
3174 demuxer_style |= SEEK_FORWARD;
3176 if (hr_seek)
3177 demuxer_amount -= opts->hr_seek_demuxer_offset;
3178 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3179 demuxer_style);
3180 if (seekresult == 0) {
3181 if (need_reset) {
3182 reinit_audio_chain(mpctx);
3183 seek_reset(mpctx, !timeline_fallthrough, false);
3185 return -1;
3188 if (need_reset)
3189 reinit_audio_chain(mpctx);
3190 /* If we just reinitialized audio it doesn't need to be reset,
3191 * and resetting could lose audio some decoders produce during init. */
3192 seek_reset(mpctx, !timeline_fallthrough, !need_reset);
3194 /* Use the target time as "current position" for further relative
3195 * seeks etc until a new video frame has been decoded */
3196 if (seek.type == MPSEEK_ABSOLUTE) {
3197 mpctx->video_pts = seek.amount;
3198 mpctx->last_seek_pts = seek.amount;
3199 } else
3200 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3202 if (hr_seek) {
3203 mpctx->hrseek_active = true;
3204 mpctx->hrseek_framedrop = true;
3205 mpctx->hrseek_pts = seek.amount;
3208 mpctx->start_timestamp = GetTimerMS();
3210 return 0;
3213 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3214 int exact)
3216 struct seek_params *seek = &mpctx->seek;
3217 switch (type) {
3218 case MPSEEK_RELATIVE:
3219 if (seek->type == MPSEEK_FACTOR)
3220 return; // Well... not common enough to bother doing better
3221 seek->amount += amount;
3222 seek->exact = FFMAX(seek->exact, exact);
3223 if (seek->type == MPSEEK_NONE)
3224 seek->exact = exact;
3225 if (seek->type == MPSEEK_ABSOLUTE)
3226 return;
3227 if (seek->amount == 0) {
3228 *seek = (struct seek_params){ 0 };
3229 return;
3231 seek->type = MPSEEK_RELATIVE;
3232 return;
3233 case MPSEEK_ABSOLUTE:
3234 case MPSEEK_FACTOR:
3235 *seek = (struct seek_params) {
3236 .type = type,
3237 .amount = amount,
3238 .exact = exact,
3240 return;
3241 case MPSEEK_NONE:
3242 *seek = (struct seek_params){ 0 };
3243 return;
3245 abort();
3249 double get_time_length(struct MPContext *mpctx)
3251 if (mpctx->timeline)
3252 return mpctx->timeline[mpctx->num_timeline_parts].start;
3254 struct demuxer *demuxer = mpctx->demuxer;
3255 double get_time_ans;
3256 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3257 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3258 (void *) &get_time_ans) > 0)
3259 return get_time_ans;
3261 struct sh_video *sh_video = mpctx->d_video->sh;
3262 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3263 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3264 return (double) (demuxer->movi_end - demuxer->movi_start) /
3265 (sh_video->i_bps + sh_audio->i_bps);
3266 if (sh_video && sh_video->i_bps)
3267 return (double) (demuxer->movi_end - demuxer->movi_start) /
3268 sh_video->i_bps;
3269 if (sh_audio && sh_audio->i_bps)
3270 return (double) (demuxer->movi_end - demuxer->movi_start) /
3271 sh_audio->i_bps;
3272 return 0;
3275 /* If there are timestamps from stream level then use those (for example
3276 * DVDs can have consistent times there while the MPEG-level timestamps
3277 * reset). */
3278 double get_current_time(struct MPContext *mpctx)
3280 struct demuxer *demuxer = mpctx->demuxer;
3281 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3282 return demuxer->stream_pts;
3283 if (mpctx->sh_video) {
3284 double pts = mpctx->video_pts;
3285 if (pts != MP_NOPTS_VALUE)
3286 return pts;
3288 double apts = playing_audio_pts(mpctx);
3289 if (apts != MP_NOPTS_VALUE)
3290 return apts;
3291 return mpctx->last_seek_pts;
3294 int get_percent_pos(struct MPContext *mpctx)
3296 struct demuxer *demuxer = mpctx->demuxer;
3297 int ans = 0;
3298 if (mpctx->timeline)
3299 ans = get_current_time(mpctx) * 100 /
3300 mpctx->timeline[mpctx->num_timeline_parts].start;
3301 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3303 else {
3304 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3305 off_t pos = demuxer->filepos > 0 ?
3306 demuxer->filepos : stream_tell(demuxer->stream);
3307 if (len > 0)
3308 ans = (pos - demuxer->movi_start) / len;
3309 else
3310 ans = 0;
3312 if (ans < 0)
3313 ans = 0;
3314 if (ans > 100)
3315 ans = 100;
3316 return ans;
3319 // -2 is no chapters, -1 is before first chapter
3320 int get_current_chapter(struct MPContext *mpctx)
3322 double current_pts = get_current_time(mpctx);
3323 if (!mpctx->chapters)
3324 return FFMAX(mpctx->last_chapter_seek,
3325 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3327 int i;
3328 for (i = 1; i < mpctx->num_chapters; i++)
3329 if (current_pts < mpctx->chapters[i].start)
3330 break;
3331 return FFMAX(mpctx->last_chapter_seek, i - 1);
3334 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3336 char *name = chapter_name(mpctx, chapter);
3337 if (name) {
3338 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3339 } else {
3340 int chapter_count = get_chapter_count(mpctx);
3341 if (chapter_count <= 0)
3342 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3343 else
3344 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3345 chapter_count);
3347 return name;
3350 // returns NULL if chapter name unavailable
3351 char *chapter_name(struct MPContext *mpctx, int chapter)
3353 if (!mpctx->chapters)
3354 return demuxer_chapter_name(mpctx->demuxer, chapter);
3355 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3358 // returns the start of the chapter in seconds
3359 double chapter_start_time(struct MPContext *mpctx, int chapter)
3361 if (!mpctx->chapters)
3362 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3363 return mpctx->chapters[chapter].start;
3366 int get_chapter_count(struct MPContext *mpctx)
3368 if (!mpctx->chapters)
3369 return demuxer_chapter_count(mpctx->demuxer);
3370 return mpctx->num_chapters;
3373 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3375 mpctx->last_chapter_seek = -2;
3376 if (!mpctx->chapters) {
3377 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3378 if (res >= 0) {
3379 if (*seek_pts == -1)
3380 seek_reset(mpctx, true, true);
3381 else {
3382 mpctx->last_chapter_seek = res;
3383 mpctx->last_chapter_pts = *seek_pts;
3386 return res;
3389 if (chapter >= mpctx->num_chapters)
3390 return -1;
3391 if (chapter < 0)
3392 chapter = 0;
3393 *seek_pts = mpctx->chapters[chapter].start;
3394 mpctx->last_chapter_seek = chapter;
3395 mpctx->last_chapter_pts = *seek_pts;
3396 return chapter;
3400 static void run_playloop(struct MPContext *mpctx)
3402 struct MPOpts *opts = &mpctx->opts;
3403 bool full_audio_buffers = false;
3404 bool audio_left = false, video_left = false;
3405 double endpts = end_at.type == END_AT_TIME ? end_at.pos : MP_NOPTS_VALUE;
3406 bool end_is_chapter = false;
3407 double sleeptime = WAKEUP_PERIOD;
3408 bool was_restart = mpctx->restart_playback;
3410 if (mpctx->timeline) {
3411 double end = mpctx->timeline[mpctx->timeline_part + 1].start;
3412 if (endpts == MP_NOPTS_VALUE || end < endpts) {
3413 endpts = end;
3414 end_is_chapter = true;
3418 if (opts->chapterrange[1] > 0) {
3419 int cur_chapter = get_current_chapter(mpctx);
3420 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3421 mpctx->stop_play = PT_NEXT_ENTRY;
3424 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3425 mpctx->sh_audio = mpctx->d_audio->sh;
3426 mpctx->sh_audio->ds = mpctx->d_audio;
3427 reinit_audio_chain(mpctx);
3430 if (mpctx->step_frames && !mpctx->sh_video) {
3431 mpctx->step_frames = 0;
3432 pause_player(mpctx);
3435 if (mpctx->sh_audio && !mpctx->restart_playback && !mpctx->ao->untimed) {
3436 int status = fill_audio_out_buffers(mpctx, endpts);
3437 full_audio_buffers = status >= 0;
3438 // Not at audio stream EOF yet
3439 audio_left = status > -2;
3442 double buffered_audio = -1;
3443 while (mpctx->sh_video) { // never loops, for "break;" only
3444 struct vo *vo = mpctx->video_out;
3445 vo_pts = mpctx->sh_video->timer * 90000.0;
3446 vo_fps = mpctx->sh_video->fps;
3448 video_left = vo->hasframe || vo->frame_loaded;
3449 if (!vo->frame_loaded && (!mpctx->paused || mpctx->restart_playback)) {
3450 double frame_time = update_video(mpctx);
3451 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3452 if (mpctx->sh_video->vf_initialized < 0) {
3453 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3454 "\nFATAL: Could not initialize video filters (-vf) "
3455 "or video output (-vo).\n");
3456 mpctx->stop_play = PT_NEXT_ENTRY;
3457 return;
3459 video_left = frame_time >= 0;
3460 if (video_left && !mpctx->restart_playback) {
3461 mpctx->time_frame += frame_time / opts->playback_speed;
3462 adjust_sync(mpctx, frame_time);
3466 if (endpts != MP_NOPTS_VALUE)
3467 video_left &= mpctx->sh_video->pts < endpts;
3469 // ================================================================
3471 current_module = "vo_check_events";
3472 vo_check_events(vo);
3474 #ifdef CONFIG_X11
3475 if (stop_xscreensaver && vo->x11)
3476 xscreensaver_heartbeat(vo->x11);
3477 #endif
3478 if (heartbeat_cmd) {
3479 static unsigned last_heartbeat;
3480 unsigned now = GetTimerMS();
3481 if (now - last_heartbeat > 30000) {
3482 last_heartbeat = now;
3483 system(heartbeat_cmd);
3487 if (!video_left || (mpctx->paused && !mpctx->restart_playback))
3488 break;
3489 if (!vo->frame_loaded) {
3490 sleeptime = 0;
3491 break;
3494 mpctx->time_frame -= get_relative_time(mpctx);
3495 if (full_audio_buffers && !mpctx->restart_playback) {
3496 buffered_audio = ao_get_delay(mpctx->ao);
3497 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", buffered_audio);
3499 if (opts->autosync) {
3500 /* Smooth reported playback position from AO by averaging
3501 * it with the value expected based on previus value and
3502 * time elapsed since then. May help smooth video timing
3503 * with audio output that have inaccurate position reporting.
3504 * This is badly implemented; the behavior of the smoothing
3505 * now undesirably depends on how often this code runs
3506 * (mainly depends on video frame rate). */
3507 float predicted = (mpctx->delay / opts->playback_speed +
3508 mpctx->time_frame);
3509 float difference = buffered_audio - predicted;
3510 buffered_audio = predicted + difference / opts->autosync;
3513 mpctx->time_frame = (buffered_audio -
3514 mpctx->delay / opts->playback_speed);
3515 } else {
3516 /* If we're more than 200 ms behind the right playback
3517 * position, don't try to speed up display of following
3518 * frames to catch up; continue with default speed from
3519 * the current frame instead.
3520 * If benchmark is set always output frames immediately
3521 * without sleeping.
3523 if (mpctx->time_frame < -0.2 || opts->benchmark)
3524 mpctx->time_frame = 0;
3527 double vsleep = mpctx->time_frame - vo->flip_queue_offset;
3528 if (vsleep > 0.050) {
3529 sleeptime = FFMIN(sleeptime, vsleep - 0.040);
3530 break;
3532 sleeptime = 0;
3534 //=================== FLIP PAGE (VIDEO BLT): ======================
3536 current_module = "flip_page";
3537 vo_new_frame_imminent(vo);
3538 struct sh_video *sh_video = mpctx->sh_video;
3539 mpctx->video_pts = sh_video->pts;
3540 update_subtitles(mpctx, sh_video->pts, false);
3541 update_teletext(sh_video, mpctx->demuxer, 0);
3542 update_osd_msg(mpctx);
3543 struct vf_instance *vf = sh_video->vfilter;
3544 mpctx->osd->sub_pts = mpctx->video_pts;
3545 if (mpctx->osd->sub_pts != MP_NOPTS_VALUE)
3546 mpctx->osd->sub_pts += sub_delay - mpctx->osd->sub_offset;
3547 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3548 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3549 vo_osd_changed(0);
3551 mpctx->time_frame -= get_relative_time(mpctx);
3552 mpctx->time_frame -= vo->flip_queue_offset;
3553 float aq_sleep_time = mpctx->time_frame;
3554 if (mpctx->time_frame > 0.001
3555 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3556 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3557 mpctx->time_frame += vo->flip_queue_offset;
3559 unsigned int t2 = GetTimer();
3560 /* Playing with playback speed it's possible to get pathological
3561 * cases with mpctx->time_frame negative enough to cause an
3562 * overflow in pts_us calculation, thus the FFMAX. */
3563 double time_frame = FFMAX(mpctx->time_frame, -1);
3564 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3565 int duration = -1;
3566 double pts2 = vo->next_pts2;
3567 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts &&
3568 !mpctx->restart_playback) {
3569 // expected A/V sync correction is ignored
3570 double diff = (pts2 - mpctx->video_pts);
3571 diff /= opts->playback_speed;
3572 if (mpctx->time_frame < 0)
3573 diff += mpctx->time_frame;
3574 if (diff < 0)
3575 diff = 0;
3576 if (diff > 10)
3577 diff = 10;
3578 duration = diff * 1e6;
3580 vo_flip_page(vo, pts_us | 1, duration);
3582 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3583 vout_time_usage += mpctx->last_vo_flip_duration;
3584 if (vo->driver->flip_page_timed) {
3585 // No need to adjust sync based on flip speed
3586 mpctx->last_vo_flip_duration = 0;
3587 // For print_status - VO call finishing early is OK for sync
3588 mpctx->time_frame -= get_relative_time(mpctx);
3590 if (mpctx->restart_playback) {
3591 mpctx->syncing_audio = true;
3592 if (mpctx->sh_audio)
3593 fill_audio_out_buffers(mpctx, endpts);
3594 mpctx->restart_playback = false;
3595 mpctx->time_frame = 0;
3596 get_relative_time(mpctx);
3598 print_status(mpctx, MP_NOPTS_VALUE, true);
3599 screenshot_flip(mpctx);
3601 if (opts->auto_quality > 0) {
3602 current_module = "autoq";
3603 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3604 ++output_quality;
3605 else if (output_quality > 1 && aq_sleep_time < 0)
3606 --output_quality;
3607 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3608 output_quality = 0;
3609 set_video_quality(mpctx->sh_video, output_quality);
3612 if (play_n_frames >= 0) {
3613 --play_n_frames;
3614 if (play_n_frames <= 0)
3615 mpctx->stop_play = PT_NEXT_ENTRY;
3617 if (mpctx->step_frames > 0) {
3618 mpctx->step_frames--;
3619 if (mpctx->step_frames == 0)
3620 pause_player(mpctx);
3622 break;
3623 } // video
3625 #ifdef CONFIG_DVDNAV
3626 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3627 nav_highlight_t hl;
3628 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3629 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3630 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3631 vo_osd_changed(OSDTYPE_DVDNAV);
3632 } else {
3633 osd_set_nav_box(0, 0, 0, 0);
3634 vo_osd_changed(OSDTYPE_DVDNAV);
3635 vo_osd_changed(OSDTYPE_SPU);
3638 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3639 double ar = -1.0;
3640 if (mpctx->sh_video &&
3641 stream_control(mpctx->demuxer->stream,
3642 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3643 != STREAM_UNSUPPORTED)
3644 mpctx->sh_video->stream_aspect = ar;
3647 #endif
3649 if (mpctx->sh_audio && (mpctx->restart_playback ? !video_left :
3650 mpctx->ao->untimed && (mpctx->delay <= 0 ||
3651 !video_left))) {
3652 int status = fill_audio_out_buffers(mpctx, endpts);
3653 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3654 // Not at audio stream EOF yet
3655 audio_left = status > -2;
3657 if (!video_left)
3658 mpctx->restart_playback = false;
3659 if (mpctx->sh_audio && buffered_audio == -1)
3660 buffered_audio = mpctx->paused ? 0 : ao_get_delay(mpctx->ao);
3662 update_osd_msg(mpctx);
3663 if (mpctx->paused)
3664 update_pause_message(mpctx);
3665 if (!video_left && (!mpctx->paused || was_restart)) {
3666 double a_pos = 0;
3667 if (mpctx->sh_audio) {
3668 a_pos = (written_audio_pts(mpctx) -
3669 mpctx->opts.playback_speed * buffered_audio);
3671 print_status(mpctx, a_pos, false);
3673 if (!mpctx->sh_video)
3674 update_subtitles(mpctx, a_pos, false);
3677 /* It's possible for the user to simultaneously switch both audio
3678 * and video streams to "disabled" at runtime. Handle this by waiting
3679 * rather than immediately stopping playback due to EOF.
3681 * When all audio has been written to output driver, stay in the
3682 * main loop handling commands until it has been mostly consumed,
3683 * except in the gapless case, where the next file will be started
3684 * while audio from the current one still remains to be played.
3686 * We want this check to trigger if we seeked to this position,
3687 * but not if we paused at it with audio possibly still buffered in
3688 * the AO. There's currently no working way to check buffered audio
3689 * inside AO while paused. Thus the "was_restart" check below, which
3690 * should trigger after seek only, when we know there's no audio
3691 * buffered.
3693 if ((mpctx->sh_audio || mpctx->sh_video) && !audio_left && !video_left
3694 && (opts->gapless_audio || buffered_audio < 0.05)
3695 && (!mpctx->paused || was_restart)) {
3696 if (end_is_chapter) {
3697 seek(mpctx, (struct seek_params){
3698 .type = MPSEEK_ABSOLUTE,
3699 .amount = mpctx->timeline[mpctx->timeline_part+1].start
3700 }, true);
3701 } else
3702 mpctx->stop_play = AT_END_OF_FILE;
3703 } else if (!mpctx->stop_play) {
3704 double audio_sleep = 9;
3705 if (mpctx->sh_audio && !mpctx->paused) {
3706 if (mpctx->ao->untimed) {
3707 if (!video_left)
3708 audio_sleep = 0;
3709 } else if (full_audio_buffers) {
3710 audio_sleep = buffered_audio - 0.050;
3711 // Keep extra safety margin if the buffers are large
3712 if (audio_sleep > 0.100)
3713 audio_sleep = FFMAX(audio_sleep - 0.200, 0.100);
3714 else
3715 audio_sleep = FFMAX(audio_sleep, 0.020);
3716 } else
3717 audio_sleep = 0.020;
3719 sleeptime = FFMIN(sleeptime, audio_sleep);
3720 if (sleeptime > 0) {
3721 if (!mpctx->sh_video)
3722 goto novideo;
3723 int hack = vo_osd_changed(0);
3724 vo_osd_changed(hack);
3725 if (hack || mpctx->video_out->want_redraw) {
3726 if (redraw_osd(mpctx) < 0) {
3727 if (mpctx->paused && video_left)
3728 add_step_frame(mpctx);
3729 else
3730 goto novideo;
3731 } else
3732 vo_osd_changed(0);
3733 } else {
3734 novideo:
3735 mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
3740 //================= Keyboard events, SEEKing ====================
3742 current_module = "key_events";
3744 mp_cmd_t *cmd;
3745 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3746 /* Allow running consecutive seek commands to combine them,
3747 * but execute the seek before running other commands.
3748 * If the user seeks continuously (keeps arrow key down)
3749 * try to finish showing a frame from one location before doing
3750 * another seek (which could lead to unchanging display). */
3751 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3752 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3753 && GetTimerMS() - mpctx->start_timestamp < 300)
3754 break;
3755 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3756 run_command(mpctx, cmd);
3757 mp_cmd_free(cmd);
3758 if (mpctx->stop_play)
3759 break;
3762 // handle -sstep
3763 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3764 mpctx->osd_function = OSD_FFW;
3765 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3768 /* Looping. */
3769 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3770 mpctx->stop_play == PT_NEXT_ENTRY)) {
3771 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3773 if (opts->loop_times > 1)
3774 opts->loop_times--;
3775 else if (opts->loop_times == 1)
3776 opts->loop_times = -1;
3777 play_n_frames = play_n_frames_mf;
3778 mpctx->stop_play = 0;
3779 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3782 if (mpctx->seek.type) {
3783 seek(mpctx, mpctx->seek, false);
3784 mpctx->seek = (struct seek_params){ 0 };
3789 static int read_keys(void *ctx, int fd)
3791 if (getch2(ctx))
3792 return MP_INPUT_NOTHING;
3793 return MP_INPUT_DEAD;
3796 static bool attachment_is_font(struct demux_attachment *att)
3798 if (!att->name || !att->type || !att->data || !att->data_size)
3799 return false;
3800 // match against MIME types
3801 if (strcmp(att->type, "application/x-truetype-font") == 0
3802 || strcmp(att->type, "application/x-font") == 0)
3803 return true;
3804 // fallback: match against file extension
3805 if (strlen(att->name) > 4) {
3806 char *ext = att->name + strlen(att->name) - 4;
3807 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3808 || strcasecmp(ext, ".otf") == 0)
3809 return true;
3811 return false;
3814 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3816 if (audio_id == -1)
3817 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3818 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3819 demuxer_switch_audio(demuxer, audio_id);
3820 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3821 demuxer->audio->id = -2;
3822 demuxer->audio->sh = NULL;
3824 return demuxer->audio->id;
3827 static void print_version(const char *name)
3829 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3831 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3832 GetCpuCaps(&gCpuCaps);
3833 #if ARCH_X86
3834 mp_msg(MSGT_CPLAYER, MSGL_V,
3835 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3836 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3837 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3838 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3839 #if CONFIG_RUNTIME_CPUDETECT
3840 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3841 #else
3842 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3843 if (HAVE_MMX)
3844 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3845 if (HAVE_MMX2)
3846 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3847 if (HAVE_AMD3DNOW)
3848 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3849 if (HAVE_AMD3DNOWEXT)
3850 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3851 if (HAVE_SSE)
3852 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3853 if (HAVE_SSE2)
3854 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3855 if (HAVE_SSSE3)
3856 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3857 if (HAVE_CMOV)
3858 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3859 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3860 #endif /* CONFIG_RUNTIME_CPUDETECT */
3861 #endif /* ARCH_X86 */
3862 print_libav_versions();
3865 #ifdef PTW32_STATIC_LIB
3866 static void detach_ptw32(void)
3868 pthread_win32_thread_detach_np();
3869 pthread_win32_process_detach_np();
3871 #endif
3873 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3874 * file for some tools to link against. */
3875 #ifndef DISABLE_MAIN
3876 int main(int argc, char *argv[])
3878 #ifdef PTW32_STATIC_LIB
3879 pthread_win32_process_attach_np();
3880 pthread_win32_thread_attach_np();
3881 atexit(detach_ptw32);
3882 #endif
3883 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3884 || !strcmp(argv[1], "--leak-report")))
3885 talloc_enable_leak_report();
3887 #ifdef __MINGW32__
3888 mp_get_converted_argv(&argc, &argv);
3889 #endif
3891 char *mem_ptr;
3893 // movie info:
3895 /* Flag indicating whether MPlayer should exit without playing anything. */
3896 int opt_exit = 0;
3897 int i;
3899 struct MPContext *mpctx = talloc(NULL, MPContext);
3900 *mpctx = (struct MPContext){
3901 .osd_function = OSD_PLAY,
3902 .begin_skip = MP_NOPTS_VALUE,
3903 .play_tree_step = 1,
3904 .global_sub_pos = -1,
3905 .set_of_sub_pos = -1,
3906 .file_format = DEMUXER_TYPE_UNKNOWN,
3907 .last_dvb_step = 1,
3908 .paused_cache_fill = -1,
3911 InitTimer();
3912 srand(GetTimerMS());
3914 mp_msg_init();
3915 init_libav();
3917 struct MPOpts *opts = &mpctx->opts;
3918 set_default_mplayer_options(opts);
3919 // Create the config context and register the options
3920 mpctx->mconfig = m_config_new(opts, cfg_include);
3921 m_config_register_options(mpctx->mconfig, mplayer_opts);
3922 m_config_register_options(mpctx->mconfig, common_opts);
3923 mp_input_register_options(mpctx->mconfig);
3924 m_config_initialize(mpctx->mconfig, opts);
3926 // Preparse the command line
3927 m_config_preparse_command_line(mpctx->mconfig, argc, argv, &verbose);
3929 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3930 set_path_env();
3931 #endif
3933 #ifdef CONFIG_TV
3934 stream_tv_defaults.immediate = 1;
3935 #endif
3937 parse_cfgfiles(mpctx, mpctx->mconfig);
3939 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3940 if (mpctx->playtree == NULL)
3941 opt_exit = 1;
3942 else {
3943 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3944 if (mpctx->playtree) {
3945 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3946 mpctx->mconfig);
3947 if (mpctx->playtree_iter) {
3948 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3949 PLAY_TREE_ITER_ENTRY) {
3950 play_tree_iter_free(mpctx->playtree_iter);
3951 mpctx->playtree_iter = NULL;
3953 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3959 print_version("MPlayer2");
3961 #if defined(__MINGW32__) || defined(__CYGWIN__)
3963 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3964 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3965 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3966 if (kernel32) {
3967 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3968 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3970 if (setDEP)
3971 setDEP(3);
3972 if (setDllDir)
3973 setDllDir("");
3975 // stop Windows from showing all kinds of annoying error dialogs
3976 SetErrorMode(0x8003);
3977 // request 1ms timer resolution
3978 timeBeginPeriod(1);
3979 #endif
3981 #ifdef CONFIG_PRIORITY
3982 set_priority();
3983 #endif
3985 if (opts->video_driver_list &&
3986 strcmp(opts->video_driver_list[0], "help") == 0) {
3987 list_video_out();
3988 opt_exit = 1;
3991 if (opts->audio_driver_list &&
3992 strcmp(opts->audio_driver_list[0], "help") == 0) {
3993 list_audio_out();
3994 opt_exit = 1;
3997 /* Check codecs.conf. */
3998 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
3999 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4000 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4001 if (!parse_codec_cfg(NULL))
4002 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4003 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4004 "Using built-in default codecs.conf.\n");
4007 free(mem_ptr); // release the buffer created by get_path()
4010 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4011 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4012 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4013 list_codecs(1);
4014 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4015 opt_exit = 1;
4017 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4018 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4019 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4020 list_codecs(0);
4021 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4022 opt_exit = 1;
4024 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4025 vfm_help();
4026 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4027 opt_exit = 1;
4029 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4030 afm_help();
4031 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4032 opt_exit = 1;
4034 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4035 af_help();
4036 printf("\n");
4037 opt_exit = 1;
4039 #ifdef CONFIG_X11
4040 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4041 fstype_help();
4042 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4043 opt_exit = 1;
4045 #endif
4046 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4047 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4048 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4049 demuxer_help();
4050 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4051 opt_exit = 1;
4053 if (opts->list_properties) {
4054 property_print_help();
4055 opt_exit = 1;
4058 if (opt_exit)
4059 exit_player(mpctx, EXIT_NONE);
4061 if (!mpctx->filename && !opts->player_idle_mode) {
4062 // no file/vcd/dvd -> show HELP:
4063 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4064 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4067 /* Display what configure line was used */
4068 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4070 // Many users forget to include command line in bugreports...
4071 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4072 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4073 for (i = 1; i < argc; i++)
4074 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4075 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4078 //------ load global data first ------
4080 #ifdef CONFIG_ASS
4081 mpctx->ass_library = mp_ass_init(opts);
4082 #endif
4084 mpctx->osd = osd_create(opts, mpctx->ass_library);
4086 #ifdef HAVE_RTC
4087 if (opts->rtc) {
4088 char *rtc_device = opts->rtc_device;
4089 // seteuid(0); /* Can't hurt to try to get root here */
4090 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4091 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4092 "(it should be readable by the user.)\n",
4093 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4094 else {
4095 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4097 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4098 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4099 "ioctl (rtc_irqp_set %lu): %s\n",
4100 irqp, strerror(errno));
4101 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4102 close(rtc_fd);
4103 rtc_fd = -1;
4104 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4105 /* variable only by the root */
4106 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4107 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4108 close(rtc_fd);
4109 rtc_fd = -1;
4110 } else
4111 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4112 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4115 if (rtc_fd < 0)
4116 #endif /* HAVE_RTC */
4117 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4118 opts->softsleep ? "software" : timer_name);
4120 #ifdef HAVE_TERMCAP
4121 load_termcap(NULL); // load key-codes
4122 #endif
4124 // ========== Init keyboard FIFO (connection to libvo) ============
4126 // Init input system
4127 current_module = "init_input";
4128 mpctx->input = mp_input_init(&opts->input);
4129 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4130 if (slave_mode)
4131 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4132 else if (opts->consolecontrols)
4133 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4134 // Set the libstream interrupt callback
4135 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4137 current_module = NULL;
4139 /// Catch signals
4140 #ifndef __MINGW32__
4141 signal(SIGCHLD, child_sighandler);
4142 #endif
4144 #ifdef CONFIG_CRASH_DEBUG
4145 prog_path = argv[0];
4146 #endif
4147 //========= Catch terminate signals: ================
4148 // terminate requests:
4149 signal(SIGTERM, exit_sighandler); // kill
4150 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4152 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4154 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4155 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4156 #ifdef CONFIG_SIGHANDLER
4157 // fatal errors:
4158 signal(SIGBUS, exit_sighandler); // bus error
4159 signal(SIGSEGV, exit_sighandler); // segfault
4160 signal(SIGILL, exit_sighandler); // illegal instruction
4161 signal(SIGFPE, exit_sighandler); // floating point exc.
4162 signal(SIGABRT, exit_sighandler); // abort()
4163 #ifdef CONFIG_CRASH_DEBUG
4164 if (crash_debug)
4165 signal(SIGTRAP, exit_sighandler);
4166 #endif
4167 #endif
4169 // ***************** Now, let's see the per-file stuff ******************
4171 play_next_file:
4173 // init global sub numbers
4174 mpctx->global_sub_size = 0;
4175 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4177 if (mpctx->filename) {
4178 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4179 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4180 load_per_file_config(mpctx->mconfig, mpctx->filename);
4183 if (opts->video_driver_list)
4184 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4185 opts->video_driver_list[0]);
4186 if (opts->audio_driver_list)
4187 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4188 opts->audio_driver_list[0]);
4190 // We must enable getch2 here to be able to interrupt network connection
4191 // or cache filling
4192 if (opts->consolecontrols && !slave_mode) {
4193 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4194 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4195 "WARNING: getch2_init called twice!\n");
4196 else
4197 getch2_enable(); // prepare stdin for hotkeys...
4198 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4199 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4202 // ================= idle loop (STOP state) =========================
4203 while (opts->player_idle_mode && !mpctx->filename) {
4204 uninit_player(mpctx, INITIALIZED_AO | INITIALIZED_VO);
4205 play_tree_t *entry = NULL;
4206 mp_cmd_t *cmd;
4207 while (!(cmd = mp_input_get_cmd(mpctx->input, WAKEUP_PERIOD * 1000,
4208 false)));
4209 switch (cmd->id) {
4210 case MP_CMD_LOADFILE:
4211 // prepare a tree entry with the new filename
4212 entry = play_tree_new();
4213 play_tree_add_file(entry, cmd->args[0].v.s);
4214 // The entry is added to the main playtree after the switch().
4215 break;
4216 case MP_CMD_LOADLIST:
4217 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4218 break;
4219 case MP_CMD_QUIT:
4220 exit_player_with_rc(mpctx, EXIT_QUIT,
4221 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4222 break;
4223 case MP_CMD_VO_FULLSCREEN:
4224 case MP_CMD_GET_PROPERTY:
4225 case MP_CMD_SET_PROPERTY:
4226 case MP_CMD_STEP_PROPERTY:
4227 run_command(mpctx, cmd);
4228 break;
4231 mp_cmd_free(cmd);
4233 if (entry) { // user entered a command that gave a valid entry
4234 if (mpctx->playtree)
4235 // the playtree is always a node with one child. let's clear it
4236 play_tree_free_list(mpctx->playtree->child, 1);
4237 else
4238 // .. or make a brand new playtree
4239 mpctx->playtree = play_tree_new();
4241 if (!mpctx->playtree)
4242 continue; // couldn't make playtree! wait for next command
4244 play_tree_set_child(mpctx->playtree, entry);
4246 /* Make iterator start at the top the of tree. */
4247 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4248 mpctx->mconfig);
4249 if (!mpctx->playtree_iter)
4250 continue;
4252 // find the first real item in the tree
4253 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4254 PLAY_TREE_ITER_ENTRY) {
4255 // no items!
4256 play_tree_iter_free(mpctx->playtree_iter);
4257 mpctx->playtree_iter = NULL;
4258 continue; // wait for next command
4260 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4264 #ifdef CONFIG_ASS
4265 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4266 #endif
4267 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4268 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4270 if (mpctx->filename) {
4271 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4272 filename_recode(mpctx->filename));
4273 if (use_filename_title && opts->vo_wintitle == NULL)
4274 opts->vo_wintitle = talloc_strdup(NULL,
4275 mp_basename(mpctx->filename));
4278 if (edl_output_filename) {
4279 if (edl_fd)
4280 fclose(edl_fd);
4281 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4282 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4283 "Can't open EDL file [%s] for writing.\n",
4284 filename_recode(edl_output_filename));
4288 //==================== Open VOB-Sub ============================
4290 current_module = "vobsub";
4291 if (opts->vobsub_name) {
4292 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4293 if (vo_vobsub == NULL)
4294 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4295 filename_recode(opts->vobsub_name));
4296 } else if (opts->sub_auto && mpctx->filename) {
4297 char **vob = find_vob_subtitles(opts, mpctx->filename);
4298 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4299 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4300 if (vo_vobsub)
4301 break;
4303 talloc_free(vob);
4305 if (vo_vobsub) {
4306 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4307 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4308 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4309 mpctx);
4311 // setup global sub numbering
4312 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4313 vobsub_get_indexes_count(vo_vobsub);
4316 //============ Open & Sync STREAM --- fork cache2 ====================
4318 mpctx->stream = NULL;
4319 mpctx->demuxer = NULL;
4320 mpctx->d_audio = NULL;
4321 mpctx->d_video = NULL;
4322 mpctx->d_sub = NULL;
4323 mpctx->sh_audio = NULL;
4324 mpctx->sh_video = NULL;
4326 current_module = "open_stream";
4327 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4328 if (!mpctx->stream) { // error...
4329 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4330 goto goto_next_file;
4332 mpctx->initialized_flags |= INITIALIZED_STREAM;
4334 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4335 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4336 "playlist support will not be used automatically.\n"
4337 "MPlayer's playlist code is unsafe and should only be used with "
4338 "trusted sources.\nPlayback will probably fail.\n\n");
4339 #if 0
4340 play_tree_t *entry;
4341 // Handle playlist
4342 current_module = "handle_playlist";
4343 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4344 filename_recode(mpctx->filename));
4345 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4346 mpctx->eof = playtree_add_playlist(mpctx, entry);
4347 goto goto_next_file;
4348 #endif
4350 mpctx->stream->start_pos += seek_to_byte;
4352 if (stream_dump_type == 5) {
4353 unsigned char buf[4096];
4354 int len;
4355 FILE *f;
4356 current_module = "dumpstream";
4357 stream_reset(mpctx->stream);
4358 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4359 f = fopen(opts->stream_dump_name, "wb");
4360 if (!f) {
4361 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4362 exit_player(mpctx, EXIT_ERROR);
4364 if (opts->chapterrange[0] > 1) {
4365 int chapter = opts->chapterrange[0] - 1;
4366 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4368 struct stream_dump_progress info;
4369 stream_dump_progress_start(&info);
4370 while (!mpctx->stream->eof && !async_quit_request) {
4371 len = stream_read(mpctx->stream, buf, 4096);
4372 if (len > 0) {
4373 if (fwrite(buf, len, 1, f) != 1) {
4374 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4375 exit_player(mpctx, EXIT_ERROR);
4378 stream_dump_progress(&info, len, mpctx->stream);
4379 if (opts->chapterrange[1] > 0) {
4380 int chapter = -1;
4381 if (stream_control(mpctx->stream,
4382 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4383 && chapter + 1 > opts->chapterrange[1])
4384 break;
4387 if (fclose(f)) {
4388 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4389 opts->stream_dump_name);
4390 exit_player(mpctx, EXIT_ERROR);
4392 stream_dump_progress_end(&info, opts->stream_dump_name);
4393 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4394 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4397 #ifdef CONFIG_DVDREAD
4398 if (mpctx->stream->type == STREAMTYPE_DVD) {
4399 current_module = "dvd lang->id";
4400 if (opts->audio_lang && opts->audio_id == -1)
4401 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4402 if (opts->sub_lang && opts->sub_id == -1)
4403 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4404 // setup global sub numbering
4405 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4406 current_module = NULL;
4408 #endif
4410 #ifdef CONFIG_DVDNAV
4411 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4412 current_module = "dvdnav lang->id";
4413 if (opts->audio_lang && opts->audio_id == -1)
4414 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4415 opts->audio_lang);
4416 dvdsub_lang_id = -3;
4417 if (opts->sub_lang && opts->sub_id == -1)
4418 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4419 mpctx->stream, opts->sub_lang);
4420 // setup global sub numbering
4421 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4422 mpctx->stream);
4423 current_module = NULL;
4425 #endif
4427 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4428 goto_enable_cache:
4429 if (opts->stream_cache_size > 0) {
4430 int res;
4431 current_module = "enable_cache";
4432 res = stream_enable_cache_percent(mpctx->stream,
4433 opts->stream_cache_size,
4434 opts->stream_cache_min_percent,
4435 opts->stream_cache_seek_min_percent);
4436 if (res == 0)
4437 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4438 goto goto_next_file;
4441 //============ Open DEMUXERS --- DETECT file type =======================
4442 current_module = "demux_open";
4444 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4445 opts->audio_id, opts->video_id, opts->sub_id,
4446 mpctx->filename);
4448 // HACK to get MOV Reference Files working
4450 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4451 unsigned char *playlist_entry;
4452 play_tree_t *list = NULL, *entry = NULL;
4454 current_module = "handle_demux_playlist";
4455 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4456 char *temp;
4457 const char *bname;
4459 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4460 filename_recode(playlist_entry));
4462 bname = mp_basename(playlist_entry);
4463 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4464 !strncmp(bname + 3, "gateQT", 6))
4465 continue;
4467 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4468 continue;
4470 entry = play_tree_new();
4472 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4473 playlist_entry)) { // add reference path of current file
4474 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4475 mpctx->filename)) + strlen(playlist_entry) + 1));
4476 if (temp) {
4477 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4478 strlen(mp_basename(mpctx->filename)));
4479 temp[strlen(mpctx->filename) - strlen(mp_basename(
4480 mpctx->filename))] = '\0';
4481 strcat(temp, playlist_entry);
4482 if (!strcmp(temp, mpctx->filename)) {
4483 free(temp);
4484 continue;
4486 play_tree_add_file(entry, temp);
4487 mp_msg(MSGT_CPLAYER, MSGL_V,
4488 "Resolving reference to %s.\n", temp);
4489 free(temp);
4491 } else
4492 play_tree_add_file(entry, playlist_entry);
4494 if (!list)
4495 list = entry;
4496 else
4497 play_tree_append_entry(list, entry);
4499 free_demuxer(mpctx->demuxer);
4500 mpctx->demuxer = NULL;
4502 if (list) {
4503 entry = play_tree_new();
4504 play_tree_set_child(entry, list);
4505 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4506 goto goto_next_file;
4510 if (!mpctx->demuxer) {
4511 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4512 goto goto_next_file;
4515 if (mpctx->demuxer->matroska_data.ordered_chapters)
4516 build_ordered_chapter_timeline(mpctx);
4518 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4519 build_edl_timeline(mpctx);
4521 if (mpctx->timeline) {
4522 mpctx->timeline_part = 0;
4523 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4525 int part_count = mpctx->num_timeline_parts;
4526 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4527 "sources. Total length %.3f seconds.\n", part_count,
4528 mpctx->num_sources, mpctx->timeline[part_count].start);
4529 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4530 for (int i = 0; i < mpctx->num_sources; i++)
4531 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4532 filename_recode(mpctx->sources[i].demuxer->filename));
4533 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4534 "source_start, source):\n");
4535 for (int i = 0; i < part_count; i++) {
4536 struct timeline_part *p = mpctx->timeline + i;
4537 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4538 p->source_start, p->source - mpctx->sources);
4540 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4541 mpctx->timeline[part_count].start);
4544 if (!mpctx->sources) {
4545 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4546 *mpctx->sources = (struct content_source){
4547 .stream = mpctx->stream,
4548 .demuxer = mpctx->demuxer
4550 mpctx->num_sources = 1;
4553 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4555 #ifdef CONFIG_ASS
4556 if (opts->ass_enabled) {
4557 for (int j = 0; j < mpctx->num_sources; j++) {
4558 struct demuxer *d = mpctx->sources[j].demuxer;
4559 for (int i = 0; i < d->num_attachments; i++) {
4560 struct demux_attachment *att = d->attachments + i;
4561 if (opts->use_embedded_fonts && attachment_is_font(att))
4562 ass_add_font(mpctx->ass_library, att->name, att->data,
4563 att->data_size);
4567 /* libass seems to misbehave if fonts are changed while a renderer
4568 * exists, so we (re)create the renderer after fonts are set.
4570 assert(!mpctx->osd->ass_renderer);
4571 mpctx->osd->ass_renderer = ass_renderer_init(mpctx->osd->ass_library);
4572 if (!mpctx->osd->ass_renderer) {
4573 mp_msg(MSGT_OSD, MSGL_FATAL, "Failed to create libass renderer\n");
4574 exit_player(mpctx, EXIT_ERROR);
4576 mp_ass_configure_fonts(mpctx->osd->ass_renderer);
4577 #endif
4579 current_module = "demux_open2";
4581 mpctx->d_audio = mpctx->demuxer->audio;
4582 mpctx->d_video = mpctx->demuxer->video;
4583 mpctx->d_sub = mpctx->demuxer->sub;
4585 if (ts_prog) {
4586 int tmp = ts_prog;
4587 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4589 // select audio stream
4590 for (int i = 0; i < mpctx->num_sources; i++)
4591 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4592 opts->audio_lang);
4594 // DUMP STREAMS:
4595 if ((stream_dump_type) && (stream_dump_type < 4)) {
4596 FILE *f;
4597 demux_stream_t *ds = NULL;
4598 current_module = "dump";
4599 // select stream to dump
4600 switch (stream_dump_type) {
4601 case 1: ds = mpctx->d_audio;
4602 break;
4603 case 2: ds = mpctx->d_video;
4604 break;
4605 case 3: ds = mpctx->d_sub;
4606 break;
4608 if (!ds) {
4609 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4610 "dump: FATAL: Selected stream missing!\n");
4611 exit_player(mpctx, EXIT_ERROR);
4613 // disable other streams:
4614 if (mpctx->d_audio && mpctx->d_audio != ds) {
4615 ds_free_packs(mpctx->d_audio);
4616 mpctx->d_audio->id = -2;
4618 if (mpctx->d_video && mpctx->d_video != ds) {
4619 ds_free_packs(mpctx->d_video);
4620 mpctx->d_video->id = -2;
4622 if (mpctx->d_sub && mpctx->d_sub != ds) {
4623 ds_free_packs(mpctx->d_sub);
4624 mpctx->d_sub->id = -2;
4626 // let's dump it!
4627 f = fopen(opts->stream_dump_name, "wb");
4628 if (!f) {
4629 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4630 exit_player(mpctx, EXIT_ERROR);
4632 struct stream_dump_progress info;
4633 stream_dump_progress_start(&info);
4634 while (!ds->eof) {
4635 unsigned char *start;
4636 int in_size = ds_get_packet(ds, &start);
4637 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4638 && stream_dump_type == 2)
4639 fwrite(&in_size, 1, 4, f);
4640 if (in_size > 0) {
4641 fwrite(start, in_size, 1, f);
4642 stream_dump_progress(&info, in_size, mpctx->stream);
4644 if (opts->chapterrange[1] > 0) {
4645 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4646 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4647 break;
4650 fclose(f);
4651 stream_dump_progress_end(&info, opts->stream_dump_name);
4652 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4653 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4656 mpctx->sh_audio = mpctx->d_audio->sh;
4657 mpctx->sh_video = mpctx->d_video->sh;
4659 if (mpctx->sh_video) {
4660 current_module = "video_read_properties";
4661 if (!video_read_properties(mpctx->sh_video)) {
4662 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4663 mpctx->sh_video = mpctx->d_video->sh = NULL;
4664 } else {
4665 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4666 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4667 mpctx->demuxer->file_format, mpctx->sh_video->format,
4668 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4669 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4670 if (force_fps) {
4671 mpctx->sh_video->fps = force_fps;
4672 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4674 vo_fps = mpctx->sh_video->fps;
4676 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4677 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4678 "header or invalid, use the -fps option.\n");
4684 if (!mpctx->sh_video && !mpctx->sh_audio) {
4685 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4686 #ifdef CONFIG_DVBIN
4687 if (mpctx->stream->type == STREAMTYPE_DVB) {
4688 int dir;
4689 int v = mpctx->last_dvb_step;
4690 if (v > 0)
4691 dir = DVB_CHANNEL_HIGHER;
4692 else
4693 dir = DVB_CHANNEL_LOWER;
4695 if (dvb_step_channel(mpctx->stream, dir)) {
4696 mpctx->stop_play = PT_NEXT_ENTRY;
4697 mpctx->dvbin_reopen = 1;
4700 #endif
4701 goto goto_next_file; // exit_player(_("Fatal error"));
4704 /* display clip info */
4705 demux_info_print(mpctx->demuxer);
4707 //================= Read SUBTITLES (DVD & TEXT) =========================
4708 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4709 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4710 init_vo_spudec(mpctx);
4712 // after reading video params we should load subtitles because
4713 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4714 // check .sub
4715 current_module = "read_subtitles_file";
4716 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4717 if (opts->sub_name) {
4718 for (i = 0; opts->sub_name[i] != NULL; ++i)
4719 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4721 if (opts->sub_auto) { // auto load sub file ...
4722 char **tmp = find_text_subtitles(opts, mpctx->filename);
4723 int nsub = MP_TALLOC_ELEMS(tmp);
4724 for (int i = 0; i < nsub; i++)
4725 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4726 talloc_free(tmp);
4728 if (mpctx->set_of_sub_size > 0)
4729 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4731 if (select_subtitle(mpctx)) {
4732 if (mpctx->subdata)
4733 switch (stream_dump_type) {
4734 case 3: list_sub_file(mpctx->subdata);
4735 break;
4736 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4737 break;
4738 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4739 break;
4740 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4741 break;
4742 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4743 break;
4744 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4745 break;
4749 print_file_properties(mpctx, mpctx->filename);
4751 reinit_video_chain(mpctx);
4752 if (!mpctx->sh_video && !mpctx->sh_audio)
4753 goto goto_next_file;
4755 //================== MAIN: ==========================
4756 current_module = "main";
4758 if (opts->playing_msg) {
4759 char *msg = property_expand_string(mpctx, opts->playing_msg);
4760 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4761 free(msg);
4765 // Disable the term OSD in verbose mode
4766 if (verbose)
4767 opts->term_osd = 0;
4769 // Make sure old OSD does not stay around
4770 clear_osd_msgs();
4772 //================ SETUP AUDIO ==========================
4774 if (mpctx->sh_audio) {
4775 reinit_audio_chain(mpctx);
4776 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4777 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4778 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4781 current_module = "av_init";
4783 if (mpctx->sh_video) {
4784 mpctx->sh_video->timer = 0;
4785 if (!ignore_start)
4786 audio_delay += mpctx->sh_video->stream_delay;
4788 if (mpctx->sh_audio) {
4789 if (start_volume >= 0)
4790 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4791 if (!ignore_start)
4792 audio_delay -= mpctx->sh_audio->stream_delay;
4795 if (!mpctx->sh_audio) {
4796 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4797 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4798 mpctx->d_audio->packs);
4799 ds_free_packs(mpctx->d_audio); // free buffered chunks
4801 if (!mpctx->sh_video) {
4802 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4803 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4804 mpctx->d_video->packs);
4805 ds_free_packs(mpctx->d_video);
4806 mpctx->d_video->id = -2;
4809 if (!mpctx->sh_video && !mpctx->sh_audio)
4810 goto goto_next_file;
4812 if (force_fps && mpctx->sh_video) {
4813 vo_fps = mpctx->sh_video->fps = force_fps;
4814 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4815 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4816 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4817 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4820 mp_input_set_section(mpctx->input, NULL);
4821 //TODO: add desired (stream-based) sections here
4822 if (mpctx->stream->type == STREAMTYPE_TV)
4823 mp_input_set_section(mpctx->input, "tv");
4824 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4825 mp_input_set_section(mpctx->input, "dvdnav");
4827 //==================== START PLAYING =======================
4829 if (opts->loop_times > 1)
4830 opts->loop_times--;
4831 else if (opts->loop_times == 1)
4832 opts->loop_times = -1;
4834 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4836 total_time_usage_start = GetTimer();
4837 audio_time_usage = 0;
4838 video_time_usage = 0;
4839 vout_time_usage = 0;
4840 total_frame_cnt = 0;
4841 drop_frame_cnt = 0; // fix for multifile fps benchmark
4842 play_n_frames = play_n_frames_mf;
4844 if (play_n_frames == 0) {
4845 mpctx->stop_play = PT_NEXT_ENTRY;
4846 goto goto_next_file;
4849 mpctx->time_frame = 0;
4850 mpctx->drop_message_shown = 0;
4851 mpctx->restart_playback = true;
4852 mpctx->video_pts = 0;
4853 mpctx->last_seek_pts = 0;
4854 mpctx->hrseek_active = false;
4855 mpctx->hrseek_framedrop = false;
4856 mpctx->step_frames = 0;
4857 mpctx->total_avsync_change = 0;
4858 mpctx->last_chapter_seek = -2;
4860 // If there's a timeline force an absolute seek to initialize state
4861 if (opts->seek_to_sec || mpctx->timeline) {
4862 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4863 seek(mpctx, mpctx->seek, false);
4864 end_at.pos += opts->seek_to_sec;
4866 if (opts->chapterrange[0] > 0) {
4867 double pts;
4868 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4869 && pts > -1.0) {
4870 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4871 seek(mpctx, mpctx->seek, false);
4875 if (end_at.type == END_AT_SIZE) {
4876 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4877 "Option -endpos in MPlayer does not yet support size units.\n");
4878 end_at.type = END_AT_NONE;
4881 #ifdef CONFIG_DVDNAV
4882 mp_dvdnav_context_free(mpctx);
4883 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4884 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4885 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4887 #endif
4889 mpctx->seek = (struct seek_params){ 0 };
4890 get_relative_time(mpctx); // reset current delta
4891 // Make sure VO knows current pause state
4892 if (mpctx->sh_video)
4893 vo_control(mpctx->video_out,
4894 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4896 while (!mpctx->stop_play)
4897 run_playloop(mpctx);
4899 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4901 #ifdef CONFIG_DVBIN
4902 if (mpctx->dvbin_reopen) {
4903 mpctx->stop_play = 0;
4904 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4905 cache_uninit(mpctx->stream);
4906 mpctx->dvbin_reopen = 0;
4907 goto goto_enable_cache;
4909 #endif
4911 goto_next_file: // don't jump here after ao/vo/getch initialization!
4913 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4915 if (opts->benchmark) {
4916 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4917 double total_time_usage;
4918 total_time_usage_start = GetTimer() - total_time_usage_start;
4919 total_time_usage = (float)total_time_usage_start * 0.000001;
4920 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4921 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4922 video_time_usage, vout_time_usage, audio_time_usage,
4923 total_time_usage - tot, total_time_usage);
4924 if (total_time_usage > 0.0)
4925 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4926 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4927 100.0 * video_time_usage / total_time_usage,
4928 100.0 * vout_time_usage / total_time_usage,
4929 100.0 * audio_time_usage / total_time_usage,
4930 100.0 * (total_time_usage - tot) / total_time_usage,
4931 100.0);
4932 if (total_frame_cnt && frame_dropping)
4933 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4934 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4935 total_frame_cnt - drop_frame_cnt,
4936 (total_time_usage > 0.5) ? ((total_frame_cnt -
4937 drop_frame_cnt) / total_time_usage) : 0,
4938 drop_frame_cnt,
4939 100 * drop_frame_cnt / total_frame_cnt,
4940 total_frame_cnt,
4941 (total_time_usage > 0.5) ?
4942 (total_frame_cnt / total_time_usage) : 0);
4945 // time to uninit all, except global stuff:
4946 int uninitialize_parts = INITIALIZED_ALL;
4947 if (opts->fixed_vo)
4948 uninitialize_parts -= INITIALIZED_VO;
4949 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4950 uninitialize_parts -= INITIALIZED_AO;
4951 uninit_player(mpctx, uninitialize_parts);
4953 if (mpctx->set_of_sub_size > 0) {
4954 current_module = "sub_free";
4955 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
4956 sub_free(mpctx->set_of_subtitles[i]);
4957 talloc_free(mpctx->set_of_ass_tracks[i]);
4959 mpctx->set_of_sub_size = 0;
4961 mpctx->vo_sub_last = vo_sub = NULL;
4962 mpctx->subdata = NULL;
4963 #ifdef CONFIG_ASS
4964 if (mpctx->osd->ass_renderer)
4965 ass_renderer_done(mpctx->osd->ass_renderer);
4966 mpctx->osd->ass_renderer = NULL;
4967 ass_clear_fonts(mpctx->ass_library);
4968 #endif
4970 if (!mpctx->stop_play) // In case some goto jumped here...
4971 mpctx->stop_play = PT_NEXT_ENTRY;
4973 int playtree_direction = 1;
4975 if (mpctx->stop_play == PT_NEXT_ENTRY
4976 || mpctx->stop_play == PT_PREV_ENTRY) {
4977 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
4978 != PLAY_TREE_ITER_ENTRY) {
4979 play_tree_iter_free(mpctx->playtree_iter);
4980 mpctx->playtree_iter = NULL;
4982 mpctx->play_tree_step = 1;
4983 } else if (mpctx->stop_play == PT_UP_NEXT ||
4984 mpctx->stop_play == PT_UP_PREV) {
4985 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4986 if (mpctx->playtree_iter) {
4987 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
4988 PLAY_TREE_ITER_ENTRY) {
4989 play_tree_iter_free(mpctx->playtree_iter);
4990 mpctx->playtree_iter = NULL;
4993 } else if (mpctx->stop_play == PT_STOP) {
4994 play_tree_iter_free(mpctx->playtree_iter);
4995 mpctx->playtree_iter = NULL;
4996 } else // NEXT PREV SRC
4997 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4999 while (mpctx->playtree_iter != NULL) {
5000 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5001 playtree_direction);
5002 if (mpctx->filename == NULL) {
5003 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5004 0) != PLAY_TREE_ITER_ENTRY) {
5005 play_tree_iter_free(mpctx->playtree_iter);
5006 mpctx->playtree_iter = NULL;
5009 } else
5010 break;
5013 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5014 if (!mpctx->playtree_iter)
5015 mpctx->filename = NULL;
5016 mpctx->stop_play = 0;
5017 goto play_next_file;
5020 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5022 return 1;
5024 #endif /* DISABLE_MAIN */