mixer: fix lowering hw volume while muted
[mplayer.git] / mplayer.c
blob7e0ca020c908500fb1ae6190b93a7e3ef4ae529c
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 mixer_uninit(&mpctx->mixer);
675 if (mpctx->ao)
676 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
677 mpctx->ao = NULL;
680 current_module = NULL;
683 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
685 uninit_player(mpctx, INITIALIZED_ALL);
686 #if defined(__MINGW32__) || defined(__CYGWIN__)
687 timeEndPeriod(1);
688 #endif
690 current_module = "uninit_input";
691 mp_input_uninit(mpctx->input);
693 osd_free(mpctx->osd);
695 #ifdef CONFIG_ASS
696 ass_library_done(mpctx->ass_library);
697 mpctx->ass_library = NULL;
698 #endif
700 current_module = "exit_player";
702 if (mpctx->playtree_iter)
703 play_tree_iter_free(mpctx->playtree_iter);
704 mpctx->playtree_iter = NULL;
705 if (mpctx->playtree)
706 play_tree_free(mpctx->playtree, 1);
707 mpctx->playtree = NULL;
709 talloc_free(mpctx->key_fifo);
711 switch (how) {
712 case EXIT_QUIT:
713 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
714 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
715 break;
716 case EXIT_EOF:
717 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
718 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
719 break;
720 case EXIT_ERROR:
721 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
722 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
723 break;
724 default:
725 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
727 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
728 "max framesize was %d bytes\n", max_framesize);
730 // must be last since e.g. mp_msg uses option values
731 // that will be freed by this.
732 if (mpctx->mconfig)
733 m_config_free(mpctx->mconfig);
734 mpctx->mconfig = NULL;
736 talloc_free(mpctx);
738 exit(rc);
741 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
743 exit_player_with_rc(mpctx, how, 1);
746 #ifndef __MINGW32__
747 static void child_sighandler(int x)
749 pid_t pid;
750 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
752 #endif
754 #ifdef CONFIG_CRASH_DEBUG
755 static char *prog_path;
756 static int crash_debug = 0;
757 #endif
759 static void exit_sighandler(int x)
761 static int sig_count = 0;
762 #ifdef CONFIG_CRASH_DEBUG
763 if (!crash_debug || x != SIGTRAP)
764 #endif
765 ++sig_count;
766 if (sig_count == 5) {
767 /* We're crashing bad and can't uninit cleanly :(
768 * by popular request, we make one last (dirty)
769 * effort to restore the user's
770 * terminal. */
771 getch2_disable();
772 exit(1);
774 if (sig_count == 6)
775 exit(1);
776 if (sig_count > 6) {
777 // can't stop :(
778 #ifndef __MINGW32__
779 kill(getpid(), SIGKILL);
780 #endif
782 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
783 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
784 "\nMPlayer interrupted by signal %d in module: %s\n", x,
785 current_module ? current_module : "unknown");
786 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
787 if (sig_count <= 1)
788 switch (x) {
789 case SIGINT:
790 case SIGPIPE:
791 case SIGQUIT:
792 case SIGTERM:
793 case SIGKILL:
794 async_quit_request = 1;
795 return; // killed from keyboard (^C) or killed [-9]
796 case SIGILL:
797 #if CONFIG_RUNTIME_CPUDETECT
798 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
799 #else
800 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
801 #endif
802 case SIGFPE:
803 case SIGSEGV:
804 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
805 default:
806 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
807 #ifdef CONFIG_CRASH_DEBUG
808 if (crash_debug) {
809 int gdb_pid;
810 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
811 gdb_pid = fork();
812 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
813 if (gdb_pid == 0) { // We are the child
814 char spid[20];
815 snprintf(spid, sizeof(spid), "%i", getppid());
816 getch2_disable(); // allow terminal to work properly with gdb
817 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
818 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
819 } else if (gdb_pid < 0)
820 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
821 else
822 waitpid(gdb_pid, NULL, 0);
823 if (x == SIGTRAP)
824 return;
826 #endif
828 getch2_disable();
829 exit(1);
832 #include "cfg-mplayer.h"
834 static int cfg_include(struct m_config *conf, char *filename)
836 return m_config_parse_config_file(conf, filename);
839 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
841 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
843 struct MPOpts *opts = &mpctx->opts;
844 char *conffile;
845 int conffile_fd;
846 if (!(opts->noconfig & 2) &&
847 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
848 exit_player(mpctx, EXIT_NONE);
849 if ((conffile = get_path("")) == NULL)
850 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
851 else {
852 mkdir(conffile, 0777);
853 free(conffile);
854 if ((conffile = get_path("config")) == NULL)
855 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
856 else {
857 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
858 0666)) != -1) {
859 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
860 "Creating config file: %s\n", conffile);
861 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
862 close(conffile_fd);
864 if (!(opts->noconfig & 1) &&
865 m_config_parse_config_file(conf, conffile) < 0)
866 exit_player(mpctx, EXIT_NONE);
867 free(conffile);
872 #define PROFILE_CFG_PROTOCOL "protocol."
874 static void load_per_protocol_config(m_config_t *conf, const char * const file)
876 char *str;
877 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
878 m_profile_t *p;
880 /* does filename actually uses a protocol ? */
881 str = strstr(file, "://");
882 if (!str)
883 return;
885 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
886 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
887 p = m_config_get_profile(conf, protocol);
888 if (p) {
889 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
890 "Loading protocol-related profile '%s'\n", protocol);
891 m_config_set_profile(conf, p);
895 #define PROFILE_CFG_EXTENSION "extension."
897 static void load_per_extension_config(m_config_t *conf, const char * const file)
899 char *str;
900 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
901 m_profile_t *p;
903 /* does filename actually have an extension ? */
904 str = strrchr(file, '.');
905 if (!str)
906 return;
908 sprintf(extension, PROFILE_CFG_EXTENSION);
909 strncat(extension, ++str, 7);
910 p = m_config_get_profile(conf, extension);
911 if (p) {
912 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
913 "Loading extension-related profile '%s'\n", extension);
914 m_config_set_profile(conf, p);
918 #define PROFILE_CFG_VO "vo."
919 #define PROFILE_CFG_AO "ao."
921 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
923 char profile[strlen(cfg) + strlen(out) + 1];
924 m_profile_t *p;
926 sprintf(profile, "%s%s", cfg, out);
927 p = m_config_get_profile(conf, profile);
928 if (p) {
929 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
930 "Loading extension-related profile '%s'\n", profile);
931 m_config_set_profile(conf, p);
936 * Tries to load a config file
937 * @return 0 if file was not found, 1 otherwise
939 static int try_load_config(m_config_t *conf, const char *file)
941 if (!mp_path_exists(file))
942 return 0;
943 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
944 m_config_parse_config_file(conf, file);
945 return 1;
948 static void load_per_file_config(m_config_t *conf, const char * const file)
950 char *confpath;
951 char cfg[MP_PATH_MAX];
952 const char *name;
954 if (strlen(file) > MP_PATH_MAX - 14) {
955 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
956 "can not load file or directory specific config files\n");
957 return;
959 sprintf(cfg, "%s.conf", file);
961 name = mp_basename(cfg);
962 if (use_filedir_conf) {
963 char dircfg[MP_PATH_MAX];
964 strcpy(dircfg, cfg);
965 strcpy(dircfg + (name - cfg), "mplayer.conf");
966 try_load_config(conf, dircfg);
968 if (try_load_config(conf, cfg))
969 return;
972 if ((confpath = get_path(name)) != NULL) {
973 try_load_config(conf, confpath);
975 free(confpath);
979 /* When libmpdemux performs a blocking operation (network connection or
980 * cache filling) if the operation fails we use this function to check
981 * if it was interrupted by the user.
982 * The function returns a new value for eof. */
983 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
985 mp_cmd_t *cmd;
986 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
987 switch (cmd->id) {
988 case MP_CMD_QUIT:
989 exit_player_with_rc(mpctx, EXIT_QUIT,
990 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
991 case MP_CMD_PLAY_TREE_STEP: {
992 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
993 mpctx->play_tree_step =
994 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
995 } break;
996 case MP_CMD_PLAY_TREE_UP_STEP: {
997 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
998 } break;
999 case MP_CMD_PLAY_ALT_SRC_STEP: {
1000 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1001 } break;
1003 mp_cmd_free(cmd);
1005 return stop_play;
1008 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1010 play_tree_add_bpf(entry, bstr(mpctx->filename));
1013 if (!entry) {
1014 entry = mpctx->playtree_iter->tree;
1015 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1016 != PLAY_TREE_ITER_ENTRY)
1017 return PT_NEXT_ENTRY;
1018 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1019 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1020 != PLAY_TREE_ITER_ENTRY)
1021 return PT_NEXT_ENTRY;
1023 play_tree_remove(entry, 1, 1);
1024 return PT_NEXT_SRC;
1026 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1027 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1028 entry = mpctx->playtree_iter->tree;
1029 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1030 != PLAY_TREE_ITER_ENTRY)
1031 return PT_NEXT_ENTRY;
1032 play_tree_remove(entry, 1, 1);
1034 return PT_NEXT_SRC;
1037 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1038 int noerr)
1040 struct MPOpts *opts = &mpctx->opts;
1041 sub_data *subd = NULL;
1042 struct sh_sub *sh = NULL;
1044 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1045 return;
1047 if (opts->ass_enabled) {
1048 #ifdef CONFIG_ASS
1049 struct ass_track *asst;
1050 #ifdef CONFIG_ICONV
1051 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1052 #else
1053 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1054 #endif
1055 bool is_native_ass = asst;
1056 if (!asst) {
1057 subd = sub_read_file(filename, fps, &mpctx->opts);
1058 if (subd) {
1059 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1060 sub_free(subd);
1061 subd = NULL;
1064 if (asst)
1065 sh = sd_ass_create_from_track(asst, is_native_ass, opts);
1066 #endif
1067 } else
1068 subd = sub_read_file(filename, fps, &mpctx->opts);
1071 if (!sh && !subd) {
1072 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1073 "Cannot load subtitles: %s\n", filename_recode(filename));
1074 return;
1077 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = sh;
1078 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1079 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1080 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1081 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1082 filename_recode(filename));
1083 ++mpctx->set_of_sub_size;
1084 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1085 mpctx->set_of_sub_size, filename_recode(filename));
1088 void init_vo_spudec(struct MPContext *mpctx)
1090 unsigned width, height;
1091 spudec_free(vo_spudec);
1092 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1093 vo_spudec = NULL;
1095 // we currently can't work without video stream
1096 if (!mpctx->sh_video)
1097 return;
1099 if (spudec_ifo) {
1100 unsigned int palette[16];
1101 current_module = "spudec_init_vobsub";
1102 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1103 1, -1, NULL) >= 0)
1104 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1107 width = mpctx->sh_video->disp_w;
1108 height = mpctx->sh_video->disp_h;
1110 #ifdef CONFIG_DVDREAD
1111 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1112 current_module = "spudec_init_dvdread";
1113 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1114 cur_pgc->palette, width, height, NULL, 0);
1116 #endif
1118 #ifdef CONFIG_DVDNAV
1119 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1120 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1121 current_module = "spudec_init_dvdnav";
1122 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1124 #endif
1126 if (vo_spudec == NULL) {
1127 sh_sub_t *sh = mpctx->d_sub->sh;
1128 current_module = "spudec_init_normal";
1129 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1130 sh->extradata_len);
1131 spudec_set_font_factor(vo_spudec, font_factor);
1134 if (vo_spudec != NULL) {
1135 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1136 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1137 mpctx);
1142 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1143 * make it all work is to use the builtin SDL-bootstrap code, which
1144 * will be done automatically by replacing our main() if we include SDL.h.
1146 #if defined(__APPLE__) && defined(CONFIG_SDL)
1147 #ifdef CONFIG_SDL_SDL_H
1148 #include <SDL/SDL.h>
1149 #else
1150 #include <SDL.h>
1151 #endif
1152 #endif
1155 * \brief append a formatted string
1156 * \param buf buffer to print into
1157 * \param pos position of terminating 0 in buf
1158 * \param len maximum number of characters in buf, not including terminating 0
1159 * \param format printf format string
1161 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1163 va_list va;
1164 va_start(va, format);
1165 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1166 va_end(va);
1167 if (*pos >= len) {
1168 buf[len] = 0;
1169 *pos = len;
1174 * \brief append time in the hh:mm:ss.f format
1175 * \param buf buffer to print into
1176 * \param pos position of terminating 0 in buf
1177 * \param len maximum number of characters in buf, not including terminating 0
1178 * \param time time value to convert/append
1180 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1182 int64_t tenths = 10 * time;
1183 int f1 = tenths % 10;
1184 int ss = (tenths / 10) % 60;
1185 int mm = (tenths / 600) % 60;
1186 int hh = tenths / 36000;
1187 if (time < 0) {
1188 saddf(buf, pos, len, "unknown");
1189 return;
1191 if (hh > 0)
1192 saddf(buf, pos, len, "%2d:", hh);
1193 if (hh > 0 || mm > 0)
1194 saddf(buf, pos, len, "%02d:", mm);
1195 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1198 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1200 struct MPOpts *opts = &mpctx->opts;
1201 sh_video_t * const sh_video = mpctx->sh_video;
1203 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1204 a_pos = playing_audio_pts(mpctx);
1205 if (mpctx->sh_audio && sh_video && at_frame) {
1206 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1207 if (mpctx->time_frame > 0)
1208 mpctx->last_av_difference +=
1209 mpctx->time_frame * opts->playback_speed;
1210 if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
1211 mpctx->last_av_difference = MP_NOPTS_VALUE;
1212 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1213 && !mpctx->drop_message_shown) {
1214 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1215 mpctx->drop_message_shown = true;
1218 if (opts->quiet)
1219 return;
1221 int width;
1222 char *line;
1223 unsigned pos = 0;
1224 get_screen_size();
1225 if (screen_width > 0)
1226 width = screen_width;
1227 else
1228 width = 80;
1229 #if defined(__MINGW32__) || defined(__CYGWIN__)
1230 /* Windows command line is broken (MinGW's rxvt works, but we
1231 * should not depend on that). */
1232 width--;
1233 #endif
1234 line = malloc(width + 1); // one additional char for the terminating null
1236 // Audio time
1237 if (mpctx->sh_audio) {
1238 if (a_pos != MP_NOPTS_VALUE)
1239 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1240 else
1241 saddf(line, &pos, width, "A: ??? ");
1242 if (!sh_video && a_pos != MP_NOPTS_VALUE) {
1243 float len = get_time_length(mpctx);
1244 saddf(line, &pos, width, "(");
1245 sadd_hhmmssf(line, &pos, width, a_pos);
1246 saddf(line, &pos, width, ") of %.1f (", len);
1247 sadd_hhmmssf(line, &pos, width, len);
1248 saddf(line, &pos, width, ") ");
1252 // Video time
1253 if (sh_video) {
1254 if (mpctx->video_pts != MP_NOPTS_VALUE)
1255 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1256 else
1257 saddf(line, &pos, width, "V: ??? ", mpctx->video_pts);
1260 // A-V sync
1261 if (mpctx->sh_audio && sh_video) {
1262 if (mpctx->last_av_difference != MP_NOPTS_VALUE)
1263 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1264 mpctx->last_av_difference, mpctx->total_avsync_change);
1265 else
1266 saddf(line, &pos, width, "A-V: ??? ct:%7.3f ",
1267 mpctx->total_avsync_change);
1270 // Video stats
1271 if (sh_video)
1272 saddf(line, &pos, width, "%3d/%3d ",
1273 (int)sh_video->num_frames,
1274 (int)sh_video->num_frames_decoded);
1276 // CPU usage
1277 if (sh_video) {
1278 if (sh_video->timer > 0.5)
1279 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1280 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1281 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1282 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1283 else
1284 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1285 } else if (mpctx->sh_audio) {
1286 if (mpctx->delay > 0.5)
1287 saddf(line, &pos, width, "%4.1f%% ",
1288 100.0 * audio_time_usage / (double)mpctx->delay);
1289 else
1290 saddf(line, &pos, width, "??,?%% ");
1293 // VO stats
1294 if (sh_video)
1295 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1297 #ifdef CONFIG_STREAM_CACHE
1298 // cache stats
1299 if (opts->stream_cache_size > 0)
1300 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1301 #endif
1303 // other
1304 if (opts->playback_speed != 1)
1305 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1307 // end
1308 if (erase_to_end_of_line) {
1309 line[pos] = 0;
1310 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1311 "%s%s\r", line, erase_to_end_of_line);
1312 } else {
1313 memset(&line[pos], ' ', width - pos);
1314 line[width] = 0;
1315 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1317 free(line);
1319 mpctx->status_printed = true;
1322 struct stream_dump_progress {
1323 uint64_t count;
1324 unsigned start_time;
1325 unsigned last_print_time;
1328 static void stream_dump_progress_start(struct stream_dump_progress *p)
1330 p->start_time = p->last_print_time = GetTimerMS();
1331 p->count = 0;
1334 static void stream_dump_progress(struct stream_dump_progress *p,
1335 uint64_t len, stream_t *stream)
1337 p->count += len;
1338 unsigned t = GetTimerMS();
1339 if (t - p->last_print_time < 1000)
1340 return;
1342 uint64_t start = stream->start_pos;
1343 uint64_t end = stream->end_pos;
1344 uint64_t pos = stream->pos;
1346 p->last_print_time = t;
1347 /* TODO: pretty print sizes; ETA */
1348 if (end > start && pos >= start && pos <= end) {
1349 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1350 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1351 p->count, 100.0 * (pos - start) / (end - start));
1352 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1353 } else {
1354 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1355 "dump: %"PRIu64 " bytes written", p->count);
1356 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1360 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1362 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1363 p->count, name);
1367 * \brief build a chain of audio filters that converts the input format
1368 * to the ao's format, taking into account the current playback_speed.
1369 * sh_audio describes the requested input format of the chain.
1370 * ao describes the requested output format of the chain.
1372 static int build_afilter_chain(struct MPContext *mpctx)
1374 struct sh_audio *sh_audio = mpctx->sh_audio;
1375 struct ao *ao = mpctx->ao;
1376 struct MPOpts *opts = &mpctx->opts;
1377 int new_srate;
1378 int result;
1379 if (!sh_audio) {
1380 mpctx->mixer.afilter = NULL;
1381 return 0;
1383 if (af_control_any_rev(sh_audio->afilter,
1384 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1385 &opts->playback_speed))
1386 new_srate = sh_audio->samplerate;
1387 else {
1388 new_srate = sh_audio->samplerate * opts->playback_speed;
1389 if (new_srate != ao->samplerate) {
1390 // limits are taken from libaf/af_resample.c
1391 if (new_srate < 8000)
1392 new_srate = 8000;
1393 if (new_srate > 192000)
1394 new_srate = 192000;
1395 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1398 result = init_audio_filters(sh_audio, new_srate,
1399 &ao->samplerate, &ao->channels, &ao->format);
1400 mpctx->mixer.afilter = sh_audio->afilter;
1401 return result;
1405 typedef struct mp_osd_msg mp_osd_msg_t;
1406 struct mp_osd_msg {
1407 /// Previous message on the stack.
1408 mp_osd_msg_t *prev;
1409 /// Message text.
1410 char *msg;
1411 int id, level, started;
1412 /// Display duration in ms.
1413 unsigned time;
1414 // Show full OSD for duration of message instead of static text ('P' key)
1415 bool show_position;
1418 /// OSD message stack.
1419 static mp_osd_msg_t *osd_msg_stack = NULL;
1422 * \brief Add a message on the OSD message stack
1424 * If a message with the same id is already present in the stack
1425 * it is pulled on top of the stack, otherwise a new message is created.
1428 static void set_osd_msg_va(int id, int level, int time, bool show_position,
1429 const char *fmt, va_list ap)
1431 mp_osd_msg_t *msg, *last = NULL;
1433 // look if the id is already in the stack
1434 for (msg = osd_msg_stack; msg && msg->id != id;
1435 last = msg, msg = msg->prev) ;
1436 // not found: alloc it
1437 if (!msg) {
1438 msg = talloc_zero(NULL, mp_osd_msg_t);
1439 msg->prev = osd_msg_stack;
1440 osd_msg_stack = msg;
1441 } else if (last) { // found, but it's not on top of the stack
1442 last->prev = msg->prev;
1443 msg->prev = osd_msg_stack;
1444 osd_msg_stack = msg;
1446 talloc_free(msg->msg);
1447 // write the msg
1448 msg->msg = talloc_vasprintf(msg, fmt, ap);
1449 // set id and time
1450 msg->id = id;
1451 msg->level = level;
1452 msg->time = time;
1453 msg->show_position = show_position;
1456 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1458 va_list ap;
1459 va_start(ap, fmt);
1460 set_osd_msg_va(id, level, time, false, fmt, ap);
1461 va_end(ap);
1464 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1466 va_list ap;
1467 va_start(ap, fmt);
1468 set_osd_msg_va(id, level, time, false, mp_gtext(fmt), ap);
1469 va_end(ap);
1472 void set_osd_progressmsg(int id, int level, int time, ...)
1474 va_list ap;
1475 va_start(ap, time);
1476 set_osd_msg_va(id, level, time, true, "", ap);
1477 va_end(ap);
1481 * \brief Remove a message from the OSD stack
1483 * This function can be used to get rid of a message right away.
1487 void rm_osd_msg(int id)
1489 mp_osd_msg_t *msg, *last = NULL;
1491 // Search for the msg
1492 for (msg = osd_msg_stack; msg && msg->id != id;
1493 last = msg, msg = msg->prev) ;
1494 if (!msg)
1495 return;
1497 // Detach it from the stack and free it
1498 if (last)
1499 last->prev = msg->prev;
1500 else
1501 osd_msg_stack = msg->prev;
1502 talloc_free(msg);
1506 * \brief Remove all messages from the OSD stack
1510 static void clear_osd_msgs(void)
1512 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1513 while (msg) {
1514 prev = msg->prev;
1515 talloc_free(msg);
1516 msg = prev;
1518 osd_msg_stack = NULL;
1522 * \brief Get the current message from the OSD stack.
1524 * This function decrements the message timer and destroys the old ones.
1525 * The message that should be displayed is returned (if any).
1529 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1531 struct MPOpts *opts = &mpctx->opts;
1532 mp_osd_msg_t *msg, *prev, *last = NULL;
1533 static unsigned last_update = 0;
1534 unsigned now = GetTimerMS();
1535 unsigned diff;
1536 char hidden_dec_done = 0;
1538 if (mpctx->osd_visible) {
1539 // 36000000 means max timed visibility is 1 hour into the future, if
1540 // the difference is greater assume it's wrapped around from below 0
1541 if (mpctx->osd_visible - now > 36000000) {
1542 mpctx->osd_visible = 0;
1543 vo_osd_progbar_type = -1; // disable
1544 vo_osd_changed(OSDTYPE_PROGBAR);
1545 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1548 if (mpctx->osd_show_percentage_until - now > 36000000)
1549 mpctx->osd_show_percentage_until = 0;
1551 if (!last_update)
1552 last_update = now;
1553 diff = now >= last_update ? now - last_update : 0;
1555 last_update = now;
1557 // Look for the first message in the stack with high enough level.
1558 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1559 prev = msg->prev;
1560 if (msg->level > opts->osd_level && hidden_dec_done)
1561 continue;
1562 // The message has a high enough level or it is the first hidden one
1563 // in both cases we decrement the timer or kill it.
1564 if (!msg->started || msg->time > diff) {
1565 if (msg->started)
1566 msg->time -= diff;
1567 else
1568 msg->started = 1;
1569 // display it
1570 if (msg->level <= opts->osd_level)
1571 return msg;
1572 hidden_dec_done = 1;
1573 continue;
1575 // kill the message
1576 talloc_free(msg);
1577 if (last) {
1578 last->prev = prev;
1579 msg = last;
1580 } else {
1581 osd_msg_stack = prev;
1582 msg = NULL;
1585 // Nothing found
1586 return NULL;
1590 * \brief Display the OSD bar.
1592 * Display the OSD bar or fall back on a simple message.
1596 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1597 double min, double max, double val)
1599 struct MPOpts *opts = &mpctx->opts;
1600 if (opts->osd_level < 1)
1601 return;
1603 if (mpctx->sh_video) {
1604 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1605 vo_osd_progbar_type = type;
1606 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1607 vo_osd_changed(OSDTYPE_PROGBAR);
1608 return;
1611 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1612 name, ROUND(100 * (val - min) / (max - min)));
1616 * \brief Display text subtitles on the OSD
1618 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1620 int i;
1621 vo_sub = subs;
1622 vo_osd_changed(OSDTYPE_SUBTITLE);
1623 if (!mpctx->sh_video) {
1624 // reverse order, since newest set_osd_msg is displayed first
1625 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1626 if (!subs || i >= subs->lines || !subs->text[i])
1627 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1628 else {
1629 // HACK: currently display time for each sub line
1630 // except the last is set to 2 seconds.
1631 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1632 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1633 "%s", subs->text[i]);
1640 * \brief Update the OSD message line.
1642 * This function displays the current message on the vo OSD or on the term.
1643 * If the stack is empty and the OSD level is high enough the timer
1644 * is displayed (only on the vo OSD).
1648 static void update_osd_msg(struct MPContext *mpctx)
1650 struct MPOpts *opts = &mpctx->opts;
1651 mp_osd_msg_t *msg;
1652 struct osd_state *osd = mpctx->osd;
1654 if (mpctx->add_osd_seek_info) {
1655 double percentage = get_percent_pos(mpctx);
1656 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1657 if (mpctx->sh_video)
1658 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1659 mpctx->add_osd_seek_info = false;
1662 // Look if we have a msg
1663 if ((msg = get_osd_msg(mpctx)) && !msg->show_position) {
1664 if (strcmp(osd->osd_text, msg->msg)) {
1665 osd_set_text(osd, msg->msg);
1666 if (mpctx->sh_video)
1667 vo_osd_changed(OSDTYPE_OSD);
1668 else if (opts->term_osd)
1669 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1670 msg->msg);
1672 return;
1675 int osdlevel = opts->osd_level;
1676 if (msg && msg->show_position)
1677 osdlevel = 3;
1679 if (mpctx->sh_video) {
1680 // fallback on the timer
1681 char osd_text_timer[128] = {0};
1682 if (osdlevel >= 2) {
1683 int len = get_time_length(mpctx);
1684 int percentage = -1;
1685 char percentage_text[10];
1686 char fractions_text[4];
1687 double fpts = get_current_time(mpctx);
1688 int pts = fpts;
1690 if (mpctx->osd_show_percentage_until)
1691 percentage = get_percent_pos(mpctx);
1693 if (percentage >= 0)
1694 snprintf(percentage_text, 9, " (%d%%)", percentage);
1695 else
1696 percentage_text[0] = 0;
1698 if (opts->osd_fractions == 1) {
1699 //print fractions as sub-second timestamp
1700 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1701 (int)((fpts - pts) * 100));
1702 } else if (opts->osd_fractions == 2) {
1703 /* Print fractions by estimating the frame count within the
1704 * second.
1706 * Rounding or cutting off numbers after the decimal point
1707 * causes problems because of float's precision and movies
1708 * whose first frame is not exactly at timestamp 0. Therefore,
1709 * we add 0.2 and cut off at the decimal point, which proved
1710 * to be good heuristic.
1712 double fps = mpctx->sh_video->fps;
1713 if (fps <= 1 || fps > 99)
1714 strcpy(fractions_text, ".??");
1715 else
1716 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1717 (int) ((fpts - pts) * fps + 0.2));
1718 } else {
1719 //do not print fractions
1720 fractions_text[0] = 0;
1723 osd_get_function_sym(osd_text_timer, sizeof(osd_text_timer),
1724 mpctx->osd_function);
1725 size_t blen = strlen(osd_text_timer);
1727 if (osdlevel == 3)
1728 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1729 " %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1730 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1731 len / 3600, (len / 60) % 60, len % 60,
1732 percentage_text);
1733 else
1734 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1735 " %02d:%02d:%02d%s%s",
1736 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1737 percentage_text);
1740 if (strcmp(osd->osd_text, osd_text_timer)) {
1741 osd_set_text(osd, osd_text_timer);
1742 vo_osd_changed(OSDTYPE_OSD);
1744 return;
1747 // Clear the term osd line
1748 if (opts->term_osd && osd->osd_text[0]) {
1749 osd->osd_text[0] = 0;
1750 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1755 void reinit_audio_chain(struct MPContext *mpctx)
1757 struct MPOpts *opts = &mpctx->opts;
1758 struct ao *ao;
1759 if (!mpctx->sh_audio) {
1760 uninit_player(mpctx, INITIALIZED_AO);
1761 return;
1763 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1764 current_module = "init_audio_codec";
1765 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1766 goto init_error;
1767 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1770 current_module = "af_preinit";
1771 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1772 mpctx->initialized_flags |= INITIALIZED_AO;
1773 mpctx->ao = ao_create(opts, mpctx->input);
1774 mpctx->ao->samplerate = force_srate;
1775 mpctx->ao->format = opts->audio_output_format;
1777 ao = mpctx->ao;
1779 // first init to detect best values
1780 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1781 // input:
1782 mpctx->sh_audio->samplerate,
1783 // output:
1784 &ao->samplerate, &ao->channels, &ao->format)) {
1785 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1786 "pre-init!\n");
1787 exit_player(mpctx, EXIT_ERROR);
1789 if (!ao->initialized) {
1790 current_module = "ao2_init";
1791 ao->buffersize = opts->ao_buffersize;
1792 ao_init(ao, opts->audio_driver_list);
1793 if (!ao->initialized) {
1794 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1795 "Could not open/initialize audio device -> no sound.\n");
1796 goto init_error;
1798 ao->buffer.start = talloc_new(ao);
1799 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1800 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1801 ao->driver->info->short_name,
1802 ao->samplerate, ao->channels,
1803 af_fmt2str_short(ao->format),
1804 af_fmt2bits(ao->format) / 8);
1805 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1806 ao->driver->info->name, ao->driver->info->author);
1807 if (strlen(ao->driver->info->comment) > 0)
1808 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1809 ao->driver->info->comment);
1812 // init audio filters:
1813 current_module = "af_init";
1814 if (!build_afilter_chain(mpctx)) {
1815 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1816 "Couldn't find matching filter/ao format!\n");
1817 goto init_error;
1819 mpctx->mixer.volstep = volstep;
1820 mpctx->mixer.softvol = opts->softvol;
1821 mpctx->mixer.softvol_max = opts->softvol_max;
1822 mixer_reinit(&mpctx->mixer, ao);
1823 mpctx->syncing_audio = true;
1824 return;
1826 init_error:
1827 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1828 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1829 mpctx->d_audio->id = -2;
1833 // Return pts value corresponding to the end point of audio written to the
1834 // ao so far.
1835 static double written_audio_pts(struct MPContext *mpctx)
1837 sh_audio_t *sh_audio = mpctx->sh_audio;
1838 if (!sh_audio)
1839 return MP_NOPTS_VALUE;
1840 demux_stream_t *d_audio = mpctx->d_audio;
1841 // first calculate the end pts of audio that has been output by decoder
1842 double a_pts = sh_audio->pts;
1843 if (a_pts != MP_NOPTS_VALUE)
1844 // Good, decoder supports new way of calculating audio pts.
1845 // sh_audio->pts is the timestamp of the latest input packet with
1846 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1847 // the amount of bytes the decoder has written after that timestamp.
1848 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1849 else {
1850 // Decoder doesn't support new way of calculating pts (or we're
1851 // being called before it has decoded anything with known timestamp).
1852 // Use the old method of audio pts calculation: take the timestamp
1853 // of last packet with known pts the decoder has read data from,
1854 // and add amount of bytes read after the beginning of that packet
1855 // divided by input bps. This will be inaccurate if the input/output
1856 // ratio is not constant for every audio packet or if it is constant
1857 // but not accurately known in sh_audio->i_bps.
1859 a_pts = d_audio->pts;
1860 if (a_pts == MP_NOPTS_VALUE)
1861 return a_pts;
1863 // ds_tell_pts returns bytes read after last timestamp from
1864 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1865 // it has read but not decoded
1866 if (sh_audio->i_bps)
1867 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1868 (double)sh_audio->i_bps;
1870 // Now a_pts hopefully holds the pts for end of audio from decoder.
1871 // Substract data in buffers between decoder and audio out.
1873 // Decoded but not filtered
1874 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1876 // Data buffered in audio filters, measured in bytes of "missing" output
1877 double buffered_output = af_calc_delay(sh_audio->afilter);
1879 // Data that was ready for ao but was buffered because ao didn't fully
1880 // accept everything to internal buffers yet
1881 buffered_output += mpctx->ao->buffer.len;
1883 // Filters divide audio length by playback_speed, so multiply by it
1884 // to get the length in original units without speedup or slowdown
1885 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1887 return a_pts + mpctx->video_offset;
1890 // Return pts value corresponding to currently playing audio.
1891 double playing_audio_pts(struct MPContext *mpctx)
1893 double pts = written_audio_pts(mpctx);
1894 if (pts == MP_NOPTS_VALUE)
1895 return pts;
1896 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1899 static bool is_av_sub(int type)
1901 return type == 'b' || type == 'p' || type == 'x';
1904 void update_subtitles(struct MPContext *mpctx, double refpts_tl, bool reset)
1906 mpctx->osd->sub_offset = mpctx->video_offset;
1907 struct MPOpts *opts = &mpctx->opts;
1908 struct sh_video *sh_video = mpctx->sh_video;
1909 struct demux_stream *d_sub = mpctx->d_sub;
1910 double refpts_s = refpts_tl - mpctx->osd->sub_offset;
1911 double curpts_s = refpts_s + sub_delay;
1912 unsigned char *packet = NULL;
1913 int len;
1914 struct sh_sub *sh_sub = d_sub->sh;
1915 int type = sh_sub ? sh_sub->type : 'v';
1916 static subtitle subs;
1917 if (reset) {
1918 if (sh_sub)
1919 sub_reset(sh_sub, mpctx->osd);
1920 sub_clear_text(&subs, MP_NOPTS_VALUE);
1921 if (vo_sub)
1922 set_osd_subtitle(mpctx, NULL);
1923 if (vo_spudec) {
1924 spudec_reset(vo_spudec);
1925 vo_osd_changed(OSDTYPE_SPU);
1927 return;
1929 // find sub
1930 if (mpctx->subdata) {
1931 if (sub_fps == 0)
1932 sub_fps = sh_video ? sh_video->fps : 25;
1933 current_module = "find_sub";
1934 find_sub(mpctx, mpctx->subdata, curpts_s *
1935 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1936 if (vo_sub)
1937 mpctx->vo_sub_last = vo_sub;
1940 // DVD sub:
1941 if (vobsub_id >= 0 || type == 'v') {
1942 int timestamp;
1943 current_module = "spudec";
1944 /* Get a sub packet from the DVD or a vobsub */
1945 while (1) {
1946 // Vobsub
1947 len = 0;
1948 if (vo_vobsub) {
1949 if (curpts_s >= 0) {
1950 len = vobsub_get_packet(vo_vobsub, curpts_s,
1951 (void **)&packet, &timestamp);
1952 if (len > 0)
1953 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1954 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1955 len, refpts_s, sh_video->timer,
1956 timestamp / 90000.0, timestamp);
1958 } else {
1959 // DVD sub
1960 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1961 if (len > 0) {
1962 // XXX This is wrong, sh_video->pts can be arbitrarily
1963 // much behind demuxing position. Unfortunately using
1964 // d_video->pts which would have been the simplest
1965 // improvement doesn't work because mpeg specific hacks
1966 // in video.c set d_video->pts to 0.
1967 float x = d_sub->pts - refpts_s;
1968 if (x > -20 && x < 20) // prevent missing subs on pts reset
1969 timestamp = 90000 * d_sub->pts;
1970 else
1971 timestamp = 90000 * curpts_s;
1972 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1973 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1974 refpts_s, d_sub->pts, timestamp);
1977 if (len <= 0 || !packet)
1978 break;
1979 // create it only here, since with some broken demuxers we might
1980 // type = v but no DVD sub and we currently do not change the
1981 // "original frame size" ever after init, leading to wrong-sized
1982 // PGS subtitles.
1983 if (!vo_spudec)
1984 vo_spudec = spudec_new(NULL);
1985 if (vo_vobsub || timestamp >= 0)
1986 spudec_assemble(vo_spudec, packet, len, timestamp);
1988 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1989 if (type == 'd' && !d_sub->demuxer->teletext) {
1990 tt_stream_props tsp = { 0 };
1991 void *ptr = &tsp;
1992 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
1993 VBI_CONTROL_TRUE)
1994 d_sub->demuxer->teletext = ptr;
1996 if (d_sub->non_interleaved)
1997 ds_get_next_pts(d_sub);
1999 while (d_sub->first) {
2000 double subpts_s = ds_get_next_pts(d_sub);
2001 if (subpts_s > curpts_s) {
2002 // Libass handled subs can be fed to it in advance
2003 if (!opts->ass_enabled || !is_text_sub(type))
2004 break;
2005 // Try to avoid demuxing whole file at once
2006 if (d_sub->non_interleaved && subpts_s > curpts_s + 1)
2007 break;
2009 double duration = d_sub->first->duration;
2010 len = ds_get_packet_sub(d_sub, &packet);
2011 if (type == 'm') {
2012 if (len < 2)
2013 continue;
2014 len = FFMIN(len - 2, AV_RB16(packet));
2015 packet += 2;
2017 if (type == 'd') {
2018 if (d_sub->demuxer->teletext) {
2019 uint8_t *p = packet;
2020 p++;
2021 len--;
2022 while (len >= 46) {
2023 int sublen = p[1];
2024 if (p[0] == 2 || p[0] == 3)
2025 teletext_control(d_sub->demuxer->teletext,
2026 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2027 p += sublen + 2;
2028 len -= sublen + 2;
2031 continue;
2033 if (sh_sub && sh_sub->active) {
2034 sub_decode(sh_sub, mpctx->osd, packet, len, subpts_s, duration);
2035 continue;
2037 if (subpts_s != MP_NOPTS_VALUE) {
2038 if (duration < 0)
2039 sub_clear_text(&subs, MP_NOPTS_VALUE);
2040 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2041 int i;
2042 unsigned char *p = packet;
2043 for (i = 0; i < 8 && *p != '\0'; p++)
2044 if (*p == ',')
2045 i++;
2046 if (*p == '\0') /* Broken line? */
2047 continue;
2048 len -= p - packet;
2049 packet = p;
2051 double endpts_s = MP_NOPTS_VALUE;
2052 if (subpts_s != MP_NOPTS_VALUE && duration >= 0)
2053 endpts_s = subpts_s + duration;
2054 sub_add_text(&subs, packet, len, endpts_s);
2055 set_osd_subtitle(mpctx, &subs);
2057 if (d_sub->non_interleaved)
2058 ds_get_next_pts(d_sub);
2060 if (!opts->ass_enabled)
2061 if (sub_clear_text(&subs, curpts_s))
2062 set_osd_subtitle(mpctx, &subs);
2064 if (vo_spudec) {
2065 spudec_heartbeat(vo_spudec, 90000 * curpts_s);
2066 if (spudec_changed(vo_spudec))
2067 vo_osd_changed(OSDTYPE_SPU);
2070 current_module = NULL;
2073 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2075 int page_changed;
2077 if (!demuxer->teletext)
2078 return;
2080 //Also forcing page update when such ioctl is not supported or call error occured
2081 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2082 &page_changed) != VBI_CONTROL_TRUE)
2083 page_changed = 1;
2085 if (!page_changed)
2086 return;
2088 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2089 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2090 vo_osd_teletext_page = NULL;
2091 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2092 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2093 vo_osd_teletext_half = 0;
2094 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2095 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2096 vo_osd_teletext_mode = 0;
2097 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2098 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2099 vo_osd_teletext_format = 0;
2100 vo_osd_changed(OSDTYPE_TELETEXT);
2102 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2105 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2107 struct MPOpts *opts = &mpctx->opts;
2108 // check for frame-drop:
2109 current_module = "check_framedrop";
2110 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2111 static int dropped_frames;
2112 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2113 float d = delay - mpctx->delay;
2114 ++total_frame_cnt;
2115 // we should avoid dropping too many frames in sequence unless we
2116 // are too late. and we allow 100ms A-V delay here:
2117 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2118 && !mpctx->restart_playback) {
2119 ++drop_frame_cnt;
2120 ++dropped_frames;
2121 return frame_dropping;
2122 } else
2123 dropped_frames = 0;
2125 return 0;
2129 #ifdef HAVE_RTC
2130 int rtc_fd = -1;
2131 #endif
2133 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2135 #ifdef HAVE_RTC
2136 if (rtc_fd >= 0) {
2137 // -------- RTC -----------
2138 current_module = "sleep_rtc";
2139 while (time_frame > 0.000) {
2140 unsigned long rtc_ts;
2141 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2142 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2143 "Linux RTC read error: %s\n", strerror(errno));
2144 time_frame -= get_relative_time(mpctx);
2146 } else
2147 #endif
2149 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2150 // unnecessarily high CPU usage
2151 struct MPOpts *opts = &mpctx->opts;
2152 float margin = opts->softsleep ? 0.011 : 0;
2153 current_module = "sleep_timer";
2154 while (time_frame > margin) {
2155 usec_sleep(1000000 * (time_frame - margin));
2156 time_frame -= get_relative_time(mpctx);
2158 if (opts->softsleep) {
2159 current_module = "sleep_soft";
2160 if (time_frame < 0)
2161 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2162 "Warning! Softsleep underflow!\n");
2163 while (time_frame > 0)
2164 time_frame -= get_relative_time(mpctx); // burn the CPU
2167 return time_frame;
2170 static int select_subtitle(MPContext *mpctx)
2172 struct MPOpts *opts = &mpctx->opts;
2173 // find the best sub to use
2174 int id;
2175 int found = 0;
2176 mpctx->global_sub_pos = -1; // no subs by default
2177 if (vobsub_id >= 0) {
2178 // if user asks for a vobsub id, use that first.
2179 id = vobsub_id;
2180 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2181 M_PROPERTY_OK;
2184 if (!found && opts->sub_id >= 0) {
2185 // if user asks for a dvd sub id, use that next.
2186 id = opts->sub_id;
2187 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2188 M_PROPERTY_OK;
2191 if (!found) {
2192 // if there are text subs to use, use those. (autosubs come last here)
2193 id = 0;
2194 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2195 M_PROPERTY_OK;
2198 if (!found && opts->sub_id == -1) {
2199 // finally select subs by language and container hints
2200 if (opts->sub_id == -1)
2201 opts->sub_id =
2202 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2203 opts->sub_lang);
2204 if (opts->sub_id >= 0) {
2205 id = opts->sub_id;
2206 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2207 M_PROPERTY_OK;
2210 return found;
2213 #ifdef CONFIG_DVDNAV
2214 #ifndef FF_B_TYPE
2215 #define FF_B_TYPE 3
2216 #endif
2217 /// store decoded video image
2218 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2219 mp_image_t *from_mpi)
2221 mp_image_t *mpi;
2223 /// Do not store B-frames
2224 if (from_mpi->pict_type == FF_B_TYPE)
2225 return to_mpi;
2227 if (to_mpi &&
2228 to_mpi->w == from_mpi->w &&
2229 to_mpi->h == from_mpi->h &&
2230 to_mpi->imgfmt == from_mpi->imgfmt)
2231 mpi = to_mpi;
2232 else {
2233 if (to_mpi)
2234 free_mp_image(to_mpi);
2235 if (from_mpi->w == 0 || from_mpi->h == 0)
2236 return NULL;
2237 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2240 copy_mpi(mpi, from_mpi);
2241 return mpi;
2244 static void mp_dvdnav_reset_stream(MPContext *ctx)
2246 struct MPOpts *opts = &ctx->opts;
2247 if (ctx->sh_video) {
2248 /// clear video pts
2249 ctx->d_video->pts = 0.0f;
2250 ctx->sh_video->pts = 0.0f;
2251 ctx->sh_video->i_pts = 0.0f;
2252 ctx->sh_video->last_pts = 0.0f;
2253 ctx->sh_video->num_buffered_pts = 0;
2254 ctx->sh_video->num_frames = 0;
2255 ctx->sh_video->num_frames_decoded = 0;
2256 ctx->sh_video->timer = 0.0f;
2257 ctx->sh_video->stream_delay = 0.0f;
2258 ctx->sh_video->timer = 0;
2259 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2262 if (ctx->sh_audio) {
2263 /// free audio packets and reset
2264 ds_free_packs(ctx->d_audio);
2265 audio_delay -= ctx->sh_audio->stream_delay;
2266 ctx->delay = -audio_delay;
2267 ao_reset(ctx->ao);
2268 resync_audio_stream(ctx->sh_audio);
2271 audio_delay = 0.0f;
2272 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2273 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2274 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2275 if (dvdsub_lang_id != opts->sub_id) {
2276 opts->sub_id = dvdsub_lang_id;
2277 select_subtitle(ctx);
2281 /// clear all EOF related flags
2282 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2285 /// Restore last decoded DVDNAV (still frame)
2286 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2287 int *in_size,
2288 unsigned char **start,
2289 mp_image_t *decoded_frame)
2291 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2292 return decoded_frame;
2294 /// a change occurred in dvdnav stream
2295 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2296 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2297 mp_dvdnav_context_free(mpctx);
2298 mp_dvdnav_reset_stream(mpctx);
2299 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2300 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2303 if (*in_size < 0) {
2304 float len;
2306 /// Display still frame, if any
2307 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2308 decoded_frame = mpctx->nav_smpi;
2310 /// increment video frame : continue playing after still frame
2311 len = get_time_length(mpctx);
2312 if (mpctx->sh_video->pts >= len &&
2313 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2314 mp_dvdnav_skip_still(mpctx->stream);
2315 mp_dvdnav_skip_wait(mpctx->stream);
2317 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2319 if (mpctx->nav_buffer) {
2320 *start = mpctx->nav_start;
2321 *in_size = mpctx->nav_in_size;
2322 if (mpctx->nav_start)
2323 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2327 return decoded_frame;
2330 /// Save last decoded DVDNAV (still frame)
2331 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2332 unsigned char *start,
2333 mp_image_t *decoded_frame)
2335 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2336 return;
2338 free(mpctx->nav_buffer);
2339 mpctx->nav_buffer = NULL;
2340 mpctx->nav_start = NULL;
2341 mpctx->nav_in_size = -1;
2343 if (in_size > 0)
2344 mpctx->nav_buffer = malloc(in_size);
2345 if (mpctx->nav_buffer) {
2346 mpctx->nav_start = start;
2347 mpctx->nav_in_size = in_size;
2348 memcpy(mpctx->nav_buffer, start, in_size);
2351 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2352 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2354 #endif /* CONFIG_DVDNAV */
2356 /* Modify video timing to match the audio timeline. There are two main
2357 * reasons this is needed. First, video and audio can start from different
2358 * positions at beginning of file or after a seek (MPlayer starts both
2359 * immediately even if they have different pts). Second, the file can have
2360 * audio timestamps that are inconsistent with the duration of the audio
2361 * packets, for example two consecutive timestamp values differing by
2362 * one second but only a packet with enough samples for half a second
2363 * of playback between them.
2365 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2367 current_module = "av_sync";
2369 if (!mpctx->sh_audio || mpctx->syncing_audio)
2370 return;
2372 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2373 double v_pts = mpctx->sh_video->pts;
2374 double av_delay = a_pts - v_pts;
2375 // Try to sync vo_flip() so it will *finish* at given time
2376 av_delay += mpctx->last_vo_flip_duration;
2377 av_delay -= audio_delay; // This much pts difference is desired
2379 double change = av_delay * 0.1;
2380 double max_change = default_max_pts_correction >= 0 ?
2381 default_max_pts_correction : frame_time * 0.1;
2382 if (change < -max_change)
2383 change = -max_change;
2384 else if (change > max_change)
2385 change = max_change;
2386 mpctx->delay += change;
2387 mpctx->total_avsync_change += change;
2390 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2391 double pts)
2393 if (mpctx->paused)
2394 return 0;
2395 struct ao *ao = mpctx->ao;
2396 double bps = ao->bps / mpctx->opts.playback_speed;
2397 ao->pts = pts;
2398 // hack used by some mpeg-writing AOs
2399 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2400 mpctx->delay) * 90000.0;
2401 int played = ao_play(mpctx->ao, data, len, flags);
2402 if (played > 0) {
2403 mpctx->delay += played / bps;
2404 // Keep correct pts for remaining data - could be used to flush
2405 // remaining buffer when closing ao.
2406 ao->pts += played / bps;
2408 return played;
2411 #define ASYNC_PLAY_DONE -3
2412 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2414 struct ao *ao = mpctx->ao;
2415 struct MPOpts *opts = &mpctx->opts;
2416 sh_audio_t * const sh_audio = mpctx->sh_audio;
2417 int res;
2419 // Timing info may not be set without
2420 res = decode_audio(sh_audio, &ao->buffer, 1);
2421 if (res < 0)
2422 return res;
2424 int bytes;
2425 bool did_retry = false;
2426 double written_pts;
2427 double bps = ao->bps / opts->playback_speed;
2428 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2429 mpctx->hrseek_active = false;
2430 while (1) {
2431 written_pts = written_audio_pts(mpctx);
2432 double ptsdiff;
2433 if (hrseek)
2434 ptsdiff = written_pts - mpctx->hrseek_pts;
2435 else
2436 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2437 - audio_delay;
2438 bytes = ptsdiff * bps;
2439 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2441 // ogg demuxers give packets without timing
2442 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2443 if (!did_retry) {
2444 // Try to read more data to see packets that have pts
2445 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2446 if (res < 0)
2447 return res;
2448 did_retry = true;
2449 continue;
2451 bytes = 0;
2454 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2455 bytes = 0;
2457 if (bytes > 0)
2458 break;
2460 mpctx->syncing_audio = false;
2461 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2462 int res = decode_audio(sh_audio, &ao->buffer, a);
2463 bytes += ao->buffer.len;
2464 if (bytes >= 0) {
2465 memmove(ao->buffer.start,
2466 ao->buffer.start + ao->buffer.len - bytes, bytes);
2467 ao->buffer.len = bytes;
2468 if (res < 0)
2469 return res;
2470 return decode_audio(sh_audio, &ao->buffer, playsize);
2472 ao->buffer.len = 0;
2473 if (res < 0)
2474 return res;
2476 if (hrseek)
2477 // Don't add silence in audio-only case even if position is too late
2478 return 0;
2479 int fillbyte = 0;
2480 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2481 fillbyte = 0x80;
2482 if (bytes >= playsize) {
2483 /* This case could fall back to the one below with
2484 * bytes = playsize, but then silence would keep accumulating
2485 * in a_out_buffer if the AO accepts less data than it asks for
2486 * in playsize. */
2487 char *p = malloc(playsize);
2488 memset(p, fillbyte, playsize);
2489 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2490 free(p);
2491 return ASYNC_PLAY_DONE;
2493 mpctx->syncing_audio = false;
2494 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2495 return decode_audio(sh_audio, &ao->buffer, playsize);
2498 static int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
2500 struct MPOpts *opts = &mpctx->opts;
2501 struct ao *ao = mpctx->ao;
2502 unsigned int t;
2503 double tt;
2504 int playsize;
2505 int playflags = 0;
2506 bool audio_eof = false;
2507 bool partial_fill = false;
2508 sh_audio_t * const sh_audio = mpctx->sh_audio;
2509 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2510 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2512 current_module = "play_audio";
2514 // hack used by some mpeg-writing AOs
2515 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2516 mpctx->delay) * 90000.0;
2518 if (mpctx->paused)
2519 playsize = 1; // just initialize things (audio pts at least)
2520 else
2521 playsize = ao_get_space(ao);
2523 // Fill buffer if needed:
2524 current_module = "decode_audio";
2525 t = GetTimer();
2527 // Coming here with hrseek_active still set means audio-only
2528 if (!mpctx->sh_video)
2529 mpctx->syncing_audio = false;
2530 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2531 mpctx->syncing_audio = false;
2532 mpctx->hrseek_active = false;
2535 int res;
2536 if (mpctx->syncing_audio || mpctx->hrseek_active)
2537 res = audio_start_sync(mpctx, playsize);
2538 else
2539 res = decode_audio(sh_audio, &ao->buffer, playsize);
2540 if (res < 0) { // EOF, error or format change
2541 if (res == -2) {
2542 /* The format change isn't handled too gracefully. A more precise
2543 * implementation would require draining buffered old-format audio
2544 * while displaying video, then doing the output format switch.
2546 uninit_player(mpctx, INITIALIZED_AO);
2547 reinit_audio_chain(mpctx);
2548 return -1;
2549 } else if (res == ASYNC_PLAY_DONE)
2550 return 0;
2551 else if (mpctx->d_audio->eof)
2552 audio_eof = true;
2554 t = GetTimer() - t;
2555 tt = t * 0.000001f;
2556 audio_time_usage += tt;
2557 if (endpts != MP_NOPTS_VALUE && modifiable_audio_format) {
2558 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2559 * ao->bps / opts->playback_speed;
2560 if (playsize > bytes) {
2561 playsize = FFMAX(bytes, 0);
2562 playflags |= AOPLAY_FINAL_CHUNK;
2563 audio_eof = true;
2564 partial_fill = true;
2568 assert(ao->buffer.len % unitsize == 0);
2569 if (playsize > ao->buffer.len) {
2570 partial_fill = true;
2571 playsize = ao->buffer.len;
2572 if (audio_eof)
2573 playflags |= AOPLAY_FINAL_CHUNK;
2575 playsize -= playsize % unitsize;
2576 if (!playsize)
2577 return partial_fill && audio_eof ? -2 : -partial_fill;
2579 // play audio:
2580 current_module = "play_audio";
2582 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2583 written_audio_pts(mpctx));
2584 assert(played % unitsize == 0);
2585 ao->buffer_playable_size = playsize - played;
2587 if (played > 0) {
2588 ao->buffer.len -= played;
2589 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2590 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2591 // Sanity check to avoid hanging in case current ao doesn't output
2592 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2593 return -2;
2596 return -partial_fill;
2599 int reinit_video_chain(struct MPContext *mpctx)
2601 struct MPOpts *opts = &mpctx->opts;
2602 sh_video_t * const sh_video = mpctx->sh_video;
2603 if (!sh_video) {
2604 uninit_player(mpctx, INITIALIZED_VO);
2605 return 0;
2607 double ar = -1.0;
2608 //================== Init VIDEO (codec & libvo) ==========================
2609 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2610 current_module = "preinit_libvo";
2612 //shouldn't we set dvideo->id=-2 when we fail?
2613 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2614 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->key_fifo,
2615 mpctx->input))) {
2616 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2617 "the selected video_out (-vo) device.\n");
2618 goto err_out;
2620 mpctx->initialized_flags |= INITIALIZED_VO;
2623 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2624 &ar) != STREAM_UNSUPPORTED)
2625 mpctx->sh_video->stream_aspect = ar;
2626 current_module = "init_video_filters";
2628 char *vf_arg[] = {
2629 "_oldargs_", (char *)mpctx->video_out, NULL
2631 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2634 #ifdef CONFIG_ASS
2635 if (opts->ass_enabled) {
2636 int i;
2637 int insert = 1;
2638 if (opts->vf_settings)
2639 for (i = 0; opts->vf_settings[i].name; ++i)
2640 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2641 insert = 0;
2642 break;
2644 if (insert) {
2645 extern vf_info_t vf_info_ass;
2646 const vf_info_t *libass_vfs[] = {
2647 &vf_info_ass, NULL
2649 char *vf_arg[] = {
2650 "auto", "1", NULL
2652 int retcode = 0;
2653 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2654 sh_video->vfilter,
2655 "ass", vf_arg,
2656 &retcode);
2657 if (vf_ass)
2658 sh_video->vfilter = vf_ass;
2659 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2660 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2661 else
2662 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2663 "ASS: cannot add video filter\n");
2666 #endif
2668 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2670 if (opts->ass_enabled)
2671 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2672 mpctx->ass_library);
2674 current_module = "init_video_codec";
2676 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2678 if (!sh_video->initialized) {
2679 if (!opts->fixed_vo)
2680 uninit_player(mpctx, INITIALIZED_VO);
2681 goto err_out;
2684 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2686 if (sh_video->codec)
2687 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2688 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2690 sh_video->last_pts = MP_NOPTS_VALUE;
2691 sh_video->num_buffered_pts = 0;
2692 sh_video->next_frame_time = 0;
2693 mpctx->restart_playback = true;
2694 mpctx->delay = 0;
2696 if (opts->auto_quality > 0) {
2697 // Auto quality option enabled
2698 output_quality = get_video_quality_max(sh_video);
2699 if (opts->auto_quality > output_quality)
2700 opts->auto_quality = output_quality;
2701 else
2702 output_quality = opts->auto_quality;
2703 mp_msg(MSGT_CPLAYER, MSGL_V,
2704 "AutoQ: setting quality to %d.\n", output_quality);
2705 set_video_quality(sh_video, output_quality);
2708 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2710 current_module = "init_vo";
2712 return 1;
2714 err_out:
2715 mpctx->sh_video = mpctx->d_video->sh = NULL;
2716 return 0;
2719 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2721 struct sh_video *sh_video = mpctx->sh_video;
2722 double frame_time = 0;
2723 struct vo *video_out = mpctx->video_out;
2724 while (1) {
2725 current_module = "filter_video";
2726 // In nocorrect-pts mode there is no way to properly time these frames
2727 if (vo_get_buffered_frame(video_out, 0) >= 0)
2728 break;
2729 if (vf_output_queued_frame(sh_video->vfilter))
2730 break;
2731 unsigned char *packet = NULL;
2732 frame_time = sh_video->next_frame_time;
2733 if (mpctx->restart_playback)
2734 frame_time = 0;
2735 int in_size = 0;
2736 while (!in_size)
2737 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2738 &packet, force_fps);
2739 if (in_size < 0) {
2740 #ifdef CONFIG_DVDNAV
2741 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2742 if (mp_dvdnav_is_eof(mpctx->stream))
2743 return -1;
2744 if (mpctx->d_video)
2745 mpctx->d_video->eof = 0;
2746 if (mpctx->d_audio)
2747 mpctx->d_audio->eof = 0;
2748 mpctx->stream->eof = 0;
2749 } else
2750 #endif
2751 return -1;
2753 if (in_size > max_framesize)
2754 max_framesize = in_size;
2755 sh_video->timer += frame_time;
2756 if (mpctx->sh_audio)
2757 mpctx->delay -= frame_time;
2758 // video_read_frame can change fps (e.g. for ASF video)
2759 vo_fps = sh_video->fps;
2760 int framedrop_type = check_framedrop(mpctx, frame_time);
2761 current_module = "decode video";
2763 void *decoded_frame;
2764 #ifdef CONFIG_DVDNAV
2765 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2766 if (in_size >= 0 && !decoded_frame)
2767 #endif
2768 decoded_frame = decode_video(sh_video, sh_video->ds->current, packet,
2769 in_size, framedrop_type, sh_video->pts);
2770 #ifdef CONFIG_DVDNAV
2771 // Save last still frame for future display
2772 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2773 #endif
2774 if (decoded_frame) {
2775 current_module = "filter video";
2776 filter_video(sh_video, decoded_frame, sh_video->pts);
2778 break;
2780 return frame_time;
2783 static void determine_frame_pts(struct MPContext *mpctx)
2785 struct sh_video *sh_video = mpctx->sh_video;
2786 struct MPOpts *opts = &mpctx->opts;
2788 if (opts->user_pts_assoc_mode)
2789 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2790 else if (sh_video->pts_assoc_mode == 0) {
2791 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2792 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2793 sh_video->pts_assoc_mode = 1;
2794 else
2795 sh_video->pts_assoc_mode = 2;
2796 } else {
2797 int probcount1 = sh_video->num_reordered_pts_problems;
2798 int probcount2 = sh_video->num_sorted_pts_problems;
2799 if (sh_video->pts_assoc_mode == 2) {
2800 int tmp = probcount1;
2801 probcount1 = probcount2;
2802 probcount2 = tmp;
2804 if (probcount1 >= probcount2 * 1.5 + 2) {
2805 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2806 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2807 "%d.\n", sh_video->pts_assoc_mode);
2810 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2811 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2814 static double update_video(struct MPContext *mpctx)
2816 struct sh_video *sh_video = mpctx->sh_video;
2817 struct vo *video_out = mpctx->video_out;
2818 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2819 mpctx->osd); // hack for vf_expand
2820 if (!mpctx->opts.correct_pts)
2821 return update_video_nocorrect_pts(mpctx);
2823 double pts;
2825 while (1) {
2826 current_module = "filter_video";
2827 if (vo_get_buffered_frame(video_out, false) >= 0)
2828 break;
2829 // XXX Time used in this call is not counted in any performance
2830 // timer now
2831 if (vf_output_queued_frame(sh_video->vfilter))
2832 break;
2833 int in_size = 0;
2834 unsigned char *buf = NULL;
2835 pts = MP_NOPTS_VALUE;
2836 struct demux_packet *pkt;
2837 while (1) {
2838 pkt = ds_get_packet2(mpctx->d_video, false);
2839 if (!pkt || pkt->len)
2840 break;
2841 /* Packets with size 0 are assumed to not correspond to frames,
2842 * but to indicate the absence of a frame in formats like AVI
2843 * that must have packets at fixed timecode intervals. */
2845 if (pkt) {
2846 in_size = pkt->len;
2847 buf = pkt->buffer;
2848 pts = pkt->pts;
2850 if (pts != MP_NOPTS_VALUE)
2851 pts += mpctx->video_offset;
2852 if (in_size > max_framesize)
2853 max_framesize = in_size;
2854 current_module = "decode video";
2855 if (pts >= mpctx->hrseek_pts - .005)
2856 mpctx->hrseek_framedrop = false;
2857 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2858 check_framedrop(mpctx, sh_video->frametime);
2859 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2860 framedrop_type, pts);
2861 if (decoded_frame) {
2862 determine_frame_pts(mpctx);
2863 current_module = "filter video";
2864 filter_video(sh_video, decoded_frame, sh_video->pts);
2865 } else if (!pkt) {
2866 if (vo_get_buffered_frame(video_out, true) < 0)
2867 return -1;
2869 break;
2872 if (!video_out->frame_loaded)
2873 return 0;
2875 pts = video_out->next_pts;
2876 if (pts == MP_NOPTS_VALUE) {
2877 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2878 // Try to use decoder pts from before filters
2879 pts = sh_video->pts;
2880 if (pts == MP_NOPTS_VALUE)
2881 pts = sh_video->last_pts;
2883 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2884 vo_skip_frame(video_out);
2885 return 0;
2887 mpctx->hrseek_active = false;
2888 sh_video->pts = pts;
2889 if (sh_video->last_pts == MP_NOPTS_VALUE)
2890 sh_video->last_pts = sh_video->pts;
2891 else if (sh_video->last_pts > sh_video->pts) {
2892 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2893 sh_video->pts, sh_video->last_pts);
2894 /* If the difference in pts is small treat it as jitter around the
2895 * right value (possibly caused by incorrect timestamp ordering) and
2896 * just show this frame immediately after the last one.
2897 * Treat bigger differences as timestamp resets and start counting
2898 * timing of later frames from the position of this one. */
2899 if (sh_video->last_pts - sh_video->pts > 0.5)
2900 sh_video->last_pts = sh_video->pts;
2901 else
2902 sh_video->pts = sh_video->last_pts;
2904 double frame_time = sh_video->pts - sh_video->last_pts;
2905 sh_video->last_pts = sh_video->pts;
2906 sh_video->timer += frame_time;
2907 if (mpctx->sh_audio)
2908 mpctx->delay -= frame_time;
2909 return frame_time;
2912 static int get_cache_fill(struct MPContext *mpctx)
2914 #ifdef CONFIG_STREAM_CACHE
2915 struct MPOpts *opts = &mpctx->opts;
2916 if (opts->stream_cache_size > 0)
2917 return cache_fill_status(mpctx->stream);
2918 #endif
2919 return -1;
2922 static void update_pause_message(struct MPContext *mpctx)
2924 struct MPOpts *opts = &mpctx->opts;
2926 if (opts->quiet)
2927 return;
2929 int cache_fill = get_cache_fill(mpctx);
2930 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2932 if (!mpctx->status_printed && !cache_changed)
2933 return;
2935 char *msg = mp_gtext(" ===== PAUSE =====");
2936 char *tmpmem = NULL;
2937 if (cache_fill >= 0)
2938 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
2940 if (opts->term_osd && !mpctx->sh_video) {
2941 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
2942 update_osd_msg(mpctx);
2943 } else {
2944 if (mpctx->status_printed)
2945 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
2946 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
2949 mpctx->paused_cache_fill = cache_fill;
2950 mpctx->status_printed = false;
2952 talloc_free(tmpmem);
2955 void pause_player(struct MPContext *mpctx)
2957 if (mpctx->paused)
2958 return;
2959 mpctx->paused = 1;
2960 mpctx->step_frames = 0;
2961 mpctx->time_frame -= get_relative_time(mpctx);
2962 mpctx->osd_function = OSD_PAUSE;
2964 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2965 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2967 if (mpctx->ao && mpctx->sh_audio)
2968 ao_pause(mpctx->ao); // pause audio, keep data if possible
2970 mpctx->paused_cache_fill = get_cache_fill(mpctx);
2971 mpctx->status_printed = true;
2972 update_pause_message(mpctx);
2974 if (!mpctx->opts.quiet)
2975 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2978 void unpause_player(struct MPContext *mpctx)
2980 if (!mpctx->paused)
2981 return;
2982 mpctx->paused = 0;
2983 if (!mpctx->step_frames)
2984 mpctx->osd_function = OSD_PLAY;
2986 if (mpctx->ao && mpctx->sh_audio)
2987 ao_resume(mpctx->ao);
2988 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2989 && !mpctx->step_frames)
2990 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2991 (void)get_relative_time(mpctx); // ignore time that passed during pause
2994 static int redraw_osd(struct MPContext *mpctx)
2996 struct sh_video *sh_video = mpctx->sh_video;
2997 struct vf_instance *vf = sh_video->vfilter;
2998 if (sh_video->output_flags & VFCAP_OSD_FILTER)
2999 return -1;
3000 if (vo_redraw_frame(mpctx->video_out) < 0)
3001 return -1;
3002 mpctx->osd->sub_pts = mpctx->video_pts;
3003 if (mpctx->osd->sub_pts != MP_NOPTS_VALUE)
3004 mpctx->osd->sub_pts += sub_delay - mpctx->osd->sub_offset;
3006 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3007 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3008 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3009 vo_flip_page(mpctx->video_out, 0, -1);
3010 return 0;
3013 void add_step_frame(struct MPContext *mpctx)
3015 mpctx->step_frames++;
3016 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3017 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3018 unpause_player(mpctx);
3021 static void seek_reset(struct MPContext *mpctx, bool reset_ao, bool reset_ac)
3023 if (mpctx->sh_video) {
3024 current_module = "seek_video_reset";
3025 resync_video_stream(mpctx->sh_video);
3026 mpctx->sh_video->timer = 0;
3027 vo_seek_reset(mpctx->video_out);
3028 mpctx->sh_video->timer = 0;
3029 mpctx->sh_video->num_buffered_pts = 0;
3030 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3031 mpctx->delay = 0;
3032 mpctx->time_frame = 0;
3033 // Not all demuxers set d_video->pts during seek, so this value
3034 // (which is used by at least vobsub code below) may be completely
3035 // wrong (probably 0).
3036 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3037 mpctx->video_pts = mpctx->sh_video->pts;
3038 update_subtitles(mpctx, mpctx->sh_video->pts, true);
3039 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3042 if (mpctx->sh_audio && reset_ac) {
3043 current_module = "seek_audio_reset";
3044 resync_audio_stream(mpctx->sh_audio);
3045 if (reset_ao)
3046 ao_reset(mpctx->ao);
3047 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3048 mpctx->sh_audio->a_buffer_len = 0;
3049 if (!mpctx->sh_video)
3050 update_subtitles(mpctx, mpctx->sh_audio->pts, true);
3053 if (vo_vobsub && mpctx->sh_video) {
3054 current_module = "seek_vobsub_reset";
3055 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3058 mpctx->restart_playback = true;
3059 mpctx->hrseek_active = false;
3060 mpctx->hrseek_framedrop = false;
3061 mpctx->total_avsync_change = 0;
3062 audio_time_usage = 0;
3063 video_time_usage = 0;
3064 vout_time_usage = 0;
3065 drop_frame_cnt = 0;
3067 current_module = NULL;
3070 static bool timeline_set_part(struct MPContext *mpctx, int i)
3072 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3073 struct timeline_part *n = mpctx->timeline + i;
3074 mpctx->timeline_part = i;
3075 mpctx->video_offset = n->start - n->source_start;
3076 if (n->source == p->source)
3077 return false;
3078 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3079 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3080 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3081 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3082 mpctx->stop_play = orig_stop_play;
3083 mpctx->demuxer = n->source->demuxer;
3084 mpctx->d_video = mpctx->demuxer->video;
3085 mpctx->d_audio = mpctx->demuxer->audio;
3086 mpctx->d_sub = mpctx->demuxer->sub;
3087 mpctx->sh_video = mpctx->d_video->sh;
3088 mpctx->sh_audio = mpctx->d_audio->sh;
3089 return true;
3092 // Given pts, switch playback to the corresponding part.
3093 // Return offset within that part.
3094 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3095 bool *need_reset)
3097 if (pts < 0)
3098 pts = 0;
3099 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3100 struct timeline_part *p = mpctx->timeline + i;
3101 if (pts < (p + 1)->start) {
3102 *need_reset = timeline_set_part(mpctx, i);
3103 return pts - p->start + p->source_start;
3106 return -1;
3110 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3111 static int seek(MPContext *mpctx, struct seek_params seek,
3112 bool timeline_fallthrough)
3114 struct MPOpts *opts = &mpctx->opts;
3116 current_module = "seek";
3117 if (mpctx->stop_play == AT_END_OF_FILE)
3118 mpctx->stop_play = KEEP_PLAYING;
3119 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3120 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3121 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3122 || opts->hr_seek > 0 || seek.exact > 0;
3123 if (seek.type == MPSEEK_FACTOR
3124 || seek.type == MPSEEK_ABSOLUTE
3125 && seek.amount < mpctx->last_chapter_pts
3126 || seek.amount < 0)
3127 mpctx->last_chapter_seek = -2;
3128 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3129 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3130 seek.type = MPSEEK_ABSOLUTE;
3132 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3133 && seek.type == MPSEEK_RELATIVE) {
3134 seek.type = MPSEEK_ABSOLUTE;
3135 seek.direction = seek.amount > 0 ? 1 : -1;
3136 seek.amount += get_current_time(mpctx);
3139 /* At least the liba52 decoder wants to read from the input stream
3140 * during initialization, so reinit must be done after the demux_seek()
3141 * call that clears possible stream EOF. */
3142 bool need_reset = false;
3143 double demuxer_amount = seek.amount;
3144 if (mpctx->timeline) {
3145 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3146 &need_reset);
3147 if (demuxer_amount == -1) {
3148 mpctx->stop_play = AT_END_OF_FILE;
3149 // Clear audio from current position
3150 if (mpctx->sh_audio && !timeline_fallthrough) {
3151 ao_reset(mpctx->ao);
3152 mpctx->sh_audio->a_buffer_len = 0;
3154 return -1;
3157 if (need_reset) {
3158 reinit_video_chain(mpctx);
3159 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos},
3160 mpctx);
3163 int demuxer_style = 0;
3164 switch (seek.type) {
3165 case MPSEEK_FACTOR:
3166 demuxer_style |= SEEK_FACTOR; // fallthrough
3167 case MPSEEK_ABSOLUTE:
3168 demuxer_style |= SEEK_ABSOLUTE;
3170 if (hr_seek || seek.direction < 0)
3171 demuxer_style |= SEEK_BACKWARD;
3172 else if (seek.direction > 0)
3173 demuxer_style |= SEEK_FORWARD;
3175 if (hr_seek)
3176 demuxer_amount -= opts->hr_seek_demuxer_offset;
3177 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3178 demuxer_style);
3179 if (seekresult == 0) {
3180 if (need_reset) {
3181 reinit_audio_chain(mpctx);
3182 seek_reset(mpctx, !timeline_fallthrough, false);
3184 return -1;
3187 if (need_reset)
3188 reinit_audio_chain(mpctx);
3189 /* If we just reinitialized audio it doesn't need to be reset,
3190 * and resetting could lose audio some decoders produce during init. */
3191 seek_reset(mpctx, !timeline_fallthrough, !need_reset);
3193 /* Use the target time as "current position" for further relative
3194 * seeks etc until a new video frame has been decoded */
3195 if (seek.type == MPSEEK_ABSOLUTE) {
3196 mpctx->video_pts = seek.amount;
3197 mpctx->last_seek_pts = seek.amount;
3198 } else
3199 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3201 if (hr_seek) {
3202 mpctx->hrseek_active = true;
3203 mpctx->hrseek_framedrop = true;
3204 mpctx->hrseek_pts = seek.amount;
3207 mpctx->start_timestamp = GetTimerMS();
3209 return 0;
3212 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3213 int exact)
3215 struct seek_params *seek = &mpctx->seek;
3216 switch (type) {
3217 case MPSEEK_RELATIVE:
3218 if (seek->type == MPSEEK_FACTOR)
3219 return; // Well... not common enough to bother doing better
3220 seek->amount += amount;
3221 seek->exact = FFMAX(seek->exact, exact);
3222 if (seek->type == MPSEEK_NONE)
3223 seek->exact = exact;
3224 if (seek->type == MPSEEK_ABSOLUTE)
3225 return;
3226 if (seek->amount == 0) {
3227 *seek = (struct seek_params){ 0 };
3228 return;
3230 seek->type = MPSEEK_RELATIVE;
3231 return;
3232 case MPSEEK_ABSOLUTE:
3233 case MPSEEK_FACTOR:
3234 *seek = (struct seek_params) {
3235 .type = type,
3236 .amount = amount,
3237 .exact = exact,
3239 return;
3240 case MPSEEK_NONE:
3241 *seek = (struct seek_params){ 0 };
3242 return;
3244 abort();
3248 double get_time_length(struct MPContext *mpctx)
3250 if (mpctx->timeline)
3251 return mpctx->timeline[mpctx->num_timeline_parts].start;
3253 struct demuxer *demuxer = mpctx->demuxer;
3254 double get_time_ans;
3255 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3256 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3257 (void *) &get_time_ans) > 0)
3258 return get_time_ans;
3260 struct sh_video *sh_video = mpctx->d_video->sh;
3261 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3262 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3263 return (double) (demuxer->movi_end - demuxer->movi_start) /
3264 (sh_video->i_bps + sh_audio->i_bps);
3265 if (sh_video && sh_video->i_bps)
3266 return (double) (demuxer->movi_end - demuxer->movi_start) /
3267 sh_video->i_bps;
3268 if (sh_audio && sh_audio->i_bps)
3269 return (double) (demuxer->movi_end - demuxer->movi_start) /
3270 sh_audio->i_bps;
3271 return 0;
3274 /* If there are timestamps from stream level then use those (for example
3275 * DVDs can have consistent times there while the MPEG-level timestamps
3276 * reset). */
3277 double get_current_time(struct MPContext *mpctx)
3279 struct demuxer *demuxer = mpctx->demuxer;
3280 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3281 return demuxer->stream_pts;
3282 if (mpctx->sh_video) {
3283 double pts = mpctx->video_pts;
3284 if (pts != MP_NOPTS_VALUE)
3285 return pts;
3287 double apts = playing_audio_pts(mpctx);
3288 if (apts != MP_NOPTS_VALUE)
3289 return apts;
3290 return mpctx->last_seek_pts;
3293 int get_percent_pos(struct MPContext *mpctx)
3295 struct demuxer *demuxer = mpctx->demuxer;
3296 int ans = 0;
3297 if (mpctx->timeline)
3298 ans = get_current_time(mpctx) * 100 /
3299 mpctx->timeline[mpctx->num_timeline_parts].start;
3300 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3302 else {
3303 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3304 off_t pos = demuxer->filepos > 0 ?
3305 demuxer->filepos : stream_tell(demuxer->stream);
3306 if (len > 0)
3307 ans = (pos - demuxer->movi_start) / len;
3308 else
3309 ans = 0;
3311 if (ans < 0)
3312 ans = 0;
3313 if (ans > 100)
3314 ans = 100;
3315 return ans;
3318 // -2 is no chapters, -1 is before first chapter
3319 int get_current_chapter(struct MPContext *mpctx)
3321 double current_pts = get_current_time(mpctx);
3322 if (!mpctx->chapters)
3323 return FFMAX(mpctx->last_chapter_seek,
3324 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3326 int i;
3327 for (i = 1; i < mpctx->num_chapters; i++)
3328 if (current_pts < mpctx->chapters[i].start)
3329 break;
3330 return FFMAX(mpctx->last_chapter_seek, i - 1);
3333 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3335 char *name = chapter_name(mpctx, chapter);
3336 if (name) {
3337 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3338 } else {
3339 int chapter_count = get_chapter_count(mpctx);
3340 if (chapter_count <= 0)
3341 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3342 else
3343 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3344 chapter_count);
3346 return name;
3349 // returns NULL if chapter name unavailable
3350 char *chapter_name(struct MPContext *mpctx, int chapter)
3352 if (!mpctx->chapters)
3353 return demuxer_chapter_name(mpctx->demuxer, chapter);
3354 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3357 // returns the start of the chapter in seconds
3358 double chapter_start_time(struct MPContext *mpctx, int chapter)
3360 if (!mpctx->chapters)
3361 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3362 return mpctx->chapters[chapter].start;
3365 int get_chapter_count(struct MPContext *mpctx)
3367 if (!mpctx->chapters)
3368 return demuxer_chapter_count(mpctx->demuxer);
3369 return mpctx->num_chapters;
3372 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3374 mpctx->last_chapter_seek = -2;
3375 if (!mpctx->chapters) {
3376 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3377 if (res >= 0) {
3378 if (*seek_pts == -1)
3379 seek_reset(mpctx, true, true);
3380 else {
3381 mpctx->last_chapter_seek = res;
3382 mpctx->last_chapter_pts = *seek_pts;
3385 return res;
3388 if (chapter >= mpctx->num_chapters)
3389 return -1;
3390 if (chapter < 0)
3391 chapter = 0;
3392 *seek_pts = mpctx->chapters[chapter].start;
3393 mpctx->last_chapter_seek = chapter;
3394 mpctx->last_chapter_pts = *seek_pts;
3395 return chapter;
3399 static void run_playloop(struct MPContext *mpctx)
3401 struct MPOpts *opts = &mpctx->opts;
3402 bool full_audio_buffers = false;
3403 bool audio_left = false, video_left = false;
3404 double endpts = end_at.type == END_AT_TIME ? end_at.pos : MP_NOPTS_VALUE;
3405 bool end_is_chapter = false;
3406 double sleeptime = WAKEUP_PERIOD;
3407 bool was_restart = mpctx->restart_playback;
3409 if (mpctx->timeline) {
3410 double end = mpctx->timeline[mpctx->timeline_part + 1].start;
3411 if (endpts == MP_NOPTS_VALUE || end < endpts) {
3412 endpts = end;
3413 end_is_chapter = true;
3417 if (opts->chapterrange[1] > 0) {
3418 int cur_chapter = get_current_chapter(mpctx);
3419 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3420 mpctx->stop_play = PT_NEXT_ENTRY;
3423 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3424 mpctx->sh_audio = mpctx->d_audio->sh;
3425 mpctx->sh_audio->ds = mpctx->d_audio;
3426 reinit_audio_chain(mpctx);
3429 if (mpctx->step_frames && !mpctx->sh_video) {
3430 mpctx->step_frames = 0;
3431 pause_player(mpctx);
3434 if (mpctx->sh_audio && !mpctx->restart_playback && !mpctx->ao->untimed) {
3435 int status = fill_audio_out_buffers(mpctx, endpts);
3436 full_audio_buffers = status >= 0;
3437 // Not at audio stream EOF yet
3438 audio_left = status > -2;
3441 double buffered_audio = -1;
3442 while (mpctx->sh_video) { // never loops, for "break;" only
3443 struct vo *vo = mpctx->video_out;
3444 vo_pts = mpctx->sh_video->timer * 90000.0;
3445 vo_fps = mpctx->sh_video->fps;
3447 video_left = vo->hasframe || vo->frame_loaded;
3448 if (!vo->frame_loaded && (!mpctx->paused || mpctx->restart_playback)) {
3449 double frame_time = update_video(mpctx);
3450 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3451 if (mpctx->sh_video->vf_initialized < 0) {
3452 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3453 "\nFATAL: Could not initialize video filters (-vf) "
3454 "or video output (-vo).\n");
3455 mpctx->stop_play = PT_NEXT_ENTRY;
3456 return;
3458 video_left = frame_time >= 0;
3459 if (video_left && !mpctx->restart_playback) {
3460 mpctx->time_frame += frame_time / opts->playback_speed;
3461 adjust_sync(mpctx, frame_time);
3465 if (endpts != MP_NOPTS_VALUE)
3466 video_left &= mpctx->sh_video->pts < endpts;
3468 // ================================================================
3470 current_module = "vo_check_events";
3471 vo_check_events(vo);
3473 #ifdef CONFIG_X11
3474 if (stop_xscreensaver && vo->x11)
3475 xscreensaver_heartbeat(vo->x11);
3476 #endif
3477 if (heartbeat_cmd) {
3478 static unsigned last_heartbeat;
3479 unsigned now = GetTimerMS();
3480 if (now - last_heartbeat > 30000) {
3481 last_heartbeat = now;
3482 system(heartbeat_cmd);
3486 if (!video_left || (mpctx->paused && !mpctx->restart_playback))
3487 break;
3488 if (!vo->frame_loaded) {
3489 sleeptime = 0;
3490 break;
3493 mpctx->time_frame -= get_relative_time(mpctx);
3494 if (full_audio_buffers && !mpctx->restart_playback) {
3495 buffered_audio = ao_get_delay(mpctx->ao);
3496 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", buffered_audio);
3498 if (opts->autosync) {
3499 /* Smooth reported playback position from AO by averaging
3500 * it with the value expected based on previus value and
3501 * time elapsed since then. May help smooth video timing
3502 * with audio output that have inaccurate position reporting.
3503 * This is badly implemented; the behavior of the smoothing
3504 * now undesirably depends on how often this code runs
3505 * (mainly depends on video frame rate). */
3506 float predicted = (mpctx->delay / opts->playback_speed +
3507 mpctx->time_frame);
3508 float difference = buffered_audio - predicted;
3509 buffered_audio = predicted + difference / opts->autosync;
3512 mpctx->time_frame = (buffered_audio -
3513 mpctx->delay / opts->playback_speed);
3514 } else {
3515 /* If we're more than 200 ms behind the right playback
3516 * position, don't try to speed up display of following
3517 * frames to catch up; continue with default speed from
3518 * the current frame instead.
3519 * If benchmark is set always output frames immediately
3520 * without sleeping.
3522 if (mpctx->time_frame < -0.2 || opts->benchmark)
3523 mpctx->time_frame = 0;
3526 double vsleep = mpctx->time_frame - vo->flip_queue_offset;
3527 if (vsleep > 0.050) {
3528 sleeptime = FFMIN(sleeptime, vsleep - 0.040);
3529 break;
3531 sleeptime = 0;
3533 //=================== FLIP PAGE (VIDEO BLT): ======================
3535 current_module = "flip_page";
3536 vo_new_frame_imminent(vo);
3537 struct sh_video *sh_video = mpctx->sh_video;
3538 mpctx->video_pts = sh_video->pts;
3539 update_subtitles(mpctx, sh_video->pts, false);
3540 update_teletext(sh_video, mpctx->demuxer, 0);
3541 update_osd_msg(mpctx);
3542 struct vf_instance *vf = sh_video->vfilter;
3543 mpctx->osd->sub_pts = mpctx->video_pts;
3544 if (mpctx->osd->sub_pts != MP_NOPTS_VALUE)
3545 mpctx->osd->sub_pts += sub_delay - mpctx->osd->sub_offset;
3546 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3547 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3548 vo_osd_changed(0);
3550 mpctx->time_frame -= get_relative_time(mpctx);
3551 mpctx->time_frame -= vo->flip_queue_offset;
3552 float aq_sleep_time = mpctx->time_frame;
3553 if (mpctx->time_frame > 0.001
3554 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3555 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3556 mpctx->time_frame += vo->flip_queue_offset;
3558 unsigned int t2 = GetTimer();
3559 /* Playing with playback speed it's possible to get pathological
3560 * cases with mpctx->time_frame negative enough to cause an
3561 * overflow in pts_us calculation, thus the FFMAX. */
3562 double time_frame = FFMAX(mpctx->time_frame, -1);
3563 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3564 int duration = -1;
3565 double pts2 = vo->next_pts2;
3566 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts &&
3567 !mpctx->restart_playback) {
3568 // expected A/V sync correction is ignored
3569 double diff = (pts2 - mpctx->video_pts);
3570 diff /= opts->playback_speed;
3571 if (mpctx->time_frame < 0)
3572 diff += mpctx->time_frame;
3573 if (diff < 0)
3574 diff = 0;
3575 if (diff > 10)
3576 diff = 10;
3577 duration = diff * 1e6;
3579 vo_flip_page(vo, pts_us | 1, duration);
3581 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3582 vout_time_usage += mpctx->last_vo_flip_duration;
3583 if (vo->driver->flip_page_timed) {
3584 // No need to adjust sync based on flip speed
3585 mpctx->last_vo_flip_duration = 0;
3586 // For print_status - VO call finishing early is OK for sync
3587 mpctx->time_frame -= get_relative_time(mpctx);
3589 if (mpctx->restart_playback) {
3590 mpctx->syncing_audio = true;
3591 if (mpctx->sh_audio)
3592 fill_audio_out_buffers(mpctx, endpts);
3593 mpctx->restart_playback = false;
3594 mpctx->time_frame = 0;
3595 get_relative_time(mpctx);
3597 print_status(mpctx, MP_NOPTS_VALUE, true);
3598 screenshot_flip(mpctx);
3600 if (opts->auto_quality > 0) {
3601 current_module = "autoq";
3602 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3603 ++output_quality;
3604 else if (output_quality > 1 && aq_sleep_time < 0)
3605 --output_quality;
3606 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3607 output_quality = 0;
3608 set_video_quality(mpctx->sh_video, output_quality);
3611 if (play_n_frames >= 0) {
3612 --play_n_frames;
3613 if (play_n_frames <= 0)
3614 mpctx->stop_play = PT_NEXT_ENTRY;
3616 if (mpctx->step_frames > 0) {
3617 mpctx->step_frames--;
3618 if (mpctx->step_frames == 0)
3619 pause_player(mpctx);
3621 break;
3622 } // video
3624 #ifdef CONFIG_DVDNAV
3625 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3626 nav_highlight_t hl;
3627 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3628 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3629 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3630 vo_osd_changed(OSDTYPE_DVDNAV);
3631 } else {
3632 osd_set_nav_box(0, 0, 0, 0);
3633 vo_osd_changed(OSDTYPE_DVDNAV);
3634 vo_osd_changed(OSDTYPE_SPU);
3637 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3638 double ar = -1.0;
3639 if (mpctx->sh_video &&
3640 stream_control(mpctx->demuxer->stream,
3641 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3642 != STREAM_UNSUPPORTED)
3643 mpctx->sh_video->stream_aspect = ar;
3646 #endif
3648 if (mpctx->sh_audio && (mpctx->restart_playback ? !video_left :
3649 mpctx->ao->untimed && (mpctx->delay <= 0 ||
3650 !video_left))) {
3651 int status = fill_audio_out_buffers(mpctx, endpts);
3652 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3653 // Not at audio stream EOF yet
3654 audio_left = status > -2;
3656 if (!video_left)
3657 mpctx->restart_playback = false;
3658 if (mpctx->sh_audio && buffered_audio == -1)
3659 buffered_audio = mpctx->paused ? 0 : ao_get_delay(mpctx->ao);
3661 update_osd_msg(mpctx);
3662 if (mpctx->paused)
3663 update_pause_message(mpctx);
3664 if (!video_left && (!mpctx->paused || was_restart)) {
3665 double a_pos = 0;
3666 if (mpctx->sh_audio) {
3667 a_pos = (written_audio_pts(mpctx) -
3668 mpctx->opts.playback_speed * buffered_audio);
3670 print_status(mpctx, a_pos, false);
3672 if (!mpctx->sh_video)
3673 update_subtitles(mpctx, a_pos, false);
3676 /* It's possible for the user to simultaneously switch both audio
3677 * and video streams to "disabled" at runtime. Handle this by waiting
3678 * rather than immediately stopping playback due to EOF.
3680 * When all audio has been written to output driver, stay in the
3681 * main loop handling commands until it has been mostly consumed,
3682 * except in the gapless case, where the next file will be started
3683 * while audio from the current one still remains to be played.
3685 * We want this check to trigger if we seeked to this position,
3686 * but not if we paused at it with audio possibly still buffered in
3687 * the AO. There's currently no working way to check buffered audio
3688 * inside AO while paused. Thus the "was_restart" check below, which
3689 * should trigger after seek only, when we know there's no audio
3690 * buffered.
3692 if ((mpctx->sh_audio || mpctx->sh_video) && !audio_left && !video_left
3693 && (opts->gapless_audio || buffered_audio < 0.05)
3694 && (!mpctx->paused || was_restart)) {
3695 if (end_is_chapter) {
3696 seek(mpctx, (struct seek_params){
3697 .type = MPSEEK_ABSOLUTE,
3698 .amount = mpctx->timeline[mpctx->timeline_part+1].start
3699 }, true);
3700 } else
3701 mpctx->stop_play = AT_END_OF_FILE;
3702 } else if (!mpctx->stop_play) {
3703 double audio_sleep = 9;
3704 if (mpctx->sh_audio && !mpctx->paused) {
3705 if (mpctx->ao->untimed) {
3706 if (!video_left)
3707 audio_sleep = 0;
3708 } else if (full_audio_buffers) {
3709 audio_sleep = buffered_audio - 0.050;
3710 // Keep extra safety margin if the buffers are large
3711 if (audio_sleep > 0.100)
3712 audio_sleep = FFMAX(audio_sleep - 0.200, 0.100);
3713 else
3714 audio_sleep = FFMAX(audio_sleep, 0.020);
3715 } else
3716 audio_sleep = 0.020;
3718 sleeptime = FFMIN(sleeptime, audio_sleep);
3719 if (sleeptime > 0) {
3720 if (!mpctx->sh_video)
3721 goto novideo;
3722 int hack = vo_osd_changed(0);
3723 vo_osd_changed(hack);
3724 if (hack || mpctx->video_out->want_redraw) {
3725 if (redraw_osd(mpctx) < 0) {
3726 if (mpctx->paused && video_left)
3727 add_step_frame(mpctx);
3728 else
3729 goto novideo;
3730 } else
3731 vo_osd_changed(0);
3732 } else {
3733 novideo:
3734 mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
3739 //================= Keyboard events, SEEKing ====================
3741 current_module = "key_events";
3743 mp_cmd_t *cmd;
3744 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3745 /* Allow running consecutive seek commands to combine them,
3746 * but execute the seek before running other commands.
3747 * If the user seeks continuously (keeps arrow key down)
3748 * try to finish showing a frame from one location before doing
3749 * another seek (which could lead to unchanging display). */
3750 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3751 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3752 && GetTimerMS() - mpctx->start_timestamp < 300)
3753 break;
3754 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3755 run_command(mpctx, cmd);
3756 mp_cmd_free(cmd);
3757 if (mpctx->stop_play)
3758 break;
3761 // handle -sstep
3762 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3763 mpctx->osd_function = OSD_FFW;
3764 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3767 /* Looping. */
3768 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3769 mpctx->stop_play == PT_NEXT_ENTRY)) {
3770 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3772 if (opts->loop_times > 1)
3773 opts->loop_times--;
3774 else if (opts->loop_times == 1)
3775 opts->loop_times = -1;
3776 play_n_frames = play_n_frames_mf;
3777 mpctx->stop_play = 0;
3778 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3781 if (mpctx->seek.type) {
3782 seek(mpctx, mpctx->seek, false);
3783 mpctx->seek = (struct seek_params){ 0 };
3788 static int read_keys(void *ctx, int fd)
3790 if (getch2(ctx))
3791 return MP_INPUT_NOTHING;
3792 return MP_INPUT_DEAD;
3795 static bool attachment_is_font(struct demux_attachment *att)
3797 if (!att->name || !att->type || !att->data || !att->data_size)
3798 return false;
3799 // match against MIME types
3800 if (strcmp(att->type, "application/x-truetype-font") == 0
3801 || strcmp(att->type, "application/x-font") == 0)
3802 return true;
3803 // fallback: match against file extension
3804 if (strlen(att->name) > 4) {
3805 char *ext = att->name + strlen(att->name) - 4;
3806 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3807 || strcasecmp(ext, ".otf") == 0)
3808 return true;
3810 return false;
3813 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3815 if (audio_id == -1)
3816 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3817 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3818 demuxer_switch_audio(demuxer, audio_id);
3819 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3820 demuxer->audio->id = -2;
3821 demuxer->audio->sh = NULL;
3823 return demuxer->audio->id;
3826 static void print_version(const char *name)
3828 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3830 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3831 GetCpuCaps(&gCpuCaps);
3832 #if ARCH_X86
3833 mp_msg(MSGT_CPLAYER, MSGL_V,
3834 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3835 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3836 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3837 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3838 #if CONFIG_RUNTIME_CPUDETECT
3839 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3840 #else
3841 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3842 if (HAVE_MMX)
3843 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3844 if (HAVE_MMX2)
3845 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3846 if (HAVE_AMD3DNOW)
3847 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3848 if (HAVE_AMD3DNOWEXT)
3849 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3850 if (HAVE_SSE)
3851 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3852 if (HAVE_SSE2)
3853 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3854 if (HAVE_SSSE3)
3855 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3856 if (HAVE_CMOV)
3857 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3858 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3859 #endif /* CONFIG_RUNTIME_CPUDETECT */
3860 #endif /* ARCH_X86 */
3861 print_libav_versions();
3864 #ifdef PTW32_STATIC_LIB
3865 static void detach_ptw32(void)
3867 pthread_win32_thread_detach_np();
3868 pthread_win32_process_detach_np();
3870 #endif
3872 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3873 * file for some tools to link against. */
3874 #ifndef DISABLE_MAIN
3875 int main(int argc, char *argv[])
3877 #ifdef PTW32_STATIC_LIB
3878 pthread_win32_process_attach_np();
3879 pthread_win32_thread_attach_np();
3880 atexit(detach_ptw32);
3881 #endif
3882 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3883 || !strcmp(argv[1], "--leak-report")))
3884 talloc_enable_leak_report();
3886 #ifdef __MINGW32__
3887 mp_get_converted_argv(&argc, &argv);
3888 #endif
3890 char *mem_ptr;
3892 // movie info:
3894 /* Flag indicating whether MPlayer should exit without playing anything. */
3895 int opt_exit = 0;
3896 int i;
3898 struct MPContext *mpctx = talloc(NULL, MPContext);
3899 *mpctx = (struct MPContext){
3900 .osd_function = OSD_PLAY,
3901 .begin_skip = MP_NOPTS_VALUE,
3902 .play_tree_step = 1,
3903 .global_sub_pos = -1,
3904 .set_of_sub_pos = -1,
3905 .file_format = DEMUXER_TYPE_UNKNOWN,
3906 .last_dvb_step = 1,
3907 .paused_cache_fill = -1,
3910 InitTimer();
3911 srand(GetTimerMS());
3913 mp_msg_init();
3914 init_libav();
3916 struct MPOpts *opts = &mpctx->opts;
3917 set_default_mplayer_options(opts);
3918 // Create the config context and register the options
3919 mpctx->mconfig = m_config_new(opts, cfg_include);
3920 m_config_register_options(mpctx->mconfig, mplayer_opts);
3921 m_config_register_options(mpctx->mconfig, common_opts);
3922 mp_input_register_options(mpctx->mconfig);
3923 m_config_initialize(mpctx->mconfig, opts);
3925 // Preparse the command line
3926 m_config_preparse_command_line(mpctx->mconfig, argc, argv, &verbose);
3928 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3929 set_path_env();
3930 #endif
3932 #ifdef CONFIG_TV
3933 stream_tv_defaults.immediate = 1;
3934 #endif
3936 parse_cfgfiles(mpctx, mpctx->mconfig);
3938 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3939 if (mpctx->playtree == NULL)
3940 opt_exit = 1;
3941 else {
3942 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3943 if (mpctx->playtree) {
3944 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3945 mpctx->mconfig);
3946 if (mpctx->playtree_iter) {
3947 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3948 PLAY_TREE_ITER_ENTRY) {
3949 play_tree_iter_free(mpctx->playtree_iter);
3950 mpctx->playtree_iter = NULL;
3952 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3958 print_version("MPlayer2");
3960 #if defined(__MINGW32__) || defined(__CYGWIN__)
3962 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3963 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3964 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3965 if (kernel32) {
3966 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3967 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3969 if (setDEP)
3970 setDEP(3);
3971 if (setDllDir)
3972 setDllDir("");
3974 // stop Windows from showing all kinds of annoying error dialogs
3975 SetErrorMode(0x8003);
3976 // request 1ms timer resolution
3977 timeBeginPeriod(1);
3978 #endif
3980 #ifdef CONFIG_PRIORITY
3981 set_priority();
3982 #endif
3984 if (opts->video_driver_list &&
3985 strcmp(opts->video_driver_list[0], "help") == 0) {
3986 list_video_out();
3987 opt_exit = 1;
3990 if (opts->audio_driver_list &&
3991 strcmp(opts->audio_driver_list[0], "help") == 0) {
3992 list_audio_out();
3993 opt_exit = 1;
3996 /* Check codecs.conf. */
3997 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
3998 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
3999 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4000 if (!parse_codec_cfg(NULL))
4001 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4002 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4003 "Using built-in default codecs.conf.\n");
4006 free(mem_ptr); // release the buffer created by get_path()
4009 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4010 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4011 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4012 list_codecs(1);
4013 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4014 opt_exit = 1;
4016 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4017 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4018 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4019 list_codecs(0);
4020 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4021 opt_exit = 1;
4023 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4024 vfm_help();
4025 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4026 opt_exit = 1;
4028 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4029 afm_help();
4030 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4031 opt_exit = 1;
4033 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4034 af_help();
4035 printf("\n");
4036 opt_exit = 1;
4038 #ifdef CONFIG_X11
4039 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4040 fstype_help();
4041 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4042 opt_exit = 1;
4044 #endif
4045 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4046 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4047 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4048 demuxer_help();
4049 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4050 opt_exit = 1;
4052 if (opts->list_properties) {
4053 property_print_help();
4054 opt_exit = 1;
4057 if (opt_exit)
4058 exit_player(mpctx, EXIT_NONE);
4060 if (!mpctx->filename && !opts->player_idle_mode) {
4061 // no file/vcd/dvd -> show HELP:
4062 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4063 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4066 /* Display what configure line was used */
4067 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4069 // Many users forget to include command line in bugreports...
4070 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4071 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4072 for (i = 1; i < argc; i++)
4073 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4074 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4077 //------ load global data first ------
4079 #ifdef CONFIG_ASS
4080 mpctx->ass_library = mp_ass_init(opts);
4081 #endif
4083 mpctx->osd = osd_create(opts, mpctx->ass_library);
4085 #ifdef HAVE_RTC
4086 if (opts->rtc) {
4087 char *rtc_device = opts->rtc_device;
4088 // seteuid(0); /* Can't hurt to try to get root here */
4089 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4090 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4091 "(it should be readable by the user.)\n",
4092 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4093 else {
4094 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4096 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4097 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4098 "ioctl (rtc_irqp_set %lu): %s\n",
4099 irqp, strerror(errno));
4100 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4101 close(rtc_fd);
4102 rtc_fd = -1;
4103 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4104 /* variable only by the root */
4105 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4106 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4107 close(rtc_fd);
4108 rtc_fd = -1;
4109 } else
4110 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4111 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4114 if (rtc_fd < 0)
4115 #endif /* HAVE_RTC */
4116 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4117 opts->softsleep ? "software" : timer_name);
4119 #ifdef HAVE_TERMCAP
4120 load_termcap(NULL); // load key-codes
4121 #endif
4123 // ========== Init keyboard FIFO (connection to libvo) ============
4125 // Init input system
4126 current_module = "init_input";
4127 mpctx->input = mp_input_init(&opts->input);
4128 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4129 if (slave_mode)
4130 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4131 else if (opts->consolecontrols)
4132 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4133 // Set the libstream interrupt callback
4134 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4136 current_module = NULL;
4138 /// Catch signals
4139 #ifndef __MINGW32__
4140 signal(SIGCHLD, child_sighandler);
4141 #endif
4143 #ifdef CONFIG_CRASH_DEBUG
4144 prog_path = argv[0];
4145 #endif
4146 //========= Catch terminate signals: ================
4147 // terminate requests:
4148 signal(SIGTERM, exit_sighandler); // kill
4149 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4151 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4153 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4154 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4155 #ifdef CONFIG_SIGHANDLER
4156 // fatal errors:
4157 signal(SIGBUS, exit_sighandler); // bus error
4158 signal(SIGSEGV, exit_sighandler); // segfault
4159 signal(SIGILL, exit_sighandler); // illegal instruction
4160 signal(SIGFPE, exit_sighandler); // floating point exc.
4161 signal(SIGABRT, exit_sighandler); // abort()
4162 #ifdef CONFIG_CRASH_DEBUG
4163 if (crash_debug)
4164 signal(SIGTRAP, exit_sighandler);
4165 #endif
4166 #endif
4168 // ***************** Now, let's see the per-file stuff ******************
4170 play_next_file:
4172 // init global sub numbers
4173 mpctx->global_sub_size = 0;
4174 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4176 if (mpctx->filename) {
4177 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4178 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4179 load_per_file_config(mpctx->mconfig, mpctx->filename);
4182 if (opts->video_driver_list)
4183 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4184 opts->video_driver_list[0]);
4185 if (opts->audio_driver_list)
4186 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4187 opts->audio_driver_list[0]);
4189 // We must enable getch2 here to be able to interrupt network connection
4190 // or cache filling
4191 if (opts->consolecontrols && !slave_mode) {
4192 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4193 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4194 "WARNING: getch2_init called twice!\n");
4195 else
4196 getch2_enable(); // prepare stdin for hotkeys...
4197 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4198 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4201 // ================= idle loop (STOP state) =========================
4202 while (opts->player_idle_mode && !mpctx->filename) {
4203 uninit_player(mpctx, INITIALIZED_AO | INITIALIZED_VO);
4204 play_tree_t *entry = NULL;
4205 mp_cmd_t *cmd;
4206 while (!(cmd = mp_input_get_cmd(mpctx->input, WAKEUP_PERIOD * 1000,
4207 false)));
4208 switch (cmd->id) {
4209 case MP_CMD_LOADFILE:
4210 // prepare a tree entry with the new filename
4211 entry = play_tree_new();
4212 play_tree_add_file(entry, cmd->args[0].v.s);
4213 // The entry is added to the main playtree after the switch().
4214 break;
4215 case MP_CMD_LOADLIST:
4216 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4217 break;
4218 case MP_CMD_QUIT:
4219 exit_player_with_rc(mpctx, EXIT_QUIT,
4220 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4221 break;
4222 case MP_CMD_VO_FULLSCREEN:
4223 case MP_CMD_GET_PROPERTY:
4224 case MP_CMD_SET_PROPERTY:
4225 case MP_CMD_STEP_PROPERTY:
4226 run_command(mpctx, cmd);
4227 break;
4230 mp_cmd_free(cmd);
4232 if (entry) { // user entered a command that gave a valid entry
4233 if (mpctx->playtree)
4234 // the playtree is always a node with one child. let's clear it
4235 play_tree_free_list(mpctx->playtree->child, 1);
4236 else
4237 // .. or make a brand new playtree
4238 mpctx->playtree = play_tree_new();
4240 if (!mpctx->playtree)
4241 continue; // couldn't make playtree! wait for next command
4243 play_tree_set_child(mpctx->playtree, entry);
4245 /* Make iterator start at the top the of tree. */
4246 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4247 mpctx->mconfig);
4248 if (!mpctx->playtree_iter)
4249 continue;
4251 // find the first real item in the tree
4252 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4253 PLAY_TREE_ITER_ENTRY) {
4254 // no items!
4255 play_tree_iter_free(mpctx->playtree_iter);
4256 mpctx->playtree_iter = NULL;
4257 continue; // wait for next command
4259 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4263 #ifdef CONFIG_ASS
4264 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4265 #endif
4266 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4267 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4269 if (mpctx->filename) {
4270 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4271 filename_recode(mpctx->filename));
4272 if (use_filename_title && opts->vo_wintitle == NULL)
4273 opts->vo_wintitle = talloc_strdup(NULL,
4274 mp_basename(mpctx->filename));
4277 if (edl_output_filename) {
4278 if (edl_fd)
4279 fclose(edl_fd);
4280 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4281 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4282 "Can't open EDL file [%s] for writing.\n",
4283 filename_recode(edl_output_filename));
4287 //==================== Open VOB-Sub ============================
4289 current_module = "vobsub";
4290 if (opts->vobsub_name) {
4291 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4292 if (vo_vobsub == NULL)
4293 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4294 filename_recode(opts->vobsub_name));
4295 } else if (opts->sub_auto && mpctx->filename) {
4296 char **vob = find_vob_subtitles(opts, mpctx->filename);
4297 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4298 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4299 if (vo_vobsub)
4300 break;
4302 talloc_free(vob);
4304 if (vo_vobsub) {
4305 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4306 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4307 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4308 mpctx);
4310 // setup global sub numbering
4311 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4312 vobsub_get_indexes_count(vo_vobsub);
4315 //============ Open & Sync STREAM --- fork cache2 ====================
4317 mpctx->stream = NULL;
4318 mpctx->demuxer = NULL;
4319 mpctx->d_audio = NULL;
4320 mpctx->d_video = NULL;
4321 mpctx->d_sub = NULL;
4322 mpctx->sh_audio = NULL;
4323 mpctx->sh_video = NULL;
4325 current_module = "open_stream";
4326 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4327 if (!mpctx->stream) { // error...
4328 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4329 goto goto_next_file;
4331 mpctx->initialized_flags |= INITIALIZED_STREAM;
4333 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4334 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4335 "playlist support will not be used automatically.\n"
4336 "MPlayer's playlist code is unsafe and should only be used with "
4337 "trusted sources.\nPlayback will probably fail.\n\n");
4338 #if 0
4339 play_tree_t *entry;
4340 // Handle playlist
4341 current_module = "handle_playlist";
4342 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4343 filename_recode(mpctx->filename));
4344 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4345 mpctx->eof = playtree_add_playlist(mpctx, entry);
4346 goto goto_next_file;
4347 #endif
4349 mpctx->stream->start_pos += seek_to_byte;
4351 if (stream_dump_type == 5) {
4352 unsigned char buf[4096];
4353 int len;
4354 FILE *f;
4355 current_module = "dumpstream";
4356 stream_reset(mpctx->stream);
4357 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4358 f = fopen(opts->stream_dump_name, "wb");
4359 if (!f) {
4360 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4361 exit_player(mpctx, EXIT_ERROR);
4363 if (opts->chapterrange[0] > 1) {
4364 int chapter = opts->chapterrange[0] - 1;
4365 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4367 struct stream_dump_progress info;
4368 stream_dump_progress_start(&info);
4369 while (!mpctx->stream->eof && !async_quit_request) {
4370 len = stream_read(mpctx->stream, buf, 4096);
4371 if (len > 0) {
4372 if (fwrite(buf, len, 1, f) != 1) {
4373 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4374 exit_player(mpctx, EXIT_ERROR);
4377 stream_dump_progress(&info, len, mpctx->stream);
4378 if (opts->chapterrange[1] > 0) {
4379 int chapter = -1;
4380 if (stream_control(mpctx->stream,
4381 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4382 && chapter + 1 > opts->chapterrange[1])
4383 break;
4386 if (fclose(f)) {
4387 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4388 opts->stream_dump_name);
4389 exit_player(mpctx, EXIT_ERROR);
4391 stream_dump_progress_end(&info, opts->stream_dump_name);
4392 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4393 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4396 #ifdef CONFIG_DVDREAD
4397 if (mpctx->stream->type == STREAMTYPE_DVD) {
4398 current_module = "dvd lang->id";
4399 if (opts->audio_lang && opts->audio_id == -1)
4400 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4401 if (opts->sub_lang && opts->sub_id == -1)
4402 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4403 // setup global sub numbering
4404 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4405 current_module = NULL;
4407 #endif
4409 #ifdef CONFIG_DVDNAV
4410 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4411 current_module = "dvdnav lang->id";
4412 if (opts->audio_lang && opts->audio_id == -1)
4413 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4414 opts->audio_lang);
4415 dvdsub_lang_id = -3;
4416 if (opts->sub_lang && opts->sub_id == -1)
4417 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4418 mpctx->stream, opts->sub_lang);
4419 // setup global sub numbering
4420 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4421 mpctx->stream);
4422 current_module = NULL;
4424 #endif
4426 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4427 goto_enable_cache:
4428 if (opts->stream_cache_size > 0) {
4429 int res;
4430 current_module = "enable_cache";
4431 res = stream_enable_cache_percent(mpctx->stream,
4432 opts->stream_cache_size,
4433 opts->stream_cache_min_percent,
4434 opts->stream_cache_seek_min_percent);
4435 if (res == 0)
4436 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4437 goto goto_next_file;
4440 //============ Open DEMUXERS --- DETECT file type =======================
4441 current_module = "demux_open";
4443 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4444 opts->audio_id, opts->video_id, opts->sub_id,
4445 mpctx->filename);
4447 // HACK to get MOV Reference Files working
4449 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4450 unsigned char *playlist_entry;
4451 play_tree_t *list = NULL, *entry = NULL;
4453 current_module = "handle_demux_playlist";
4454 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4455 char *temp;
4456 const char *bname;
4458 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4459 filename_recode(playlist_entry));
4461 bname = mp_basename(playlist_entry);
4462 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4463 !strncmp(bname + 3, "gateQT", 6))
4464 continue;
4466 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4467 continue;
4469 entry = play_tree_new();
4471 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4472 playlist_entry)) { // add reference path of current file
4473 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4474 mpctx->filename)) + strlen(playlist_entry) + 1));
4475 if (temp) {
4476 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4477 strlen(mp_basename(mpctx->filename)));
4478 temp[strlen(mpctx->filename) - strlen(mp_basename(
4479 mpctx->filename))] = '\0';
4480 strcat(temp, playlist_entry);
4481 if (!strcmp(temp, mpctx->filename)) {
4482 free(temp);
4483 continue;
4485 play_tree_add_file(entry, temp);
4486 mp_msg(MSGT_CPLAYER, MSGL_V,
4487 "Resolving reference to %s.\n", temp);
4488 free(temp);
4490 } else
4491 play_tree_add_file(entry, playlist_entry);
4493 if (!list)
4494 list = entry;
4495 else
4496 play_tree_append_entry(list, entry);
4498 free_demuxer(mpctx->demuxer);
4499 mpctx->demuxer = NULL;
4501 if (list) {
4502 entry = play_tree_new();
4503 play_tree_set_child(entry, list);
4504 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4505 goto goto_next_file;
4509 if (!mpctx->demuxer) {
4510 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4511 goto goto_next_file;
4514 if (mpctx->demuxer->matroska_data.ordered_chapters)
4515 build_ordered_chapter_timeline(mpctx);
4517 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4518 build_edl_timeline(mpctx);
4520 if (mpctx->timeline) {
4521 mpctx->timeline_part = 0;
4522 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4524 int part_count = mpctx->num_timeline_parts;
4525 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4526 "sources. Total length %.3f seconds.\n", part_count,
4527 mpctx->num_sources, mpctx->timeline[part_count].start);
4528 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4529 for (int i = 0; i < mpctx->num_sources; i++)
4530 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4531 filename_recode(mpctx->sources[i].demuxer->filename));
4532 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4533 "source_start, source):\n");
4534 for (int i = 0; i < part_count; i++) {
4535 struct timeline_part *p = mpctx->timeline + i;
4536 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4537 p->source_start, p->source - mpctx->sources);
4539 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4540 mpctx->timeline[part_count].start);
4543 if (!mpctx->sources) {
4544 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4545 *mpctx->sources = (struct content_source){
4546 .stream = mpctx->stream,
4547 .demuxer = mpctx->demuxer
4549 mpctx->num_sources = 1;
4552 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4554 #ifdef CONFIG_ASS
4555 if (opts->ass_enabled) {
4556 for (int j = 0; j < mpctx->num_sources; j++) {
4557 struct demuxer *d = mpctx->sources[j].demuxer;
4558 for (int i = 0; i < d->num_attachments; i++) {
4559 struct demux_attachment *att = d->attachments + i;
4560 if (opts->use_embedded_fonts && attachment_is_font(att))
4561 ass_add_font(mpctx->ass_library, att->name, att->data,
4562 att->data_size);
4566 /* libass seems to misbehave if fonts are changed while a renderer
4567 * exists, so we (re)create the renderer after fonts are set.
4569 assert(!mpctx->osd->ass_renderer);
4570 mpctx->osd->ass_renderer = ass_renderer_init(mpctx->osd->ass_library);
4571 if (!mpctx->osd->ass_renderer) {
4572 mp_msg(MSGT_OSD, MSGL_FATAL, "Failed to create libass renderer\n");
4573 exit_player(mpctx, EXIT_ERROR);
4575 mp_ass_configure_fonts(mpctx->osd->ass_renderer);
4576 #endif
4578 current_module = "demux_open2";
4580 mpctx->d_audio = mpctx->demuxer->audio;
4581 mpctx->d_video = mpctx->demuxer->video;
4582 mpctx->d_sub = mpctx->demuxer->sub;
4584 if (ts_prog) {
4585 int tmp = ts_prog;
4586 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4588 // select audio stream
4589 for (int i = 0; i < mpctx->num_sources; i++)
4590 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4591 opts->audio_lang);
4593 // DUMP STREAMS:
4594 if ((stream_dump_type) && (stream_dump_type < 4)) {
4595 FILE *f;
4596 demux_stream_t *ds = NULL;
4597 current_module = "dump";
4598 // select stream to dump
4599 switch (stream_dump_type) {
4600 case 1: ds = mpctx->d_audio;
4601 break;
4602 case 2: ds = mpctx->d_video;
4603 break;
4604 case 3: ds = mpctx->d_sub;
4605 break;
4607 if (!ds) {
4608 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4609 "dump: FATAL: Selected stream missing!\n");
4610 exit_player(mpctx, EXIT_ERROR);
4612 // disable other streams:
4613 if (mpctx->d_audio && mpctx->d_audio != ds) {
4614 ds_free_packs(mpctx->d_audio);
4615 mpctx->d_audio->id = -2;
4617 if (mpctx->d_video && mpctx->d_video != ds) {
4618 ds_free_packs(mpctx->d_video);
4619 mpctx->d_video->id = -2;
4621 if (mpctx->d_sub && mpctx->d_sub != ds) {
4622 ds_free_packs(mpctx->d_sub);
4623 mpctx->d_sub->id = -2;
4625 // let's dump it!
4626 f = fopen(opts->stream_dump_name, "wb");
4627 if (!f) {
4628 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4629 exit_player(mpctx, EXIT_ERROR);
4631 struct stream_dump_progress info;
4632 stream_dump_progress_start(&info);
4633 while (!ds->eof) {
4634 unsigned char *start;
4635 int in_size = ds_get_packet(ds, &start);
4636 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4637 && stream_dump_type == 2)
4638 fwrite(&in_size, 1, 4, f);
4639 if (in_size > 0) {
4640 fwrite(start, in_size, 1, f);
4641 stream_dump_progress(&info, in_size, mpctx->stream);
4643 if (opts->chapterrange[1] > 0) {
4644 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4645 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4646 break;
4649 fclose(f);
4650 stream_dump_progress_end(&info, opts->stream_dump_name);
4651 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4652 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4655 mpctx->sh_audio = mpctx->d_audio->sh;
4656 mpctx->sh_video = mpctx->d_video->sh;
4658 if (mpctx->sh_video) {
4659 current_module = "video_read_properties";
4660 if (!video_read_properties(mpctx->sh_video)) {
4661 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4662 mpctx->sh_video = mpctx->d_video->sh = NULL;
4663 } else {
4664 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4665 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4666 mpctx->demuxer->file_format, mpctx->sh_video->format,
4667 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4668 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4669 if (force_fps) {
4670 mpctx->sh_video->fps = force_fps;
4671 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4673 vo_fps = mpctx->sh_video->fps;
4675 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4676 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4677 "header or invalid, use the -fps option.\n");
4683 if (!mpctx->sh_video && !mpctx->sh_audio) {
4684 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4685 #ifdef CONFIG_DVBIN
4686 if (mpctx->stream->type == STREAMTYPE_DVB) {
4687 int dir;
4688 int v = mpctx->last_dvb_step;
4689 if (v > 0)
4690 dir = DVB_CHANNEL_HIGHER;
4691 else
4692 dir = DVB_CHANNEL_LOWER;
4694 if (dvb_step_channel(mpctx->stream, dir)) {
4695 mpctx->stop_play = PT_NEXT_ENTRY;
4696 mpctx->dvbin_reopen = 1;
4699 #endif
4700 goto goto_next_file; // exit_player(_("Fatal error"));
4703 /* display clip info */
4704 demux_info_print(mpctx->demuxer);
4706 //================= Read SUBTITLES (DVD & TEXT) =========================
4707 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4708 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4709 init_vo_spudec(mpctx);
4711 // after reading video params we should load subtitles because
4712 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4713 // check .sub
4714 current_module = "read_subtitles_file";
4715 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4716 if (opts->sub_name) {
4717 for (i = 0; opts->sub_name[i] != NULL; ++i)
4718 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4720 if (opts->sub_auto) { // auto load sub file ...
4721 char **tmp = find_text_subtitles(opts, mpctx->filename);
4722 int nsub = MP_TALLOC_ELEMS(tmp);
4723 for (int i = 0; i < nsub; i++)
4724 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4725 talloc_free(tmp);
4727 if (mpctx->set_of_sub_size > 0)
4728 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4730 if (select_subtitle(mpctx)) {
4731 if (mpctx->subdata)
4732 switch (stream_dump_type) {
4733 case 3: list_sub_file(mpctx->subdata);
4734 break;
4735 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4736 break;
4737 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4738 break;
4739 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4740 break;
4741 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4742 break;
4743 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4744 break;
4748 print_file_properties(mpctx, mpctx->filename);
4750 reinit_video_chain(mpctx);
4751 if (!mpctx->sh_video && !mpctx->sh_audio)
4752 goto goto_next_file;
4754 //================== MAIN: ==========================
4755 current_module = "main";
4757 if (opts->playing_msg) {
4758 char *msg = property_expand_string(mpctx, opts->playing_msg);
4759 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4760 free(msg);
4764 // Disable the term OSD in verbose mode
4765 if (verbose)
4766 opts->term_osd = 0;
4768 // Make sure old OSD does not stay around
4769 clear_osd_msgs();
4771 //================ SETUP AUDIO ==========================
4773 if (mpctx->sh_audio) {
4774 reinit_audio_chain(mpctx);
4775 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4776 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4777 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4780 current_module = "av_init";
4782 if (mpctx->sh_video) {
4783 mpctx->sh_video->timer = 0;
4784 if (!ignore_start)
4785 audio_delay += mpctx->sh_video->stream_delay;
4787 if (mpctx->sh_audio) {
4788 if (start_volume >= 0)
4789 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4790 if (!ignore_start)
4791 audio_delay -= mpctx->sh_audio->stream_delay;
4794 if (!mpctx->sh_audio) {
4795 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4796 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4797 mpctx->d_audio->packs);
4798 ds_free_packs(mpctx->d_audio); // free buffered chunks
4800 if (!mpctx->sh_video) {
4801 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4802 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4803 mpctx->d_video->packs);
4804 ds_free_packs(mpctx->d_video);
4805 mpctx->d_video->id = -2;
4808 if (!mpctx->sh_video && !mpctx->sh_audio)
4809 goto goto_next_file;
4811 if (force_fps && mpctx->sh_video) {
4812 vo_fps = mpctx->sh_video->fps = force_fps;
4813 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4814 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4815 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4816 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4819 mp_input_set_section(mpctx->input, NULL);
4820 //TODO: add desired (stream-based) sections here
4821 if (mpctx->stream->type == STREAMTYPE_TV)
4822 mp_input_set_section(mpctx->input, "tv");
4823 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4824 mp_input_set_section(mpctx->input, "dvdnav");
4826 //==================== START PLAYING =======================
4828 if (opts->loop_times > 1)
4829 opts->loop_times--;
4830 else if (opts->loop_times == 1)
4831 opts->loop_times = -1;
4833 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4835 total_time_usage_start = GetTimer();
4836 audio_time_usage = 0;
4837 video_time_usage = 0;
4838 vout_time_usage = 0;
4839 total_frame_cnt = 0;
4840 drop_frame_cnt = 0; // fix for multifile fps benchmark
4841 play_n_frames = play_n_frames_mf;
4843 if (play_n_frames == 0) {
4844 mpctx->stop_play = PT_NEXT_ENTRY;
4845 goto goto_next_file;
4848 mpctx->time_frame = 0;
4849 mpctx->drop_message_shown = 0;
4850 mpctx->restart_playback = true;
4851 mpctx->video_pts = 0;
4852 mpctx->last_seek_pts = 0;
4853 mpctx->hrseek_active = false;
4854 mpctx->hrseek_framedrop = false;
4855 mpctx->step_frames = 0;
4856 mpctx->total_avsync_change = 0;
4857 mpctx->last_chapter_seek = -2;
4859 // If there's a timeline force an absolute seek to initialize state
4860 if (opts->seek_to_sec || mpctx->timeline) {
4861 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4862 seek(mpctx, mpctx->seek, false);
4863 end_at.pos += opts->seek_to_sec;
4865 if (opts->chapterrange[0] > 0) {
4866 double pts;
4867 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4868 && pts > -1.0) {
4869 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4870 seek(mpctx, mpctx->seek, false);
4874 if (end_at.type == END_AT_SIZE) {
4875 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4876 "Option -endpos in MPlayer does not yet support size units.\n");
4877 end_at.type = END_AT_NONE;
4880 #ifdef CONFIG_DVDNAV
4881 mp_dvdnav_context_free(mpctx);
4882 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4883 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4884 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4886 #endif
4888 mpctx->seek = (struct seek_params){ 0 };
4889 get_relative_time(mpctx); // reset current delta
4890 // Make sure VO knows current pause state
4891 if (mpctx->sh_video)
4892 vo_control(mpctx->video_out,
4893 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4895 while (!mpctx->stop_play)
4896 run_playloop(mpctx);
4898 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4900 #ifdef CONFIG_DVBIN
4901 if (mpctx->dvbin_reopen) {
4902 mpctx->stop_play = 0;
4903 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4904 cache_uninit(mpctx->stream);
4905 mpctx->dvbin_reopen = 0;
4906 goto goto_enable_cache;
4908 #endif
4910 goto_next_file: // don't jump here after ao/vo/getch initialization!
4912 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4914 if (opts->benchmark) {
4915 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4916 double total_time_usage;
4917 total_time_usage_start = GetTimer() - total_time_usage_start;
4918 total_time_usage = (float)total_time_usage_start * 0.000001;
4919 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4920 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4921 video_time_usage, vout_time_usage, audio_time_usage,
4922 total_time_usage - tot, total_time_usage);
4923 if (total_time_usage > 0.0)
4924 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4925 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4926 100.0 * video_time_usage / total_time_usage,
4927 100.0 * vout_time_usage / total_time_usage,
4928 100.0 * audio_time_usage / total_time_usage,
4929 100.0 * (total_time_usage - tot) / total_time_usage,
4930 100.0);
4931 if (total_frame_cnt && frame_dropping)
4932 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4933 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4934 total_frame_cnt - drop_frame_cnt,
4935 (total_time_usage > 0.5) ? ((total_frame_cnt -
4936 drop_frame_cnt) / total_time_usage) : 0,
4937 drop_frame_cnt,
4938 100 * drop_frame_cnt / total_frame_cnt,
4939 total_frame_cnt,
4940 (total_time_usage > 0.5) ?
4941 (total_frame_cnt / total_time_usage) : 0);
4944 // time to uninit all, except global stuff:
4945 int uninitialize_parts = INITIALIZED_ALL;
4946 if (opts->fixed_vo)
4947 uninitialize_parts -= INITIALIZED_VO;
4948 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4949 uninitialize_parts -= INITIALIZED_AO;
4950 uninit_player(mpctx, uninitialize_parts);
4952 if (mpctx->set_of_sub_size > 0) {
4953 current_module = "sub_free";
4954 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
4955 sub_free(mpctx->set_of_subtitles[i]);
4956 talloc_free(mpctx->set_of_ass_tracks[i]);
4958 mpctx->set_of_sub_size = 0;
4960 mpctx->vo_sub_last = vo_sub = NULL;
4961 mpctx->subdata = NULL;
4962 #ifdef CONFIG_ASS
4963 if (mpctx->osd->ass_renderer)
4964 ass_renderer_done(mpctx->osd->ass_renderer);
4965 mpctx->osd->ass_renderer = NULL;
4966 ass_clear_fonts(mpctx->ass_library);
4967 #endif
4969 if (!mpctx->stop_play) // In case some goto jumped here...
4970 mpctx->stop_play = PT_NEXT_ENTRY;
4972 int playtree_direction = 1;
4974 if (mpctx->stop_play == PT_NEXT_ENTRY
4975 || mpctx->stop_play == PT_PREV_ENTRY) {
4976 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
4977 != PLAY_TREE_ITER_ENTRY) {
4978 play_tree_iter_free(mpctx->playtree_iter);
4979 mpctx->playtree_iter = NULL;
4981 mpctx->play_tree_step = 1;
4982 } else if (mpctx->stop_play == PT_UP_NEXT ||
4983 mpctx->stop_play == PT_UP_PREV) {
4984 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4985 if (mpctx->playtree_iter) {
4986 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
4987 PLAY_TREE_ITER_ENTRY) {
4988 play_tree_iter_free(mpctx->playtree_iter);
4989 mpctx->playtree_iter = NULL;
4992 } else if (mpctx->stop_play == PT_STOP) {
4993 play_tree_iter_free(mpctx->playtree_iter);
4994 mpctx->playtree_iter = NULL;
4995 } else // NEXT PREV SRC
4996 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4998 while (mpctx->playtree_iter != NULL) {
4999 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5000 playtree_direction);
5001 if (mpctx->filename == NULL) {
5002 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5003 0) != PLAY_TREE_ITER_ENTRY) {
5004 play_tree_iter_free(mpctx->playtree_iter);
5005 mpctx->playtree_iter = NULL;
5008 } else
5009 break;
5012 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5013 if (!mpctx->playtree_iter)
5014 mpctx->filename = NULL;
5015 mpctx->stop_play = 0;
5016 goto play_next_file;
5019 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5021 return 1;
5023 #endif /* DISABLE_MAIN */