mixer: reindent/cosmetic changes
[mplayer.git] / mplayer.c
blob76c2001c6903778c773baf9b152cdb92f016e832
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 #endif
35 #include <string.h>
36 #include <unistd.h>
38 // #include <sys/mman.h>
39 #include <sys/types.h>
40 #ifndef __MINGW32__
41 #include <sys/ioctl.h>
42 #include <sys/wait.h>
43 #else
44 #define SIGHUP 1 /* hangup */
45 #define SIGQUIT 3 /* quit */
46 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
47 #define SIGBUS 10 /* bus error */
48 #define SIGPIPE 13 /* broken pipe */
49 #endif
51 #include <sys/time.h>
52 #include <sys/stat.h>
54 #include <signal.h>
55 #include <time.h>
56 #include <fcntl.h>
57 #include <limits.h>
59 #include <errno.h>
61 #include "mp_msg.h"
62 #include "av_log.h"
65 #include "m_option.h"
66 #include "m_config.h"
67 #include "mplayer.h"
68 #include "m_property.h"
70 #include "sub/subreader.h"
71 #include "sub/find_subfiles.h"
72 #include "sub/dec_sub.h"
74 #include "mp_osd.h"
75 #include "libvo/video_out.h"
76 #include "screenshot.h"
78 #include "sub/font_load.h"
79 #include "sub/sub.h"
80 #include "sub/av_sub.h"
81 #include "libmpcodecs/dec_teletext.h"
82 #include "cpudetect.h"
83 #include "version.h"
85 #ifdef CONFIG_X11
86 #include "libvo/x11_common.h"
87 #endif
89 #include "libao2/audio_out.h"
91 #include "codec-cfg.h"
93 #include "sub/spudec.h"
94 #include "sub/vobsub.h"
96 #include "osdep/getch2.h"
97 #include "osdep/timer.h"
99 #include "input/input.h"
101 int slave_mode = 0;
102 int enable_mouse_movements = 0;
103 float start_volume = -1;
105 #include "osdep/priority.h"
107 char *heartbeat_cmd;
109 #ifdef HAVE_RTC
110 #ifdef __linux__
111 #include <linux/rtc.h>
112 #else
113 #include <rtc.h>
114 #define RTC_IRQP_SET RTCIO_IRQP_SET
115 #define RTC_PIE_ON RTCIO_PIE_ON
116 #endif /* __linux__ */
117 #endif /* HAVE_RTC */
119 #include "stream/tv.h"
120 #include "stream/stream_radio.h"
121 #ifdef CONFIG_DVBIN
122 #include "stream/dvbin.h"
123 #endif
124 #include "stream/cache2.h"
126 //**************************************************************************//
127 // Playtree
128 //**************************************************************************//
129 #include "playtree.h"
130 #include "playtreeparser.h"
132 //**************************************************************************//
133 // Config
134 //**************************************************************************//
135 #include "parser-cfg.h"
136 #include "parser-mpcmd.h"
138 //**************************************************************************//
139 // Config file
140 //**************************************************************************//
142 static int cfg_inc_verbose(m_option_t *conf)
144 ++verbose;
145 return 0;
148 #include "path.h"
150 //**************************************************************************//
151 //**************************************************************************//
152 // Input media streaming & demultiplexer:
153 //**************************************************************************//
155 static int max_framesize = 0;
157 #include "stream/stream.h"
158 #include "libmpdemux/demuxer.h"
159 #include "libmpdemux/stheader.h"
161 #ifdef CONFIG_DVDREAD
162 #include "stream/stream_dvd.h"
163 #endif
164 #include "stream/stream_dvdnav.h"
166 #include "libmpcodecs/dec_audio.h"
167 #include "libmpcodecs/dec_video.h"
168 #include "libmpcodecs/mp_image.h"
169 #include "libmpcodecs/vf.h"
170 #include "libmpcodecs/vd.h"
172 #include "mixer.h"
174 #include "mp_core.h"
175 #include "options.h"
176 #include "defaultopts.h"
178 static const char help_text[] = _(
179 "Usage: mplayer [options] [url|path/]filename\n"
180 "\n"
181 "Basic options: (complete list in the man page)\n"
182 " -vo <drv> select video output driver ('-vo help' for a list)\n"
183 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
184 #ifdef CONFIG_VCD
185 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
186 #endif
187 #ifdef CONFIG_DVDREAD
188 " dvd://<titleno> play DVD title from device instead of plain file\n"
189 #endif
190 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
191 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
192 " -nosound do not play sound\n"
193 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
194 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
195 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
196 " -playlist <file> specify playlist file\n"
197 " -vid x -aid y select video (x) and audio (y) stream to play\n"
198 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
199 " -pp <quality> enable postprocessing filter (details in the man page)\n"
200 " -framedrop enable frame dropping (for slow machines)\n"
201 "\n"
202 "Basic keys: (complete list in the man page, also check input.conf)\n"
203 " <- or -> seek backward/forward 10 seconds\n"
204 " down or up seek backward/forward 1 minute\n"
205 " pgdown or pgup seek backward/forward 10 minutes\n"
206 " < or > step backward/forward in playlist\n"
207 " p or SPACE pause movie (press any key to continue)\n"
208 " q or ESC stop playing and quit program\n"
209 " + or - adjust audio delay by +/- 0.1 second\n"
210 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
211 " * or / increase or decrease PCM volume\n"
212 " x or z adjust subtitle delay by +/- 0.1 second\n"
213 " r or t adjust subtitle position up/down, also see -vf expand\n"
214 " double click toggle fullscreen\n"
215 " right click pause (press again to continue)\n"
216 "\n"
217 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
218 "\n");
221 #define Exit_SIGILL_RTCpuSel _(\
222 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
223 " It may be a bug in our new runtime CPU-detection code...\n"\
224 " Please read DOCS/HTML/en/bugreports.html.\n")
226 #define Exit_SIGILL _(\
227 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
228 " It usually happens when you run it on a CPU different than the one it was\n"\
229 " compiled/optimized for.\n"\
230 " Verify this!\n")
232 #define Exit_SIGSEGV_SIGFPE _(\
233 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
234 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
235 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
237 #define Exit_SIGCRASH _(\
238 "- MPlayer crashed. This shouldn't happen.\n"\
239 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
240 " gcc version. If you think it's MPlayer's fault, please read\n"\
241 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
242 " won't help unless you provide this information when reporting a possible bug.\n")
244 #define SystemTooSlow _("\n\n"\
245 " ************************************************\n"\
246 " **** Your system is too SLOW to play this! ****\n"\
247 " ************************************************\n\n"\
248 "Possible reasons, problems, workarounds:\n"\
249 "- Most common: broken/buggy _audio_ driver\n"\
250 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
251 " - Experiment with different values for -autosync, 30 is a good start.\n"\
252 "- Slow video output\n"\
253 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
254 "- Slow CPU\n"\
255 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
256 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
257 "- Broken file\n"\
258 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
259 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
260 " - Try -cache 8192.\n"\
261 "- Are you using -cache to play a non-interleaved AVI file?\n"\
262 " - Try -nocache.\n"\
263 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
264 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
267 //**************************************************************************//
268 //**************************************************************************//
270 #include "mp_fifo.h"
272 // benchmark:
273 double video_time_usage;
274 double vout_time_usage;
275 static double audio_time_usage;
276 static int total_time_usage_start;
277 static int total_frame_cnt;
278 static int drop_frame_cnt; // total number of dropped frames
280 // options:
281 static int output_quality;
283 // seek:
284 static off_t seek_to_byte;
285 static off_t step_sec;
287 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
289 // codecs:
290 char **audio_codec_list; // override audio codec
291 char **video_codec_list; // override video codec
292 char **audio_fm_list; // override audio codec family
293 char **video_fm_list; // override video codec family
295 // this dvdsub_id was selected via slang
296 // use this to allow dvdnav to follow -slang across stream resets,
297 // in particular the subtitle ID for a language changes
298 int dvdsub_lang_id;
299 int vobsub_id = -1;
300 static char *spudec_ifo = NULL;
301 int forced_subs_only = 0;
303 // cache2:
304 int stream_cache_size = -1;
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 // sub:
321 char *font_name = NULL;
322 char *sub_font_name = NULL;
323 extern int font_fontconfig;
324 float font_factor = 0.75;
325 float sub_delay = 0;
326 float sub_fps = 0;
327 int subcc_enabled = 0;
328 int suboverlap_enabled = 1;
330 #include "sub/ass_mp.h"
332 char *current_module; // for debugging
335 // ---
337 FILE *edl_fd; // file to write to when in -edlout mode.
338 char *edl_output_filename; // file to put EDL entries in (-edlout)
340 int use_filedir_conf;
341 int use_filename_title;
343 #include "mpcommon.h"
344 #include "command.h"
346 #include "metadata.h"
348 static float get_relative_time(struct MPContext *mpctx)
350 unsigned int new_time = GetTimer();
351 unsigned int delta = new_time - mpctx->last_time;
352 mpctx->last_time = new_time;
353 return delta * 0.000001;
356 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
358 switch (type) {
359 /* check for valid video stream */
360 case META_VIDEO_CODEC:
361 case META_VIDEO_BITRATE:
362 case META_VIDEO_RESOLUTION:
363 if (!mpctx->sh_video)
364 return 0;
365 break;
367 /* check for valid audio stream */
368 case META_AUDIO_CODEC:
369 case META_AUDIO_BITRATE:
370 case META_AUDIO_SAMPLES:
371 if (!mpctx->sh_audio)
372 return 0;
373 break;
375 /* check for valid demuxer */
376 case META_INFO_TITLE:
377 case META_INFO_ARTIST:
378 case META_INFO_ALBUM:
379 case META_INFO_YEAR:
380 case META_INFO_COMMENT:
381 case META_INFO_TRACK:
382 case META_INFO_GENRE:
383 if (!mpctx->demuxer)
384 return 0;
385 break;
387 default:
388 break;
391 return 1;
394 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
396 char **info = mpctx->demuxer->info;
397 int n;
399 if (!info || !tag)
400 return talloc_strdup(NULL, "");
402 for (n = 0; info[2 * n] != NULL; n++)
403 if (!strcasecmp(info[2 * n], tag))
404 break;
406 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
409 char *get_metadata(struct MPContext *mpctx, metadata_t type)
411 sh_audio_t * const sh_audio = mpctx->sh_audio;
412 sh_video_t * const sh_video = mpctx->sh_video;
414 if (!is_valid_metadata_type(mpctx, type))
415 return NULL;
417 switch (type) {
418 case META_NAME:
419 return talloc_strdup(NULL, mp_basename(mpctx->filename));
420 case META_VIDEO_CODEC:
421 if (sh_video->format == 0x10000001)
422 return talloc_strdup(NULL, "mpeg1");
423 else if (sh_video->format == 0x10000002)
424 return talloc_strdup(NULL, "mpeg2");
425 else if (sh_video->format == 0x10000004)
426 return talloc_strdup(NULL, "mpeg4");
427 else if (sh_video->format == 0x10000005)
428 return talloc_strdup(NULL, "h264");
429 else if (sh_video->format >= 0x20202020)
430 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
431 else
432 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
433 case META_VIDEO_BITRATE:
434 return talloc_asprintf(NULL, "%d kbps",
435 (int) (sh_video->i_bps * 8 / 1024));
436 case META_VIDEO_RESOLUTION:
437 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
438 sh_video->disp_h);
439 case META_AUDIO_CODEC:
440 if (sh_audio->codec && sh_audio->codec->name)
441 return talloc_strdup(NULL, sh_audio->codec->name);
442 return talloc_strdup(NULL, "");
443 case META_AUDIO_BITRATE:
444 return talloc_asprintf(NULL, "%d kbps",
445 (int) (sh_audio->i_bps * 8 / 1000));
446 case META_AUDIO_SAMPLES:
447 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
448 sh_audio->channels);
450 /* check for valid demuxer */
451 case META_INFO_TITLE:
452 return get_demuxer_info(mpctx, "Title");
454 case META_INFO_ARTIST:
455 return get_demuxer_info(mpctx, "Artist");
457 case META_INFO_ALBUM:
458 return get_demuxer_info(mpctx, "Album");
460 case META_INFO_YEAR:
461 return get_demuxer_info(mpctx, "Year");
463 case META_INFO_COMMENT:
464 return get_demuxer_info(mpctx, "Comment");
466 case META_INFO_TRACK:
467 return get_demuxer_info(mpctx, "Track");
469 case META_INFO_GENRE:
470 return get_demuxer_info(mpctx, "Genre");
472 default:
473 break;
476 return talloc_strdup(NULL, "");
479 static void print_file_properties(struct MPContext *mpctx, const char *filename)
481 double start_pts = MP_NOPTS_VALUE;
482 double video_start_pts = MP_NOPTS_VALUE;
483 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
484 filename_recode(filename));
485 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
486 mpctx->demuxer->desc->name);
487 if (mpctx->sh_video) {
488 /* Assume FOURCC if all bytes >= 0x20 (' ') */
489 if (mpctx->sh_video->format >= 0x20202020)
490 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
491 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
492 else
493 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
494 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
495 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
496 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
497 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
498 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
499 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
500 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
501 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
502 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
503 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
504 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
505 video_start_pts = ds_get_next_pts(mpctx->d_video);
507 if (mpctx->sh_audio) {
508 /* Assume FOURCC if all bytes >= 0x20 (' ') */
509 if (mpctx->sh_audio->format >= 0x20202020)
510 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
511 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
512 else
513 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
514 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
515 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
516 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
517 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
518 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
519 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
520 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
521 start_pts = ds_get_next_pts(mpctx->d_audio);
523 if (video_start_pts != MP_NOPTS_VALUE) {
524 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
525 (mpctx->sh_video && video_start_pts < start_pts))
526 start_pts = video_start_pts;
528 if (start_pts != MP_NOPTS_VALUE)
529 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
530 else
531 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
532 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
533 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
534 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
535 mpctx->stream->seek
536 && (!mpctx->demuxer || mpctx->demuxer->seekable));
537 if (mpctx->demuxer) {
538 int chapter_count = get_chapter_count(mpctx);
539 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
540 for (int i = 0; i < chapter_count; i++) {
541 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
542 // in milliseconds
543 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
544 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
545 char *name = chapter_name(mpctx, i);
546 if (name) {
547 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
548 name);
549 talloc_free(name);
555 /// step size of mixer changes
556 int volstep = 3;
558 #ifdef CONFIG_DVDNAV
559 static void mp_dvdnav_context_free(MPContext *ctx)
561 if (ctx->nav_smpi)
562 free_mp_image(ctx->nav_smpi);
563 ctx->nav_smpi = NULL;
564 free(ctx->nav_buffer);
565 ctx->nav_buffer = NULL;
566 ctx->nav_start = NULL;
567 ctx->nav_in_size = 0;
569 #endif
571 static void uninit_subs(struct demuxer *demuxer)
573 for (int i = 0; i < MAX_S_STREAMS; i++) {
574 struct sh_sub *sh = demuxer->s_streams[i];
575 if (sh && sh->initialized)
576 sub_uninit(sh);
580 void uninit_player(struct MPContext *mpctx, unsigned int mask)
582 mask &= mpctx->initialized_flags;
584 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
586 if (mask & INITIALIZED_ACODEC) {
587 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
588 current_module = "uninit_acodec";
589 if (mpctx->sh_audio)
590 uninit_audio(mpctx->sh_audio);
591 mpctx->sh_audio = NULL;
592 mpctx->mixer.afilter = NULL;
595 if (mask & INITIALIZED_SUB) {
596 mpctx->initialized_flags &= ~INITIALIZED_SUB;
597 if (mpctx->d_sub->sh)
598 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
601 if (mask & INITIALIZED_VCODEC) {
602 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
603 current_module = "uninit_vcodec";
604 if (mpctx->sh_video)
605 uninit_video(mpctx->sh_video);
606 mpctx->sh_video = NULL;
609 if (mask & INITIALIZED_DEMUXER) {
610 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
611 current_module = "free_demuxer";
612 if (mpctx->num_sources) {
613 mpctx->demuxer = mpctx->sources[0].demuxer;
614 for (int i = 1; i < mpctx->num_sources; i++) {
615 uninit_subs(mpctx->sources[i].demuxer);
616 free_stream(mpctx->sources[i].stream);
617 free_demuxer(mpctx->sources[i].demuxer);
620 talloc_free(mpctx->sources);
621 mpctx->sources = NULL;
622 mpctx->num_sources = 0;
623 talloc_free(mpctx->timeline);
624 mpctx->timeline = NULL;
625 mpctx->num_timeline_parts = 0;
626 talloc_free(mpctx->chapters);
627 mpctx->chapters = NULL;
628 mpctx->num_chapters = 0;
629 mpctx->video_offset = 0;
630 if (mpctx->demuxer) {
631 mpctx->stream = mpctx->demuxer->stream;
632 uninit_subs(mpctx->demuxer);
633 free_demuxer(mpctx->demuxer);
635 mpctx->demuxer = NULL;
638 // kill the cache process:
639 if (mask & INITIALIZED_STREAM) {
640 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
641 current_module = "uninit_stream";
642 if (mpctx->stream)
643 free_stream(mpctx->stream);
644 mpctx->stream = NULL;
647 if (mask & INITIALIZED_VO) {
648 mpctx->initialized_flags &= ~INITIALIZED_VO;
649 current_module = "uninit_vo";
650 vo_destroy(mpctx->video_out);
651 mpctx->video_out = NULL;
652 #ifdef CONFIG_DVDNAV
653 mp_dvdnav_context_free(mpctx);
654 #endif
657 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
658 if (mask & INITIALIZED_GETCH2) {
659 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
660 current_module = "uninit_getch2";
661 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
662 // restore terminal:
663 getch2_disable();
666 if (mask & INITIALIZED_VOBSUB) {
667 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
668 current_module = "uninit_vobsub";
669 if (vo_vobsub)
670 vobsub_close(vo_vobsub);
671 vo_vobsub = NULL;
674 if (mask & INITIALIZED_SPUDEC) {
675 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
676 current_module = "uninit_spudec";
677 spudec_free(vo_spudec);
678 vo_spudec = NULL;
681 if (mask & INITIALIZED_AO) {
682 mpctx->initialized_flags &= ~INITIALIZED_AO;
683 current_module = "uninit_ao";
684 if (mpctx->ao)
685 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
686 mpctx->ao = NULL;
689 current_module = NULL;
692 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
694 if (mpctx->user_muted)
695 mixer_mute(&mpctx->mixer);
696 uninit_player(mpctx, INITIALIZED_ALL);
697 #if defined(__MINGW32__) || defined(__CYGWIN__)
698 timeEndPeriod(1);
699 #endif
700 #ifdef CONFIG_X11
701 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
702 #endif
704 current_module = "uninit_input";
705 mp_input_uninit(mpctx->input);
707 #ifdef CONFIG_FREETYPE
708 current_module = "uninit_font";
709 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
710 free_font_desc(mpctx->osd->sub_font);
711 free_font_desc(vo_font);
712 vo_font = NULL;
713 done_freetype();
714 #endif
715 osd_free(mpctx->osd);
717 #ifdef CONFIG_ASS
718 ass_library_done(mpctx->ass_library);
719 mpctx->ass_library = NULL;
720 #endif
722 current_module = "exit_player";
724 if (mpctx->playtree_iter)
725 play_tree_iter_free(mpctx->playtree_iter);
726 mpctx->playtree_iter = NULL;
727 if (mpctx->playtree)
728 play_tree_free(mpctx->playtree, 1);
729 mpctx->playtree = NULL;
731 talloc_free(mpctx->key_fifo);
733 switch (how) {
734 case EXIT_QUIT:
735 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
736 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
737 break;
738 case EXIT_EOF:
739 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
740 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
741 break;
742 case EXIT_ERROR:
743 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
744 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
745 break;
746 default:
747 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
749 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
750 "max framesize was %d bytes\n", max_framesize);
752 // must be last since e.g. mp_msg uses option values
753 // that will be freed by this.
754 if (mpctx->mconfig)
755 m_config_free(mpctx->mconfig);
756 mpctx->mconfig = NULL;
758 talloc_free(mpctx);
760 exit(rc);
763 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
765 exit_player_with_rc(mpctx, how, 1);
768 #ifndef __MINGW32__
769 static void child_sighandler(int x)
771 pid_t pid;
772 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
774 #endif
776 #ifdef CONFIG_CRASH_DEBUG
777 static char *prog_path;
778 static int crash_debug = 0;
779 #endif
781 static void exit_sighandler(int x)
783 static int sig_count = 0;
784 #ifdef CONFIG_CRASH_DEBUG
785 if (!crash_debug || x != SIGTRAP)
786 #endif
787 ++sig_count;
788 if (sig_count == 5) {
789 /* We're crashing bad and can't uninit cleanly :(
790 * by popular request, we make one last (dirty)
791 * effort to restore the user's
792 * terminal. */
793 getch2_disable();
794 exit(1);
796 if (sig_count == 6)
797 exit(1);
798 if (sig_count > 6) {
799 // can't stop :(
800 #ifndef __MINGW32__
801 kill(getpid(), SIGKILL);
802 #endif
804 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
805 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
806 "\nMPlayer interrupted by signal %d in module: %s\n", x,
807 current_module ? current_module : "unknown");
808 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
809 if (sig_count <= 1)
810 switch (x) {
811 case SIGINT:
812 case SIGPIPE:
813 case SIGQUIT:
814 case SIGTERM:
815 case SIGKILL:
816 async_quit_request = 1;
817 return; // killed from keyboard (^C) or killed [-9]
818 case SIGILL:
819 #if CONFIG_RUNTIME_CPUDETECT
820 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
821 #else
822 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
823 #endif
824 case SIGFPE:
825 case SIGSEGV:
826 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
827 default:
828 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
829 #ifdef CONFIG_CRASH_DEBUG
830 if (crash_debug) {
831 int gdb_pid;
832 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
833 gdb_pid = fork();
834 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
835 if (gdb_pid == 0) { // We are the child
836 char spid[20];
837 snprintf(spid, sizeof(spid), "%i", getppid());
838 getch2_disable(); // allow terminal to work properly with gdb
839 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
840 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
841 } else if (gdb_pid < 0)
842 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
843 else
844 waitpid(gdb_pid, NULL, 0);
845 if (x == SIGTRAP)
846 return;
848 #endif
850 getch2_disable();
851 exit(1);
854 #include "cfg-mplayer.h"
856 static int cfg_include(m_option_t *conf, char *filename)
858 return m_config_parse_config_file(conf->priv, filename);
861 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
863 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
865 struct MPOpts *opts = &mpctx->opts;
866 char *conffile;
867 int conffile_fd;
868 if (!(opts->noconfig & 2) &&
869 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
870 exit_player(mpctx, EXIT_NONE);
871 if ((conffile = get_path("")) == NULL)
872 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
873 else {
874 mkdir(conffile, 0777);
875 free(conffile);
876 if ((conffile = get_path("config")) == NULL)
877 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
878 else {
879 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
880 0666)) != -1) {
881 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
882 "Creating config file: %s\n", conffile);
883 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
884 close(conffile_fd);
886 if (!(opts->noconfig & 1) &&
887 m_config_parse_config_file(conf, conffile) < 0)
888 exit_player(mpctx, EXIT_NONE);
889 free(conffile);
894 #define PROFILE_CFG_PROTOCOL "protocol."
896 static void load_per_protocol_config(m_config_t *conf, const char * const file)
898 char *str;
899 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
900 m_profile_t *p;
902 /* does filename actually uses a protocol ? */
903 str = strstr(file, "://");
904 if (!str)
905 return;
907 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
908 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
909 p = m_config_get_profile(conf, protocol);
910 if (p) {
911 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
912 "Loading protocol-related profile '%s'\n", protocol);
913 m_config_set_profile(conf, p);
917 #define PROFILE_CFG_EXTENSION "extension."
919 static void load_per_extension_config(m_config_t *conf, const char * const file)
921 char *str;
922 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
923 m_profile_t *p;
925 /* does filename actually have an extension ? */
926 str = strrchr(file, '.');
927 if (!str)
928 return;
930 sprintf(extension, PROFILE_CFG_EXTENSION);
931 strncat(extension, ++str, 7);
932 p = m_config_get_profile(conf, extension);
933 if (p) {
934 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
935 "Loading extension-related profile '%s'\n", extension);
936 m_config_set_profile(conf, p);
940 #define PROFILE_CFG_VO "vo."
941 #define PROFILE_CFG_AO "ao."
943 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
945 char profile[strlen(cfg) + strlen(out) + 1];
946 m_profile_t *p;
948 sprintf(profile, "%s%s", cfg, out);
949 p = m_config_get_profile(conf, profile);
950 if (p) {
951 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
952 "Loading extension-related profile '%s'\n", profile);
953 m_config_set_profile(conf, p);
958 * Tries to load a config file
959 * @return 0 if file was not found, 1 otherwise
961 static int try_load_config(m_config_t *conf, const char *file)
963 if (!mp_path_exists(file))
964 return 0;
965 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
966 m_config_parse_config_file(conf, file);
967 return 1;
970 static void load_per_file_config(m_config_t *conf, const char * const file)
972 char *confpath;
973 char cfg[MP_PATH_MAX];
974 const char *name;
976 if (strlen(file) > MP_PATH_MAX - 14) {
977 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
978 "can not load file or directory specific config files\n");
979 return;
981 sprintf(cfg, "%s.conf", file);
983 name = mp_basename(cfg);
984 if (use_filedir_conf) {
985 char dircfg[MP_PATH_MAX];
986 strcpy(dircfg, cfg);
987 strcpy(dircfg + (name - cfg), "mplayer.conf");
988 try_load_config(conf, dircfg);
990 if (try_load_config(conf, cfg))
991 return;
994 if ((confpath = get_path(name)) != NULL) {
995 try_load_config(conf, confpath);
997 free(confpath);
1001 /* When libmpdemux performs a blocking operation (network connection or
1002 * cache filling) if the operation fails we use this function to check
1003 * if it was interrupted by the user.
1004 * The function returns a new value for eof. */
1005 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1007 mp_cmd_t *cmd;
1008 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1009 switch (cmd->id) {
1010 case MP_CMD_QUIT:
1011 exit_player_with_rc(mpctx, EXIT_QUIT,
1012 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1013 case MP_CMD_PLAY_TREE_STEP: {
1014 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1015 mpctx->play_tree_step =
1016 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1017 } break;
1018 case MP_CMD_PLAY_TREE_UP_STEP: {
1019 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1020 } break;
1021 case MP_CMD_PLAY_ALT_SRC_STEP: {
1022 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1023 } break;
1025 mp_cmd_free(cmd);
1027 return stop_play;
1030 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1032 play_tree_add_bpf(entry, bstr(mpctx->filename));
1035 if (!entry) {
1036 entry = mpctx->playtree_iter->tree;
1037 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1038 != PLAY_TREE_ITER_ENTRY)
1039 return PT_NEXT_ENTRY;
1040 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1041 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1042 != PLAY_TREE_ITER_ENTRY)
1043 return PT_NEXT_ENTRY;
1045 play_tree_remove(entry, 1, 1);
1046 return PT_NEXT_SRC;
1048 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1049 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1050 entry = mpctx->playtree_iter->tree;
1051 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1052 != PLAY_TREE_ITER_ENTRY)
1053 return PT_NEXT_ENTRY;
1054 play_tree_remove(entry, 1, 1);
1056 return PT_NEXT_SRC;
1059 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1060 int noerr)
1062 struct MPOpts *opts = &mpctx->opts;
1063 sub_data *subd = NULL;
1064 struct ass_track *asst = NULL;
1065 bool is_native_ass = false;
1067 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1068 return;
1070 #ifdef CONFIG_ASS
1071 if (opts->ass_enabled) {
1072 #ifdef CONFIG_ICONV
1073 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1074 #else
1075 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1076 #endif
1077 is_native_ass = asst;
1078 if (!asst) {
1079 subd = sub_read_file(filename, fps, &mpctx->opts);
1080 if (subd) {
1081 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1082 sub_free(subd);
1083 subd = NULL;
1086 } else
1087 #endif
1088 subd = sub_read_file(filename, fps, &mpctx->opts);
1091 if (!asst && !subd) {
1092 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1093 "Cannot load subtitles: %s\n", filename_recode(filename));
1094 return;
1097 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1098 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1099 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1100 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1101 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1102 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1103 filename_recode(filename));
1104 ++mpctx->set_of_sub_size;
1105 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1106 mpctx->set_of_sub_size, filename_recode(filename));
1109 void init_vo_spudec(struct MPContext *mpctx)
1111 unsigned width, height;
1112 spudec_free(vo_spudec);
1113 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1114 vo_spudec = NULL;
1116 // we currently can't work without video stream
1117 if (!mpctx->sh_video)
1118 return;
1120 if (spudec_ifo) {
1121 unsigned int palette[16];
1122 current_module = "spudec_init_vobsub";
1123 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1124 1, -1, NULL) >= 0)
1125 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1128 width = mpctx->sh_video->disp_w;
1129 height = mpctx->sh_video->disp_h;
1131 #ifdef CONFIG_DVDREAD
1132 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1133 current_module = "spudec_init_dvdread";
1134 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1135 cur_pgc->palette, width, height, NULL, 0);
1137 #endif
1139 #ifdef CONFIG_DVDNAV
1140 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1141 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1142 current_module = "spudec_init_dvdnav";
1143 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1145 #endif
1147 if (vo_spudec == NULL) {
1148 sh_sub_t *sh = mpctx->d_sub->sh;
1149 current_module = "spudec_init_normal";
1150 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1151 sh->extradata_len);
1152 spudec_set_font_factor(vo_spudec, font_factor);
1155 if (vo_spudec != NULL) {
1156 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1157 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1158 mpctx);
1163 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1164 * make it all work is to use the builtin SDL-bootstrap code, which
1165 * will be done automatically by replacing our main() if we include SDL.h.
1167 #if defined(__APPLE__) && defined(CONFIG_SDL)
1168 #ifdef CONFIG_SDL_SDL_H
1169 #include <SDL/SDL.h>
1170 #else
1171 #include <SDL.h>
1172 #endif
1173 #endif
1176 * \brief append a formatted string
1177 * \param buf buffer to print into
1178 * \param pos position of terminating 0 in buf
1179 * \param len maximum number of characters in buf, not including terminating 0
1180 * \param format printf format string
1182 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1184 va_list va;
1185 va_start(va, format);
1186 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1187 va_end(va);
1188 if (*pos >= len) {
1189 buf[len] = 0;
1190 *pos = len;
1195 * \brief append time in the hh:mm:ss.f format
1196 * \param buf buffer to print into
1197 * \param pos position of terminating 0 in buf
1198 * \param len maximum number of characters in buf, not including terminating 0
1199 * \param time time value to convert/append
1201 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1203 int64_t tenths = 10 * time;
1204 int f1 = tenths % 10;
1205 int ss = (tenths / 10) % 60;
1206 int mm = (tenths / 600) % 60;
1207 int hh = tenths / 36000;
1208 if (time < 0) {
1209 saddf(buf, pos, len, "unknown");
1210 return;
1212 if (hh > 0)
1213 saddf(buf, pos, len, "%2d:", hh);
1214 if (hh > 0 || mm > 0)
1215 saddf(buf, pos, len, "%02d:", mm);
1216 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1219 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1221 struct MPOpts *opts = &mpctx->opts;
1222 sh_video_t * const sh_video = mpctx->sh_video;
1224 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1225 a_pos = playing_audio_pts(mpctx);
1226 if (mpctx->sh_audio && sh_video && at_frame) {
1227 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1228 if (mpctx->time_frame > 0)
1229 mpctx->last_av_difference +=
1230 mpctx->time_frame * opts->playback_speed;
1231 if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
1232 mpctx->last_av_difference = MP_NOPTS_VALUE;
1233 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1234 && !mpctx->drop_message_shown) {
1235 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1236 mpctx->drop_message_shown = true;
1239 if (opts->quiet)
1240 return;
1242 int width;
1243 char *line;
1244 unsigned pos = 0;
1245 get_screen_size();
1246 if (screen_width > 0)
1247 width = screen_width;
1248 else
1249 width = 80;
1250 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1251 /* Windows command line is broken (MinGW's rxvt works, but we
1252 * should not depend on that). */
1253 width--;
1254 #endif
1255 line = malloc(width + 1); // one additional char for the terminating null
1257 // Audio time
1258 if (mpctx->sh_audio) {
1259 if (a_pos != MP_NOPTS_VALUE)
1260 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1261 else
1262 saddf(line, &pos, width, "A: ??? ");
1263 if (!sh_video && a_pos != MP_NOPTS_VALUE) {
1264 float len = get_time_length(mpctx);
1265 saddf(line, &pos, width, "(");
1266 sadd_hhmmssf(line, &pos, width, a_pos);
1267 saddf(line, &pos, width, ") of %.1f (", len);
1268 sadd_hhmmssf(line, &pos, width, len);
1269 saddf(line, &pos, width, ") ");
1273 // Video time
1274 if (sh_video) {
1275 if (mpctx->video_pts != MP_NOPTS_VALUE)
1276 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1277 else
1278 saddf(line, &pos, width, "V: ??? ", mpctx->video_pts);
1281 // A-V sync
1282 if (mpctx->sh_audio && sh_video) {
1283 if (mpctx->last_av_difference != MP_NOPTS_VALUE)
1284 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1285 mpctx->last_av_difference, mpctx->total_avsync_change);
1286 else
1287 saddf(line, &pos, width, "A-V: ??? ct:%7.3f ",
1288 mpctx->total_avsync_change);
1291 // Video stats
1292 if (sh_video)
1293 saddf(line, &pos, width, "%3d/%3d ",
1294 (int)sh_video->num_frames,
1295 (int)sh_video->num_frames_decoded);
1297 // CPU usage
1298 if (sh_video) {
1299 if (sh_video->timer > 0.5)
1300 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1301 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1302 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1303 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1304 else
1305 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1306 } else if (mpctx->sh_audio) {
1307 if (mpctx->delay > 0.5)
1308 saddf(line, &pos, width, "%4.1f%% ",
1309 100.0 * audio_time_usage / (double)mpctx->delay);
1310 else
1311 saddf(line, &pos, width, "??,?%% ");
1314 // VO stats
1315 if (sh_video)
1316 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1318 #ifdef CONFIG_STREAM_CACHE
1319 // cache stats
1320 if (stream_cache_size > 0)
1321 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1322 #endif
1324 // other
1325 if (opts->playback_speed != 1)
1326 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1328 // end
1329 if (erase_to_end_of_line) {
1330 line[pos] = 0;
1331 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1332 "%s%s\r", line, erase_to_end_of_line);
1333 } else {
1334 memset(&line[pos], ' ', width - pos);
1335 line[width] = 0;
1336 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1338 free(line);
1340 mpctx->status_printed = true;
1343 struct stream_dump_progress {
1344 uint64_t count;
1345 unsigned start_time;
1346 unsigned last_print_time;
1349 static void stream_dump_progress_start(struct stream_dump_progress *p)
1351 p->start_time = p->last_print_time = GetTimerMS();
1352 p->count = 0;
1355 static void stream_dump_progress(struct stream_dump_progress *p,
1356 uint64_t len, stream_t *stream)
1358 p->count += len;
1359 unsigned t = GetTimerMS();
1360 if (t - p->last_print_time < 1000)
1361 return;
1363 uint64_t start = stream->start_pos;
1364 uint64_t end = stream->end_pos;
1365 uint64_t pos = stream->pos;
1367 p->last_print_time = t;
1368 /* TODO: pretty print sizes; ETA */
1369 if (end > start && pos >= start && pos <= end) {
1370 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1371 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1372 p->count, 100.0 * (pos - start) / (end - start));
1373 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1374 } else {
1375 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1376 "dump: %"PRIu64 " bytes written", p->count);
1377 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1381 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1383 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1384 p->count, name);
1388 * \brief build a chain of audio filters that converts the input format
1389 * to the ao's format, taking into account the current playback_speed.
1390 * sh_audio describes the requested input format of the chain.
1391 * ao describes the requested output format of the chain.
1393 static int build_afilter_chain(struct MPContext *mpctx)
1395 struct sh_audio *sh_audio = mpctx->sh_audio;
1396 struct ao *ao = mpctx->ao;
1397 struct MPOpts *opts = &mpctx->opts;
1398 int new_srate;
1399 int result;
1400 if (!sh_audio) {
1401 mpctx->mixer.afilter = NULL;
1402 return 0;
1404 if (af_control_any_rev(sh_audio->afilter,
1405 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1406 &opts->playback_speed))
1407 new_srate = sh_audio->samplerate;
1408 else {
1409 new_srate = sh_audio->samplerate * opts->playback_speed;
1410 if (new_srate != ao->samplerate) {
1411 // limits are taken from libaf/af_resample.c
1412 if (new_srate < 8000)
1413 new_srate = 8000;
1414 if (new_srate > 192000)
1415 new_srate = 192000;
1416 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1419 result = init_audio_filters(sh_audio, new_srate,
1420 &ao->samplerate, &ao->channels, &ao->format);
1421 mpctx->mixer.afilter = sh_audio->afilter;
1422 return result;
1426 typedef struct mp_osd_msg mp_osd_msg_t;
1427 struct mp_osd_msg {
1428 /// Previous message on the stack.
1429 mp_osd_msg_t *prev;
1430 /// Message text.
1431 char *msg;
1432 int id, level, started;
1433 /// Display duration in ms.
1434 unsigned time;
1437 /// OSD message stack.
1438 static mp_osd_msg_t *osd_msg_stack = NULL;
1441 * \brief Add a message on the OSD message stack
1443 * If a message with the same id is already present in the stack
1444 * it is pulled on top of the stack, otherwise a new message is created.
1447 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1448 va_list ap)
1450 mp_osd_msg_t *msg, *last = NULL;
1452 // look if the id is already in the stack
1453 for (msg = osd_msg_stack; msg && msg->id != id;
1454 last = msg, msg = msg->prev) ;
1455 // not found: alloc it
1456 if (!msg) {
1457 msg = talloc_zero(NULL, mp_osd_msg_t);
1458 msg->prev = osd_msg_stack;
1459 osd_msg_stack = msg;
1460 } else if (last) { // found, but it's not on top of the stack
1461 last->prev = msg->prev;
1462 msg->prev = osd_msg_stack;
1463 osd_msg_stack = msg;
1465 talloc_free(msg->msg);
1466 // write the msg
1467 msg->msg = talloc_vasprintf(msg, fmt, ap);
1468 // set id and time
1469 msg->id = id;
1470 msg->level = level;
1471 msg->time = time;
1475 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1477 va_list ap;
1478 va_start(ap, fmt);
1479 set_osd_msg_va(id, level, time, fmt, ap);
1480 va_end(ap);
1483 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1485 va_list ap;
1486 va_start(ap, fmt);
1487 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1488 va_end(ap);
1492 * \brief Remove a message from the OSD stack
1494 * This function can be used to get rid of a message right away.
1498 void rm_osd_msg(int id)
1500 mp_osd_msg_t *msg, *last = NULL;
1502 // Search for the msg
1503 for (msg = osd_msg_stack; msg && msg->id != id;
1504 last = msg, msg = msg->prev) ;
1505 if (!msg)
1506 return;
1508 // Detach it from the stack and free it
1509 if (last)
1510 last->prev = msg->prev;
1511 else
1512 osd_msg_stack = msg->prev;
1513 talloc_free(msg);
1517 * \brief Remove all messages from the OSD stack
1521 static void clear_osd_msgs(void)
1523 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1524 while (msg) {
1525 prev = msg->prev;
1526 talloc_free(msg);
1527 msg = prev;
1529 osd_msg_stack = NULL;
1533 * \brief Get the current message from the OSD stack.
1535 * This function decrements the message timer and destroys the old ones.
1536 * The message that should be displayed is returned (if any).
1540 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1542 struct MPOpts *opts = &mpctx->opts;
1543 mp_osd_msg_t *msg, *prev, *last = NULL;
1544 static unsigned last_update = 0;
1545 unsigned now = GetTimerMS();
1546 unsigned diff;
1547 char hidden_dec_done = 0;
1549 if (mpctx->osd_visible) {
1550 // 36000000 means max timed visibility is 1 hour into the future, if
1551 // the difference is greater assume it's wrapped around from below 0
1552 if (mpctx->osd_visible - now > 36000000) {
1553 mpctx->osd_visible = 0;
1554 vo_osd_progbar_type = -1; // disable
1555 vo_osd_changed(OSDTYPE_PROGBAR);
1556 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1559 if (mpctx->osd_show_percentage_until - now > 36000000)
1560 mpctx->osd_show_percentage_until = 0;
1562 if (!last_update)
1563 last_update = now;
1564 diff = now >= last_update ? now - last_update : 0;
1566 last_update = now;
1568 // Look for the first message in the stack with high enough level.
1569 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1570 prev = msg->prev;
1571 if (msg->level > opts->osd_level && hidden_dec_done)
1572 continue;
1573 // The message has a high enough level or it is the first hidden one
1574 // in both cases we decrement the timer or kill it.
1575 if (!msg->started || msg->time > diff) {
1576 if (msg->started)
1577 msg->time -= diff;
1578 else
1579 msg->started = 1;
1580 // display it
1581 if (msg->level <= opts->osd_level)
1582 return msg;
1583 hidden_dec_done = 1;
1584 continue;
1586 // kill the message
1587 talloc_free(msg);
1588 if (last) {
1589 last->prev = prev;
1590 msg = last;
1591 } else {
1592 osd_msg_stack = prev;
1593 msg = NULL;
1596 // Nothing found
1597 return NULL;
1601 * \brief Display the OSD bar.
1603 * Display the OSD bar or fall back on a simple message.
1607 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1608 double min, double max, double val)
1610 struct MPOpts *opts = &mpctx->opts;
1611 if (opts->osd_level < 1)
1612 return;
1614 if (mpctx->sh_video) {
1615 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1616 vo_osd_progbar_type = type;
1617 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1618 vo_osd_changed(OSDTYPE_PROGBAR);
1619 return;
1622 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1623 name, ROUND(100 * (val - min) / (max - min)));
1627 * \brief Display text subtitles on the OSD
1629 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1631 int i;
1632 vo_sub = subs;
1633 vo_osd_changed(OSDTYPE_SUBTITLE);
1634 if (!mpctx->sh_video) {
1635 // reverse order, since newest set_osd_msg is displayed first
1636 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1637 if (!subs || i >= subs->lines || !subs->text[i])
1638 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1639 else {
1640 // HACK: currently display time for each sub line
1641 // except the last is set to 2 seconds.
1642 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1643 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1644 "%s", subs->text[i]);
1651 * \brief Update the OSD message line.
1653 * This function displays the current message on the vo OSD or on the term.
1654 * If the stack is empty and the OSD level is high enough the timer
1655 * is displayed (only on the vo OSD).
1659 static void update_osd_msg(struct MPContext *mpctx)
1661 struct MPOpts *opts = &mpctx->opts;
1662 mp_osd_msg_t *msg;
1663 struct osd_state *osd = mpctx->osd;
1664 char osd_text_timer[128];
1666 if (mpctx->add_osd_seek_info) {
1667 double percentage = get_percent_pos(mpctx);
1668 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1669 if (mpctx->sh_video)
1670 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1671 mpctx->add_osd_seek_info = false;
1674 // Look if we have a msg
1675 if ((msg = get_osd_msg(mpctx))) {
1676 if (strcmp(osd->osd_text, msg->msg)) {
1677 osd_set_text(osd, msg->msg);
1678 if (mpctx->sh_video)
1679 vo_osd_changed(OSDTYPE_OSD);
1680 else if (opts->term_osd)
1681 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1682 msg->msg);
1684 return;
1687 if (mpctx->sh_video) {
1688 // fallback on the timer
1689 if (opts->osd_level >= 2) {
1690 int len = get_time_length(mpctx);
1691 int percentage = -1;
1692 char percentage_text[10];
1693 char fractions_text[4];
1694 double fpts = get_current_time(mpctx);
1695 int pts = fpts;
1697 if (mpctx->osd_show_percentage_until)
1698 percentage = get_percent_pos(mpctx);
1700 if (percentage >= 0)
1701 snprintf(percentage_text, 9, " (%d%%)", percentage);
1702 else
1703 percentage_text[0] = 0;
1705 if (opts->osd_fractions == 1) {
1706 //print fractions as sub-second timestamp
1707 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1708 (int)((fpts - pts) * 100));
1709 } else if (opts->osd_fractions == 2) {
1710 /* Print fractions by estimating the frame count within the
1711 * second.
1713 * Rounding or cutting off numbers after the decimal point
1714 * causes problems because of float's precision and movies
1715 * whose first frame is not exactly at timestamp 0. Therefore,
1716 * we add 0.2 and cut off at the decimal point, which proved
1717 * to be good heuristic.
1719 double fps = mpctx->sh_video->fps;
1720 if (fps <= 1 || fps > 99)
1721 strcpy(fractions_text, ".??");
1722 else
1723 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1724 (int) ((fpts - pts) * fps + 0.2));
1725 } else {
1726 //do not print fractions
1727 fractions_text[0] = 0;
1730 if (opts->osd_level == 3)
1731 snprintf(osd_text_timer, sizeof(osd_text_timer),
1732 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1733 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1734 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1735 percentage_text);
1736 else
1737 snprintf(osd_text_timer, sizeof(osd_text_timer),
1738 "%c %02d:%02d:%02d%s%s",
1739 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1740 pts % 60, fractions_text, percentage_text);
1741 } else
1742 osd_text_timer[0] = 0;
1744 if (strcmp(osd->osd_text, osd_text_timer)) {
1745 osd_set_text(osd, osd_text_timer);
1746 vo_osd_changed(OSDTYPE_OSD);
1748 return;
1751 // Clear the term osd line
1752 if (opts->term_osd && osd->osd_text[0]) {
1753 osd->osd_text[0] = 0;
1754 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1759 void reinit_audio_chain(struct MPContext *mpctx)
1761 struct MPOpts *opts = &mpctx->opts;
1762 struct ao *ao;
1763 if (!mpctx->sh_audio)
1764 return;
1765 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1766 current_module = "init_audio_codec";
1767 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1768 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1769 goto init_error;
1770 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1771 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1775 current_module = "af_preinit";
1776 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1777 mpctx->initialized_flags |= INITIALIZED_AO;
1778 mpctx->ao = ao_create();
1779 mpctx->ao->samplerate = force_srate;
1780 mpctx->ao->format = opts->audio_output_format;
1782 ao = mpctx->ao;
1784 // first init to detect best values
1785 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1786 // input:
1787 mpctx->sh_audio->samplerate,
1788 // output:
1789 &ao->samplerate, &ao->channels, &ao->format)) {
1790 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1791 "pre-init!\n");
1792 exit_player(mpctx, EXIT_ERROR);
1794 if (!ao->initialized) {
1795 current_module = "ao2_init";
1796 ao->buffersize = opts->ao_buffersize;
1797 ao_init(ao, opts->audio_driver_list);
1798 if (!ao->initialized) {
1799 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1800 "Could not open/initialize audio device -> no sound.\n");
1801 goto init_error;
1803 ao->buffer.start = talloc_new(ao);
1804 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1805 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1806 ao->driver->info->short_name,
1807 ao->samplerate, ao->channels,
1808 af_fmt2str_short(ao->format),
1809 af_fmt2bits(ao->format) / 8);
1810 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1811 ao->driver->info->name, ao->driver->info->author);
1812 if (strlen(ao->driver->info->comment) > 0)
1813 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1814 ao->driver->info->comment);
1817 // init audio filters:
1818 current_module = "af_init";
1819 if (!build_afilter_chain(mpctx)) {
1820 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1821 "Couldn't find matching filter/ao format!\n");
1822 goto init_error;
1824 mpctx->mixer.ao = ao;
1825 mpctx->mixer.volstep = volstep;
1826 mpctx->syncing_audio = true;
1827 return;
1829 init_error:
1830 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1831 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1832 mpctx->d_audio->id = -2;
1836 // Return pts value corresponding to the end point of audio written to the
1837 // ao so far.
1838 static double written_audio_pts(struct MPContext *mpctx)
1840 sh_audio_t *sh_audio = mpctx->sh_audio;
1841 demux_stream_t *d_audio = mpctx->d_audio;
1842 // first calculate the end pts of audio that has been output by decoder
1843 double a_pts = sh_audio->pts;
1844 if (a_pts != MP_NOPTS_VALUE)
1845 // Good, decoder supports new way of calculating audio pts.
1846 // sh_audio->pts is the timestamp of the latest input packet with
1847 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1848 // the amount of bytes the decoder has written after that timestamp.
1849 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1850 else {
1851 // Decoder doesn't support new way of calculating pts (or we're
1852 // being called before it has decoded anything with known timestamp).
1853 // Use the old method of audio pts calculation: take the timestamp
1854 // of last packet with known pts the decoder has read data from,
1855 // and add amount of bytes read after the beginning of that packet
1856 // divided by input bps. This will be inaccurate if the input/output
1857 // ratio is not constant for every audio packet or if it is constant
1858 // but not accurately known in sh_audio->i_bps.
1860 a_pts = d_audio->pts;
1861 if (a_pts == MP_NOPTS_VALUE)
1862 return a_pts;
1864 // ds_tell_pts returns bytes read after last timestamp from
1865 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1866 // it has read but not decoded
1867 if (sh_audio->i_bps)
1868 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1869 (double)sh_audio->i_bps;
1871 // Now a_pts hopefully holds the pts for end of audio from decoder.
1872 // Substract data in buffers between decoder and audio out.
1874 // Decoded but not filtered
1875 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1877 // Data buffered in audio filters, measured in bytes of "missing" output
1878 double buffered_output = af_calc_delay(sh_audio->afilter);
1880 // Data that was ready for ao but was buffered because ao didn't fully
1881 // accept everything to internal buffers yet
1882 buffered_output += mpctx->ao->buffer.len;
1884 // Filters divide audio length by playback_speed, so multiply by it
1885 // to get the length in original units without speedup or slowdown
1886 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1888 return a_pts + mpctx->video_offset;
1891 // Return pts value corresponding to currently playing audio.
1892 double playing_audio_pts(struct MPContext *mpctx)
1894 double pts = written_audio_pts(mpctx);
1895 if (pts == MP_NOPTS_VALUE)
1896 return pts;
1897 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1900 static bool is_av_sub(int type)
1902 return type == 'b' || type == 'p' || type == 'x';
1905 void update_subtitles(struct MPContext *mpctx, double refpts,
1906 double sub_offset, bool reset)
1908 struct MPOpts *opts = &mpctx->opts;
1909 struct sh_video *sh_video = mpctx->sh_video;
1910 struct demux_stream *d_sub = mpctx->d_sub;
1911 double curpts = refpts + 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 if (is_av_sub(type))
1928 reset_avsub(sh_sub);
1929 return;
1931 // find sub
1932 if (mpctx->subdata) {
1933 if (sub_fps == 0)
1934 sub_fps = sh_video ? sh_video->fps : 25;
1935 current_module = "find_sub";
1936 find_sub(mpctx, mpctx->subdata, curpts *
1937 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1938 if (vo_sub)
1939 mpctx->vo_sub_last = vo_sub;
1942 // DVD sub:
1943 if (vobsub_id >= 0 || type == 'v') {
1944 int timestamp;
1945 current_module = "spudec";
1946 /* Get a sub packet from the DVD or a vobsub */
1947 while (1) {
1948 // Vobsub
1949 len = 0;
1950 if (vo_vobsub) {
1951 if (curpts >= 0) {
1952 len = vobsub_get_packet(vo_vobsub, curpts,
1953 (void **)&packet, &timestamp);
1954 if (len > 0)
1955 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1956 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1957 len, refpts, sh_video->timer,
1958 timestamp / 90000.0, timestamp);
1960 } else {
1961 // DVD sub
1962 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1963 if (len > 0) {
1964 // XXX This is wrong, sh_video->pts can be arbitrarily
1965 // much behind demuxing position. Unfortunately using
1966 // d_video->pts which would have been the simplest
1967 // improvement doesn't work because mpeg specific hacks
1968 // in video.c set d_video->pts to 0.
1969 float x = d_sub->pts - refpts;
1970 if (x > -20 && x < 20) // prevent missing subs on pts reset
1971 timestamp = 90000 * d_sub->pts;
1972 else
1973 timestamp = 90000 * curpts;
1974 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1975 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1976 refpts, d_sub->pts, timestamp);
1979 if (len <= 0 || !packet)
1980 break;
1981 // create it only here, since with some broken demuxers we might
1982 // type = v but no DVD sub and we currently do not change the
1983 // "original frame size" ever after init, leading to wrong-sized
1984 // PGS subtitles.
1985 if (!vo_spudec)
1986 vo_spudec = spudec_new(NULL);
1987 if (vo_vobsub || timestamp >= 0)
1988 spudec_assemble(vo_spudec, packet, len, timestamp);
1990 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1991 if (type == 'd' && !d_sub->demuxer->teletext) {
1992 tt_stream_props tsp = { 0 };
1993 void *ptr = &tsp;
1994 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
1995 VBI_CONTROL_TRUE)
1996 d_sub->demuxer->teletext = ptr;
1998 if (d_sub->non_interleaved)
1999 ds_get_next_pts(d_sub);
2001 while (d_sub->first) {
2002 double subpts = ds_get_next_pts(d_sub) + sub_offset;
2003 if (subpts > curpts) {
2004 // Libass handled subs can be fed to it in advance
2005 if (!opts->ass_enabled || !is_text_sub(type))
2006 break;
2007 // Try to avoid demuxing whole file at once
2008 if (d_sub->non_interleaved && subpts > curpts + 1)
2009 break;
2011 double duration = d_sub->first->duration;
2012 len = ds_get_packet_sub(d_sub, &packet);
2013 if (is_av_sub(type)) {
2014 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2015 if (ret < 0)
2016 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2017 "subtitle\n");
2018 continue;
2020 if (type == 'm') {
2021 if (len < 2)
2022 continue;
2023 len = FFMIN(len - 2, AV_RB16(packet));
2024 packet += 2;
2026 if (type == 'd') {
2027 if (d_sub->demuxer->teletext) {
2028 uint8_t *p = packet;
2029 p++;
2030 len--;
2031 while (len >= 46) {
2032 int sublen = p[1];
2033 if (p[0] == 2 || p[0] == 3)
2034 teletext_control(d_sub->demuxer->teletext,
2035 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2036 p += sublen + 2;
2037 len -= sublen + 2;
2040 continue;
2042 if (sh_sub && sh_sub->active) {
2043 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2044 continue;
2046 if (subpts != MP_NOPTS_VALUE) {
2047 if (duration < 0)
2048 sub_clear_text(&subs, MP_NOPTS_VALUE);
2049 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2050 int i;
2051 unsigned char *p = packet;
2052 for (i = 0; i < 8 && *p != '\0'; p++)
2053 if (*p == ',')
2054 i++;
2055 if (*p == '\0') /* Broken line? */
2056 continue;
2057 len -= p - packet;
2058 packet = p;
2060 double endpts = MP_NOPTS_VALUE;
2061 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2062 endpts = subpts + duration;
2063 sub_add_text(&subs, packet, len, endpts);
2064 set_osd_subtitle(mpctx, &subs);
2066 if (d_sub->non_interleaved)
2067 ds_get_next_pts(d_sub);
2069 if (!opts->ass_enabled)
2070 if (sub_clear_text(&subs, curpts))
2071 set_osd_subtitle(mpctx, &subs);
2073 if (vo_spudec) {
2074 spudec_heartbeat(vo_spudec, 90000 * curpts);
2075 if (spudec_changed(vo_spudec))
2076 vo_osd_changed(OSDTYPE_SPU);
2079 current_module = NULL;
2082 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2084 int page_changed;
2086 if (!demuxer->teletext)
2087 return;
2089 //Also forcing page update when such ioctl is not supported or call error occured
2090 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2091 &page_changed) != VBI_CONTROL_TRUE)
2092 page_changed = 1;
2094 if (!page_changed)
2095 return;
2097 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2098 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2099 vo_osd_teletext_page = NULL;
2100 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2101 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2102 vo_osd_teletext_half = 0;
2103 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2104 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2105 vo_osd_teletext_mode = 0;
2106 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2107 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2108 vo_osd_teletext_format = 0;
2109 vo_osd_changed(OSDTYPE_TELETEXT);
2111 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2114 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2116 struct MPOpts *opts = &mpctx->opts;
2117 // check for frame-drop:
2118 current_module = "check_framedrop";
2119 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2120 static int dropped_frames;
2121 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2122 float d = delay - mpctx->delay;
2123 ++total_frame_cnt;
2124 // we should avoid dropping too many frames in sequence unless we
2125 // are too late. and we allow 100ms A-V delay here:
2126 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2127 && !mpctx->restart_playback) {
2128 ++drop_frame_cnt;
2129 ++dropped_frames;
2130 return frame_dropping;
2131 } else
2132 dropped_frames = 0;
2134 return 0;
2138 #ifdef HAVE_RTC
2139 int rtc_fd = -1;
2140 #endif
2142 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2144 #ifdef HAVE_RTC
2145 if (rtc_fd >= 0) {
2146 // -------- RTC -----------
2147 current_module = "sleep_rtc";
2148 while (time_frame > 0.000) {
2149 unsigned long rtc_ts;
2150 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2151 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2152 "Linux RTC read error: %s\n", strerror(errno));
2153 time_frame -= get_relative_time(mpctx);
2155 } else
2156 #endif
2158 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2159 // unnecessarily high CPU usage
2160 struct MPOpts *opts = &mpctx->opts;
2161 float margin = opts->softsleep ? 0.011 : 0;
2162 current_module = "sleep_timer";
2163 while (time_frame > margin) {
2164 usec_sleep(1000000 * (time_frame - margin));
2165 time_frame -= get_relative_time(mpctx);
2167 if (opts->softsleep) {
2168 current_module = "sleep_soft";
2169 if (time_frame < 0)
2170 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2171 "Warning! Softsleep underflow!\n");
2172 while (time_frame > 0)
2173 time_frame -= get_relative_time(mpctx); // burn the CPU
2176 return time_frame;
2179 static int select_subtitle(MPContext *mpctx)
2181 struct MPOpts *opts = &mpctx->opts;
2182 // find the best sub to use
2183 int id;
2184 int found = 0;
2185 mpctx->global_sub_pos = -1; // no subs by default
2186 if (vobsub_id >= 0) {
2187 // if user asks for a vobsub id, use that first.
2188 id = vobsub_id;
2189 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2190 M_PROPERTY_OK;
2193 if (!found && opts->sub_id >= 0) {
2194 // if user asks for a dvd sub id, use that next.
2195 id = opts->sub_id;
2196 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2197 M_PROPERTY_OK;
2200 if (!found) {
2201 // if there are text subs to use, use those. (autosubs come last here)
2202 id = 0;
2203 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2204 M_PROPERTY_OK;
2207 if (!found && opts->sub_id == -1) {
2208 // finally select subs by language and container hints
2209 if (opts->sub_id == -1)
2210 opts->sub_id =
2211 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2212 opts->sub_lang);
2213 if (opts->sub_id >= 0) {
2214 id = opts->sub_id;
2215 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2216 M_PROPERTY_OK;
2219 return found;
2222 #ifdef CONFIG_DVDNAV
2223 #ifndef FF_B_TYPE
2224 #define FF_B_TYPE 3
2225 #endif
2226 /// store decoded video image
2227 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2228 mp_image_t *from_mpi)
2230 mp_image_t *mpi;
2232 /// Do not store B-frames
2233 if (from_mpi->pict_type == FF_B_TYPE)
2234 return to_mpi;
2236 if (to_mpi &&
2237 to_mpi->w == from_mpi->w &&
2238 to_mpi->h == from_mpi->h &&
2239 to_mpi->imgfmt == from_mpi->imgfmt)
2240 mpi = to_mpi;
2241 else {
2242 if (to_mpi)
2243 free_mp_image(to_mpi);
2244 if (from_mpi->w == 0 || from_mpi->h == 0)
2245 return NULL;
2246 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2249 copy_mpi(mpi, from_mpi);
2250 return mpi;
2253 static void mp_dvdnav_reset_stream(MPContext *ctx)
2255 struct MPOpts *opts = &ctx->opts;
2256 if (ctx->sh_video) {
2257 /// clear video pts
2258 ctx->d_video->pts = 0.0f;
2259 ctx->sh_video->pts = 0.0f;
2260 ctx->sh_video->i_pts = 0.0f;
2261 ctx->sh_video->last_pts = 0.0f;
2262 ctx->sh_video->num_buffered_pts = 0;
2263 ctx->sh_video->num_frames = 0;
2264 ctx->sh_video->num_frames_decoded = 0;
2265 ctx->sh_video->timer = 0.0f;
2266 ctx->sh_video->stream_delay = 0.0f;
2267 ctx->sh_video->timer = 0;
2268 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2271 if (ctx->sh_audio) {
2272 /// free audio packets and reset
2273 ds_free_packs(ctx->d_audio);
2274 audio_delay -= ctx->sh_audio->stream_delay;
2275 ctx->delay = -audio_delay;
2276 ao_reset(ctx->ao);
2277 resync_audio_stream(ctx->sh_audio);
2280 audio_delay = 0.0f;
2281 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2282 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2283 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2284 if (dvdsub_lang_id != opts->sub_id) {
2285 opts->sub_id = dvdsub_lang_id;
2286 select_subtitle(ctx);
2290 /// clear all EOF related flags
2291 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2294 /// Restore last decoded DVDNAV (still frame)
2295 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2296 int *in_size,
2297 unsigned char **start,
2298 mp_image_t *decoded_frame)
2300 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2301 return decoded_frame;
2303 /// a change occurred in dvdnav stream
2304 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2305 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2306 mp_dvdnav_context_free(mpctx);
2307 mp_dvdnav_reset_stream(mpctx);
2308 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2309 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2312 if (*in_size < 0) {
2313 float len;
2315 /// Display still frame, if any
2316 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2317 decoded_frame = mpctx->nav_smpi;
2319 /// increment video frame : continue playing after still frame
2320 len = get_time_length(mpctx);
2321 if (mpctx->sh_video->pts >= len &&
2322 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2323 mp_dvdnav_skip_still(mpctx->stream);
2324 mp_dvdnav_skip_wait(mpctx->stream);
2326 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2328 if (mpctx->nav_buffer) {
2329 *start = mpctx->nav_start;
2330 *in_size = mpctx->nav_in_size;
2331 if (mpctx->nav_start)
2332 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2336 return decoded_frame;
2339 /// Save last decoded DVDNAV (still frame)
2340 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2341 unsigned char *start,
2342 mp_image_t *decoded_frame)
2344 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2345 return;
2347 free(mpctx->nav_buffer);
2348 mpctx->nav_buffer = NULL;
2349 mpctx->nav_start = NULL;
2350 mpctx->nav_in_size = -1;
2352 if (in_size > 0)
2353 mpctx->nav_buffer = malloc(in_size);
2354 if (mpctx->nav_buffer) {
2355 mpctx->nav_start = start;
2356 mpctx->nav_in_size = in_size;
2357 memcpy(mpctx->nav_buffer, start, in_size);
2360 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2361 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2363 #endif /* CONFIG_DVDNAV */
2365 /* Modify video timing to match the audio timeline. There are two main
2366 * reasons this is needed. First, video and audio can start from different
2367 * positions at beginning of file or after a seek (MPlayer starts both
2368 * immediately even if they have different pts). Second, the file can have
2369 * audio timestamps that are inconsistent with the duration of the audio
2370 * packets, for example two consecutive timestamp values differing by
2371 * one second but only a packet with enough samples for half a second
2372 * of playback between them.
2374 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2376 current_module = "av_sync";
2378 if (!mpctx->sh_audio || mpctx->syncing_audio)
2379 return;
2381 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2382 double v_pts = mpctx->sh_video->pts;
2383 double av_delay = a_pts - v_pts;
2384 // Try to sync vo_flip() so it will *finish* at given time
2385 av_delay += mpctx->last_vo_flip_duration;
2386 av_delay -= audio_delay; // This much pts difference is desired
2388 double change = av_delay * 0.1;
2389 double max_change = default_max_pts_correction >= 0 ?
2390 default_max_pts_correction : frame_time * 0.1;
2391 if (change < -max_change)
2392 change = -max_change;
2393 else if (change > max_change)
2394 change = max_change;
2395 mpctx->delay += change;
2396 mpctx->total_avsync_change += change;
2399 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2400 double pts)
2402 if (mpctx->paused)
2403 return 0;
2404 struct ao *ao = mpctx->ao;
2405 double bps = ao->bps / mpctx->opts.playback_speed;
2406 ao->pts = pts;
2407 // hack used by some mpeg-writing AOs
2408 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2409 mpctx->delay) * 90000.0;
2410 int played = ao_play(mpctx->ao, data, len, flags);
2411 if (played > 0) {
2412 mpctx->delay += played / bps;
2413 // Keep correct pts for remaining data - could be used to flush
2414 // remaining buffer when closing ao.
2415 ao->pts += played / bps;
2417 return played;
2420 #define ASYNC_PLAY_DONE -3
2421 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2423 struct ao *ao = mpctx->ao;
2424 struct MPOpts *opts = &mpctx->opts;
2425 sh_audio_t * const sh_audio = mpctx->sh_audio;
2426 int res;
2428 // Timing info may not be set without
2429 res = decode_audio(sh_audio, &ao->buffer, 1);
2430 if (res < 0)
2431 return res;
2433 int bytes;
2434 bool did_retry = false;
2435 double written_pts;
2436 double bps = ao->bps / opts->playback_speed;
2437 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2438 mpctx->hrseek_active = false;
2439 while (1) {
2440 written_pts = written_audio_pts(mpctx);
2441 double ptsdiff;
2442 if (hrseek)
2443 ptsdiff = written_pts - mpctx->hrseek_pts;
2444 else
2445 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2446 - audio_delay;
2447 bytes = ptsdiff * bps;
2448 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2450 // ogg demuxers give packets without timing
2451 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2452 if (!did_retry) {
2453 // Try to read more data to see packets that have pts
2454 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2455 if (res < 0)
2456 return res;
2457 did_retry = true;
2458 continue;
2460 bytes = 0;
2463 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2464 bytes = 0;
2466 if (bytes > 0)
2467 break;
2469 mpctx->syncing_audio = false;
2470 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2471 int res = decode_audio(sh_audio, &ao->buffer, a);
2472 bytes += ao->buffer.len;
2473 if (bytes >= 0) {
2474 memmove(ao->buffer.start,
2475 ao->buffer.start + ao->buffer.len - bytes, bytes);
2476 ao->buffer.len = bytes;
2477 if (res < 0)
2478 return res;
2479 return decode_audio(sh_audio, &ao->buffer, playsize);
2481 ao->buffer.len = 0;
2482 if (res < 0)
2483 return res;
2485 if (hrseek)
2486 // Don't add silence in audio-only case even if position is too late
2487 return 0;
2488 int fillbyte = 0;
2489 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2490 fillbyte = 0x80;
2491 if (bytes >= playsize) {
2492 /* This case could fall back to the one below with
2493 * bytes = playsize, but then silence would keep accumulating
2494 * in a_out_buffer if the AO accepts less data than it asks for
2495 * in playsize. */
2496 char *p = malloc(playsize);
2497 memset(p, fillbyte, playsize);
2498 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2499 free(p);
2500 return ASYNC_PLAY_DONE;
2502 mpctx->syncing_audio = false;
2503 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2504 return decode_audio(sh_audio, &ao->buffer, playsize);
2507 static int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
2509 struct MPOpts *opts = &mpctx->opts;
2510 struct ao *ao = mpctx->ao;
2511 unsigned int t;
2512 double tt;
2513 int playsize;
2514 int playflags = 0;
2515 bool audio_eof = false;
2516 bool partial_fill = false;
2517 sh_audio_t * const sh_audio = mpctx->sh_audio;
2518 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2519 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2521 current_module = "play_audio";
2523 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2524 return 0;
2526 // hack used by some mpeg-writing AOs
2527 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2528 mpctx->delay) * 90000.0;
2530 if (mpctx->paused)
2531 playsize = 1; // just initialize things (audio pts at least)
2532 else
2533 playsize = ao_get_space(ao);
2535 // Fill buffer if needed:
2536 current_module = "decode_audio";
2537 t = GetTimer();
2539 // Coming here with hrseek_active still set means audio-only
2540 if (!mpctx->sh_video)
2541 mpctx->syncing_audio = false;
2542 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2543 mpctx->syncing_audio = false;
2544 mpctx->hrseek_active = false;
2547 int res;
2548 if (mpctx->syncing_audio || mpctx->hrseek_active)
2549 res = audio_start_sync(mpctx, playsize);
2550 else
2551 res = decode_audio(sh_audio, &ao->buffer, playsize);
2552 if (res < 0) { // EOF, error or format change
2553 if (res == -2) {
2554 /* The format change isn't handled too gracefully. A more precise
2555 * implementation would require draining buffered old-format audio
2556 * while displaying video, then doing the output format switch.
2558 uninit_player(mpctx, INITIALIZED_AO);
2559 reinit_audio_chain(mpctx);
2560 return -1;
2561 } else if (res == ASYNC_PLAY_DONE)
2562 return 0;
2563 else if (mpctx->d_audio->eof)
2564 audio_eof = true;
2566 t = GetTimer() - t;
2567 tt = t * 0.000001f;
2568 audio_time_usage += tt;
2569 if (endpts != MP_NOPTS_VALUE && modifiable_audio_format) {
2570 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2571 * ao->bps / opts->playback_speed;
2572 if (playsize > bytes) {
2573 playsize = FFMAX(bytes, 0);
2574 playflags |= AOPLAY_FINAL_CHUNK;
2575 audio_eof = true;
2576 partial_fill = true;
2580 assert(ao->buffer.len % unitsize == 0);
2581 if (playsize > ao->buffer.len) {
2582 partial_fill = true;
2583 playsize = ao->buffer.len;
2584 if (audio_eof)
2585 playflags |= AOPLAY_FINAL_CHUNK;
2587 playsize -= playsize % unitsize;
2588 if (!playsize)
2589 return partial_fill && audio_eof ? -2 : -partial_fill;
2591 // play audio:
2592 current_module = "play_audio";
2594 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2595 written_audio_pts(mpctx));
2596 assert(played % unitsize == 0);
2597 ao->buffer_playable_size = playsize - played;
2599 if (played > 0) {
2600 ao->buffer.len -= played;
2601 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2602 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2603 // Sanity check to avoid hanging in case current ao doesn't output
2604 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2605 return -2;
2608 return -partial_fill;
2611 int reinit_video_chain(struct MPContext *mpctx)
2613 struct MPOpts *opts = &mpctx->opts;
2614 sh_video_t * const sh_video = mpctx->sh_video;
2615 if (!sh_video)
2616 return 0;
2617 double ar = -1.0;
2618 //================== Init VIDEO (codec & libvo) ==========================
2619 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2620 current_module = "preinit_libvo";
2622 //shouldn't we set dvideo->id=-2 when we fail?
2623 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2624 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2625 mpctx->key_fifo,
2626 mpctx->input))) {
2627 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2628 "the selected video_out (-vo) device.\n");
2629 goto err_out;
2631 mpctx->initialized_flags |= INITIALIZED_VO;
2634 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2635 &ar) != STREAM_UNSUPPORTED)
2636 mpctx->sh_video->stream_aspect = ar;
2637 current_module = "init_video_filters";
2639 char *vf_arg[] = {
2640 "_oldargs_", (char *)mpctx->video_out, NULL
2642 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2645 #ifdef CONFIG_ASS
2646 if (opts->ass_enabled) {
2647 int i;
2648 int insert = 1;
2649 if (opts->vf_settings)
2650 for (i = 0; opts->vf_settings[i].name; ++i)
2651 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2652 insert = 0;
2653 break;
2655 if (insert) {
2656 extern vf_info_t vf_info_ass;
2657 const vf_info_t *libass_vfs[] = {
2658 &vf_info_ass, NULL
2660 char *vf_arg[] = {
2661 "auto", "1", NULL
2663 int retcode = 0;
2664 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2665 sh_video->vfilter,
2666 "ass", vf_arg,
2667 &retcode);
2668 if (vf_ass)
2669 sh_video->vfilter = vf_ass;
2670 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2671 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2672 else
2673 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2674 "ASS: cannot add video filter\n");
2677 #endif
2679 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2681 #ifdef CONFIG_ASS
2682 if (opts->ass_enabled)
2683 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2684 mpctx->ass_library);
2685 #endif
2687 current_module = "init_video_codec";
2689 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2690 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2691 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2693 if (!sh_video->initialized) {
2694 if (!opts->fixed_vo)
2695 uninit_player(mpctx, INITIALIZED_VO);
2696 goto err_out;
2699 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2701 if (sh_video->codec)
2702 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2703 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2705 sh_video->last_pts = MP_NOPTS_VALUE;
2706 sh_video->num_buffered_pts = 0;
2707 sh_video->next_frame_time = 0;
2709 if (opts->auto_quality > 0) {
2710 // Auto quality option enabled
2711 output_quality = get_video_quality_max(sh_video);
2712 if (opts->auto_quality > output_quality)
2713 opts->auto_quality = output_quality;
2714 else
2715 output_quality = opts->auto_quality;
2716 mp_msg(MSGT_CPLAYER, MSGL_V,
2717 "AutoQ: setting quality to %d.\n", output_quality);
2718 set_video_quality(sh_video, output_quality);
2721 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2723 current_module = "init_vo";
2725 return 1;
2727 err_out:
2728 mpctx->sh_video = mpctx->d_video->sh = NULL;
2729 return 0;
2732 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2734 struct sh_video *sh_video = mpctx->sh_video;
2735 double frame_time = 0;
2736 struct vo *video_out = mpctx->video_out;
2737 while (1) {
2738 current_module = "filter_video";
2739 // In nocorrect-pts mode there is no way to properly time these frames
2740 if (vo_get_buffered_frame(video_out, 0) >= 0)
2741 break;
2742 if (vf_output_queued_frame(sh_video->vfilter))
2743 break;
2744 unsigned char *packet = NULL;
2745 frame_time = sh_video->next_frame_time;
2746 if (mpctx->restart_playback)
2747 frame_time = 0;
2748 int in_size = 0;
2749 while (!in_size)
2750 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2751 &packet, force_fps);
2752 if (in_size < 0) {
2753 #ifdef CONFIG_DVDNAV
2754 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2755 if (mp_dvdnav_is_eof(mpctx->stream))
2756 return -1;
2757 if (mpctx->d_video)
2758 mpctx->d_video->eof = 0;
2759 if (mpctx->d_audio)
2760 mpctx->d_audio->eof = 0;
2761 mpctx->stream->eof = 0;
2762 } else
2763 #endif
2764 return -1;
2766 if (in_size > max_framesize)
2767 max_framesize = in_size;
2768 sh_video->timer += frame_time;
2769 if (mpctx->sh_audio)
2770 mpctx->delay -= frame_time;
2771 // video_read_frame can change fps (e.g. for ASF video)
2772 vo_fps = sh_video->fps;
2773 int framedrop_type = check_framedrop(mpctx, frame_time);
2774 current_module = "decode video";
2776 void *decoded_frame;
2777 #ifdef CONFIG_DVDNAV
2778 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2779 if (in_size >= 0 && !decoded_frame)
2780 #endif
2781 decoded_frame = decode_video(sh_video, NULL, packet, in_size,
2782 framedrop_type, sh_video->pts);
2783 #ifdef CONFIG_DVDNAV
2784 // Save last still frame for future display
2785 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2786 #endif
2787 if (decoded_frame) {
2788 current_module = "filter video";
2789 filter_video(sh_video, decoded_frame, sh_video->pts);
2791 break;
2793 return frame_time;
2796 static void determine_frame_pts(struct MPContext *mpctx)
2798 struct sh_video *sh_video = mpctx->sh_video;
2799 struct MPOpts *opts = &mpctx->opts;
2801 if (opts->user_pts_assoc_mode)
2802 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2803 else if (sh_video->pts_assoc_mode == 0) {
2804 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2805 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2806 sh_video->pts_assoc_mode = 1;
2807 else
2808 sh_video->pts_assoc_mode = 2;
2809 } else {
2810 int probcount1 = sh_video->num_reordered_pts_problems;
2811 int probcount2 = sh_video->num_sorted_pts_problems;
2812 if (sh_video->pts_assoc_mode == 2) {
2813 int tmp = probcount1;
2814 probcount1 = probcount2;
2815 probcount2 = tmp;
2817 if (probcount1 >= probcount2 * 1.5 + 2) {
2818 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2819 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2820 "%d.\n", sh_video->pts_assoc_mode);
2823 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2824 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2827 static double update_video(struct MPContext *mpctx)
2829 struct sh_video *sh_video = mpctx->sh_video;
2830 struct vo *video_out = mpctx->video_out;
2831 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2832 mpctx->osd); // hack for vf_expand
2833 if (!mpctx->opts.correct_pts)
2834 return update_video_nocorrect_pts(mpctx);
2836 double pts;
2838 while (1) {
2839 current_module = "filter_video";
2840 if (vo_get_buffered_frame(video_out, false) >= 0)
2841 break;
2842 // XXX Time used in this call is not counted in any performance
2843 // timer now
2844 if (vf_output_queued_frame(sh_video->vfilter))
2845 break;
2846 int in_size = 0;
2847 unsigned char *buf = NULL;
2848 pts = MP_NOPTS_VALUE;
2849 struct demux_packet *pkt;
2850 while (1) {
2851 pkt = ds_get_packet2(mpctx->d_video, false);
2852 if (!pkt || pkt->len)
2853 break;
2854 /* Packets with size 0 are assumed to not correspond to frames,
2855 * but to indicate the absence of a frame in formats like AVI
2856 * that must have packets at fixed timecode intervals. */
2858 if (pkt) {
2859 in_size = pkt->len;
2860 buf = pkt->buffer;
2861 pts = pkt->pts;
2863 if (pts != MP_NOPTS_VALUE)
2864 pts += mpctx->video_offset;
2865 if (in_size > max_framesize)
2866 max_framesize = in_size;
2867 current_module = "decode video";
2868 if (pts >= mpctx->hrseek_pts - .005)
2869 mpctx->hrseek_framedrop = false;
2870 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2871 check_framedrop(mpctx, sh_video->frametime);
2872 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2873 framedrop_type, pts);
2874 if (decoded_frame) {
2875 determine_frame_pts(mpctx);
2876 current_module = "filter video";
2877 filter_video(sh_video, decoded_frame, sh_video->pts);
2878 } else if (!pkt) {
2879 if (vo_get_buffered_frame(video_out, true) < 0)
2880 return -1;
2882 break;
2885 if (!video_out->frame_loaded)
2886 return 0;
2888 pts = video_out->next_pts;
2889 if (pts == MP_NOPTS_VALUE) {
2890 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2891 // Try to use decoder pts from before filters
2892 pts = sh_video->pts;
2893 if (pts == MP_NOPTS_VALUE)
2894 pts = sh_video->last_pts;
2896 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2897 vo_skip_frame(video_out);
2898 return 0;
2900 mpctx->hrseek_active = false;
2901 sh_video->pts = pts;
2902 if (sh_video->last_pts == MP_NOPTS_VALUE)
2903 sh_video->last_pts = sh_video->pts;
2904 else if (sh_video->last_pts > sh_video->pts) {
2905 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2906 sh_video->pts, sh_video->last_pts);
2907 /* If the difference in pts is small treat it as jitter around the
2908 * right value (possibly caused by incorrect timestamp ordering) and
2909 * just show this frame immediately after the last one.
2910 * Treat bigger differences as timestamp resets and start counting
2911 * timing of later frames from the position of this one. */
2912 if (sh_video->last_pts - sh_video->pts > 0.5)
2913 sh_video->last_pts = sh_video->pts;
2914 else
2915 sh_video->pts = sh_video->last_pts;
2917 double frame_time = sh_video->pts - sh_video->last_pts;
2918 sh_video->last_pts = sh_video->pts;
2919 sh_video->timer += frame_time;
2920 if (mpctx->sh_audio)
2921 mpctx->delay -= frame_time;
2922 return frame_time;
2925 static int get_cache_fill(struct MPContext *mpctx)
2927 #ifdef CONFIG_STREAM_CACHE
2928 if (stream_cache_size > 0)
2929 return cache_fill_status(mpctx->stream);
2930 #endif
2931 return -1;
2934 static void update_pause_message(struct MPContext *mpctx)
2936 struct MPOpts *opts = &mpctx->opts;
2938 if (opts->quiet)
2939 return;
2941 int cache_fill = get_cache_fill(mpctx);
2942 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2944 if (!mpctx->status_printed && !cache_changed)
2945 return;
2947 char *msg = mp_gtext(" ===== PAUSE =====");
2948 char *tmpmem = NULL;
2949 if (cache_fill >= 0)
2950 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
2952 if (opts->term_osd && !mpctx->sh_video) {
2953 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
2954 update_osd_msg(mpctx);
2955 } else {
2956 if (mpctx->status_printed)
2957 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
2958 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
2961 mpctx->paused_cache_fill = cache_fill;
2962 mpctx->status_printed = false;
2964 talloc_free(tmpmem);
2967 void pause_player(struct MPContext *mpctx)
2969 if (mpctx->paused)
2970 return;
2971 mpctx->paused = 1;
2972 mpctx->step_frames = 0;
2973 mpctx->time_frame -= get_relative_time(mpctx);
2974 mpctx->osd_function = OSD_PAUSE;
2976 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2977 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2979 if (mpctx->ao && mpctx->sh_audio)
2980 ao_pause(mpctx->ao); // pause audio, keep data if possible
2982 mpctx->paused_cache_fill = get_cache_fill(mpctx);
2983 mpctx->status_printed = true;
2984 update_pause_message(mpctx);
2986 if (!mpctx->opts.quiet)
2987 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2990 void unpause_player(struct MPContext *mpctx)
2992 if (!mpctx->paused)
2993 return;
2994 mpctx->paused = 0;
2995 if (!mpctx->step_frames)
2996 mpctx->osd_function = OSD_PLAY;
2998 if (mpctx->ao && mpctx->sh_audio)
2999 ao_resume(mpctx->ao);
3000 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3001 && !mpctx->step_frames)
3002 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3003 (void)get_relative_time(mpctx); // ignore time that passed during pause
3006 static int redraw_osd(struct MPContext *mpctx)
3008 struct sh_video *sh_video = mpctx->sh_video;
3009 struct vf_instance *vf = sh_video->vfilter;
3010 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3011 return -1;
3012 if (vo_redraw_frame(mpctx->video_out) < 0)
3013 return -1;
3014 mpctx->osd->pts = mpctx->video_pts;
3015 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3016 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3017 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3018 vo_flip_page(mpctx->video_out, 0, -1);
3019 return 0;
3022 void add_step_frame(struct MPContext *mpctx)
3024 mpctx->step_frames++;
3025 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3026 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3027 unpause_player(mpctx);
3030 static void reinit_decoders(struct MPContext *mpctx)
3032 reinit_video_chain(mpctx);
3033 reinit_audio_chain(mpctx);
3034 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3037 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3039 if (mpctx->sh_video) {
3040 current_module = "seek_video_reset";
3041 resync_video_stream(mpctx->sh_video);
3042 mpctx->sh_video->timer = 0;
3043 vo_seek_reset(mpctx->video_out);
3044 mpctx->sh_video->timer = 0;
3045 mpctx->sh_video->num_buffered_pts = 0;
3046 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3047 mpctx->delay = 0;
3048 mpctx->time_frame = 0;
3049 // Not all demuxers set d_video->pts during seek, so this value
3050 // (which is used by at least vobsub code below) may be completely
3051 // wrong (probably 0).
3052 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3053 mpctx->video_pts = mpctx->sh_video->pts;
3054 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3055 true);
3056 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3059 if (mpctx->sh_audio) {
3060 current_module = "seek_audio_reset";
3061 resync_audio_stream(mpctx->sh_audio);
3062 if (reset_ao)
3063 ao_reset(mpctx->ao);
3064 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3065 mpctx->sh_audio->a_buffer_len = 0;
3066 if (!mpctx->sh_video)
3067 update_subtitles(mpctx, mpctx->sh_audio->pts,
3068 mpctx->video_offset, true);
3071 if (vo_vobsub && mpctx->sh_video) {
3072 current_module = "seek_vobsub_reset";
3073 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3076 mpctx->restart_playback = true;
3077 mpctx->hrseek_active = false;
3078 mpctx->hrseek_framedrop = false;
3079 mpctx->total_avsync_change = 0;
3080 audio_time_usage = 0;
3081 video_time_usage = 0;
3082 vout_time_usage = 0;
3083 drop_frame_cnt = 0;
3085 current_module = NULL;
3088 static bool timeline_set_part(struct MPContext *mpctx, int i)
3090 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3091 struct timeline_part *n = mpctx->timeline + i;
3092 mpctx->timeline_part = i;
3093 mpctx->video_offset = n->start - n->source_start;
3094 if (n->source == p->source)
3095 return false;
3096 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3097 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3098 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3099 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3100 mpctx->stop_play = orig_stop_play;
3101 mpctx->demuxer = n->source->demuxer;
3102 mpctx->d_video = mpctx->demuxer->video;
3103 mpctx->d_audio = mpctx->demuxer->audio;
3104 mpctx->d_sub = mpctx->demuxer->sub;
3105 mpctx->sh_video = mpctx->d_video->sh;
3106 mpctx->sh_audio = mpctx->d_audio->sh;
3107 return true;
3110 // Given pts, switch playback to the corresponding part.
3111 // Return offset within that part.
3112 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3113 bool *need_reset)
3115 if (pts < 0)
3116 pts = 0;
3117 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3118 struct timeline_part *p = mpctx->timeline + i;
3119 if (pts < (p + 1)->start) {
3120 *need_reset = timeline_set_part(mpctx, i);
3121 return pts - p->start + p->source_start;
3124 return -1;
3128 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3129 static int seek(MPContext *mpctx, struct seek_params seek,
3130 bool timeline_fallthrough)
3132 struct MPOpts *opts = &mpctx->opts;
3134 current_module = "seek";
3135 if (mpctx->stop_play == AT_END_OF_FILE)
3136 mpctx->stop_play = KEEP_PLAYING;
3137 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3138 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3139 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3140 || opts->hr_seek > 0 || seek.exact > 0;
3141 if (seek.type == MPSEEK_FACTOR
3142 || seek.type == MPSEEK_ABSOLUTE
3143 && seek.amount < mpctx->last_chapter_pts
3144 || seek.amount < 0)
3145 mpctx->last_chapter_seek = -2;
3146 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3147 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3148 seek.type = MPSEEK_ABSOLUTE;
3150 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3151 && seek.type == MPSEEK_RELATIVE) {
3152 seek.type = MPSEEK_ABSOLUTE;
3153 seek.direction = seek.amount > 0 ? 1 : -1;
3154 seek.amount += get_current_time(mpctx);
3157 /* At least the liba52 decoder wants to read from the input stream
3158 * during initialization, so reinit must be done after the demux_seek()
3159 * call that clears possible stream EOF. */
3160 bool need_reset = false;
3161 double demuxer_amount = seek.amount;
3162 if (mpctx->timeline) {
3163 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3164 &need_reset);
3165 if (demuxer_amount == -1) {
3166 mpctx->stop_play = AT_END_OF_FILE;
3167 // Clear audio from current position
3168 if (mpctx->sh_audio) {
3169 ao_reset(mpctx->ao);
3170 mpctx->sh_audio->a_buffer_len = 0;
3172 return -1;
3175 int demuxer_style = 0;
3176 switch (seek.type) {
3177 case MPSEEK_FACTOR:
3178 demuxer_style |= SEEK_FACTOR; // fallthrough
3179 case MPSEEK_ABSOLUTE:
3180 demuxer_style |= SEEK_ABSOLUTE;
3182 if (hr_seek || seek.direction < 0)
3183 demuxer_style |= SEEK_BACKWARD;
3184 else if (seek.direction > 0)
3185 demuxer_style |= SEEK_FORWARD;
3187 if (hr_seek)
3188 demuxer_amount -= opts->hr_seek_demuxer_offset;
3189 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3190 demuxer_style);
3191 if (need_reset)
3192 reinit_decoders(mpctx);
3193 if (seekresult == 0)
3194 return -1;
3196 seek_reset(mpctx, !timeline_fallthrough);
3198 /* Use the target time as "current position" for further relative
3199 * seeks etc until a new video frame has been decoded */
3200 if (seek.type == MPSEEK_ABSOLUTE) {
3201 mpctx->video_pts = seek.amount;
3202 mpctx->last_seek_pts = seek.amount;
3203 } else
3204 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3206 if (hr_seek) {
3207 mpctx->hrseek_active = true;
3208 mpctx->hrseek_framedrop = true;
3209 mpctx->hrseek_pts = seek.amount;
3212 mpctx->start_timestamp = GetTimerMS();
3214 return 0;
3217 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3218 int exact)
3220 struct seek_params *seek = &mpctx->seek;
3221 switch (type) {
3222 case MPSEEK_RELATIVE:
3223 if (seek->type == MPSEEK_FACTOR)
3224 return; // Well... not common enough to bother doing better
3225 seek->amount += amount;
3226 seek->exact = FFMAX(seek->exact, exact);
3227 if (seek->type == MPSEEK_NONE)
3228 seek->exact = exact;
3229 if (seek->type == MPSEEK_ABSOLUTE)
3230 return;
3231 if (seek->amount == 0) {
3232 *seek = (struct seek_params){ 0 };
3233 return;
3235 seek->type = MPSEEK_RELATIVE;
3236 return;
3237 case MPSEEK_ABSOLUTE:
3238 case MPSEEK_FACTOR:
3239 *seek = (struct seek_params) {
3240 .type = type,
3241 .amount = amount,
3242 .exact = exact,
3244 return;
3245 case MPSEEK_NONE:
3246 *seek = (struct seek_params){ 0 };
3247 return;
3249 abort();
3253 double get_time_length(struct MPContext *mpctx)
3255 if (mpctx->timeline)
3256 return mpctx->timeline[mpctx->num_timeline_parts].start;
3258 struct demuxer *demuxer = mpctx->demuxer;
3259 double get_time_ans;
3260 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3261 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3262 (void *) &get_time_ans) > 0)
3263 return get_time_ans;
3265 struct sh_video *sh_video = mpctx->d_video->sh;
3266 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3267 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3268 return (double) (demuxer->movi_end - demuxer->movi_start) /
3269 (sh_video->i_bps + sh_audio->i_bps);
3270 if (sh_video && sh_video->i_bps)
3271 return (double) (demuxer->movi_end - demuxer->movi_start) /
3272 sh_video->i_bps;
3273 if (sh_audio && sh_audio->i_bps)
3274 return (double) (demuxer->movi_end - demuxer->movi_start) /
3275 sh_audio->i_bps;
3276 return 0;
3279 /* If there are timestamps from stream level then use those (for example
3280 * DVDs can have consistent times there while the MPEG-level timestamps
3281 * reset). */
3282 double get_current_time(struct MPContext *mpctx)
3284 struct demuxer *demuxer = mpctx->demuxer;
3285 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3286 return demuxer->stream_pts;
3287 if (mpctx->sh_video) {
3288 double pts = mpctx->video_pts;
3289 if (pts != MP_NOPTS_VALUE)
3290 return pts;
3292 double apts = playing_audio_pts(mpctx);
3293 if (apts != MP_NOPTS_VALUE)
3294 return apts;
3295 return mpctx->last_seek_pts;
3298 int get_percent_pos(struct MPContext *mpctx)
3300 struct demuxer *demuxer = mpctx->demuxer;
3301 int ans = 0;
3302 if (mpctx->timeline)
3303 ans = get_current_time(mpctx) * 100 /
3304 mpctx->timeline[mpctx->num_timeline_parts].start;
3305 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3307 else {
3308 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3309 off_t pos = demuxer->filepos > 0 ?
3310 demuxer->filepos : stream_tell(demuxer->stream);
3311 if (len > 0)
3312 ans = (pos - demuxer->movi_start) / len;
3313 else
3314 ans = 0;
3316 if (ans < 0)
3317 ans = 0;
3318 if (ans > 100)
3319 ans = 100;
3320 return ans;
3323 // -2 is no chapters, -1 is before first chapter
3324 int get_current_chapter(struct MPContext *mpctx)
3326 double current_pts = get_current_time(mpctx);
3327 if (!mpctx->chapters)
3328 return FFMAX(mpctx->last_chapter_seek,
3329 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3331 int i;
3332 for (i = 1; i < mpctx->num_chapters; i++)
3333 if (current_pts < mpctx->chapters[i].start)
3334 break;
3335 return FFMAX(mpctx->last_chapter_seek, i - 1);
3338 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3340 char *name = chapter_name(mpctx, chapter);
3341 if (name) {
3342 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3343 } else {
3344 int chapter_count = get_chapter_count(mpctx);
3345 if (chapter_count <= 0)
3346 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3347 else
3348 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3349 chapter_count);
3351 return name;
3354 // returns NULL if chapter name unavailable
3355 char *chapter_name(struct MPContext *mpctx, int chapter)
3357 if (!mpctx->chapters)
3358 return demuxer_chapter_name(mpctx->demuxer, chapter);
3359 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3362 // returns the start of the chapter in seconds
3363 double chapter_start_time(struct MPContext *mpctx, int chapter)
3365 if (!mpctx->chapters)
3366 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3367 return mpctx->chapters[chapter].start;
3370 int get_chapter_count(struct MPContext *mpctx)
3372 if (!mpctx->chapters)
3373 return demuxer_chapter_count(mpctx->demuxer);
3374 return mpctx->num_chapters;
3377 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3379 mpctx->last_chapter_seek = -2;
3380 if (!mpctx->chapters) {
3381 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3382 if (res >= 0) {
3383 if (*seek_pts == -1)
3384 seek_reset(mpctx, true);
3385 else {
3386 mpctx->last_chapter_seek = res;
3387 mpctx->last_chapter_pts = *seek_pts;
3390 return res;
3393 if (chapter >= mpctx->num_chapters)
3394 return -1;
3395 if (chapter < 0)
3396 chapter = 0;
3397 *seek_pts = mpctx->chapters[chapter].start;
3398 mpctx->last_chapter_seek = chapter;
3399 mpctx->last_chapter_pts = *seek_pts;
3400 return chapter;
3404 static void run_playloop(struct MPContext *mpctx)
3406 struct MPOpts *opts = &mpctx->opts;
3407 bool full_audio_buffers = false;
3408 bool audio_left = false, video_left = false;
3409 double endpts = end_at.type == END_AT_TIME ? end_at.pos : MP_NOPTS_VALUE;
3410 bool end_is_chapter = false;
3411 double sleeptime = 0.5;
3412 bool was_restart = mpctx->restart_playback;
3414 if (mpctx->timeline) {
3415 double end = mpctx->timeline[mpctx->timeline_part + 1].start;
3416 if (endpts == MP_NOPTS_VALUE || end < endpts) {
3417 endpts = end;
3418 end_is_chapter = true;
3422 if (opts->chapterrange[1] > 0) {
3423 int cur_chapter = get_current_chapter(mpctx);
3424 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3425 mpctx->stop_play = PT_NEXT_ENTRY;
3428 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3429 mpctx->sh_audio = mpctx->d_audio->sh;
3430 mpctx->sh_audio->ds = mpctx->d_audio;
3431 reinit_audio_chain(mpctx);
3434 if (mpctx->step_frames && !mpctx->sh_video) {
3435 mpctx->step_frames = 0;
3436 pause_player(mpctx);
3439 if (mpctx->sh_audio && !mpctx->restart_playback) {
3440 int status = fill_audio_out_buffers(mpctx, endpts);
3441 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3442 // Not at audio stream EOF yet
3443 audio_left = status > -2;
3446 double buffered_audio = -1;
3447 while (mpctx->sh_video) { // never loops, for "break;" only
3448 vo_pts = mpctx->sh_video->timer * 90000.0;
3449 vo_fps = mpctx->sh_video->fps;
3451 video_left = mpctx->video_out->hasframe;
3452 if (!mpctx->video_out->frame_loaded
3453 && (!mpctx->paused || mpctx->restart_playback)) {
3454 double frame_time = update_video(mpctx);
3455 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3456 if (mpctx->sh_video->vf_initialized < 0) {
3457 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3458 "\nFATAL: Could not initialize video filters (-vf) "
3459 "or video output (-vo).\n");
3460 mpctx->stop_play = PT_NEXT_ENTRY;
3461 return;
3463 video_left = frame_time >= 0;
3464 if (endpts != MP_NOPTS_VALUE)
3465 video_left &= mpctx->sh_video->pts < endpts;
3466 if (video_left && !mpctx->restart_playback) {
3467 mpctx->time_frame += frame_time / opts->playback_speed;
3468 adjust_sync(mpctx, frame_time);
3472 // ================================================================
3474 current_module = "vo_check_events";
3475 vo_check_events(mpctx->video_out);
3477 #ifdef CONFIG_X11
3478 if (stop_xscreensaver) {
3479 current_module = "stop_xscreensaver";
3480 xscreensaver_heartbeat(mpctx->x11_state);
3482 #endif
3483 if (heartbeat_cmd) {
3484 static unsigned last_heartbeat;
3485 unsigned now = GetTimerMS();
3486 if (now - last_heartbeat > 30000) {
3487 last_heartbeat = now;
3488 system(heartbeat_cmd);
3492 if (!video_left || (mpctx->paused && !mpctx->restart_playback))
3493 break;
3494 if (!mpctx->video_out->frame_loaded) {
3495 sleeptime = 0;
3496 break;
3499 mpctx->time_frame -= get_relative_time(mpctx);
3500 if (full_audio_buffers && !mpctx->restart_playback) {
3501 buffered_audio = ao_get_delay(mpctx->ao);
3502 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", buffered_audio);
3504 if (opts->autosync) {
3505 /* Smooth reported playback position from AO by averaging
3506 * it with the value expected based on previus value and
3507 * time elapsed since then. May help smooth video timing
3508 * with audio output that have inaccurate position reporting.
3509 * This is badly implemented; the behavior of the smoothing
3510 * now undesirably depends on how often this code runs
3511 * (mainly depends on video frame rate). */
3512 float predicted = (mpctx->delay / opts->playback_speed +
3513 mpctx->time_frame);
3514 float difference = buffered_audio - predicted;
3515 buffered_audio = predicted + difference / opts->autosync;
3518 mpctx->time_frame = (buffered_audio -
3519 mpctx->delay / opts->playback_speed);
3520 } else {
3521 /* If we're more than 200 ms behind the right playback
3522 * position, don't try to speed up display of following
3523 * frames to catch up; continue with default speed from
3524 * the current frame instead.
3525 * If benchmark is set always output frames immediately
3526 * without sleeping.
3528 if (mpctx->time_frame < -0.2 || opts->benchmark)
3529 mpctx->time_frame = 0;
3532 double vsleep = mpctx->time_frame - mpctx->video_out->flip_queue_offset;
3533 if (vsleep > 0.050) {
3534 sleeptime = FFMIN(sleeptime, vsleep - 0.040);
3535 break;
3537 sleeptime = 0;
3539 //=================== FLIP PAGE (VIDEO BLT): ======================
3541 current_module = "flip_page";
3542 vo_new_frame_imminent(mpctx->video_out);
3543 struct sh_video *sh_video = mpctx->sh_video;
3544 mpctx->video_pts = sh_video->pts;
3545 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3546 update_teletext(sh_video, mpctx->demuxer, 0);
3547 update_osd_msg(mpctx);
3548 struct vf_instance *vf = sh_video->vfilter;
3549 mpctx->osd->pts = mpctx->video_pts;
3550 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3551 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3552 vo_osd_changed(0);
3554 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3555 float aq_sleep_time = mpctx->time_frame;
3556 if (mpctx->time_frame > 0.001
3557 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3558 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3559 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3561 unsigned int t2 = GetTimer();
3562 /* Playing with playback speed it's possible to get pathological
3563 * cases with mpctx->time_frame negative enough to cause an
3564 * overflow in pts_us calculation, thus the FFMAX. */
3565 double time_frame = FFMAX(mpctx->time_frame, -1);
3566 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3567 int duration = -1;
3568 double pts2 = mpctx->video_out->next_pts2;
3569 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts &&
3570 !mpctx->restart_playback) {
3571 // expected A/V sync correction is ignored
3572 double diff = (pts2 - mpctx->video_pts);
3573 diff /= opts->playback_speed;
3574 if (mpctx->time_frame < 0)
3575 diff += mpctx->time_frame;
3576 if (diff < 0)
3577 diff = 0;
3578 if (diff > 10)
3579 diff = 10;
3580 duration = diff * 1e6;
3582 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3584 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3585 vout_time_usage += mpctx->last_vo_flip_duration;
3586 if (mpctx->video_out->driver->flip_page_timed) {
3587 // No need to adjust sync based on flip speed
3588 mpctx->last_vo_flip_duration = 0;
3589 // For print_status - VO call finishing early is OK for sync
3590 mpctx->time_frame -= get_relative_time(mpctx);
3592 if (mpctx->restart_playback) {
3593 mpctx->syncing_audio = true;
3594 if (mpctx->sh_audio)
3595 fill_audio_out_buffers(mpctx, endpts);
3596 mpctx->restart_playback = false;
3597 mpctx->time_frame = 0;
3598 get_relative_time(mpctx);
3600 print_status(mpctx, MP_NOPTS_VALUE, true);
3601 screenshot_flip(mpctx);
3603 if (opts->auto_quality > 0) {
3604 current_module = "autoq";
3605 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3606 ++output_quality;
3607 else if (output_quality > 1 && aq_sleep_time < 0)
3608 --output_quality;
3609 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3610 output_quality = 0;
3611 set_video_quality(mpctx->sh_video, output_quality);
3614 if (play_n_frames >= 0) {
3615 --play_n_frames;
3616 if (play_n_frames <= 0)
3617 mpctx->stop_play = PT_NEXT_ENTRY;
3619 if (mpctx->step_frames > 0) {
3620 mpctx->step_frames--;
3621 if (mpctx->step_frames == 0)
3622 pause_player(mpctx);
3624 break;
3625 } // video
3627 #ifdef CONFIG_DVDNAV
3628 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3629 nav_highlight_t hl;
3630 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3631 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3632 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3633 vo_osd_changed(OSDTYPE_DVDNAV);
3634 } else {
3635 osd_set_nav_box(0, 0, 0, 0);
3636 vo_osd_changed(OSDTYPE_DVDNAV);
3637 vo_osd_changed(OSDTYPE_SPU);
3640 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3641 double ar = -1.0;
3642 if (mpctx->sh_video &&
3643 stream_control(mpctx->demuxer->stream,
3644 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3645 != STREAM_UNSUPPORTED)
3646 mpctx->sh_video->stream_aspect = ar;
3649 #endif
3651 if (mpctx->restart_playback && !video_left) {
3652 if (mpctx->sh_audio) {
3653 int status = fill_audio_out_buffers(mpctx, endpts);
3654 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3655 // Not at audio stream EOF yet
3656 audio_left = status > -2;
3658 mpctx->restart_playback = false;
3660 if (mpctx->sh_audio && buffered_audio == -1)
3661 buffered_audio = mpctx->paused ? 0 : ao_get_delay(mpctx->ao);
3663 update_osd_msg(mpctx);
3664 if (mpctx->paused)
3665 update_pause_message(mpctx);
3666 if (!video_left && (!mpctx->paused || was_restart)) {
3667 double a_pos = 0;
3668 if (mpctx->sh_audio) {
3669 a_pos = (written_audio_pts(mpctx) -
3670 mpctx->opts.playback_speed * buffered_audio);
3672 print_status(mpctx, a_pos, false);
3674 if (!mpctx->sh_video)
3675 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3678 /* It's possible for the user to simultaneously switch both audio
3679 * and video streams to "disabled" at runtime. Handle this by waiting
3680 * rather than immediately stopping playback due to EOF.
3682 * When all audio has been written to output driver, stay in the
3683 * main loop handling commands until it has been mostly consumed,
3684 * except in the gapless case, where the next file will be started
3685 * while audio from the current one still remains to be played.
3687 * We want this check to trigger if we seeked to this position,
3688 * but not if we paused at it with audio possibly still buffered in
3689 * the AO. There's currently no working way to check buffered audio
3690 * inside AO while paused. Thus the "was_restart" check below, which
3691 * should trigger after seek only, when we know there's no audio
3692 * buffered.
3694 if ((mpctx->sh_audio || mpctx->sh_video) && !audio_left && !video_left
3695 && (opts->gapless_audio || buffered_audio < 0.05)
3696 && (!mpctx->paused || was_restart)) {
3697 if (end_is_chapter) {
3698 seek(mpctx, (struct seek_params){
3699 .type = MPSEEK_ABSOLUTE,
3700 .amount = mpctx->timeline[mpctx->timeline_part+1].start
3701 }, true);
3702 } else
3703 mpctx->stop_play = AT_END_OF_FILE;
3704 } else if (!mpctx->stop_play) {
3705 double audio_sleep = 9;
3706 if (mpctx->sh_audio && !mpctx->paused) {
3707 if (mpctx->ao->untimed) {
3708 if (!mpctx->sh_video)
3709 audio_sleep = 0;
3710 } else if (full_audio_buffers) {
3711 audio_sleep = buffered_audio - 0.050;
3712 // Keep extra safety margin if the buffers are large
3713 if (audio_sleep > 0.100)
3714 audio_sleep = FFMAX(audio_sleep - 0.200, 0.100);
3715 else
3716 audio_sleep = FFMAX(audio_sleep, 0.020);
3717 } else
3718 audio_sleep = 0.020;
3720 sleeptime = FFMIN(sleeptime, audio_sleep);
3721 if (sleeptime > 0) {
3722 if (!mpctx->sh_video)
3723 goto novideo;
3724 int hack = vo_osd_changed(0);
3725 vo_osd_changed(hack);
3726 if (hack || mpctx->video_out->want_redraw) {
3727 if (redraw_osd(mpctx) < 0) {
3728 if (mpctx->paused && video_left)
3729 add_step_frame(mpctx);
3730 else
3731 goto novideo;
3732 } else
3733 vo_osd_changed(0);
3734 } else {
3735 novideo:
3736 mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
3741 //================= Keyboard events, SEEKing ====================
3743 current_module = "key_events";
3745 mp_cmd_t *cmd;
3746 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3747 /* Allow running consecutive seek commands to combine them,
3748 * but execute the seek before running other commands.
3749 * If the user seeks continuously (keeps arrow key down)
3750 * try to finish showing a frame from one location before doing
3751 * another seek (which could lead to unchanging display). */
3752 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3753 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3754 && GetTimerMS() - mpctx->start_timestamp < 300)
3755 break;
3756 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3757 run_command(mpctx, cmd);
3758 mp_cmd_free(cmd);
3759 if (mpctx->stop_play)
3760 break;
3763 // handle -sstep
3764 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3765 mpctx->osd_function = OSD_FFW;
3766 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3769 /* Looping. */
3770 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3771 mpctx->stop_play == PT_NEXT_ENTRY)) {
3772 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3774 if (opts->loop_times > 1)
3775 opts->loop_times--;
3776 else if (opts->loop_times == 1)
3777 opts->loop_times = -1;
3778 play_n_frames = play_n_frames_mf;
3779 mpctx->stop_play = 0;
3780 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3783 if (mpctx->seek.type) {
3784 seek(mpctx, mpctx->seek, false);
3785 mpctx->seek = (struct seek_params){ 0 };
3790 static int read_keys(void *ctx, int fd)
3792 getch2(ctx);
3793 return MP_INPUT_NOTHING;
3796 static bool attachment_is_font(struct demux_attachment *att)
3798 if (!att->name || !att->type || !att->data || !att->data_size)
3799 return false;
3800 // match against MIME types
3801 if (strcmp(att->type, "application/x-truetype-font") == 0
3802 || strcmp(att->type, "application/x-font") == 0)
3803 return true;
3804 // fallback: match against file extension
3805 if (strlen(att->name) > 4) {
3806 char *ext = att->name + strlen(att->name) - 4;
3807 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3808 || strcasecmp(ext, ".otf") == 0)
3809 return true;
3811 return false;
3814 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3816 if (audio_id == -1)
3817 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3818 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3819 demuxer_switch_audio(demuxer, audio_id);
3820 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3821 demuxer->audio->id = -2;
3822 demuxer->audio->sh = NULL;
3824 return demuxer->audio->id;
3827 static void print_version(const char *name)
3829 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3831 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3832 GetCpuCaps(&gCpuCaps);
3833 #if ARCH_X86
3834 mp_msg(MSGT_CPLAYER, MSGL_V,
3835 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3836 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3837 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3838 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3839 #if CONFIG_RUNTIME_CPUDETECT
3840 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3841 #else
3842 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3843 if (HAVE_MMX)
3844 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3845 if (HAVE_MMX2)
3846 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3847 if (HAVE_AMD3DNOW)
3848 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3849 if (HAVE_AMD3DNOWEXT)
3850 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3851 if (HAVE_SSE)
3852 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3853 if (HAVE_SSE2)
3854 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3855 if (HAVE_SSSE3)
3856 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3857 if (HAVE_CMOV)
3858 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3859 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3860 #endif /* CONFIG_RUNTIME_CPUDETECT */
3861 #endif /* ARCH_X86 */
3862 print_libav_versions();
3865 #ifdef PTW32_STATIC_LIB
3866 static void detach_ptw32(void)
3868 pthread_win32_thread_detach_np();
3869 pthread_win32_process_detach_np();
3871 #endif
3873 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3874 * file for some tools to link against. */
3875 #ifndef DISABLE_MAIN
3876 int main(int argc, char *argv[])
3878 #ifdef PTW32_STATIC_LIB
3879 pthread_win32_process_attach_np();
3880 pthread_win32_thread_attach_np();
3881 atexit(detach_ptw32);
3882 #endif
3883 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3884 || !strcmp(argv[1], "--leak-report")))
3885 talloc_enable_leak_report();
3887 #ifdef __MINGW32__
3888 mp_get_converted_argv(&argc, &argv);
3889 #endif
3891 char *mem_ptr;
3893 // movie info:
3895 /* Flag indicating whether MPlayer should exit without playing anything. */
3896 int opt_exit = 0;
3897 int i;
3899 struct MPContext *mpctx = talloc(NULL, MPContext);
3900 *mpctx = (struct MPContext){
3901 .osd_function = OSD_PLAY,
3902 .begin_skip = MP_NOPTS_VALUE,
3903 .play_tree_step = 1,
3904 .global_sub_pos = -1,
3905 .set_of_sub_pos = -1,
3906 .file_format = DEMUXER_TYPE_UNKNOWN,
3907 .last_dvb_step = 1,
3908 .paused_cache_fill = -1,
3911 InitTimer();
3912 srand(GetTimerMS());
3914 mp_msg_init();
3915 init_libav();
3917 #ifdef CONFIG_X11
3918 mpctx->x11_state = vo_x11_init_state();
3919 #endif
3920 struct MPOpts *opts = &mpctx->opts;
3921 set_default_mplayer_options(opts);
3922 // Create the config context and register the options
3923 mpctx->mconfig = m_config_new(opts, cfg_include);
3924 m_config_register_options(mpctx->mconfig, mplayer_opts);
3925 m_config_register_options(mpctx->mconfig, common_opts);
3926 mp_input_register_options(mpctx->mconfig);
3928 // Preparse the command line
3929 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
3931 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3932 set_path_env();
3933 #endif
3935 #ifdef CONFIG_TV
3936 stream_tv_defaults.immediate = 1;
3937 #endif
3939 parse_cfgfiles(mpctx, mpctx->mconfig);
3941 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3942 if (mpctx->playtree == NULL)
3943 opt_exit = 1;
3944 else {
3945 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3946 if (mpctx->playtree) {
3947 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3948 mpctx->mconfig);
3949 if (mpctx->playtree_iter) {
3950 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3951 PLAY_TREE_ITER_ENTRY) {
3952 play_tree_iter_free(mpctx->playtree_iter);
3953 mpctx->playtree_iter = NULL;
3955 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3961 print_version("MPlayer2");
3963 #if defined(__MINGW32__) || defined(__CYGWIN__)
3965 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3966 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3967 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3968 if (kernel32) {
3969 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3970 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3972 if (setDEP)
3973 setDEP(3);
3974 if (setDllDir)
3975 setDllDir("");
3977 // stop Windows from showing all kinds of annoying error dialogs
3978 SetErrorMode(0x8003);
3979 // request 1ms timer resolution
3980 timeBeginPeriod(1);
3981 #endif
3983 #ifdef CONFIG_PRIORITY
3984 set_priority();
3985 #endif
3987 if (opts->video_driver_list &&
3988 strcmp(opts->video_driver_list[0], "help") == 0) {
3989 list_video_out();
3990 opt_exit = 1;
3993 if (opts->audio_driver_list &&
3994 strcmp(opts->audio_driver_list[0], "help") == 0) {
3995 list_audio_out();
3996 opt_exit = 1;
3999 /* Check codecs.conf. */
4000 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4001 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4002 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4003 if (!parse_codec_cfg(NULL))
4004 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4005 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4006 "Using built-in default codecs.conf.\n");
4009 free(mem_ptr); // release the buffer created by get_path()
4012 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4013 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4014 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4015 list_codecs(1);
4016 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4017 opt_exit = 1;
4019 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4020 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4021 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4022 list_codecs(0);
4023 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4024 opt_exit = 1;
4026 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4027 vfm_help();
4028 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4029 opt_exit = 1;
4031 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4032 afm_help();
4033 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4034 opt_exit = 1;
4036 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4037 af_help();
4038 printf("\n");
4039 opt_exit = 1;
4041 #ifdef CONFIG_X11
4042 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4043 fstype_help();
4044 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4045 opt_exit = 1;
4047 #endif
4048 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4049 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4050 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4051 demuxer_help();
4052 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4053 opt_exit = 1;
4055 if (opts->list_properties) {
4056 property_print_help();
4057 opt_exit = 1;
4060 if (opt_exit)
4061 exit_player(mpctx, EXIT_NONE);
4063 if (!mpctx->filename && !opts->player_idle_mode) {
4064 // no file/vcd/dvd -> show HELP:
4065 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4066 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4069 /* Display what configure line was used */
4070 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4072 // Many users forget to include command line in bugreports...
4073 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4074 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4075 for (i = 1; i < argc; i++)
4076 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4077 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4080 //------ load global data first ------
4082 mpctx->osd = osd_create();
4084 // check font
4085 #ifdef CONFIG_FREETYPE
4086 init_freetype();
4087 #endif
4088 #ifdef CONFIG_FONTCONFIG
4089 if (font_fontconfig <= 0) {
4090 #endif
4091 #ifdef CONFIG_BITMAP_FONT
4092 if (font_name) {
4093 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4094 if (!vo_font)
4095 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4096 filename_recode(font_name));
4097 } else {
4098 // try default:
4099 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4100 font_factor, verbose > 1);
4101 free(mem_ptr); // release the buffer created by get_path()
4102 if (!vo_font)
4103 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4104 font_factor, verbose > 1);
4106 if (sub_font_name)
4107 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4108 verbose > 1);
4109 else
4110 mpctx->osd->sub_font = vo_font;
4111 #endif
4112 #ifdef CONFIG_FONTCONFIG
4114 #endif
4116 #ifdef CONFIG_ASS
4117 mpctx->ass_library = mp_ass_init(opts);
4118 mpctx->osd->ass_library = mpctx->ass_library;
4119 #endif
4121 #ifdef HAVE_RTC
4122 if (opts->rtc) {
4123 char *rtc_device = opts->rtc_device;
4124 // seteuid(0); /* Can't hurt to try to get root here */
4125 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4126 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4127 "(it should be readable by the user.)\n",
4128 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4129 else {
4130 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4132 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4133 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4134 "ioctl (rtc_irqp_set %lu): %s\n",
4135 irqp, strerror(errno));
4136 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4137 close(rtc_fd);
4138 rtc_fd = -1;
4139 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4140 /* variable only by the root */
4141 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4142 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4143 close(rtc_fd);
4144 rtc_fd = -1;
4145 } else
4146 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4147 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4150 if (rtc_fd < 0)
4151 #endif /* HAVE_RTC */
4152 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4153 opts->softsleep ? "software" : timer_name);
4155 #ifdef HAVE_TERMCAP
4156 load_termcap(NULL); // load key-codes
4157 #endif
4159 // ========== Init keyboard FIFO (connection to libvo) ============
4161 // Init input system
4162 current_module = "init_input";
4163 mpctx->input = mp_input_init(&opts->input);
4164 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4165 if (slave_mode)
4166 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4167 else if (opts->consolecontrols)
4168 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4169 // Set the libstream interrupt callback
4170 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4172 current_module = NULL;
4174 /// Catch signals
4175 #ifndef __MINGW32__
4176 signal(SIGCHLD, child_sighandler);
4177 #endif
4179 #ifdef CONFIG_CRASH_DEBUG
4180 prog_path = argv[0];
4181 #endif
4182 //========= Catch terminate signals: ================
4183 // terminate requests:
4184 signal(SIGTERM, exit_sighandler); // kill
4185 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4187 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4189 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4190 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4191 #ifdef CONFIG_SIGHANDLER
4192 // fatal errors:
4193 signal(SIGBUS, exit_sighandler); // bus error
4194 signal(SIGSEGV, exit_sighandler); // segfault
4195 signal(SIGILL, exit_sighandler); // illegal instruction
4196 signal(SIGFPE, exit_sighandler); // floating point exc.
4197 signal(SIGABRT, exit_sighandler); // abort()
4198 #ifdef CONFIG_CRASH_DEBUG
4199 if (crash_debug)
4200 signal(SIGTRAP, exit_sighandler);
4201 #endif
4202 #endif
4204 // ***************** Now, let's see the per-file stuff ******************
4206 play_next_file:
4208 // init global sub numbers
4209 mpctx->global_sub_size = 0;
4210 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4212 if (mpctx->filename) {
4213 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4214 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4215 load_per_file_config(mpctx->mconfig, mpctx->filename);
4218 if (opts->video_driver_list)
4219 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4220 opts->video_driver_list[0]);
4221 if (opts->audio_driver_list)
4222 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4223 opts->audio_driver_list[0]);
4225 // We must enable getch2 here to be able to interrupt network connection
4226 // or cache filling
4227 if (opts->consolecontrols && !slave_mode) {
4228 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4229 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4230 "WARNING: getch2_init called twice!\n");
4231 else
4232 getch2_enable(); // prepare stdin for hotkeys...
4233 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4234 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4237 // ================= GUI idle loop (STOP state) =========================
4238 while (opts->player_idle_mode && !mpctx->filename) {
4239 play_tree_t *entry = NULL;
4240 mp_cmd_t *cmd;
4241 if (mpctx->video_out && mpctx->video_out->config_ok)
4242 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4243 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4244 if (mpctx->video_out)
4245 vo_check_events(mpctx->video_out);
4246 usec_sleep(20000);
4248 switch (cmd->id) {
4249 case MP_CMD_LOADFILE:
4250 // prepare a tree entry with the new filename
4251 entry = play_tree_new();
4252 play_tree_add_file(entry, cmd->args[0].v.s);
4253 // The entry is added to the main playtree after the switch().
4254 break;
4255 case MP_CMD_LOADLIST:
4256 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4257 break;
4258 case MP_CMD_QUIT:
4259 exit_player_with_rc(mpctx, EXIT_QUIT,
4260 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4261 break;
4262 case MP_CMD_VO_FULLSCREEN:
4263 case MP_CMD_GET_PROPERTY:
4264 case MP_CMD_SET_PROPERTY:
4265 case MP_CMD_STEP_PROPERTY:
4266 run_command(mpctx, cmd);
4267 break;
4270 mp_cmd_free(cmd);
4272 if (entry) { // user entered a command that gave a valid entry
4273 if (mpctx->playtree)
4274 // the playtree is always a node with one child. let's clear it
4275 play_tree_free_list(mpctx->playtree->child, 1);
4276 else
4277 // .. or make a brand new playtree
4278 mpctx->playtree = play_tree_new();
4280 if (!mpctx->playtree)
4281 continue; // couldn't make playtree! wait for next command
4283 play_tree_set_child(mpctx->playtree, entry);
4285 /* Make iterator start at the top the of tree. */
4286 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4287 mpctx->mconfig);
4288 if (!mpctx->playtree_iter)
4289 continue;
4291 // find the first real item in the tree
4292 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4293 PLAY_TREE_ITER_ENTRY) {
4294 // no items!
4295 play_tree_iter_free(mpctx->playtree_iter);
4296 mpctx->playtree_iter = NULL;
4297 continue; // wait for next command
4299 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4303 #ifdef CONFIG_ASS
4304 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4305 #endif
4306 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4307 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4309 if (mpctx->filename) {
4310 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4311 filename_recode(mpctx->filename));
4312 if (use_filename_title && opts->vo_wintitle == NULL)
4313 opts->vo_wintitle = talloc_strdup(NULL,
4314 mp_basename(mpctx->filename));
4317 if (edl_output_filename) {
4318 if (edl_fd)
4319 fclose(edl_fd);
4320 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4321 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4322 "Can't open EDL file [%s] for writing.\n",
4323 filename_recode(edl_output_filename));
4327 //==================== Open VOB-Sub ============================
4329 current_module = "vobsub";
4330 if (opts->vobsub_name) {
4331 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4332 if (vo_vobsub == NULL)
4333 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4334 filename_recode(opts->vobsub_name));
4335 } else if (opts->sub_auto && mpctx->filename) {
4336 char **vob = find_vob_subtitles(opts, mpctx->filename);
4337 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4338 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4339 if (vo_vobsub)
4340 break;
4342 talloc_free(vob);
4344 if (vo_vobsub) {
4345 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4346 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4347 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4348 mpctx);
4350 // setup global sub numbering
4351 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4352 vobsub_get_indexes_count(vo_vobsub);
4355 //============ Open & Sync STREAM --- fork cache2 ====================
4357 mpctx->stream = NULL;
4358 mpctx->demuxer = NULL;
4359 mpctx->d_audio = NULL;
4360 mpctx->d_video = NULL;
4361 mpctx->d_sub = NULL;
4362 mpctx->sh_audio = NULL;
4363 mpctx->sh_video = NULL;
4365 current_module = "open_stream";
4366 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4367 if (!mpctx->stream) { // error...
4368 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4369 goto goto_next_file;
4371 mpctx->initialized_flags |= INITIALIZED_STREAM;
4373 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4374 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4375 "playlist support will not be used automatically.\n"
4376 "MPlayer's playlist code is unsafe and should only be used with "
4377 "trusted sources.\nPlayback will probably fail.\n\n");
4378 #if 0
4379 play_tree_t *entry;
4380 // Handle playlist
4381 current_module = "handle_playlist";
4382 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4383 filename_recode(mpctx->filename));
4384 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4385 mpctx->eof = playtree_add_playlist(mpctx, entry);
4386 goto goto_next_file;
4387 #endif
4389 mpctx->stream->start_pos += seek_to_byte;
4391 if (stream_dump_type == 5) {
4392 unsigned char buf[4096];
4393 int len;
4394 FILE *f;
4395 current_module = "dumpstream";
4396 stream_reset(mpctx->stream);
4397 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4398 f = fopen(opts->stream_dump_name, "wb");
4399 if (!f) {
4400 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4401 exit_player(mpctx, EXIT_ERROR);
4403 if (opts->chapterrange[0] > 1) {
4404 int chapter = opts->chapterrange[0] - 1;
4405 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4407 struct stream_dump_progress info;
4408 stream_dump_progress_start(&info);
4409 while (!mpctx->stream->eof && !async_quit_request) {
4410 len = stream_read(mpctx->stream, buf, 4096);
4411 if (len > 0) {
4412 if (fwrite(buf, len, 1, f) != 1) {
4413 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4414 exit_player(mpctx, EXIT_ERROR);
4417 stream_dump_progress(&info, len, mpctx->stream);
4418 if (opts->chapterrange[1] > 0) {
4419 int chapter = -1;
4420 if (stream_control(mpctx->stream,
4421 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4422 && chapter + 1 > opts->chapterrange[1])
4423 break;
4426 if (fclose(f)) {
4427 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4428 opts->stream_dump_name);
4429 exit_player(mpctx, EXIT_ERROR);
4431 stream_dump_progress_end(&info, opts->stream_dump_name);
4432 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4433 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4436 #ifdef CONFIG_DVDREAD
4437 if (mpctx->stream->type == STREAMTYPE_DVD) {
4438 current_module = "dvd lang->id";
4439 if (opts->audio_lang && opts->audio_id == -1)
4440 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4441 if (opts->sub_lang && opts->sub_id == -1)
4442 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4443 // setup global sub numbering
4444 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4445 current_module = NULL;
4447 #endif
4449 #ifdef CONFIG_DVDNAV
4450 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4451 current_module = "dvdnav lang->id";
4452 if (opts->audio_lang && opts->audio_id == -1)
4453 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4454 opts->audio_lang);
4455 dvdsub_lang_id = -3;
4456 if (opts->sub_lang && opts->sub_id == -1)
4457 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4458 mpctx->stream, opts->sub_lang);
4459 // setup global sub numbering
4460 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4461 mpctx->stream);
4462 current_module = NULL;
4464 #endif
4466 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4467 goto_enable_cache:
4468 if (stream_cache_size > 0) {
4469 int res;
4470 float stream_cache_min_percent = opts->stream_cache_min_percent;
4471 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4472 current_module = "enable_cache";
4473 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4474 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4475 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4476 if (res == 0)
4477 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4478 goto goto_next_file;
4481 //============ Open DEMUXERS --- DETECT file type =======================
4482 current_module = "demux_open";
4484 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4485 opts->audio_id, opts->video_id, opts->sub_id,
4486 mpctx->filename);
4488 // HACK to get MOV Reference Files working
4490 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4491 unsigned char *playlist_entry;
4492 play_tree_t *list = NULL, *entry = NULL;
4494 current_module = "handle_demux_playlist";
4495 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4496 char *temp;
4497 const char *bname;
4499 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4500 filename_recode(playlist_entry));
4502 bname = mp_basename(playlist_entry);
4503 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4504 !strncmp(bname + 3, "gateQT", 6))
4505 continue;
4507 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4508 continue;
4510 entry = play_tree_new();
4512 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4513 playlist_entry)) { // add reference path of current file
4514 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4515 mpctx->filename)) + strlen(playlist_entry) + 1));
4516 if (temp) {
4517 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4518 strlen(mp_basename(mpctx->filename)));
4519 temp[strlen(mpctx->filename) - strlen(mp_basename(
4520 mpctx->filename))] = '\0';
4521 strcat(temp, playlist_entry);
4522 if (!strcmp(temp, mpctx->filename)) {
4523 free(temp);
4524 continue;
4526 play_tree_add_file(entry, temp);
4527 mp_msg(MSGT_CPLAYER, MSGL_V,
4528 "Resolving reference to %s.\n", temp);
4529 free(temp);
4531 } else
4532 play_tree_add_file(entry, playlist_entry);
4534 if (!list)
4535 list = entry;
4536 else
4537 play_tree_append_entry(list, entry);
4539 free_demuxer(mpctx->demuxer);
4540 mpctx->demuxer = NULL;
4542 if (list) {
4543 entry = play_tree_new();
4544 play_tree_set_child(entry, list);
4545 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4546 goto goto_next_file;
4550 if (!mpctx->demuxer) {
4551 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4552 goto goto_next_file;
4555 if (mpctx->demuxer->matroska_data.ordered_chapters)
4556 build_ordered_chapter_timeline(mpctx);
4558 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4559 build_edl_timeline(mpctx);
4561 if (mpctx->timeline) {
4562 mpctx->timeline_part = 0;
4563 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4565 int part_count = mpctx->num_timeline_parts;
4566 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4567 "sources. Total length %.3f seconds.\n", part_count,
4568 mpctx->num_sources, mpctx->timeline[part_count].start);
4569 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4570 for (int i = 0; i < mpctx->num_sources; i++)
4571 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4572 filename_recode(mpctx->sources[i].demuxer->filename));
4573 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4574 "source_start, source):\n");
4575 for (int i = 0; i < part_count; i++) {
4576 struct timeline_part *p = mpctx->timeline + i;
4577 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4578 p->source_start, p->source - mpctx->sources);
4580 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4581 mpctx->timeline[part_count].start);
4584 if (!mpctx->sources) {
4585 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4586 *mpctx->sources = (struct content_source){
4587 .stream = mpctx->stream,
4588 .demuxer = mpctx->demuxer
4590 mpctx->num_sources = 1;
4593 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4595 #ifdef CONFIG_ASS
4596 if (opts->ass_enabled && mpctx->ass_library) {
4597 for (int j = 0; j < mpctx->num_sources; j++) {
4598 struct demuxer *d = mpctx->sources[j].demuxer;
4599 for (int i = 0; i < d->num_attachments; i++) {
4600 struct demux_attachment *att = d->attachments + i;
4601 if (opts->use_embedded_fonts && attachment_is_font(att))
4602 ass_add_font(mpctx->ass_library, att->name, att->data,
4603 att->data_size);
4607 #endif
4609 current_module = "demux_open2";
4611 mpctx->d_audio = mpctx->demuxer->audio;
4612 mpctx->d_video = mpctx->demuxer->video;
4613 mpctx->d_sub = mpctx->demuxer->sub;
4615 if (ts_prog) {
4616 int tmp = ts_prog;
4617 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4619 // select audio stream
4620 for (int i = 0; i < mpctx->num_sources; i++)
4621 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4622 opts->audio_lang);
4624 // DUMP STREAMS:
4625 if ((stream_dump_type) && (stream_dump_type < 4)) {
4626 FILE *f;
4627 demux_stream_t *ds = NULL;
4628 current_module = "dump";
4629 // select stream to dump
4630 switch (stream_dump_type) {
4631 case 1: ds = mpctx->d_audio;
4632 break;
4633 case 2: ds = mpctx->d_video;
4634 break;
4635 case 3: ds = mpctx->d_sub;
4636 break;
4638 if (!ds) {
4639 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4640 "dump: FATAL: Selected stream missing!\n");
4641 exit_player(mpctx, EXIT_ERROR);
4643 // disable other streams:
4644 if (mpctx->d_audio && mpctx->d_audio != ds) {
4645 ds_free_packs(mpctx->d_audio);
4646 mpctx->d_audio->id = -2;
4648 if (mpctx->d_video && mpctx->d_video != ds) {
4649 ds_free_packs(mpctx->d_video);
4650 mpctx->d_video->id = -2;
4652 if (mpctx->d_sub && mpctx->d_sub != ds) {
4653 ds_free_packs(mpctx->d_sub);
4654 mpctx->d_sub->id = -2;
4656 // let's dump it!
4657 f = fopen(opts->stream_dump_name, "wb");
4658 if (!f) {
4659 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4660 exit_player(mpctx, EXIT_ERROR);
4662 struct stream_dump_progress info;
4663 stream_dump_progress_start(&info);
4664 while (!ds->eof) {
4665 unsigned char *start;
4666 int in_size = ds_get_packet(ds, &start);
4667 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4668 && stream_dump_type == 2)
4669 fwrite(&in_size, 1, 4, f);
4670 if (in_size > 0) {
4671 fwrite(start, in_size, 1, f);
4672 stream_dump_progress(&info, in_size, mpctx->stream);
4674 if (opts->chapterrange[1] > 0) {
4675 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4676 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4677 break;
4680 fclose(f);
4681 stream_dump_progress_end(&info, opts->stream_dump_name);
4682 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4683 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4686 mpctx->sh_audio = mpctx->d_audio->sh;
4687 mpctx->sh_video = mpctx->d_video->sh;
4689 if (mpctx->sh_video) {
4690 current_module = "video_read_properties";
4691 if (!video_read_properties(mpctx->sh_video)) {
4692 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4693 mpctx->sh_video = mpctx->d_video->sh = NULL;
4694 } else {
4695 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4696 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4697 mpctx->demuxer->file_format, mpctx->sh_video->format,
4698 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4699 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4700 if (force_fps) {
4701 mpctx->sh_video->fps = force_fps;
4702 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4704 vo_fps = mpctx->sh_video->fps;
4706 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4707 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4708 "header or invalid, use the -fps option.\n");
4714 if (!mpctx->sh_video && !mpctx->sh_audio) {
4715 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4716 #ifdef CONFIG_DVBIN
4717 if (mpctx->stream->type == STREAMTYPE_DVB) {
4718 int dir;
4719 int v = mpctx->last_dvb_step;
4720 if (v > 0)
4721 dir = DVB_CHANNEL_HIGHER;
4722 else
4723 dir = DVB_CHANNEL_LOWER;
4725 if (dvb_step_channel(mpctx->stream, dir)) {
4726 mpctx->stop_play = PT_NEXT_ENTRY;
4727 mpctx->dvbin_reopen = 1;
4730 #endif
4731 goto goto_next_file; // exit_player(_("Fatal error"));
4734 /* display clip info */
4735 demux_info_print(mpctx->demuxer);
4737 //================= Read SUBTITLES (DVD & TEXT) =========================
4738 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4739 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4740 init_vo_spudec(mpctx);
4742 // after reading video params we should load subtitles because
4743 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4744 // check .sub
4745 current_module = "read_subtitles_file";
4746 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4747 if (opts->sub_name) {
4748 for (i = 0; opts->sub_name[i] != NULL; ++i)
4749 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4751 if (opts->sub_auto) { // auto load sub file ...
4752 char **tmp = find_text_subtitles(opts, mpctx->filename);
4753 int nsub = MP_TALLOC_ELEMS(tmp);
4754 for (int i = 0; i < nsub; i++)
4755 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4756 talloc_free(tmp);
4758 if (mpctx->set_of_sub_size > 0)
4759 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4761 if (select_subtitle(mpctx)) {
4762 if (mpctx->subdata)
4763 switch (stream_dump_type) {
4764 case 3: list_sub_file(mpctx->subdata);
4765 break;
4766 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4767 break;
4768 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4769 break;
4770 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4771 break;
4772 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4773 break;
4774 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4775 break;
4779 print_file_properties(mpctx, mpctx->filename);
4781 reinit_video_chain(mpctx);
4782 if (mpctx->sh_video) {
4783 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4784 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4785 #ifdef CONFIG_FREETYPE
4786 force_load_font = 1;
4787 #endif
4788 } else if (!mpctx->sh_audio)
4789 goto goto_next_file;
4791 //================== MAIN: ==========================
4792 current_module = "main";
4794 if (opts->playing_msg) {
4795 char *msg = property_expand_string(mpctx, opts->playing_msg);
4796 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4797 free(msg);
4801 // Disable the term OSD in verbose mode
4802 if (verbose)
4803 opts->term_osd = 0;
4805 // Make sure old OSD does not stay around,
4806 // e.g. with -fixed-vo and same-resolution files
4807 clear_osd_msgs();
4808 update_osd_msg(mpctx);
4810 //================ SETUP AUDIO ==========================
4812 if (mpctx->sh_audio) {
4813 reinit_audio_chain(mpctx);
4814 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4815 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4816 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4819 current_module = "av_init";
4821 if (mpctx->sh_video) {
4822 mpctx->sh_video->timer = 0;
4823 if (!ignore_start)
4824 audio_delay += mpctx->sh_video->stream_delay;
4826 if (mpctx->sh_audio) {
4827 if (start_volume >= 0)
4828 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4829 if (!ignore_start)
4830 audio_delay -= mpctx->sh_audio->stream_delay;
4831 mpctx->delay = -audio_delay;
4834 if (!mpctx->sh_audio) {
4835 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4836 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4837 mpctx->d_audio->packs);
4838 ds_free_packs(mpctx->d_audio); // free buffered chunks
4840 if (!mpctx->sh_video) {
4841 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4842 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4843 mpctx->d_video->packs);
4844 ds_free_packs(mpctx->d_video);
4845 mpctx->d_video->id = -2;
4848 if (!mpctx->sh_video && !mpctx->sh_audio)
4849 goto goto_next_file;
4851 if (force_fps && mpctx->sh_video) {
4852 vo_fps = mpctx->sh_video->fps = force_fps;
4853 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4854 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4855 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4856 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4859 mp_input_set_section(mpctx->input, NULL);
4860 //TODO: add desired (stream-based) sections here
4861 if (mpctx->stream->type == STREAMTYPE_TV)
4862 mp_input_set_section(mpctx->input, "tv");
4863 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4864 mp_input_set_section(mpctx->input, "dvdnav");
4866 //==================== START PLAYING =======================
4868 if (opts->loop_times > 1)
4869 opts->loop_times--;
4870 else if (opts->loop_times == 1)
4871 opts->loop_times = -1;
4873 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4875 total_time_usage_start = GetTimer();
4876 audio_time_usage = 0;
4877 video_time_usage = 0;
4878 vout_time_usage = 0;
4879 total_frame_cnt = 0;
4880 drop_frame_cnt = 0; // fix for multifile fps benchmark
4881 play_n_frames = play_n_frames_mf;
4883 if (play_n_frames == 0) {
4884 mpctx->stop_play = PT_NEXT_ENTRY;
4885 goto goto_next_file;
4888 mpctx->time_frame = 0;
4889 mpctx->drop_message_shown = 0;
4890 mpctx->restart_playback = true;
4891 mpctx->video_pts = 0;
4892 mpctx->last_seek_pts = 0;
4893 mpctx->hrseek_active = false;
4894 mpctx->hrseek_framedrop = false;
4895 mpctx->step_frames = 0;
4896 mpctx->total_avsync_change = 0;
4897 mpctx->last_chapter_seek = -2;
4899 // If there's a timeline force an absolute seek to initialize state
4900 if (opts->seek_to_sec || mpctx->timeline) {
4901 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4902 seek(mpctx, mpctx->seek, false);
4903 end_at.pos += opts->seek_to_sec;
4905 if (opts->chapterrange[0] > 0) {
4906 double pts;
4907 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4908 && pts > -1.0) {
4909 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4910 seek(mpctx, mpctx->seek, false);
4914 if (end_at.type == END_AT_SIZE) {
4915 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4916 "Option -endpos in MPlayer does not yet support size units.\n");
4917 end_at.type = END_AT_NONE;
4920 #ifdef CONFIG_DVDNAV
4921 mp_dvdnav_context_free(mpctx);
4922 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4923 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4924 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4926 #endif
4928 mpctx->seek = (struct seek_params){ 0 };
4929 get_relative_time(mpctx); // reset current delta
4930 // Make sure VO knows current pause state
4931 if (mpctx->sh_video)
4932 vo_control(mpctx->video_out,
4933 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4935 while (!mpctx->stop_play)
4936 run_playloop(mpctx);
4938 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4940 #ifdef CONFIG_DVBIN
4941 if (mpctx->dvbin_reopen) {
4942 mpctx->stop_play = 0;
4943 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4944 cache_uninit(mpctx->stream);
4945 mpctx->dvbin_reopen = 0;
4946 goto goto_enable_cache;
4948 #endif
4950 goto_next_file: // don't jump here after ao/vo/getch initialization!
4952 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4954 if (opts->benchmark) {
4955 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4956 double total_time_usage;
4957 total_time_usage_start = GetTimer() - total_time_usage_start;
4958 total_time_usage = (float)total_time_usage_start * 0.000001;
4959 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4960 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4961 video_time_usage, vout_time_usage, audio_time_usage,
4962 total_time_usage - tot, total_time_usage);
4963 if (total_time_usage > 0.0)
4964 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4965 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4966 100.0 * video_time_usage / total_time_usage,
4967 100.0 * vout_time_usage / total_time_usage,
4968 100.0 * audio_time_usage / total_time_usage,
4969 100.0 * (total_time_usage - tot) / total_time_usage,
4970 100.0);
4971 if (total_frame_cnt && frame_dropping)
4972 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4973 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4974 total_frame_cnt - drop_frame_cnt,
4975 (total_time_usage > 0.5) ? ((total_frame_cnt -
4976 drop_frame_cnt) / total_time_usage) : 0,
4977 drop_frame_cnt,
4978 100 * drop_frame_cnt / total_frame_cnt,
4979 total_frame_cnt,
4980 (total_time_usage > 0.5) ?
4981 (total_frame_cnt / total_time_usage) : 0);
4984 // time to uninit all, except global stuff:
4985 int uninitialize_parts = INITIALIZED_ALL;
4986 if (opts->fixed_vo)
4987 uninitialize_parts -= INITIALIZED_VO;
4988 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4989 uninitialize_parts -= INITIALIZED_AO;
4990 uninit_player(mpctx, uninitialize_parts);
4992 if (mpctx->set_of_sub_size > 0) {
4993 current_module = "sub_free";
4994 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
4995 sub_free(mpctx->set_of_subtitles[i]);
4996 #ifdef CONFIG_ASS
4997 if (mpctx->set_of_ass_tracks[i])
4998 ass_free_track(mpctx->set_of_ass_tracks[i]);
4999 #endif
5001 mpctx->set_of_sub_size = 0;
5003 mpctx->vo_sub_last = vo_sub = NULL;
5004 mpctx->subdata = NULL;
5005 #ifdef CONFIG_ASS
5006 mpctx->osd->ass_track = NULL;
5007 if (mpctx->ass_library)
5008 ass_clear_fonts(mpctx->ass_library);
5009 #endif
5011 if (!mpctx->stop_play) // In case some goto jumped here...
5012 mpctx->stop_play = PT_NEXT_ENTRY;
5014 int playtree_direction = 1;
5016 if (mpctx->stop_play == PT_NEXT_ENTRY
5017 || mpctx->stop_play == PT_PREV_ENTRY) {
5018 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5019 != PLAY_TREE_ITER_ENTRY) {
5020 play_tree_iter_free(mpctx->playtree_iter);
5021 mpctx->playtree_iter = NULL;
5023 mpctx->play_tree_step = 1;
5024 } else if (mpctx->stop_play == PT_UP_NEXT ||
5025 mpctx->stop_play == PT_UP_PREV) {
5026 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5027 if (mpctx->playtree_iter) {
5028 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5029 PLAY_TREE_ITER_ENTRY) {
5030 play_tree_iter_free(mpctx->playtree_iter);
5031 mpctx->playtree_iter = NULL;
5034 } else if (mpctx->stop_play == PT_STOP) {
5035 play_tree_iter_free(mpctx->playtree_iter);
5036 mpctx->playtree_iter = NULL;
5037 } else // NEXT PREV SRC
5038 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5040 while (mpctx->playtree_iter != NULL) {
5041 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5042 playtree_direction);
5043 if (mpctx->filename == NULL) {
5044 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5045 0) != PLAY_TREE_ITER_ENTRY) {
5046 play_tree_iter_free(mpctx->playtree_iter);
5047 mpctx->playtree_iter = NULL;
5050 } else
5051 break;
5054 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5055 if (!mpctx->playtree_iter)
5056 mpctx->filename = NULL;
5057 mpctx->stop_play = 0;
5058 goto play_next_file;
5061 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5063 return 1;
5065 #endif /* DISABLE_MAIN */