screenshot: fix libav API use (pix_fmt and some other things)
[mplayer.git] / mplayer.c
blob3452b5df0ff2e143079993ecd493a962c8d5a666
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 #if defined(__MINGW32__) || defined(__CYGWIN__)
31 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
32 #include <windows.h>
33 #endif
34 #include <string.h>
35 #include <unistd.h>
37 // #include <sys/mman.h>
38 #include <sys/types.h>
39 #ifndef __MINGW32__
40 #include <sys/ioctl.h>
41 #include <sys/wait.h>
42 #else
43 #define SIGHUP 1 /* hangup */
44 #define SIGQUIT 3 /* quit */
45 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
46 #define SIGBUS 10 /* bus error */
47 #define SIGPIPE 13 /* broken pipe */
48 #endif
50 #include <sys/time.h>
51 #include <sys/stat.h>
53 #include <signal.h>
54 #include <time.h>
55 #include <fcntl.h>
56 #include <limits.h>
58 #include <errno.h>
60 #include "mp_msg.h"
61 #include "av_log.h"
64 #include "m_option.h"
65 #include "m_config.h"
66 #include "mplayer.h"
67 #include "m_property.h"
69 #include "sub/subreader.h"
70 #include "sub/find_subfiles.h"
71 #include "sub/dec_sub.h"
73 #include "mp_osd.h"
74 #include "libvo/video_out.h"
75 #include "screenshot.h"
77 #include "sub/font_load.h"
78 #include "sub/sub.h"
79 #include "sub/av_sub.h"
80 #include "libmpcodecs/dec_teletext.h"
81 #include "cpudetect.h"
82 #include "version.h"
84 #ifdef CONFIG_X11
85 #include "libvo/x11_common.h"
86 #endif
88 #include "libao2/audio_out.h"
90 #include "codec-cfg.h"
92 #include "edl.h"
94 #include "sub/spudec.h"
95 #include "sub/vobsub.h"
97 #include "osdep/getch2.h"
98 #include "osdep/timer.h"
100 #include "input/input.h"
102 int slave_mode = 0;
103 int enable_mouse_movements = 0;
104 float start_volume = -1;
106 #include "osdep/priority.h"
108 char *heartbeat_cmd;
110 #ifdef HAVE_RTC
111 #ifdef __linux__
112 #include <linux/rtc.h>
113 #else
114 #include <rtc.h>
115 #define RTC_IRQP_SET RTCIO_IRQP_SET
116 #define RTC_PIE_ON RTCIO_PIE_ON
117 #endif /* __linux__ */
118 #endif /* HAVE_RTC */
120 #include "stream/tv.h"
121 #include "stream/stream_radio.h"
122 #ifdef CONFIG_DVBIN
123 #include "stream/dvbin.h"
124 #endif
125 #include "stream/cache2.h"
127 //**************************************************************************//
128 // Playtree
129 //**************************************************************************//
130 #include "playtree.h"
131 #include "playtreeparser.h"
133 //**************************************************************************//
134 // Config
135 //**************************************************************************//
136 #include "parser-cfg.h"
137 #include "parser-mpcmd.h"
139 //**************************************************************************//
140 // Config file
141 //**************************************************************************//
143 static int cfg_inc_verbose(m_option_t *conf)
145 ++verbose;
146 return 0;
149 #include "path.h"
151 //**************************************************************************//
152 //**************************************************************************//
153 // Input media streaming & demultiplexer:
154 //**************************************************************************//
156 static int max_framesize = 0;
158 #include "stream/stream.h"
159 #include "libmpdemux/demuxer.h"
160 #include "libmpdemux/stheader.h"
162 #ifdef CONFIG_DVDREAD
163 #include "stream/stream_dvd.h"
164 #endif
165 #include "stream/stream_dvdnav.h"
167 #include "libmpcodecs/dec_audio.h"
168 #include "libmpcodecs/dec_video.h"
169 #include "libmpcodecs/mp_image.h"
170 #include "libmpcodecs/vf.h"
171 #include "libmpcodecs/vd.h"
173 #include "mixer.h"
175 #include "mp_core.h"
176 #include "options.h"
177 #include "defaultopts.h"
179 static const char help_text[] = _(
180 "Usage: mplayer [options] [url|path/]filename\n"
181 "\n"
182 "Basic options: (complete list in the man page)\n"
183 " -vo <drv> select video output driver ('-vo help' for a list)\n"
184 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
185 #ifdef CONFIG_VCD
186 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
187 #endif
188 #ifdef CONFIG_DVDREAD
189 " dvd://<titleno> play DVD title from device instead of plain file\n"
190 #endif
191 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
192 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
193 " -nosound do not play sound\n"
194 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
195 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
196 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
197 " -playlist <file> specify playlist file\n"
198 " -vid x -aid y select video (x) and audio (y) stream to play\n"
199 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
200 " -pp <quality> enable postprocessing filter (details in the man page)\n"
201 " -framedrop enable frame dropping (for slow machines)\n"
202 "\n"
203 "Basic keys: (complete list in the man page, also check input.conf)\n"
204 " <- or -> seek backward/forward 10 seconds\n"
205 " down or up seek backward/forward 1 minute\n"
206 " pgdown or pgup seek backward/forward 10 minutes\n"
207 " < or > step backward/forward in playlist\n"
208 " p or SPACE pause movie (press any key to continue)\n"
209 " q or ESC stop playing and quit program\n"
210 " + or - adjust audio delay by +/- 0.1 second\n"
211 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
212 " * or / increase or decrease PCM volume\n"
213 " x or z adjust subtitle delay by +/- 0.1 second\n"
214 " r or t adjust subtitle position up/down, also see -vf expand\n"
215 " double click toggle fullscreen\n"
216 " right click pause (press again to continue)\n"
217 "\n"
218 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
219 "\n");
222 #define Exit_SIGILL_RTCpuSel _(\
223 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
224 " It may be a bug in our new runtime CPU-detection code...\n"\
225 " Please read DOCS/HTML/en/bugreports.html.\n")
227 #define Exit_SIGILL _(\
228 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
229 " It usually happens when you run it on a CPU different than the one it was\n"\
230 " compiled/optimized for.\n"\
231 " Verify this!\n")
233 #define Exit_SIGSEGV_SIGFPE _(\
234 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
235 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
236 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
238 #define Exit_SIGCRASH _(\
239 "- MPlayer crashed. This shouldn't happen.\n"\
240 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
241 " gcc version. If you think it's MPlayer's fault, please read\n"\
242 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
243 " won't help unless you provide this information when reporting a possible bug.\n")
245 #define SystemTooSlow _("\n\n"\
246 " ************************************************\n"\
247 " **** Your system is too SLOW to play this! ****\n"\
248 " ************************************************\n\n"\
249 "Possible reasons, problems, workarounds:\n"\
250 "- Most common: broken/buggy _audio_ driver\n"\
251 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
252 " - Experiment with different values for -autosync, 30 is a good start.\n"\
253 "- Slow video output\n"\
254 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
255 "- Slow CPU\n"\
256 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
257 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
258 "- Broken file\n"\
259 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
260 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
261 " - Try -cache 8192.\n"\
262 "- Are you using -cache to play a non-interleaved AVI file?\n"\
263 " - Try -nocache.\n"\
264 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
265 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
268 //**************************************************************************//
269 //**************************************************************************//
271 #include "mp_fifo.h"
273 // benchmark:
274 double video_time_usage;
275 double vout_time_usage;
276 static double audio_time_usage;
277 static int total_time_usage_start;
278 static int total_frame_cnt;
279 static int drop_frame_cnt; // total number of dropped frames
281 // options:
282 static int output_quality;
284 // seek:
285 static off_t seek_to_byte;
286 static off_t step_sec;
288 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
290 // codecs:
291 char **audio_codec_list; // override audio codec
292 char **video_codec_list; // override video codec
293 char **audio_fm_list; // override audio codec family
294 char **video_fm_list; // override video codec family
296 // this dvdsub_id was selected via slang
297 // use this to allow dvdnav to follow -slang across stream resets,
298 // in particular the subtitle ID for a language changes
299 int dvdsub_lang_id;
300 int vobsub_id = -1;
301 static char *spudec_ifo = NULL;
302 int forced_subs_only = 0;
304 // cache2:
305 int stream_cache_size = -1;
307 // dump:
308 int stream_dump_type = 0;
310 // A-V sync:
311 static float default_max_pts_correction = -1;
312 float audio_delay = 0;
313 static int ignore_start = 0;
315 double force_fps = 0;
316 static int force_srate = 0;
317 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
318 static int play_n_frames = -1;
319 static int play_n_frames_mf = -1;
321 // sub:
322 char *font_name = NULL;
323 char *sub_font_name = NULL;
324 extern int font_fontconfig;
325 float font_factor = 0.75;
326 float sub_delay = 0;
327 float sub_fps = 0;
328 int subcc_enabled = 0;
329 int suboverlap_enabled = 1;
331 #include "sub/ass_mp.h"
333 char *current_module; // for debugging
336 // ---
338 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
339 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
340 FILE *edl_fd; // file to write to when in -edlout mode.
341 int use_filedir_conf;
342 int use_filename_title;
344 #include "mpcommon.h"
345 #include "command.h"
347 #include "metadata.h"
349 static float get_relative_time(struct MPContext *mpctx)
351 unsigned int new_time = GetTimer();
352 unsigned int delta = new_time - mpctx->last_time;
353 mpctx->last_time = new_time;
354 return delta * 0.000001;
357 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
359 switch (type) {
360 /* check for valid video stream */
361 case META_VIDEO_CODEC:
362 case META_VIDEO_BITRATE:
363 case META_VIDEO_RESOLUTION:
364 if (!mpctx->sh_video)
365 return 0;
366 break;
368 /* check for valid audio stream */
369 case META_AUDIO_CODEC:
370 case META_AUDIO_BITRATE:
371 case META_AUDIO_SAMPLES:
372 if (!mpctx->sh_audio)
373 return 0;
374 break;
376 /* check for valid demuxer */
377 case META_INFO_TITLE:
378 case META_INFO_ARTIST:
379 case META_INFO_ALBUM:
380 case META_INFO_YEAR:
381 case META_INFO_COMMENT:
382 case META_INFO_TRACK:
383 case META_INFO_GENRE:
384 if (!mpctx->demuxer)
385 return 0;
386 break;
388 default:
389 break;
392 return 1;
395 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
397 char **info = mpctx->demuxer->info;
398 int n;
400 if (!info || !tag)
401 return talloc_strdup(NULL, "");
403 for (n = 0; info[2 * n] != NULL; n++)
404 if (!strcasecmp(info[2 * n], tag))
405 break;
407 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
410 char *get_metadata(struct MPContext *mpctx, metadata_t type)
412 sh_audio_t * const sh_audio = mpctx->sh_audio;
413 sh_video_t * const sh_video = mpctx->sh_video;
415 if (!is_valid_metadata_type(mpctx, type))
416 return NULL;
418 switch (type) {
419 case META_NAME:
420 return talloc_strdup(NULL, mp_basename(mpctx->filename));
421 case META_VIDEO_CODEC:
422 if (sh_video->format == 0x10000001)
423 return talloc_strdup(NULL, "mpeg1");
424 else if (sh_video->format == 0x10000002)
425 return talloc_strdup(NULL, "mpeg2");
426 else if (sh_video->format == 0x10000004)
427 return talloc_strdup(NULL, "mpeg4");
428 else if (sh_video->format == 0x10000005)
429 return talloc_strdup(NULL, "h264");
430 else if (sh_video->format >= 0x20202020)
431 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
432 else
433 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
434 case META_VIDEO_BITRATE:
435 return talloc_asprintf(NULL, "%d kbps",
436 (int) (sh_video->i_bps * 8 / 1024));
437 case META_VIDEO_RESOLUTION:
438 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
439 sh_video->disp_h);
440 case META_AUDIO_CODEC:
441 if (sh_audio->codec && sh_audio->codec->name)
442 return talloc_strdup(NULL, sh_audio->codec->name);
443 return talloc_strdup(NULL, "");
444 case META_AUDIO_BITRATE:
445 return talloc_asprintf(NULL, "%d kbps",
446 (int) (sh_audio->i_bps * 8 / 1000));
447 case META_AUDIO_SAMPLES:
448 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
449 sh_audio->channels);
451 /* check for valid demuxer */
452 case META_INFO_TITLE:
453 return get_demuxer_info(mpctx, "Title");
455 case META_INFO_ARTIST:
456 return get_demuxer_info(mpctx, "Artist");
458 case META_INFO_ALBUM:
459 return get_demuxer_info(mpctx, "Album");
461 case META_INFO_YEAR:
462 return get_demuxer_info(mpctx, "Year");
464 case META_INFO_COMMENT:
465 return get_demuxer_info(mpctx, "Comment");
467 case META_INFO_TRACK:
468 return get_demuxer_info(mpctx, "Track");
470 case META_INFO_GENRE:
471 return get_demuxer_info(mpctx, "Genre");
473 default:
474 break;
477 return talloc_strdup(NULL, "");
480 static void print_file_properties(struct MPContext *mpctx, const char *filename)
482 double start_pts = MP_NOPTS_VALUE;
483 double video_start_pts = MP_NOPTS_VALUE;
484 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
485 filename_recode(filename));
486 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
487 mpctx->demuxer->desc->name);
488 if (mpctx->sh_video) {
489 /* Assume FOURCC if all bytes >= 0x20 (' ') */
490 if (mpctx->sh_video->format >= 0x20202020)
491 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
492 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
493 else
494 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
495 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
496 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
497 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
498 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
499 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
500 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
501 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
502 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
503 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
504 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
505 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
506 video_start_pts = ds_get_next_pts(mpctx->d_video);
508 if (mpctx->sh_audio) {
509 /* Assume FOURCC if all bytes >= 0x20 (' ') */
510 if (mpctx->sh_audio->format >= 0x20202020)
511 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
512 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
513 else
514 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
515 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
516 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
517 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
518 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
519 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
520 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
521 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
522 start_pts = ds_get_next_pts(mpctx->d_audio);
524 if (video_start_pts != MP_NOPTS_VALUE) {
525 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
526 (mpctx->sh_video && video_start_pts < start_pts))
527 start_pts = video_start_pts;
529 if (start_pts != MP_NOPTS_VALUE)
530 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
531 else
532 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
533 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
534 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
535 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
536 mpctx->stream->seek
537 && (!mpctx->demuxer || mpctx->demuxer->seekable));
538 if (mpctx->demuxer) {
539 int chapter_count = get_chapter_count(mpctx);
540 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
541 for (int i = 0; i < chapter_count; i++) {
542 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
543 // in milliseconds
544 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
545 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
546 char *name = chapter_name(mpctx, i);
547 if (name) {
548 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
549 name);
550 talloc_free(name);
556 /// step size of mixer changes
557 int volstep = 3;
559 #ifdef CONFIG_DVDNAV
560 static void mp_dvdnav_context_free(MPContext *ctx)
562 if (ctx->nav_smpi)
563 free_mp_image(ctx->nav_smpi);
564 ctx->nav_smpi = NULL;
565 free(ctx->nav_buffer);
566 ctx->nav_buffer = NULL;
567 ctx->nav_start = NULL;
568 ctx->nav_in_size = 0;
570 #endif
572 static void uninit_subs(struct demuxer *demuxer)
574 for (int i = 0; i < MAX_S_STREAMS; i++) {
575 struct sh_sub *sh = demuxer->s_streams[i];
576 if (sh && sh->initialized)
577 sub_uninit(sh);
581 void uninit_player(struct MPContext *mpctx, unsigned int mask)
583 mask &= mpctx->initialized_flags;
585 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
587 if (mask & INITIALIZED_ACODEC) {
588 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
589 current_module = "uninit_acodec";
590 if (mpctx->sh_audio)
591 uninit_audio(mpctx->sh_audio);
592 mpctx->sh_audio = NULL;
593 mpctx->mixer.afilter = NULL;
596 if (mask & INITIALIZED_SUB) {
597 mpctx->initialized_flags &= ~INITIALIZED_SUB;
598 if (mpctx->d_sub->sh)
599 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
602 if (mask & INITIALIZED_VCODEC) {
603 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
604 current_module = "uninit_vcodec";
605 if (mpctx->sh_video)
606 uninit_video(mpctx->sh_video);
607 mpctx->sh_video = NULL;
610 if (mask & INITIALIZED_DEMUXER) {
611 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
612 current_module = "free_demuxer";
613 if (mpctx->num_sources) {
614 mpctx->demuxer = mpctx->sources[0].demuxer;
615 for (int i = 1; i < mpctx->num_sources; i++) {
616 uninit_subs(mpctx->sources[i].demuxer);
617 free_stream(mpctx->sources[i].stream);
618 free_demuxer(mpctx->sources[i].demuxer);
621 talloc_free(mpctx->sources);
622 mpctx->sources = NULL;
623 mpctx->num_sources = 0;
624 talloc_free(mpctx->timeline);
625 mpctx->timeline = NULL;
626 mpctx->num_timeline_parts = 0;
627 talloc_free(mpctx->chapters);
628 mpctx->chapters = NULL;
629 mpctx->num_chapters = 0;
630 mpctx->video_offset = 0;
631 if (mpctx->demuxer) {
632 mpctx->stream = mpctx->demuxer->stream;
633 uninit_subs(mpctx->demuxer);
634 free_demuxer(mpctx->demuxer);
636 mpctx->demuxer = NULL;
639 // kill the cache process:
640 if (mask & INITIALIZED_STREAM) {
641 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
642 current_module = "uninit_stream";
643 if (mpctx->stream)
644 free_stream(mpctx->stream);
645 mpctx->stream = NULL;
648 if (mask & INITIALIZED_VO) {
649 mpctx->initialized_flags &= ~INITIALIZED_VO;
650 current_module = "uninit_vo";
651 vo_destroy(mpctx->video_out);
652 mpctx->video_out = NULL;
653 #ifdef CONFIG_DVDNAV
654 mp_dvdnav_context_free(mpctx);
655 #endif
658 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
659 if (mask & INITIALIZED_GETCH2) {
660 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
661 current_module = "uninit_getch2";
662 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
663 // restore terminal:
664 getch2_disable();
667 if (mask & INITIALIZED_VOBSUB) {
668 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
669 current_module = "uninit_vobsub";
670 if (vo_vobsub)
671 vobsub_close(vo_vobsub);
672 vo_vobsub = NULL;
675 if (mask & INITIALIZED_SPUDEC) {
676 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
677 current_module = "uninit_spudec";
678 spudec_free(vo_spudec);
679 vo_spudec = NULL;
682 if (mask & INITIALIZED_AO) {
683 mpctx->initialized_flags &= ~INITIALIZED_AO;
684 current_module = "uninit_ao";
685 if (mpctx->edl_muted)
686 mixer_mute(&mpctx->mixer);
687 if (mpctx->ao)
688 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
689 mpctx->ao = NULL;
692 current_module = NULL;
695 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
697 if (mpctx->user_muted && !mpctx->edl_muted)
698 mixer_mute(&mpctx->mixer);
699 uninit_player(mpctx, INITIALIZED_ALL);
700 #if defined(__MINGW32__) || defined(__CYGWIN__)
701 timeEndPeriod(1);
702 #endif
703 #ifdef CONFIG_X11
704 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
705 #endif
707 current_module = "uninit_input";
708 mp_input_uninit(mpctx->input);
710 #ifdef CONFIG_FREETYPE
711 current_module = "uninit_font";
712 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
713 free_font_desc(mpctx->osd->sub_font);
714 free_font_desc(vo_font);
715 vo_font = NULL;
716 done_freetype();
717 #endif
718 osd_free(mpctx->osd);
720 #ifdef CONFIG_ASS
721 ass_library_done(mpctx->ass_library);
722 mpctx->ass_library = NULL;
723 #endif
725 current_module = "exit_player";
727 if (mpctx->playtree_iter)
728 play_tree_iter_free(mpctx->playtree_iter);
729 mpctx->playtree_iter = NULL;
730 if (mpctx->playtree)
731 play_tree_free(mpctx->playtree, 1);
732 mpctx->playtree = NULL;
734 talloc_free(mpctx->key_fifo);
736 free(edl_records); // free mem allocated for EDL
737 edl_records = NULL;
738 switch (how) {
739 case EXIT_QUIT:
740 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
741 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
742 break;
743 case EXIT_EOF:
744 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
745 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
746 break;
747 case EXIT_ERROR:
748 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
749 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
750 break;
751 default:
752 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
754 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
755 "max framesize was %d bytes\n", max_framesize);
757 // must be last since e.g. mp_msg uses option values
758 // that will be freed by this.
759 if (mpctx->mconfig)
760 m_config_free(mpctx->mconfig);
761 mpctx->mconfig = NULL;
763 talloc_free(mpctx);
765 exit(rc);
768 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
770 exit_player_with_rc(mpctx, how, 1);
773 #ifndef __MINGW32__
774 static void child_sighandler(int x)
776 pid_t pid;
777 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
779 #endif
781 #ifdef CONFIG_CRASH_DEBUG
782 static char *prog_path;
783 static int crash_debug = 0;
784 #endif
786 static void exit_sighandler(int x)
788 static int sig_count = 0;
789 #ifdef CONFIG_CRASH_DEBUG
790 if (!crash_debug || x != SIGTRAP)
791 #endif
792 ++sig_count;
793 if (sig_count == 5) {
794 /* We're crashing bad and can't uninit cleanly :(
795 * by popular request, we make one last (dirty)
796 * effort to restore the user's
797 * terminal. */
798 getch2_disable();
799 exit(1);
801 if (sig_count == 6)
802 exit(1);
803 if (sig_count > 6) {
804 // can't stop :(
805 #ifndef __MINGW32__
806 kill(getpid(), SIGKILL);
807 #endif
809 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
810 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
811 "\nMPlayer interrupted by signal %d in module: %s\n", x,
812 current_module ? current_module : "unknown");
813 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
814 if (sig_count <= 1)
815 switch (x) {
816 case SIGINT:
817 case SIGPIPE:
818 case SIGQUIT:
819 case SIGTERM:
820 case SIGKILL:
821 async_quit_request = 1;
822 return; // killed from keyboard (^C) or killed [-9]
823 case SIGILL:
824 #if CONFIG_RUNTIME_CPUDETECT
825 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
826 #else
827 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
828 #endif
829 case SIGFPE:
830 case SIGSEGV:
831 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
832 default:
833 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
834 #ifdef CONFIG_CRASH_DEBUG
835 if (crash_debug) {
836 int gdb_pid;
837 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
838 gdb_pid = fork();
839 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
840 if (gdb_pid == 0) { // We are the child
841 char spid[20];
842 snprintf(spid, sizeof(spid), "%i", getppid());
843 getch2_disable(); // allow terminal to work properly with gdb
844 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
845 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
846 } else if (gdb_pid < 0)
847 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
848 else
849 waitpid(gdb_pid, NULL, 0);
850 if (x == SIGTRAP)
851 return;
853 #endif
855 getch2_disable();
856 exit(1);
859 #include "cfg-mplayer.h"
861 static int cfg_include(m_option_t *conf, char *filename)
863 return m_config_parse_config_file(conf->priv, filename);
866 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
868 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
870 struct MPOpts *opts = &mpctx->opts;
871 char *conffile;
872 int conffile_fd;
873 if (!(opts->noconfig & 2) &&
874 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
875 exit_player(mpctx, EXIT_NONE);
876 if ((conffile = get_path("")) == NULL)
877 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
878 else {
879 #ifdef __MINGW32__
880 mkdir(conffile);
881 #else
882 mkdir(conffile, 0777);
883 #endif
884 free(conffile);
885 if ((conffile = get_path("config")) == NULL)
886 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
887 else {
888 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
889 0666)) != -1) {
890 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
891 "Creating config file: %s\n", conffile);
892 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
893 close(conffile_fd);
895 if (!(opts->noconfig & 1) &&
896 m_config_parse_config_file(conf, conffile) < 0)
897 exit_player(mpctx, EXIT_NONE);
898 free(conffile);
903 #define PROFILE_CFG_PROTOCOL "protocol."
905 static void load_per_protocol_config(m_config_t *conf, const char * const file)
907 char *str;
908 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
909 m_profile_t *p;
911 /* does filename actually uses a protocol ? */
912 str = strstr(file, "://");
913 if (!str)
914 return;
916 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
917 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
918 p = m_config_get_profile(conf, protocol);
919 if (p) {
920 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
921 "Loading protocol-related profile '%s'\n", protocol);
922 m_config_set_profile(conf, p);
926 #define PROFILE_CFG_EXTENSION "extension."
928 static void load_per_extension_config(m_config_t *conf, const char * const file)
930 char *str;
931 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
932 m_profile_t *p;
934 /* does filename actually have an extension ? */
935 str = strrchr(file, '.');
936 if (!str)
937 return;
939 sprintf(extension, PROFILE_CFG_EXTENSION);
940 strncat(extension, ++str, 7);
941 p = m_config_get_profile(conf, extension);
942 if (p) {
943 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
944 "Loading extension-related profile '%s'\n", extension);
945 m_config_set_profile(conf, p);
949 #define PROFILE_CFG_VO "vo."
950 #define PROFILE_CFG_AO "ao."
952 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
954 char profile[strlen(cfg) + strlen(out) + 1];
955 m_profile_t *p;
957 sprintf(profile, "%s%s", cfg, out);
958 p = m_config_get_profile(conf, profile);
959 if (p) {
960 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
961 "Loading extension-related profile '%s'\n", profile);
962 m_config_set_profile(conf, p);
967 * Tries to load a config file
968 * @return 0 if file was not found, 1 otherwise
970 static int try_load_config(m_config_t *conf, const char *file)
972 struct stat st;
973 if (stat(file, &st))
974 return 0;
975 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
976 m_config_parse_config_file(conf, file);
977 return 1;
980 static void load_per_file_config(m_config_t *conf, const char * const file)
982 char *confpath;
983 char cfg[PATH_MAX];
984 const char *name;
986 if (strlen(file) > PATH_MAX - 14) {
987 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
988 "can not load file or directory specific config files\n");
989 return;
991 sprintf(cfg, "%s.conf", file);
993 name = mp_basename(cfg);
994 if (use_filedir_conf) {
995 char dircfg[PATH_MAX];
996 strcpy(dircfg, cfg);
997 strcpy(dircfg + (name - cfg), "mplayer.conf");
998 try_load_config(conf, dircfg);
1000 if (try_load_config(conf, cfg))
1001 return;
1004 if ((confpath = get_path(name)) != NULL) {
1005 try_load_config(conf, confpath);
1007 free(confpath);
1011 /* When libmpdemux performs a blocking operation (network connection or
1012 * cache filling) if the operation fails we use this function to check
1013 * if it was interrupted by the user.
1014 * The function returns a new value for eof. */
1015 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1017 mp_cmd_t *cmd;
1018 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1019 switch (cmd->id) {
1020 case MP_CMD_QUIT:
1021 exit_player_with_rc(mpctx, EXIT_QUIT,
1022 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1023 case MP_CMD_PLAY_TREE_STEP: {
1024 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1025 mpctx->play_tree_step =
1026 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1027 } break;
1028 case MP_CMD_PLAY_TREE_UP_STEP: {
1029 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1030 } break;
1031 case MP_CMD_PLAY_ALT_SRC_STEP: {
1032 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1033 } break;
1035 mp_cmd_free(cmd);
1037 return stop_play;
1040 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1042 play_tree_add_bpf(entry, bstr(mpctx->filename));
1045 if (!entry) {
1046 entry = mpctx->playtree_iter->tree;
1047 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1048 != PLAY_TREE_ITER_ENTRY)
1049 return PT_NEXT_ENTRY;
1050 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1051 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1052 != PLAY_TREE_ITER_ENTRY)
1053 return PT_NEXT_ENTRY;
1055 play_tree_remove(entry, 1, 1);
1056 return PT_NEXT_SRC;
1058 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1059 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1060 entry = mpctx->playtree_iter->tree;
1061 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1062 != PLAY_TREE_ITER_ENTRY)
1063 return PT_NEXT_ENTRY;
1064 play_tree_remove(entry, 1, 1);
1066 return PT_NEXT_SRC;
1069 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1070 int noerr)
1072 struct MPOpts *opts = &mpctx->opts;
1073 sub_data *subd = NULL;
1074 struct ass_track *asst = NULL;
1075 bool is_native_ass = false;
1077 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1078 return;
1080 #ifdef CONFIG_ASS
1081 if (opts->ass_enabled) {
1082 #ifdef CONFIG_ICONV
1083 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1084 #else
1085 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1086 #endif
1087 is_native_ass = asst;
1088 if (!asst) {
1089 subd = sub_read_file(filename, fps, &mpctx->opts);
1090 if (subd) {
1091 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1092 sub_free(subd);
1093 subd = NULL;
1096 } else
1097 #endif
1098 subd = sub_read_file(filename, fps, &mpctx->opts);
1101 if (!asst && !subd) {
1102 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1103 "Cannot load subtitles: %s\n", filename_recode(filename));
1104 return;
1107 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1108 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1109 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1110 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1111 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1112 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1113 filename_recode(filename));
1114 ++mpctx->set_of_sub_size;
1115 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1116 mpctx->set_of_sub_size, filename_recode(filename));
1119 void init_vo_spudec(struct MPContext *mpctx)
1121 unsigned width, height;
1122 spudec_free(vo_spudec);
1123 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1124 vo_spudec = NULL;
1126 // we currently can't work without video stream
1127 if (!mpctx->sh_video)
1128 return;
1130 if (spudec_ifo) {
1131 unsigned int palette[16];
1132 current_module = "spudec_init_vobsub";
1133 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1134 1, -1, NULL) >= 0)
1135 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1138 width = mpctx->sh_video->disp_w;
1139 height = mpctx->sh_video->disp_h;
1141 #ifdef CONFIG_DVDREAD
1142 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1143 current_module = "spudec_init_dvdread";
1144 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1145 cur_pgc->palette, width, height, NULL, 0);
1147 #endif
1149 #ifdef CONFIG_DVDNAV
1150 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1151 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1152 current_module = "spudec_init_dvdnav";
1153 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1155 #endif
1157 if (vo_spudec == NULL) {
1158 sh_sub_t *sh = mpctx->d_sub->sh;
1159 current_module = "spudec_init_normal";
1160 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1161 sh->extradata_len);
1162 spudec_set_font_factor(vo_spudec, font_factor);
1165 if (vo_spudec != NULL) {
1166 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1167 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1168 mpctx);
1173 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1174 * make it all work is to use the builtin SDL-bootstrap code, which
1175 * will be done automatically by replacing our main() if we include SDL.h.
1177 #if defined(__APPLE__) && defined(CONFIG_SDL)
1178 #ifdef CONFIG_SDL_SDL_H
1179 #include <SDL/SDL.h>
1180 #else
1181 #include <SDL.h>
1182 #endif
1183 #endif
1186 * \brief append a formatted string
1187 * \param buf buffer to print into
1188 * \param pos position of terminating 0 in buf
1189 * \param len maximum number of characters in buf, not including terminating 0
1190 * \param format printf format string
1192 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1194 va_list va;
1195 va_start(va, format);
1196 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1197 va_end(va);
1198 if (*pos >= len) {
1199 buf[len] = 0;
1200 *pos = len;
1205 * \brief append time in the hh:mm:ss.f format
1206 * \param buf buffer to print into
1207 * \param pos position of terminating 0 in buf
1208 * \param len maximum number of characters in buf, not including terminating 0
1209 * \param time time value to convert/append
1211 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1213 int64_t tenths = 10 * time;
1214 int f1 = tenths % 10;
1215 int ss = (tenths / 10) % 60;
1216 int mm = (tenths / 600) % 60;
1217 int hh = tenths / 36000;
1218 if (time < 0) {
1219 saddf(buf, pos, len, "unknown");
1220 return;
1222 if (hh > 0)
1223 saddf(buf, pos, len, "%2d:", hh);
1224 if (hh > 0 || mm > 0)
1225 saddf(buf, pos, len, "%02d:", mm);
1226 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1229 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1231 struct MPOpts *opts = &mpctx->opts;
1232 sh_video_t * const sh_video = mpctx->sh_video;
1234 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1235 a_pos = playing_audio_pts(mpctx);
1236 if (mpctx->sh_audio && sh_video && at_frame) {
1237 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1238 if (mpctx->time_frame > 0)
1239 mpctx->last_av_difference +=
1240 mpctx->time_frame * opts->playback_speed;
1241 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1242 && !mpctx->drop_message_shown) {
1243 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1244 mpctx->drop_message_shown = true;
1247 if (opts->quiet)
1248 return;
1250 if (a_pos == MP_NOPTS_VALUE)
1251 a_pos = -9; // don't print a huge negative number
1253 int width;
1254 char *line;
1255 unsigned pos = 0;
1256 get_screen_size();
1257 if (screen_width > 0)
1258 width = screen_width;
1259 else
1260 width = 80;
1261 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1262 /* Windows command line is broken (MinGW's rxvt works, but we
1263 * should not depend on that). */
1264 width--;
1265 #endif
1266 line = malloc(width + 1); // one additional char for the terminating null
1268 // Audio time
1269 if (mpctx->sh_audio) {
1270 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1271 if (!sh_video) {
1272 float len = get_time_length(mpctx);
1273 saddf(line, &pos, width, "(");
1274 sadd_hhmmssf(line, &pos, width, a_pos);
1275 saddf(line, &pos, width, ") of %.1f (", len);
1276 sadd_hhmmssf(line, &pos, width, len);
1277 saddf(line, &pos, width, ") ");
1281 // Video time
1282 if (sh_video)
1283 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1285 // A-V sync
1286 if (mpctx->sh_audio && sh_video)
1287 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1288 mpctx->last_av_difference, mpctx->total_avsync_change);
1290 // Video stats
1291 if (sh_video)
1292 saddf(line, &pos, width, "%3d/%3d ",
1293 (int)sh_video->num_frames,
1294 (int)sh_video->num_frames_decoded);
1296 // CPU usage
1297 if (sh_video) {
1298 if (sh_video->timer > 0.5)
1299 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1300 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1301 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1302 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1303 else
1304 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1305 } else if (mpctx->sh_audio) {
1306 if (mpctx->delay > 0.5)
1307 saddf(line, &pos, width, "%4.1f%% ",
1308 100.0 * audio_time_usage / (double)mpctx->delay);
1309 else
1310 saddf(line, &pos, width, "??,?%% ");
1313 // VO stats
1314 if (sh_video)
1315 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1317 #ifdef CONFIG_STREAM_CACHE
1318 // cache stats
1319 if (stream_cache_size > 0)
1320 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1321 #endif
1323 // other
1324 if (opts->playback_speed != 1)
1325 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1327 // end
1328 if (erase_to_end_of_line) {
1329 line[pos] = 0;
1330 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1331 "%s%s\r", line, erase_to_end_of_line);
1332 } else {
1333 memset(&line[pos], ' ', width - pos);
1334 line[width] = 0;
1335 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1337 free(line);
1339 mpctx->status_printed = true;
1342 struct stream_dump_progress {
1343 uint64_t count;
1344 unsigned start_time;
1345 unsigned last_print_time;
1348 static void stream_dump_progress_start(struct stream_dump_progress *p)
1350 p->start_time = p->last_print_time = GetTimerMS();
1351 p->count = 0;
1354 static void stream_dump_progress(struct stream_dump_progress *p,
1355 uint64_t len, stream_t *stream)
1357 p->count += len;
1358 unsigned t = GetTimerMS();
1359 if (t - p->last_print_time < 1000)
1360 return;
1362 uint64_t start = stream->start_pos;
1363 uint64_t end = stream->end_pos;
1364 uint64_t pos = stream->pos;
1366 p->last_print_time = t;
1367 /* TODO: pretty print sizes; ETA */
1368 if (end > start && pos >= start && pos <= end) {
1369 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1370 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1371 p->count, 100.0 * (pos - start) / (end - start));
1372 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1373 } else {
1374 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1375 "dump: %"PRIu64 " bytes written", p->count);
1376 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1380 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1382 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1383 p->count, name);
1387 * \brief build a chain of audio filters that converts the input format
1388 * to the ao's format, taking into account the current playback_speed.
1389 * sh_audio describes the requested input format of the chain.
1390 * ao describes the requested output format of the chain.
1392 static int build_afilter_chain(struct MPContext *mpctx)
1394 struct sh_audio *sh_audio = mpctx->sh_audio;
1395 struct ao *ao = mpctx->ao;
1396 struct MPOpts *opts = &mpctx->opts;
1397 int new_srate;
1398 int result;
1399 if (!sh_audio) {
1400 mpctx->mixer.afilter = NULL;
1401 return 0;
1403 if (af_control_any_rev(sh_audio->afilter,
1404 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1405 &opts->playback_speed))
1406 new_srate = sh_audio->samplerate;
1407 else {
1408 new_srate = sh_audio->samplerate * opts->playback_speed;
1409 if (new_srate != ao->samplerate) {
1410 // limits are taken from libaf/af_resample.c
1411 if (new_srate < 8000)
1412 new_srate = 8000;
1413 if (new_srate > 192000)
1414 new_srate = 192000;
1415 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1418 result = init_audio_filters(sh_audio, new_srate,
1419 &ao->samplerate, &ao->channels, &ao->format);
1420 mpctx->mixer.afilter = sh_audio->afilter;
1421 return result;
1425 typedef struct mp_osd_msg mp_osd_msg_t;
1426 struct mp_osd_msg {
1427 /// Previous message on the stack.
1428 mp_osd_msg_t *prev;
1429 /// Message text.
1430 char *msg;
1431 int id, level, started;
1432 /// Display duration in ms.
1433 unsigned time;
1436 /// OSD message stack.
1437 static mp_osd_msg_t *osd_msg_stack = NULL;
1440 * \brief Add a message on the OSD message stack
1442 * If a message with the same id is already present in the stack
1443 * it is pulled on top of the stack, otherwise a new message is created.
1446 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1447 va_list ap)
1449 mp_osd_msg_t *msg, *last = NULL;
1451 // look if the id is already in the stack
1452 for (msg = osd_msg_stack; msg && msg->id != id;
1453 last = msg, msg = msg->prev) ;
1454 // not found: alloc it
1455 if (!msg) {
1456 msg = talloc_zero(NULL, mp_osd_msg_t);
1457 msg->prev = osd_msg_stack;
1458 osd_msg_stack = msg;
1459 } else if (last) { // found, but it's not on top of the stack
1460 last->prev = msg->prev;
1461 msg->prev = osd_msg_stack;
1462 osd_msg_stack = msg;
1464 talloc_free(msg->msg);
1465 // write the msg
1466 msg->msg = talloc_vasprintf(msg, fmt, ap);
1467 // set id and time
1468 msg->id = id;
1469 msg->level = level;
1470 msg->time = time;
1474 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1476 va_list ap;
1477 va_start(ap, fmt);
1478 set_osd_msg_va(id, level, time, fmt, ap);
1479 va_end(ap);
1482 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1484 va_list ap;
1485 va_start(ap, fmt);
1486 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1487 va_end(ap);
1491 * \brief Remove a message from the OSD stack
1493 * This function can be used to get rid of a message right away.
1497 void rm_osd_msg(int id)
1499 mp_osd_msg_t *msg, *last = NULL;
1501 // Search for the msg
1502 for (msg = osd_msg_stack; msg && msg->id != id;
1503 last = msg, msg = msg->prev) ;
1504 if (!msg)
1505 return;
1507 // Detach it from the stack and free it
1508 if (last)
1509 last->prev = msg->prev;
1510 else
1511 osd_msg_stack = msg->prev;
1512 talloc_free(msg);
1516 * \brief Remove all messages from the OSD stack
1520 static void clear_osd_msgs(void)
1522 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1523 while (msg) {
1524 prev = msg->prev;
1525 talloc_free(msg);
1526 msg = prev;
1528 osd_msg_stack = NULL;
1532 * \brief Get the current message from the OSD stack.
1534 * This function decrements the message timer and destroys the old ones.
1535 * The message that should be displayed is returned (if any).
1539 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1541 struct MPOpts *opts = &mpctx->opts;
1542 mp_osd_msg_t *msg, *prev, *last = NULL;
1543 static unsigned last_update = 0;
1544 unsigned now = GetTimerMS();
1545 unsigned diff;
1546 char hidden_dec_done = 0;
1548 if (mpctx->osd_visible) {
1549 // 36000000 means max timed visibility is 1 hour into the future, if
1550 // the difference is greater assume it's wrapped around from below 0
1551 if (mpctx->osd_visible - now > 36000000) {
1552 mpctx->osd_visible = 0;
1553 vo_osd_progbar_type = -1; // disable
1554 vo_osd_changed(OSDTYPE_PROGBAR);
1555 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1558 if (mpctx->osd_show_percentage_until - now > 36000000)
1559 mpctx->osd_show_percentage_until = 0;
1561 if (!last_update)
1562 last_update = now;
1563 diff = now >= last_update ? now - last_update : 0;
1565 last_update = now;
1567 // Look for the first message in the stack with high enough level.
1568 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1569 prev = msg->prev;
1570 if (msg->level > opts->osd_level && hidden_dec_done)
1571 continue;
1572 // The message has a high enough level or it is the first hidden one
1573 // in both cases we decrement the timer or kill it.
1574 if (!msg->started || msg->time > diff) {
1575 if (msg->started)
1576 msg->time -= diff;
1577 else
1578 msg->started = 1;
1579 // display it
1580 if (msg->level <= opts->osd_level)
1581 return msg;
1582 hidden_dec_done = 1;
1583 continue;
1585 // kill the message
1586 talloc_free(msg);
1587 if (last) {
1588 last->prev = prev;
1589 msg = last;
1590 } else {
1591 osd_msg_stack = prev;
1592 msg = NULL;
1595 // Nothing found
1596 return NULL;
1600 * \brief Display the OSD bar.
1602 * Display the OSD bar or fall back on a simple message.
1606 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1607 double min, double max, double val)
1609 struct MPOpts *opts = &mpctx->opts;
1610 if (opts->osd_level < 1)
1611 return;
1613 if (mpctx->sh_video) {
1614 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1615 vo_osd_progbar_type = type;
1616 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1617 vo_osd_changed(OSDTYPE_PROGBAR);
1618 return;
1621 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1622 name, ROUND(100 * (val - min) / (max - min)));
1626 * \brief Display text subtitles on the OSD
1628 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1630 int i;
1631 vo_sub = subs;
1632 vo_osd_changed(OSDTYPE_SUBTITLE);
1633 if (!mpctx->sh_video) {
1634 // reverse order, since newest set_osd_msg is displayed first
1635 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1636 if (!subs || i >= subs->lines || !subs->text[i])
1637 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1638 else {
1639 // HACK: currently display time for each sub line
1640 // except the last is set to 2 seconds.
1641 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1642 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1643 "%s", subs->text[i]);
1650 * \brief Update the OSD message line.
1652 * This function displays the current message on the vo OSD or on the term.
1653 * If the stack is empty and the OSD level is high enough the timer
1654 * is displayed (only on the vo OSD).
1658 static void update_osd_msg(struct MPContext *mpctx)
1660 struct MPOpts *opts = &mpctx->opts;
1661 mp_osd_msg_t *msg;
1662 struct osd_state *osd = mpctx->osd;
1663 char osd_text_timer[128];
1665 if (mpctx->add_osd_seek_info) {
1666 double percentage = get_percent_pos(mpctx);
1667 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1668 if (mpctx->sh_video)
1669 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1670 mpctx->add_osd_seek_info = false;
1673 // Look if we have a msg
1674 if ((msg = get_osd_msg(mpctx))) {
1675 if (strcmp(osd->osd_text, msg->msg)) {
1676 osd_set_text(osd, msg->msg);
1677 if (mpctx->sh_video)
1678 vo_osd_changed(OSDTYPE_OSD);
1679 else if (opts->term_osd)
1680 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1681 msg->msg);
1683 return;
1686 if (mpctx->sh_video) {
1687 // fallback on the timer
1688 if (opts->osd_level >= 2) {
1689 int len = get_time_length(mpctx);
1690 int percentage = -1;
1691 char percentage_text[10];
1692 char fractions_text[4];
1693 double fpts = get_current_time(mpctx);
1694 int pts = fpts;
1696 if (mpctx->osd_show_percentage_until)
1697 percentage = get_percent_pos(mpctx);
1699 if (percentage >= 0)
1700 snprintf(percentage_text, 9, " (%d%%)", percentage);
1701 else
1702 percentage_text[0] = 0;
1704 if (opts->osd_fractions == 1) {
1705 //print fractions as sub-second timestamp
1706 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1707 (int)((fpts - pts) * 100));
1708 } else if (opts->osd_fractions == 2) {
1709 /* Print fractions by estimating the frame count within the
1710 * second.
1712 * Rounding or cutting off numbers after the decimal point
1713 * causes problems because of float's precision and movies
1714 * whose first frame is not exactly at timestamp 0. Therefore,
1715 * we add 0.2 and cut off at the decimal point, which proved
1716 * to be good heuristic.
1718 double fps = mpctx->sh_video->fps;
1719 if (fps <= 1 || fps > 99)
1720 strcpy(fractions_text, ".??");
1721 else
1722 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1723 (int) ((fpts - pts) * fps + 0.2));
1724 } else {
1725 //do not print fractions
1726 fractions_text[0] = 0;
1729 if (opts->osd_level == 3)
1730 snprintf(osd_text_timer, sizeof(osd_text_timer),
1731 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1732 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1733 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1734 percentage_text);
1735 else
1736 snprintf(osd_text_timer, sizeof(osd_text_timer),
1737 "%c %02d:%02d:%02d%s%s",
1738 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1739 pts % 60, fractions_text, percentage_text);
1740 } else
1741 osd_text_timer[0] = 0;
1743 if (strcmp(osd->osd_text, osd_text_timer)) {
1744 osd_set_text(osd, osd_text_timer);
1745 vo_osd_changed(OSDTYPE_OSD);
1747 return;
1750 // Clear the term osd line
1751 if (opts->term_osd && osd->osd_text[0]) {
1752 osd->osd_text[0] = 0;
1753 printf("%s\n", opts->term_osd_esc);
1758 void reinit_audio_chain(struct MPContext *mpctx)
1760 struct MPOpts *opts = &mpctx->opts;
1761 struct ao *ao;
1762 if (!mpctx->sh_audio)
1763 return;
1764 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1765 current_module = "init_audio_codec";
1766 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1767 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1768 goto init_error;
1769 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1770 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1774 current_module = "af_preinit";
1775 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1776 mpctx->initialized_flags |= INITIALIZED_AO;
1777 mpctx->ao = ao_create();
1778 mpctx->ao->samplerate = force_srate;
1779 mpctx->ao->format = opts->audio_output_format;
1781 ao = mpctx->ao;
1783 // first init to detect best values
1784 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1785 // input:
1786 mpctx->sh_audio->samplerate,
1787 // output:
1788 &ao->samplerate, &ao->channels, &ao->format)) {
1789 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1790 "pre-init!\n");
1791 exit_player(mpctx, EXIT_ERROR);
1793 if (!ao->initialized) {
1794 current_module = "ao2_init";
1795 ao->buffersize = opts->ao_buffersize;
1796 ao_init(ao, opts->audio_driver_list);
1797 if (!ao->initialized) {
1798 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1799 "Could not open/initialize audio device -> no sound.\n");
1800 goto init_error;
1802 ao->buffer.start = talloc_new(ao);
1803 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1804 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1805 ao->driver->info->short_name,
1806 ao->samplerate, ao->channels,
1807 af_fmt2str_short(ao->format),
1808 af_fmt2bits(ao->format) / 8);
1809 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1810 ao->driver->info->name, ao->driver->info->author);
1811 if (strlen(ao->driver->info->comment) > 0)
1812 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1813 ao->driver->info->comment);
1816 // init audio filters:
1817 current_module = "af_init";
1818 if (!build_afilter_chain(mpctx)) {
1819 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1820 "Couldn't find matching filter/ao format!\n");
1821 goto init_error;
1823 mpctx->mixer.ao = ao;
1824 mpctx->mixer.volstep = volstep;
1825 mpctx->syncing_audio = true;
1826 return;
1828 init_error:
1829 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1830 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1831 mpctx->d_audio->id = -2;
1835 // Return pts value corresponding to the end point of audio written to the
1836 // ao so far.
1837 static double written_audio_pts(struct MPContext *mpctx)
1839 sh_audio_t *sh_audio = mpctx->sh_audio;
1840 demux_stream_t *d_audio = mpctx->d_audio;
1841 // first calculate the end pts of audio that has been output by decoder
1842 double a_pts = sh_audio->pts;
1843 if (a_pts != MP_NOPTS_VALUE)
1844 // Good, decoder supports new way of calculating audio pts.
1845 // sh_audio->pts is the timestamp of the latest input packet with
1846 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1847 // the amount of bytes the decoder has written after that timestamp.
1848 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1849 else {
1850 // Decoder doesn't support new way of calculating pts (or we're
1851 // being called before it has decoded anything with known timestamp).
1852 // Use the old method of audio pts calculation: take the timestamp
1853 // of last packet with known pts the decoder has read data from,
1854 // and add amount of bytes read after the beginning of that packet
1855 // divided by input bps. This will be inaccurate if the input/output
1856 // ratio is not constant for every audio packet or if it is constant
1857 // but not accurately known in sh_audio->i_bps.
1859 a_pts = d_audio->pts;
1860 if (a_pts == MP_NOPTS_VALUE)
1861 return a_pts;
1863 // ds_tell_pts returns bytes read after last timestamp from
1864 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1865 // it has read but not decoded
1866 if (sh_audio->i_bps)
1867 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1868 (double)sh_audio->i_bps;
1870 // Now a_pts hopefully holds the pts for end of audio from decoder.
1871 // Substract data in buffers between decoder and audio out.
1873 // Decoded but not filtered
1874 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1876 // Data buffered in audio filters, measured in bytes of "missing" output
1877 double buffered_output = af_calc_delay(sh_audio->afilter);
1879 // Data that was ready for ao but was buffered because ao didn't fully
1880 // accept everything to internal buffers yet
1881 buffered_output += mpctx->ao->buffer.len;
1883 // Filters divide audio length by playback_speed, so multiply by it
1884 // to get the length in original units without speedup or slowdown
1885 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1887 return a_pts + mpctx->video_offset;
1890 // Return pts value corresponding to currently playing audio.
1891 double playing_audio_pts(struct MPContext *mpctx)
1893 double pts = written_audio_pts(mpctx);
1894 if (pts == MP_NOPTS_VALUE)
1895 return pts;
1896 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1899 static bool is_av_sub(int type)
1901 return type == 'b' || type == 'p' || type == 'x';
1904 void update_subtitles(struct MPContext *mpctx, double refpts,
1905 double sub_offset, bool reset)
1907 struct MPOpts *opts = &mpctx->opts;
1908 struct sh_video *sh_video = mpctx->sh_video;
1909 struct demux_stream *d_sub = mpctx->d_sub;
1910 double curpts = refpts + sub_delay;
1911 unsigned char *packet = NULL;
1912 int len;
1913 struct sh_sub *sh_sub = d_sub->sh;
1914 int type = sh_sub ? sh_sub->type : 'v';
1915 static subtitle subs;
1916 if (reset) {
1917 if (sh_sub)
1918 sub_reset(sh_sub, mpctx->osd);
1919 sub_clear_text(&subs, MP_NOPTS_VALUE);
1920 if (vo_sub)
1921 set_osd_subtitle(mpctx, NULL);
1922 if (vo_spudec) {
1923 spudec_reset(vo_spudec);
1924 vo_osd_changed(OSDTYPE_SPU);
1926 if (is_av_sub(type))
1927 reset_avsub(sh_sub);
1928 return;
1930 // find sub
1931 if (mpctx->subdata) {
1932 if (sub_fps == 0)
1933 sub_fps = sh_video ? sh_video->fps : 25;
1934 current_module = "find_sub";
1935 find_sub(mpctx, mpctx->subdata, curpts *
1936 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1937 if (vo_sub)
1938 mpctx->vo_sub_last = vo_sub;
1941 // DVD sub:
1942 if (vobsub_id >= 0 || type == 'v') {
1943 int timestamp;
1944 current_module = "spudec";
1945 /* Get a sub packet from the DVD or a vobsub */
1946 while (1) {
1947 // Vobsub
1948 len = 0;
1949 if (vo_vobsub) {
1950 if (curpts >= 0) {
1951 len = vobsub_get_packet(vo_vobsub, curpts,
1952 (void **)&packet, &timestamp);
1953 if (len > 0)
1954 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1955 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1956 len, refpts, sh_video->timer,
1957 timestamp / 90000.0, timestamp);
1959 } else {
1960 // DVD sub
1961 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1962 if (len > 0) {
1963 // XXX This is wrong, sh_video->pts can be arbitrarily
1964 // much behind demuxing position. Unfortunately using
1965 // d_video->pts which would have been the simplest
1966 // improvement doesn't work because mpeg specific hacks
1967 // in video.c set d_video->pts to 0.
1968 float x = d_sub->pts - refpts;
1969 if (x > -20 && x < 20) // prevent missing subs on pts reset
1970 timestamp = 90000 * d_sub->pts;
1971 else
1972 timestamp = 90000 * curpts;
1973 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1974 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1975 refpts, d_sub->pts, timestamp);
1978 if (len <= 0 || !packet)
1979 break;
1980 // create it only here, since with some broken demuxers we might
1981 // type = v but no DVD sub and we currently do not change the
1982 // "original frame size" ever after init, leading to wrong-sized
1983 // PGS subtitles.
1984 if (!vo_spudec)
1985 vo_spudec = spudec_new(NULL);
1986 if (vo_vobsub || timestamp >= 0)
1987 spudec_assemble(vo_spudec, packet, len, timestamp);
1989 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1990 if (type == 'd' && !d_sub->demuxer->teletext) {
1991 tt_stream_props tsp = { 0 };
1992 void *ptr = &tsp;
1993 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
1994 VBI_CONTROL_TRUE)
1995 d_sub->demuxer->teletext = ptr;
1997 if (d_sub->non_interleaved)
1998 ds_get_next_pts(d_sub);
2000 while (d_sub->first) {
2001 double subpts = ds_get_next_pts(d_sub) + sub_offset;
2002 if (subpts > curpts) {
2003 // Libass handled subs can be fed to it in advance
2004 if (!opts->ass_enabled || !is_text_sub(type))
2005 break;
2006 // Try to avoid demuxing whole file at once
2007 if (d_sub->non_interleaved && subpts > curpts + 1)
2008 break;
2010 double duration = d_sub->first->duration;
2011 len = ds_get_packet_sub(d_sub, &packet);
2012 if (is_av_sub(type)) {
2013 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2014 if (ret < 0)
2015 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2016 "subtitle\n");
2017 continue;
2019 if (type == 'm') {
2020 if (len < 2)
2021 continue;
2022 len = FFMIN(len - 2, AV_RB16(packet));
2023 packet += 2;
2025 if (type == 'd') {
2026 if (d_sub->demuxer->teletext) {
2027 uint8_t *p = packet;
2028 p++;
2029 len--;
2030 while (len >= 46) {
2031 int sublen = p[1];
2032 if (p[0] == 2 || p[0] == 3)
2033 teletext_control(d_sub->demuxer->teletext,
2034 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2035 p += sublen + 2;
2036 len -= sublen + 2;
2039 continue;
2041 if (sh_sub && sh_sub->active) {
2042 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2043 continue;
2045 if (subpts != MP_NOPTS_VALUE) {
2046 if (duration < 0)
2047 sub_clear_text(&subs, MP_NOPTS_VALUE);
2048 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2049 int i;
2050 unsigned char *p = packet;
2051 for (i = 0; i < 8 && *p != '\0'; p++)
2052 if (*p == ',')
2053 i++;
2054 if (*p == '\0') /* Broken line? */
2055 continue;
2056 len -= p - packet;
2057 packet = p;
2059 double endpts = MP_NOPTS_VALUE;
2060 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2061 endpts = subpts + duration;
2062 sub_add_text(&subs, packet, len, endpts);
2063 set_osd_subtitle(mpctx, &subs);
2065 if (d_sub->non_interleaved)
2066 ds_get_next_pts(d_sub);
2068 if (!opts->ass_enabled)
2069 if (sub_clear_text(&subs, curpts))
2070 set_osd_subtitle(mpctx, &subs);
2072 if (vo_spudec) {
2073 spudec_heartbeat(vo_spudec, 90000 * curpts);
2074 if (spudec_changed(vo_spudec))
2075 vo_osd_changed(OSDTYPE_SPU);
2078 current_module = NULL;
2081 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2083 int page_changed;
2085 if (!demuxer->teletext)
2086 return;
2088 //Also forcing page update when such ioctl is not supported or call error occured
2089 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2090 &page_changed) != VBI_CONTROL_TRUE)
2091 page_changed = 1;
2093 if (!page_changed)
2094 return;
2096 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2097 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2098 vo_osd_teletext_page = NULL;
2099 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2100 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2101 vo_osd_teletext_half = 0;
2102 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2103 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2104 vo_osd_teletext_mode = 0;
2105 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2106 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2107 vo_osd_teletext_format = 0;
2108 vo_osd_changed(OSDTYPE_TELETEXT);
2110 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2113 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2115 struct MPOpts *opts = &mpctx->opts;
2116 // check for frame-drop:
2117 current_module = "check_framedrop";
2118 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2119 static int dropped_frames;
2120 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2121 float d = delay - mpctx->delay;
2122 ++total_frame_cnt;
2123 // we should avoid dropping too many frames in sequence unless we
2124 // are too late. and we allow 100ms A-V delay here:
2125 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2126 && !mpctx->restart_playback) {
2127 ++drop_frame_cnt;
2128 ++dropped_frames;
2129 return frame_dropping;
2130 } else
2131 dropped_frames = 0;
2133 return 0;
2137 #ifdef HAVE_RTC
2138 int rtc_fd = -1;
2139 #endif
2141 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2143 #ifdef HAVE_RTC
2144 if (rtc_fd >= 0) {
2145 // -------- RTC -----------
2146 current_module = "sleep_rtc";
2147 while (time_frame > 0.000) {
2148 unsigned long rtc_ts;
2149 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2150 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2151 "Linux RTC read error: %s\n", strerror(errno));
2152 time_frame -= get_relative_time(mpctx);
2154 } else
2155 #endif
2157 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2158 // unnecessarily high CPU usage
2159 struct MPOpts *opts = &mpctx->opts;
2160 float margin = opts->softsleep ? 0.011 : 0;
2161 current_module = "sleep_timer";
2162 while (time_frame > margin) {
2163 usec_sleep(1000000 * (time_frame - margin));
2164 time_frame -= get_relative_time(mpctx);
2166 if (opts->softsleep) {
2167 current_module = "sleep_soft";
2168 if (time_frame < 0)
2169 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2170 "Warning! Softsleep underflow!\n");
2171 while (time_frame > 0)
2172 time_frame -= get_relative_time(mpctx); // burn the CPU
2175 return time_frame;
2178 static int select_subtitle(MPContext *mpctx)
2180 struct MPOpts *opts = &mpctx->opts;
2181 // find the best sub to use
2182 int id;
2183 int found = 0;
2184 mpctx->global_sub_pos = -1; // no subs by default
2185 if (vobsub_id >= 0) {
2186 // if user asks for a vobsub id, use that first.
2187 id = vobsub_id;
2188 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2189 M_PROPERTY_OK;
2192 if (!found && opts->sub_id >= 0) {
2193 // if user asks for a dvd sub id, use that next.
2194 id = opts->sub_id;
2195 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2196 M_PROPERTY_OK;
2199 if (!found) {
2200 // if there are text subs to use, use those. (autosubs come last here)
2201 id = 0;
2202 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2203 M_PROPERTY_OK;
2206 if (!found && opts->sub_id == -1) {
2207 // finally select subs by language and container hints
2208 if (opts->sub_id == -1)
2209 opts->sub_id =
2210 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2211 opts->sub_lang);
2212 if (opts->sub_id >= 0) {
2213 id = opts->sub_id;
2214 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2215 M_PROPERTY_OK;
2218 return found;
2221 #ifdef CONFIG_DVDNAV
2222 #ifndef FF_B_TYPE
2223 #define FF_B_TYPE 3
2224 #endif
2225 /// store decoded video image
2226 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2227 mp_image_t *from_mpi)
2229 mp_image_t *mpi;
2231 /// Do not store B-frames
2232 if (from_mpi->pict_type == FF_B_TYPE)
2233 return to_mpi;
2235 if (to_mpi &&
2236 to_mpi->w == from_mpi->w &&
2237 to_mpi->h == from_mpi->h &&
2238 to_mpi->imgfmt == from_mpi->imgfmt)
2239 mpi = to_mpi;
2240 else {
2241 if (to_mpi)
2242 free_mp_image(to_mpi);
2243 if (from_mpi->w == 0 || from_mpi->h == 0)
2244 return NULL;
2245 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2248 copy_mpi(mpi, from_mpi);
2249 return mpi;
2252 static void mp_dvdnav_reset_stream(MPContext *ctx)
2254 struct MPOpts *opts = &ctx->opts;
2255 if (ctx->sh_video) {
2256 /// clear video pts
2257 ctx->d_video->pts = 0.0f;
2258 ctx->sh_video->pts = 0.0f;
2259 ctx->sh_video->i_pts = 0.0f;
2260 ctx->sh_video->last_pts = 0.0f;
2261 ctx->sh_video->num_buffered_pts = 0;
2262 ctx->sh_video->num_frames = 0;
2263 ctx->sh_video->num_frames_decoded = 0;
2264 ctx->sh_video->timer = 0.0f;
2265 ctx->sh_video->stream_delay = 0.0f;
2266 ctx->sh_video->timer = 0;
2267 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2270 if (ctx->sh_audio) {
2271 /// free audio packets and reset
2272 ds_free_packs(ctx->d_audio);
2273 audio_delay -= ctx->sh_audio->stream_delay;
2274 ctx->delay = -audio_delay;
2275 ao_reset(ctx->ao);
2276 resync_audio_stream(ctx->sh_audio);
2279 audio_delay = 0.0f;
2280 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2281 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2282 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2283 if (dvdsub_lang_id != opts->sub_id) {
2284 opts->sub_id = dvdsub_lang_id;
2285 select_subtitle(ctx);
2289 /// clear all EOF related flags
2290 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2293 /// Restore last decoded DVDNAV (still frame)
2294 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2295 int *in_size,
2296 unsigned char **start,
2297 mp_image_t *decoded_frame)
2299 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2300 return decoded_frame;
2302 /// a change occurred in dvdnav stream
2303 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2304 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2305 mp_dvdnav_context_free(mpctx);
2306 mp_dvdnav_reset_stream(mpctx);
2307 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2308 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2311 if (*in_size < 0) {
2312 float len;
2314 /// Display still frame, if any
2315 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2316 decoded_frame = mpctx->nav_smpi;
2318 /// increment video frame : continue playing after still frame
2319 len = get_time_length(mpctx);
2320 if (mpctx->sh_video->pts >= len &&
2321 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2322 mp_dvdnav_skip_still(mpctx->stream);
2323 mp_dvdnav_skip_wait(mpctx->stream);
2325 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2327 if (mpctx->nav_buffer) {
2328 *start = mpctx->nav_start;
2329 *in_size = mpctx->nav_in_size;
2330 if (mpctx->nav_start)
2331 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2335 return decoded_frame;
2338 /// Save last decoded DVDNAV (still frame)
2339 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2340 unsigned char *start,
2341 mp_image_t *decoded_frame)
2343 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2344 return;
2346 free(mpctx->nav_buffer);
2347 mpctx->nav_buffer = NULL;
2348 mpctx->nav_start = NULL;
2349 mpctx->nav_in_size = -1;
2351 if (in_size > 0)
2352 mpctx->nav_buffer = malloc(in_size);
2353 if (mpctx->nav_buffer) {
2354 mpctx->nav_start = start;
2355 mpctx->nav_in_size = in_size;
2356 memcpy(mpctx->nav_buffer, start, in_size);
2359 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2360 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2362 #endif /* CONFIG_DVDNAV */
2364 /* Modify video timing to match the audio timeline. There are two main
2365 * reasons this is needed. First, video and audio can start from different
2366 * positions at beginning of file or after a seek (MPlayer starts both
2367 * immediately even if they have different pts). Second, the file can have
2368 * audio timestamps that are inconsistent with the duration of the audio
2369 * packets, for example two consecutive timestamp values differing by
2370 * one second but only a packet with enough samples for half a second
2371 * of playback between them.
2373 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2375 current_module = "av_sync";
2377 if (!mpctx->sh_audio || mpctx->syncing_audio)
2378 return;
2380 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2381 double v_pts = mpctx->sh_video->pts;
2382 double av_delay = a_pts - v_pts;
2383 // Try to sync vo_flip() so it will *finish* at given time
2384 av_delay += mpctx->last_vo_flip_duration;
2385 av_delay -= audio_delay; // This much pts difference is desired
2387 double change = av_delay * 0.1;
2388 double max_change = default_max_pts_correction >= 0 ?
2389 default_max_pts_correction : frame_time * 0.1;
2390 if (change < -max_change)
2391 change = -max_change;
2392 else if (change > max_change)
2393 change = max_change;
2394 mpctx->delay += change;
2395 mpctx->total_avsync_change += change;
2398 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2399 double pts)
2401 if (mpctx->paused)
2402 return 0;
2403 struct ao *ao = mpctx->ao;
2404 double bps = ao->bps / mpctx->opts.playback_speed;
2405 ao->pts = pts;
2406 // hack used by some mpeg-writing AOs
2407 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2408 mpctx->delay) * 90000.0;
2409 int played = ao_play(mpctx->ao, data, len, flags);
2410 if (played > 0) {
2411 mpctx->delay += played / bps;
2412 // Keep correct pts for remaining data - could be used to flush
2413 // remaining buffer when closing ao.
2414 ao->pts += played / bps;
2416 return played;
2419 #define ASYNC_PLAY_DONE -3
2420 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2422 struct ao *ao = mpctx->ao;
2423 struct MPOpts *opts = &mpctx->opts;
2424 sh_audio_t * const sh_audio = mpctx->sh_audio;
2425 int res;
2427 // Timing info may not be set without
2428 res = decode_audio(sh_audio, &ao->buffer, 1);
2429 if (res < 0)
2430 return res;
2432 int bytes;
2433 bool did_retry = false;
2434 double written_pts;
2435 double bps = ao->bps / opts->playback_speed;
2436 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2437 mpctx->hrseek_active = false;
2438 while (1) {
2439 written_pts = written_audio_pts(mpctx);
2440 double ptsdiff;
2441 if (hrseek)
2442 ptsdiff = written_pts - mpctx->hrseek_pts;
2443 else
2444 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2445 - audio_delay;
2446 bytes = ptsdiff * bps;
2447 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2449 // ogg demuxers give packets without timing
2450 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2451 if (!did_retry) {
2452 // Try to read more data to see packets that have pts
2453 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2454 if (res < 0)
2455 return res;
2456 did_retry = true;
2457 continue;
2459 bytes = 0;
2462 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2463 bytes = 0;
2465 if (bytes > 0)
2466 break;
2468 mpctx->syncing_audio = false;
2469 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2470 int res = decode_audio(sh_audio, &ao->buffer, a);
2471 bytes += ao->buffer.len;
2472 if (bytes >= 0) {
2473 memmove(ao->buffer.start,
2474 ao->buffer.start + ao->buffer.len - bytes, bytes);
2475 ao->buffer.len = bytes;
2476 if (res < 0)
2477 return res;
2478 return decode_audio(sh_audio, &ao->buffer, playsize);
2480 ao->buffer.len = 0;
2481 if (res < 0)
2482 return res;
2484 if (hrseek)
2485 // Don't add silence in audio-only case even if position is too late
2486 return 0;
2487 int fillbyte = 0;
2488 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2489 fillbyte = 0x80;
2490 if (bytes >= playsize) {
2491 /* This case could fall back to the one below with
2492 * bytes = playsize, but then silence would keep accumulating
2493 * in a_out_buffer if the AO accepts less data than it asks for
2494 * in playsize. */
2495 char *p = malloc(playsize);
2496 memset(p, fillbyte, playsize);
2497 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2498 free(p);
2499 return ASYNC_PLAY_DONE;
2501 mpctx->syncing_audio = false;
2502 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2503 return decode_audio(sh_audio, &ao->buffer, playsize);
2506 static int fill_audio_out_buffers(struct MPContext *mpctx)
2508 struct MPOpts *opts = &mpctx->opts;
2509 struct ao *ao = mpctx->ao;
2510 unsigned int t;
2511 double tt;
2512 int playsize;
2513 int playflags = 0;
2514 bool audio_eof = false;
2515 bool partial_fill = false;
2516 sh_audio_t * const sh_audio = mpctx->sh_audio;
2517 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2518 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2520 current_module = "play_audio";
2522 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2523 return 0;
2525 // hack used by some mpeg-writing AOs
2526 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2527 mpctx->delay) * 90000.0;
2529 if (mpctx->paused)
2530 playsize = 1; // just initialize things (audio pts at least)
2531 else
2532 playsize = ao_get_space(ao);
2534 // Fill buffer if needed:
2535 current_module = "decode_audio";
2536 t = GetTimer();
2538 // Coming here with hrseek_active still set means audio-only
2539 if (!mpctx->sh_video)
2540 mpctx->syncing_audio = false;
2541 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2542 mpctx->syncing_audio = false;
2543 mpctx->hrseek_active = false;
2546 int res;
2547 if (mpctx->syncing_audio || mpctx->hrseek_active)
2548 res = audio_start_sync(mpctx, playsize);
2549 else
2550 res = decode_audio(sh_audio, &ao->buffer, playsize);
2551 if (res < 0) { // EOF, error or format change
2552 if (res == -2) {
2553 /* The format change isn't handled too gracefully. A more precise
2554 * implementation would require draining buffered old-format audio
2555 * while displaying video, then doing the output format switch.
2557 uninit_player(mpctx, INITIALIZED_AO);
2558 reinit_audio_chain(mpctx);
2559 return -1;
2560 } else if (res == ASYNC_PLAY_DONE)
2561 return 0;
2562 else if (mpctx->d_audio->eof)
2563 audio_eof = true;
2565 t = GetTimer() - t;
2566 tt = t * 0.000001f;
2567 audio_time_usage += tt;
2568 if (mpctx->timeline && modifiable_audio_format) {
2569 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
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 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2612 bool sync_to_audio, float *aq_sleep_time)
2614 struct MPOpts *opts = &mpctx->opts;
2615 double audio_limit = 2;
2616 current_module = "calc_sleep_time";
2618 if (mpctx->restart_playback)
2619 return 0;
2621 *time_frame -= get_relative_time(mpctx); // reset timer
2623 if (sync_to_audio) {
2624 float delay = ao_get_delay(mpctx->ao);
2625 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2627 if (opts->autosync) {
2629 * Adjust this raw delay value by calculating the expected
2630 * delay for this frame and generating a new value which is
2631 * weighted between the two. The higher autosync is, the
2632 * closer to the delay value gets to that which "-nosound"
2633 * would have used, and the longer it will take for A/V
2634 * sync to settle at the right value (but it eventually will.)
2635 * This settling time is very short for values below 100.
2637 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2638 float difference = delay - predicted;
2639 delay = predicted + difference / (float)opts->autosync;
2642 *time_frame = delay - mpctx->delay / opts->playback_speed;
2644 // delay = amount of audio buffered in soundcard/driver
2645 delay = FFMIN(delay, 0.5);
2646 delay = FFMAX(delay, 0.1);
2647 audio_limit = delay;
2648 } else {
2649 // If we're lagging more than 200 ms behind the right playback rate,
2650 // don't try to "catch up".
2651 // If benchmark is set always output frames as fast as possible
2652 // without sleeping.
2653 if (*time_frame < -0.2 || opts->benchmark)
2654 *time_frame = 0;
2657 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2659 if (t <= 0.05)
2660 return 0;
2662 t -= 0.05;
2663 if (t > audio_limit * 0.6)
2664 t = audio_limit * 0.5;
2665 *aq_sleep_time += t;
2666 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2667 return 1;
2670 int reinit_video_chain(struct MPContext *mpctx)
2672 struct MPOpts *opts = &mpctx->opts;
2673 sh_video_t * const sh_video = mpctx->sh_video;
2674 if (!sh_video)
2675 return 0;
2676 double ar = -1.0;
2677 //================== Init VIDEO (codec & libvo) ==========================
2678 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2679 current_module = "preinit_libvo";
2681 //shouldn't we set dvideo->id=-2 when we fail?
2682 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2683 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2684 mpctx->key_fifo,
2685 mpctx->input))) {
2686 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2687 "the selected video_out (-vo) device.\n");
2688 goto err_out;
2690 mpctx->initialized_flags |= INITIALIZED_VO;
2693 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2694 &ar) != STREAM_UNSUPPORTED)
2695 mpctx->sh_video->stream_aspect = ar;
2696 current_module = "init_video_filters";
2698 char *vf_arg[] = {
2699 "_oldargs_", (char *)mpctx->video_out, NULL
2701 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2704 #ifdef CONFIG_ASS
2705 if (opts->ass_enabled) {
2706 int i;
2707 int insert = 1;
2708 if (opts->vf_settings)
2709 for (i = 0; opts->vf_settings[i].name; ++i)
2710 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2711 insert = 0;
2712 break;
2714 if (insert) {
2715 extern vf_info_t vf_info_ass;
2716 const vf_info_t *libass_vfs[] = {
2717 &vf_info_ass, NULL
2719 char *vf_arg[] = {
2720 "auto", "1", NULL
2722 int retcode = 0;
2723 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2724 sh_video->vfilter,
2725 "ass", vf_arg,
2726 &retcode);
2727 if (vf_ass)
2728 sh_video->vfilter = vf_ass;
2729 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2730 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2731 else
2732 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2733 "ASS: cannot add video filter\n");
2736 #endif
2738 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2740 #ifdef CONFIG_ASS
2741 if (opts->ass_enabled)
2742 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2743 mpctx->ass_library);
2744 #endif
2746 current_module = "init_video_codec";
2748 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2749 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2750 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2752 if (!sh_video->initialized) {
2753 if (!opts->fixed_vo)
2754 uninit_player(mpctx, INITIALIZED_VO);
2755 goto err_out;
2758 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2760 if (sh_video->codec)
2761 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2762 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2764 sh_video->last_pts = MP_NOPTS_VALUE;
2765 sh_video->num_buffered_pts = 0;
2766 sh_video->next_frame_time = 0;
2768 if (opts->auto_quality > 0) {
2769 // Auto quality option enabled
2770 output_quality = get_video_quality_max(sh_video);
2771 if (opts->auto_quality > output_quality)
2772 opts->auto_quality = output_quality;
2773 else
2774 output_quality = opts->auto_quality;
2775 mp_msg(MSGT_CPLAYER, MSGL_V,
2776 "AutoQ: setting quality to %d.\n", output_quality);
2777 set_video_quality(sh_video, output_quality);
2780 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2782 current_module = "init_vo";
2784 return 1;
2786 err_out:
2787 mpctx->sh_video = mpctx->d_video->sh = NULL;
2788 return 0;
2791 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2793 struct sh_video *sh_video = mpctx->sh_video;
2794 double frame_time = 0;
2795 struct vo *video_out = mpctx->video_out;
2796 while (1) {
2797 current_module = "filter_video";
2798 // In nocorrect-pts mode there is no way to properly time these frames
2799 if (vo_get_buffered_frame(video_out, 0) >= 0)
2800 break;
2801 if (vf_output_queued_frame(sh_video->vfilter))
2802 break;
2803 unsigned char *packet = NULL;
2804 frame_time = sh_video->next_frame_time;
2805 if (mpctx->restart_playback)
2806 frame_time = 0;
2807 int in_size = 0;
2808 while (!in_size)
2809 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2810 &packet, force_fps);
2811 if (in_size < 0) {
2812 #ifdef CONFIG_DVDNAV
2813 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2814 if (mp_dvdnav_is_eof(mpctx->stream))
2815 return -1;
2816 if (mpctx->d_video)
2817 mpctx->d_video->eof = 0;
2818 if (mpctx->d_audio)
2819 mpctx->d_audio->eof = 0;
2820 mpctx->stream->eof = 0;
2821 } else
2822 #endif
2823 return -1;
2825 if (in_size > max_framesize)
2826 max_framesize = in_size;
2827 sh_video->timer += frame_time;
2828 if (mpctx->sh_audio)
2829 mpctx->delay -= frame_time;
2830 // video_read_frame can change fps (e.g. for ASF video)
2831 vo_fps = sh_video->fps;
2832 int framedrop_type = check_framedrop(mpctx, frame_time);
2833 current_module = "decode video";
2835 void *decoded_frame;
2836 #ifdef CONFIG_DVDNAV
2837 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2838 if (in_size >= 0 && !decoded_frame)
2839 #endif
2840 decoded_frame = decode_video(sh_video, NULL, packet, in_size,
2841 framedrop_type, sh_video->pts);
2842 #ifdef CONFIG_DVDNAV
2843 // Save last still frame for future display
2844 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2845 #endif
2846 if (decoded_frame) {
2847 current_module = "filter video";
2848 filter_video(sh_video, decoded_frame, sh_video->pts);
2850 break;
2852 return frame_time;
2855 static void determine_frame_pts(struct MPContext *mpctx)
2857 struct sh_video *sh_video = mpctx->sh_video;
2858 struct MPOpts *opts = &mpctx->opts;
2860 if (opts->user_pts_assoc_mode)
2861 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2862 else if (sh_video->pts_assoc_mode == 0) {
2863 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2864 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2865 sh_video->pts_assoc_mode = 1;
2866 else
2867 sh_video->pts_assoc_mode = 2;
2868 } else {
2869 int probcount1 = sh_video->num_reordered_pts_problems;
2870 int probcount2 = sh_video->num_sorted_pts_problems;
2871 if (sh_video->pts_assoc_mode == 2) {
2872 int tmp = probcount1;
2873 probcount1 = probcount2;
2874 probcount2 = tmp;
2876 if (probcount1 >= probcount2 * 1.5 + 2) {
2877 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2878 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2879 "%d.\n", sh_video->pts_assoc_mode);
2882 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2883 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2886 static double update_video(struct MPContext *mpctx)
2888 struct sh_video *sh_video = mpctx->sh_video;
2889 struct vo *video_out = mpctx->video_out;
2890 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2891 mpctx->osd); // hack for vf_expand
2892 if (!mpctx->opts.correct_pts)
2893 return update_video_nocorrect_pts(mpctx);
2895 double pts;
2897 while (1) {
2898 current_module = "filter_video";
2899 if (vo_get_buffered_frame(video_out, false) >= 0)
2900 break;
2901 // XXX Time used in this call is not counted in any performance
2902 // timer now
2903 if (vf_output_queued_frame(sh_video->vfilter))
2904 break;
2905 int in_size = 0;
2906 unsigned char *buf = NULL;
2907 pts = MP_NOPTS_VALUE;
2908 struct demux_packet *pkt;
2909 while (1) {
2910 pkt = ds_get_packet2(mpctx->d_video, false);
2911 if (!pkt || pkt->len)
2912 break;
2913 /* Packets with size 0 are assumed to not correspond to frames,
2914 * but to indicate the absence of a frame in formats like AVI
2915 * that must have packets at fixed timecode intervals. */
2917 if (pkt) {
2918 in_size = pkt->len;
2919 buf = pkt->buffer;
2920 pts = pkt->pts;
2922 if (pts != MP_NOPTS_VALUE)
2923 pts += mpctx->video_offset;
2924 if (in_size > max_framesize)
2925 max_framesize = in_size;
2926 current_module = "decode video";
2927 if (pts >= mpctx->hrseek_pts - .005)
2928 mpctx->hrseek_framedrop = false;
2929 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2930 check_framedrop(mpctx, sh_video->frametime);
2931 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2932 framedrop_type, pts);
2933 if (decoded_frame) {
2934 determine_frame_pts(mpctx);
2935 current_module = "filter video";
2936 filter_video(sh_video, decoded_frame, sh_video->pts);
2937 } else if (!pkt) {
2938 if (vo_get_buffered_frame(video_out, true) < 0)
2939 return -1;
2941 break;
2944 if (!video_out->frame_loaded)
2945 return 0;
2947 pts = video_out->next_pts;
2948 if (pts == MP_NOPTS_VALUE) {
2949 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2950 // Try to use decoder pts from before filters
2951 pts = sh_video->pts;
2952 if (pts == MP_NOPTS_VALUE)
2953 pts = sh_video->last_pts;
2955 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2956 vo_skip_frame(video_out);
2957 return 0;
2959 mpctx->hrseek_active = false;
2960 sh_video->pts = pts;
2961 if (sh_video->last_pts == MP_NOPTS_VALUE)
2962 sh_video->last_pts = sh_video->pts;
2963 else if (sh_video->last_pts > sh_video->pts) {
2964 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2965 sh_video->pts, sh_video->last_pts);
2966 /* If the difference in pts is small treat it as jitter around the
2967 * right value (possibly caused by incorrect timestamp ordering) and
2968 * just show this frame immediately after the last one.
2969 * Treat bigger differences as timestamp resets and start counting
2970 * timing of later frames from the position of this one. */
2971 if (sh_video->last_pts - sh_video->pts > 0.5)
2972 sh_video->last_pts = sh_video->pts;
2973 else
2974 sh_video->pts = sh_video->last_pts;
2976 double frame_time = sh_video->pts - sh_video->last_pts;
2977 sh_video->last_pts = sh_video->pts;
2978 sh_video->timer += frame_time;
2979 if (mpctx->sh_audio)
2980 mpctx->delay -= frame_time;
2981 return frame_time;
2984 static int get_cache_fill(struct MPContext *mpctx)
2986 #ifdef CONFIG_STREAM_CACHE
2987 if (stream_cache_size > 0)
2988 return cache_fill_status(mpctx->stream);
2989 #endif
2990 return -1;
2993 static void update_pause_message(struct MPContext *mpctx)
2995 struct MPOpts *opts = &mpctx->opts;
2997 if (opts->quiet)
2998 return;
3000 int cache_fill = get_cache_fill(mpctx);
3001 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
3003 if (!mpctx->status_printed && !cache_changed)
3004 return;
3006 char *msg = mp_gtext(" ===== PAUSE =====");
3007 char *tmpmem = NULL;
3008 if (cache_fill >= 0)
3009 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
3011 if (opts->term_osd && !mpctx->sh_video) {
3012 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
3013 update_osd_msg(mpctx);
3014 } else {
3015 if (mpctx->status_printed)
3016 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
3017 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
3020 mpctx->paused_cache_fill = cache_fill;
3021 mpctx->status_printed = false;
3023 talloc_free(tmpmem);
3026 void pause_player(struct MPContext *mpctx)
3028 if (mpctx->paused)
3029 return;
3030 mpctx->paused = 1;
3031 mpctx->step_frames = 0;
3032 mpctx->time_frame -= get_relative_time(mpctx);
3033 mpctx->osd_function = OSD_PAUSE;
3035 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3036 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3038 if (mpctx->ao && mpctx->sh_audio)
3039 ao_pause(mpctx->ao); // pause audio, keep data if possible
3041 mpctx->paused_cache_fill = get_cache_fill(mpctx);
3042 mpctx->status_printed = true;
3043 update_pause_message(mpctx);
3045 if (!mpctx->opts.quiet)
3046 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
3049 void unpause_player(struct MPContext *mpctx)
3051 if (!mpctx->paused)
3052 return;
3053 mpctx->paused = 0;
3054 if (!mpctx->step_frames)
3055 mpctx->osd_function = OSD_PLAY;
3057 if (mpctx->ao && mpctx->sh_audio)
3058 ao_resume(mpctx->ao);
3059 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3060 && !mpctx->step_frames)
3061 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3062 (void)get_relative_time(mpctx); // ignore time that passed during pause
3065 static int redraw_osd(struct MPContext *mpctx)
3067 struct sh_video *sh_video = mpctx->sh_video;
3068 struct vf_instance *vf = sh_video->vfilter;
3069 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3070 return -1;
3071 if (vo_redraw_frame(mpctx->video_out) < 0)
3072 return -1;
3073 mpctx->osd->pts = mpctx->video_pts;
3074 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3075 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3076 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3077 vo_flip_page(mpctx->video_out, 0, -1);
3078 return 0;
3081 void add_step_frame(struct MPContext *mpctx)
3083 mpctx->step_frames++;
3084 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3085 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3086 unpause_player(mpctx);
3089 static void pause_loop(struct MPContext *mpctx)
3091 mp_cmd_t *cmd;
3093 update_pause_message(mpctx);
3095 while ((cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
3096 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
3097 if (cmd) {
3098 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3099 run_command(mpctx, cmd);
3100 mp_cmd_free(cmd);
3101 continue;
3103 if (mpctx->sh_video && mpctx->video_out)
3104 vo_check_events(mpctx->video_out);
3105 update_osd_msg(mpctx);
3106 int hack = vo_osd_changed(0);
3107 vo_osd_changed(hack);
3108 if (hack || mpctx->sh_video && mpctx->video_out->want_redraw)
3109 break;
3110 update_pause_message(mpctx);
3115 // Find the right mute status and record position for new file position
3116 static void edl_seek_reset(MPContext *mpctx)
3118 mpctx->edl_muted = 0;
3119 next_edl_record = edl_records;
3121 while (next_edl_record) {
3122 if (next_edl_record->start_sec >= get_current_time(mpctx))
3123 break;
3125 if (next_edl_record->action == EDL_MUTE)
3126 mpctx->edl_muted = !mpctx->edl_muted;
3127 next_edl_record = next_edl_record->next;
3129 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3130 mixer_mute(&mpctx->mixer);
3134 // Execute EDL command for the current position if one exists
3135 static void edl_update(MPContext *mpctx)
3137 if (!next_edl_record)
3138 return;
3140 if (!mpctx->sh_video) {
3141 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
3142 "Cannot use EDL without video, disabling.\n");
3143 free_edl(edl_records);
3144 next_edl_record = NULL;
3145 edl_records = NULL;
3146 return;
3149 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3150 if (next_edl_record->action == EDL_SKIP) {
3151 mpctx->osd_function = OSD_FFW;
3152 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3153 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3154 "[%f], length [%f]\n", next_edl_record->start_sec,
3155 next_edl_record->stop_sec, next_edl_record->length_sec);
3156 } else if (next_edl_record->action == EDL_MUTE) {
3157 mpctx->edl_muted = !mpctx->edl_muted;
3158 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3159 mixer_mute(&mpctx->mixer);
3160 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3161 next_edl_record->start_sec);
3163 next_edl_record = next_edl_record->next;
3167 static void reinit_decoders(struct MPContext *mpctx)
3169 reinit_video_chain(mpctx);
3170 reinit_audio_chain(mpctx);
3171 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3174 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3176 if (mpctx->sh_video) {
3177 current_module = "seek_video_reset";
3178 resync_video_stream(mpctx->sh_video);
3179 mpctx->sh_video->timer = 0;
3180 vo_seek_reset(mpctx->video_out);
3181 mpctx->sh_video->timer = 0;
3182 mpctx->sh_video->num_buffered_pts = 0;
3183 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3184 mpctx->delay = 0;
3185 mpctx->time_frame = 0;
3186 mpctx->restart_playback = true;
3187 // Not all demuxers set d_video->pts during seek, so this value
3188 // (which is used by at least vobsub and edl code below) may
3189 // be completely wrong (probably 0).
3190 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3191 mpctx->video_pts = mpctx->sh_video->pts;
3192 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3193 true);
3194 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3197 if (mpctx->sh_audio) {
3198 current_module = "seek_audio_reset";
3199 resync_audio_stream(mpctx->sh_audio);
3200 if (reset_ao)
3201 ao_reset(mpctx->ao);
3202 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3203 mpctx->sh_audio->a_buffer_len = 0;
3204 if (!mpctx->sh_video)
3205 update_subtitles(mpctx, mpctx->sh_audio->pts,
3206 mpctx->video_offset, true);
3209 if (vo_vobsub && mpctx->sh_video) {
3210 current_module = "seek_vobsub_reset";
3211 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3214 edl_seek_reset(mpctx);
3216 mpctx->hrseek_active = false;
3217 mpctx->hrseek_framedrop = false;
3218 mpctx->total_avsync_change = 0;
3219 audio_time_usage = 0;
3220 video_time_usage = 0;
3221 vout_time_usage = 0;
3222 drop_frame_cnt = 0;
3224 current_module = NULL;
3227 static bool timeline_set_part(struct MPContext *mpctx, int i)
3229 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3230 struct timeline_part *n = mpctx->timeline + i;
3231 mpctx->timeline_part = i;
3232 mpctx->video_offset = n->start - n->source_start;
3233 if (n->source == p->source)
3234 return false;
3235 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3236 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3237 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3238 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3239 mpctx->stop_play = orig_stop_play;
3240 mpctx->demuxer = n->source->demuxer;
3241 mpctx->d_video = mpctx->demuxer->video;
3242 mpctx->d_audio = mpctx->demuxer->audio;
3243 mpctx->d_sub = mpctx->demuxer->sub;
3244 mpctx->sh_video = mpctx->d_video->sh;
3245 mpctx->sh_audio = mpctx->d_audio->sh;
3246 return true;
3249 // Given pts, switch playback to the corresponding part.
3250 // Return offset within that part.
3251 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3252 bool *need_reset)
3254 if (pts < 0)
3255 pts = 0;
3256 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3257 struct timeline_part *p = mpctx->timeline + i;
3258 if (pts < (p + 1)->start) {
3259 *need_reset = timeline_set_part(mpctx, i);
3260 return pts - p->start + p->source_start;
3263 return -1;
3267 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3268 static int seek(MPContext *mpctx, struct seek_params seek,
3269 bool timeline_fallthrough)
3271 struct MPOpts *opts = &mpctx->opts;
3273 current_module = "seek";
3274 if (mpctx->stop_play == AT_END_OF_FILE)
3275 mpctx->stop_play = KEEP_PLAYING;
3276 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3277 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3278 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3279 || opts->hr_seek > 0 || seek.exact > 0;
3280 if (seek.type == MPSEEK_FACTOR
3281 || seek.type == MPSEEK_ABSOLUTE
3282 && seek.amount < mpctx->last_chapter_pts
3283 || seek.amount < 0)
3284 mpctx->last_chapter_seek = -2;
3285 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3286 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3287 seek.type = MPSEEK_ABSOLUTE;
3289 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3290 && seek.type == MPSEEK_RELATIVE) {
3291 seek.type = MPSEEK_ABSOLUTE;
3292 seek.direction = seek.amount > 0 ? 1 : -1;
3293 seek.amount += get_current_time(mpctx);
3296 /* At least the liba52 decoder wants to read from the input stream
3297 * during initialization, so reinit must be done after the demux_seek()
3298 * call that clears possible stream EOF. */
3299 bool need_reset = false;
3300 double demuxer_amount = seek.amount;
3301 if (mpctx->timeline) {
3302 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3303 &need_reset);
3304 if (demuxer_amount == -1) {
3305 mpctx->stop_play = AT_END_OF_FILE;
3306 // Clear audio from current position
3307 if (mpctx->sh_audio) {
3308 ao_reset(mpctx->ao);
3309 mpctx->sh_audio->a_buffer_len = 0;
3311 return -1;
3314 int demuxer_style = 0;
3315 switch (seek.type) {
3316 case MPSEEK_FACTOR:
3317 demuxer_style |= SEEK_FACTOR; // fallthrough
3318 case MPSEEK_ABSOLUTE:
3319 demuxer_style |= SEEK_ABSOLUTE;
3321 if (hr_seek || seek.direction < 0)
3322 demuxer_style |= SEEK_BACKWARD;
3323 else if (seek.direction > 0)
3324 demuxer_style |= SEEK_FORWARD;
3326 if (hr_seek)
3327 demuxer_amount -= opts->hr_seek_demuxer_offset;
3328 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3329 demuxer_style);
3330 if (need_reset)
3331 reinit_decoders(mpctx);
3332 if (seekresult == 0)
3333 return -1;
3335 seek_reset(mpctx, !timeline_fallthrough);
3337 /* Use the target time as "current position" for further relative
3338 * seeks etc until a new video frame has been decoded */
3339 if (seek.type == MPSEEK_ABSOLUTE) {
3340 mpctx->video_pts = seek.amount;
3341 mpctx->last_seek_pts = seek.amount;
3342 } else
3343 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3345 if (hr_seek) {
3346 mpctx->hrseek_active = true;
3347 mpctx->hrseek_framedrop = true;
3348 mpctx->hrseek_pts = seek.amount;
3351 mpctx->start_timestamp = GetTimerMS();
3353 return 0;
3356 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3357 int exact)
3359 struct seek_params *seek = &mpctx->seek;
3360 switch (type) {
3361 case MPSEEK_RELATIVE:
3362 if (seek->type == MPSEEK_FACTOR)
3363 return; // Well... not common enough to bother doing better
3364 seek->amount += amount;
3365 seek->exact = FFMAX(seek->exact, exact);
3366 if (seek->type == MPSEEK_NONE)
3367 seek->exact = exact;
3368 if (seek->type == MPSEEK_ABSOLUTE)
3369 return;
3370 if (seek->amount == 0) {
3371 *seek = (struct seek_params){ 0 };
3372 return;
3374 seek->type = MPSEEK_RELATIVE;
3375 return;
3376 case MPSEEK_ABSOLUTE:
3377 case MPSEEK_FACTOR:
3378 *seek = (struct seek_params) {
3379 .type = type,
3380 .amount = amount,
3381 .exact = exact,
3383 return;
3384 case MPSEEK_NONE:
3385 *seek = (struct seek_params){ 0 };
3386 return;
3388 abort();
3392 double get_time_length(struct MPContext *mpctx)
3394 if (mpctx->timeline)
3395 return mpctx->timeline[mpctx->num_timeline_parts].start;
3397 struct demuxer *demuxer = mpctx->demuxer;
3398 double get_time_ans;
3399 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3400 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3401 (void *) &get_time_ans) > 0)
3402 return get_time_ans;
3404 struct sh_video *sh_video = mpctx->d_video->sh;
3405 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3406 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3407 return (double) (demuxer->movi_end - demuxer->movi_start) /
3408 (sh_video->i_bps + sh_audio->i_bps);
3409 if (sh_video && sh_video->i_bps)
3410 return (double) (demuxer->movi_end - demuxer->movi_start) /
3411 sh_video->i_bps;
3412 if (sh_audio && sh_audio->i_bps)
3413 return (double) (demuxer->movi_end - demuxer->movi_start) /
3414 sh_audio->i_bps;
3415 return 0;
3418 /* If there are timestamps from stream level then use those (for example
3419 * DVDs can have consistent times there while the MPEG-level timestamps
3420 * reset). */
3421 double get_current_time(struct MPContext *mpctx)
3423 struct demuxer *demuxer = mpctx->demuxer;
3424 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3425 return demuxer->stream_pts;
3426 struct sh_video *sh_video = demuxer->video->sh;
3427 if (sh_video)
3428 return mpctx->video_pts;
3429 double apts = playing_audio_pts(mpctx);
3430 if (apts != MP_NOPTS_VALUE)
3431 return apts;
3432 return mpctx->last_seek_pts;
3435 int get_percent_pos(struct MPContext *mpctx)
3437 struct demuxer *demuxer = mpctx->demuxer;
3438 int ans = 0;
3439 if (mpctx->timeline)
3440 ans = get_current_time(mpctx) * 100 /
3441 mpctx->timeline[mpctx->num_timeline_parts].start;
3442 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3444 else {
3445 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3446 off_t pos = demuxer->filepos > 0 ?
3447 demuxer->filepos : stream_tell(demuxer->stream);
3448 if (len > 0)
3449 ans = (pos - demuxer->movi_start) / len;
3450 else
3451 ans = 0;
3453 if (ans < 0)
3454 ans = 0;
3455 if (ans > 100)
3456 ans = 100;
3457 return ans;
3460 // -2 is no chapters, -1 is before first chapter
3461 int get_current_chapter(struct MPContext *mpctx)
3463 double current_pts = get_current_time(mpctx);
3464 if (!mpctx->chapters)
3465 return FFMAX(mpctx->last_chapter_seek,
3466 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3468 int i;
3469 for (i = 1; i < mpctx->num_chapters; i++)
3470 if (current_pts < mpctx->chapters[i].start)
3471 break;
3472 return FFMAX(mpctx->last_chapter_seek, i - 1);
3475 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3477 char *name = chapter_name(mpctx, chapter);
3478 if (name) {
3479 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3480 } else {
3481 int chapter_count = get_chapter_count(mpctx);
3482 if (chapter_count <= 0)
3483 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3484 else
3485 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3486 chapter_count);
3488 return name;
3491 // returns NULL if chapter name unavailable
3492 char *chapter_name(struct MPContext *mpctx, int chapter)
3494 if (!mpctx->chapters)
3495 return demuxer_chapter_name(mpctx->demuxer, chapter);
3496 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3499 // returns the start of the chapter in seconds
3500 double chapter_start_time(struct MPContext *mpctx, int chapter)
3502 if (!mpctx->chapters)
3503 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3504 return mpctx->chapters[chapter].start;
3507 int get_chapter_count(struct MPContext *mpctx)
3509 if (!mpctx->chapters)
3510 return demuxer_chapter_count(mpctx->demuxer);
3511 return mpctx->num_chapters;
3514 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3516 mpctx->last_chapter_seek = -2;
3517 if (!mpctx->chapters) {
3518 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3519 if (res >= 0) {
3520 if (*seek_pts == -1)
3521 seek_reset(mpctx, true);
3522 else {
3523 mpctx->last_chapter_seek = res;
3524 mpctx->last_chapter_pts = *seek_pts;
3527 return res;
3530 if (chapter >= mpctx->num_chapters)
3531 return -1;
3532 if (chapter < 0)
3533 chapter = 0;
3534 *seek_pts = mpctx->chapters[chapter].start;
3535 mpctx->last_chapter_seek = chapter;
3536 mpctx->last_chapter_pts = *seek_pts;
3537 return chapter;
3541 static void run_playloop(struct MPContext *mpctx)
3543 struct MPOpts *opts = &mpctx->opts;
3544 float aq_sleep_time = 0;
3545 bool full_audio_buffers = false;
3547 if (opts->chapterrange[1] > 0) {
3548 int cur_chapter = get_current_chapter(mpctx);
3549 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3550 mpctx->stop_play = PT_NEXT_ENTRY;
3553 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3554 mpctx->sh_audio = mpctx->d_audio->sh;
3555 mpctx->sh_audio->ds = mpctx->d_audio;
3556 reinit_audio_chain(mpctx);
3559 /*========================== PLAY AUDIO ============================*/
3561 if (!mpctx->sh_video)
3562 mpctx->restart_playback = false;
3564 if (mpctx->sh_audio && !mpctx->restart_playback) {
3565 int status = fill_audio_out_buffers(mpctx);
3566 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3567 if (status == -2)
3568 // at eof, all audio at least written to ao
3569 if (!mpctx->sh_video)
3570 mpctx->stop_play = AT_END_OF_FILE;
3574 if (!mpctx->sh_video) {
3575 if (mpctx->step_frames) {
3576 mpctx->step_frames = 0;
3577 pause_player(mpctx);
3579 // handle audio-only case:
3580 double a_pos = 0, a_buf = 0;
3581 // sh_audio can be NULL due to video stream switching
3582 // TODO: handle this better
3583 if (mpctx->sh_audio) {
3584 a_buf = ao_get_delay(mpctx->ao);
3585 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3586 a_buf;
3589 print_status(mpctx, a_pos, false);
3591 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3592 update_osd_msg(mpctx);
3593 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3594 mpctx->stop_play = AT_END_OF_FILE;
3595 else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3596 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3597 && mpctx->sh_audio) {
3598 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3599 if (!opts->gapless_audio && p->source != (p + 1)->source
3600 && a_buf > 0.05) {
3601 mpctx->stop_play = KEEP_PLAYING;
3602 mp_input_get_cmd(mpctx->input, (a_buf - .05) * 1000, true);
3603 } else {
3604 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3605 .amount = (p + 1)->start },
3606 true);
3608 } else if (!mpctx->stop_play) {
3609 int sleep_time = 100;
3610 if (mpctx->sh_audio) {
3611 if (mpctx->ao->untimed)
3612 sleep_time = 0;
3613 else if (full_audio_buffers)
3614 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3615 else
3616 sleep_time = 20;
3617 sleep_time = FFMIN(sleep_time, 100);
3619 mp_input_get_cmd(mpctx->input, sleep_time, true);
3621 } else {
3623 /*========================== PLAY VIDEO ============================*/
3625 vo_pts = mpctx->sh_video->timer * 90000.0;
3626 vo_fps = mpctx->sh_video->fps;
3628 bool blit_frame = mpctx->video_out->frame_loaded;
3629 if (!blit_frame) {
3630 double frame_time = update_video(mpctx);
3631 blit_frame = mpctx->video_out->frame_loaded;
3632 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3633 if (mpctx->sh_video->vf_initialized < 0) {
3634 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3635 "\nFATAL: Could not initialize video filters (-vf) "
3636 "or video output (-vo).\n");
3637 mpctx->stop_play = PT_NEXT_ENTRY;
3638 return;
3640 if (frame_time < 0)
3641 mpctx->stop_play = AT_END_OF_FILE;
3642 else if (!mpctx->restart_playback) {
3643 mpctx->time_frame += frame_time / opts->playback_speed;
3644 adjust_sync(mpctx, frame_time);
3647 if (mpctx->timeline) {
3648 struct timeline_part *next =
3649 mpctx->timeline + mpctx->timeline_part + 1;
3650 if (mpctx->sh_video->pts >= next->start
3651 || mpctx->stop_play == AT_END_OF_FILE
3652 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3653 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3654 .amount = next->start },
3655 true);
3656 return;
3660 // ================================================================
3662 current_module = "vo_check_events";
3663 vo_check_events(mpctx->video_out);
3665 #ifdef CONFIG_X11
3666 if (stop_xscreensaver) {
3667 current_module = "stop_xscreensaver";
3668 xscreensaver_heartbeat(mpctx->x11_state);
3670 #endif
3671 if (heartbeat_cmd) {
3672 static unsigned last_heartbeat;
3673 unsigned now = GetTimerMS();
3674 if (now - last_heartbeat > 30000) {
3675 last_heartbeat = now;
3676 system(heartbeat_cmd);
3680 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3681 &mpctx->time_frame,
3682 full_audio_buffers,
3683 &aq_sleep_time);
3685 //=================== FLIP PAGE (VIDEO BLT): ======================
3687 current_module = "flip_page";
3688 if (!frame_time_remaining && blit_frame) {
3689 vo_new_frame_imminent(mpctx->video_out);
3690 struct sh_video *sh_video = mpctx->sh_video;
3691 mpctx->video_pts = sh_video->pts;
3692 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3693 update_teletext(sh_video, mpctx->demuxer, 0);
3694 update_osd_msg(mpctx);
3695 struct vf_instance *vf = sh_video->vfilter;
3696 mpctx->osd->pts = mpctx->video_pts;
3697 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3698 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3699 vo_osd_changed(0);
3701 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3702 aq_sleep_time += mpctx->time_frame;
3703 // flag 256 means: libvo driver does its timing (dvb card)
3704 if (mpctx->time_frame > 0.001
3705 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3706 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3707 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3709 unsigned int t2 = GetTimer();
3710 /* Playing with playback speed it's possible to get pathological
3711 * cases with mpctx->time_frame negative enough to cause an
3712 * overflow in pts_us calculation, thus the FFMAX. */
3713 double time_frame = FFMAX(mpctx->time_frame, -1);
3714 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3715 int duration = -1;
3716 double pts2 = mpctx->video_out->next_pts2;
3717 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3718 && !mpctx->restart_playback) {
3719 // expected A/V sync correction is ignored
3720 double diff = (pts2 - mpctx->video_pts);
3721 diff /= opts->playback_speed;
3722 if (mpctx->time_frame < 0)
3723 diff += mpctx->time_frame;
3724 if (diff < 0)
3725 diff = 0;
3726 if (diff > 10)
3727 diff = 10;
3728 duration = diff * 1e6;
3730 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3732 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3733 vout_time_usage += mpctx->last_vo_flip_duration;
3734 if (mpctx->video_out->driver->flip_page_timed) {
3735 // No need to adjust sync based on flip speed
3736 mpctx->last_vo_flip_duration = 0;
3737 // For print_status - VO call finishing early is OK for sync
3738 mpctx->time_frame -= get_relative_time(mpctx);
3740 if (mpctx->restart_playback) {
3741 mpctx->syncing_audio = true;
3742 if (mpctx->sh_audio)
3743 fill_audio_out_buffers(mpctx);
3744 mpctx->restart_playback = false;
3745 mpctx->time_frame = 0;
3746 get_relative_time(mpctx);
3748 print_status(mpctx, MP_NOPTS_VALUE, true);
3749 screenshot_flip(mpctx);
3750 } else
3751 print_status(mpctx, MP_NOPTS_VALUE, false);
3753 if (opts->auto_quality > 0) {
3754 current_module = "autoq";
3755 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3756 ++output_quality;
3757 else if (output_quality > 1 && aq_sleep_time < 0)
3758 --output_quality;
3759 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3760 output_quality = 0;
3761 set_video_quality(mpctx->sh_video, output_quality);
3764 if (!frame_time_remaining && blit_frame) {
3765 if (play_n_frames >= 0) {
3766 --play_n_frames;
3767 if (play_n_frames <= 0)
3768 mpctx->stop_play = PT_NEXT_ENTRY;
3770 if (mpctx->step_frames > 0) {
3771 mpctx->step_frames--;
3772 if (mpctx->step_frames == 0)
3773 pause_player(mpctx);
3777 // FIXME: add size based support for -endpos
3778 if (end_at.type == END_AT_TIME &&
3779 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3780 mpctx->stop_play = PT_NEXT_ENTRY;
3782 } // end if(mpctx->sh_video)
3784 #ifdef CONFIG_DVDNAV
3785 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3786 nav_highlight_t hl;
3787 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3788 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3789 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3790 vo_osd_changed(OSDTYPE_DVDNAV);
3791 } else {
3792 osd_set_nav_box(0, 0, 0, 0);
3793 vo_osd_changed(OSDTYPE_DVDNAV);
3794 vo_osd_changed(OSDTYPE_SPU);
3797 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3798 double ar = -1.0;
3799 if (mpctx->sh_video &&
3800 stream_control(mpctx->demuxer->stream,
3801 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3802 != STREAM_UNSUPPORTED)
3803 mpctx->sh_video->stream_aspect = ar;
3806 #endif
3808 //================= Keyboard events, SEEKing ====================
3810 current_module = "key_events";
3812 while (1) {
3813 mp_cmd_t *cmd;
3814 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3815 /* Allow running consecutive seek commands to combine them,
3816 * but execute the seek before running other commands.
3817 * If the user seeks continuously (keeps arrow key down)
3818 * try to finish showing a frame from one location before doing
3819 * another seek (which could lead to unchanging display). */
3820 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3821 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3822 && GetTimerMS() - mpctx->start_timestamp < 300)
3823 break;
3824 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3825 run_command(mpctx, cmd);
3826 mp_cmd_free(cmd);
3827 if (mpctx->stop_play)
3828 break;
3830 bool slow_video = mpctx->sh_video && mpctx->video_out->frame_loaded;
3831 if (!(mpctx->paused || slow_video) || mpctx->stop_play
3832 || mpctx->seek.type || mpctx->restart_playback)
3833 break;
3834 if (mpctx->sh_video) {
3835 update_osd_msg(mpctx);
3836 int hack = vo_osd_changed(0);
3837 vo_osd_changed(hack);
3838 if (hack || mpctx->video_out->want_redraw) {
3839 if (redraw_osd(mpctx) < 0) {
3840 if (mpctx->paused)
3841 add_step_frame(mpctx);
3842 break;
3843 } else
3844 vo_osd_changed(0);
3847 if (!mpctx->paused)
3848 break;
3849 pause_loop(mpctx);
3852 // handle -sstep
3853 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3854 mpctx->osd_function = OSD_FFW;
3855 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3858 edl_update(mpctx);
3860 /* Looping. */
3861 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3862 mpctx->stop_play == PT_NEXT_ENTRY)) {
3863 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3865 if (opts->loop_times > 1)
3866 opts->loop_times--;
3867 else if (opts->loop_times == 1)
3868 opts->loop_times = -1;
3869 play_n_frames = play_n_frames_mf;
3870 mpctx->stop_play = 0;
3871 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3874 if (mpctx->seek.type) {
3875 seek(mpctx, mpctx->seek, false);
3876 mpctx->seek = (struct seek_params){ 0 };
3881 static int read_keys(void *ctx, int fd)
3883 getch2(ctx);
3884 return MP_INPUT_NOTHING;
3887 static bool attachment_is_font(struct demux_attachment *att)
3889 if (!att->name || !att->type || !att->data || !att->data_size)
3890 return false;
3891 // match against MIME types
3892 if (strcmp(att->type, "application/x-truetype-font") == 0
3893 || strcmp(att->type, "application/x-font") == 0)
3894 return true;
3895 // fallback: match against file extension
3896 if (strlen(att->name) > 4) {
3897 char *ext = att->name + strlen(att->name) - 4;
3898 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3899 || strcasecmp(ext, ".otf") == 0)
3900 return true;
3902 return false;
3905 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3907 if (audio_id == -1)
3908 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3909 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3910 demuxer_switch_audio(demuxer, audio_id);
3911 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3912 demuxer->audio->id = -2;
3913 demuxer->audio->sh = NULL;
3915 return demuxer->audio->id;
3918 static void print_version(const char *name)
3920 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3922 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3923 GetCpuCaps(&gCpuCaps);
3924 #if ARCH_X86
3925 mp_msg(MSGT_CPLAYER, MSGL_V,
3926 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3927 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3928 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3929 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3930 #if CONFIG_RUNTIME_CPUDETECT
3931 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3932 #else
3933 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3934 if (HAVE_MMX)
3935 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3936 if (HAVE_MMX2)
3937 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3938 if (HAVE_AMD3DNOW)
3939 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3940 if (HAVE_AMD3DNOWEXT)
3941 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3942 if (HAVE_SSE)
3943 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3944 if (HAVE_SSE2)
3945 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3946 if (HAVE_SSSE3)
3947 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3948 if (HAVE_CMOV)
3949 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3950 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3951 #endif /* CONFIG_RUNTIME_CPUDETECT */
3952 #endif /* ARCH_X86 */
3953 print_libav_versions();
3956 #ifdef PTW32_STATIC_LIB
3957 static void detach_ptw32(void)
3959 pthread_win32_thread_detach_np();
3960 pthread_win32_process_detach_np();
3962 #endif
3964 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3965 * file for some tools to link against. */
3966 #ifndef DISABLE_MAIN
3967 int main(int argc, char *argv[])
3969 #ifdef PTW32_STATIC_LIB
3970 pthread_win32_process_attach_np();
3971 pthread_win32_thread_attach_np();
3972 atexit(detach_ptw32);
3973 #endif
3974 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3975 || !strcmp(argv[1], "--leak-report")))
3976 talloc_enable_leak_report();
3978 char *mem_ptr;
3980 // movie info:
3982 /* Flag indicating whether MPlayer should exit without playing anything. */
3983 int opt_exit = 0;
3984 int i;
3986 struct MPContext *mpctx = talloc(NULL, MPContext);
3987 *mpctx = (struct MPContext){
3988 .osd_function = OSD_PLAY,
3989 .begin_skip = MP_NOPTS_VALUE,
3990 .play_tree_step = 1,
3991 .global_sub_pos = -1,
3992 .set_of_sub_pos = -1,
3993 .file_format = DEMUXER_TYPE_UNKNOWN,
3994 .last_dvb_step = 1,
3995 .paused_cache_fill = -1,
3998 InitTimer();
3999 srand(GetTimerMS());
4001 mp_msg_init();
4002 init_libav();
4004 #ifdef CONFIG_X11
4005 mpctx->x11_state = vo_x11_init_state();
4006 #endif
4007 struct MPOpts *opts = &mpctx->opts;
4008 set_default_mplayer_options(opts);
4009 // Create the config context and register the options
4010 mpctx->mconfig = m_config_new(opts, cfg_include);
4011 m_config_register_options(mpctx->mconfig, mplayer_opts);
4012 m_config_register_options(mpctx->mconfig, common_opts);
4013 mp_input_register_options(mpctx->mconfig);
4015 // Preparse the command line
4016 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
4018 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
4019 set_path_env();
4020 #endif
4022 #ifdef CONFIG_TV
4023 stream_tv_defaults.immediate = 1;
4024 #endif
4026 parse_cfgfiles(mpctx, mpctx->mconfig);
4028 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
4029 if (mpctx->playtree == NULL)
4030 opt_exit = 1;
4031 else {
4032 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
4033 if (mpctx->playtree) {
4034 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4035 mpctx->mconfig);
4036 if (mpctx->playtree_iter) {
4037 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4038 PLAY_TREE_ITER_ENTRY) {
4039 play_tree_iter_free(mpctx->playtree_iter);
4040 mpctx->playtree_iter = NULL;
4042 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
4048 print_version("MPlayer2");
4050 #if defined(__MINGW32__) || defined(__CYGWIN__)
4052 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
4053 BOOL WINAPI (*setDEP)(DWORD) = NULL;
4054 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
4055 if (kernel32) {
4056 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
4057 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
4059 if (setDEP)
4060 setDEP(3);
4061 if (setDllDir)
4062 setDllDir("");
4064 // stop Windows from showing all kinds of annoying error dialogs
4065 SetErrorMode(0x8003);
4066 // request 1ms timer resolution
4067 timeBeginPeriod(1);
4068 #endif
4070 #ifdef CONFIG_PRIORITY
4071 set_priority();
4072 #endif
4074 if (opts->video_driver_list &&
4075 strcmp(opts->video_driver_list[0], "help") == 0) {
4076 list_video_out();
4077 opt_exit = 1;
4080 if (opts->audio_driver_list &&
4081 strcmp(opts->audio_driver_list[0], "help") == 0) {
4082 list_audio_out();
4083 opt_exit = 1;
4086 /* Check codecs.conf. */
4087 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4088 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4089 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4090 if (!parse_codec_cfg(NULL))
4091 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4092 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4093 "Using built-in default codecs.conf.\n");
4096 free(mem_ptr); // release the buffer created by get_path()
4099 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4100 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4101 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4102 list_codecs(1);
4103 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4104 opt_exit = 1;
4106 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4107 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4108 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4109 list_codecs(0);
4110 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4111 opt_exit = 1;
4113 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4114 vfm_help();
4115 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4116 opt_exit = 1;
4118 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4119 afm_help();
4120 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4121 opt_exit = 1;
4123 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4124 af_help();
4125 printf("\n");
4126 opt_exit = 1;
4128 #ifdef CONFIG_X11
4129 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4130 fstype_help();
4131 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4132 opt_exit = 1;
4134 #endif
4135 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4136 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4137 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4138 demuxer_help();
4139 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4140 opt_exit = 1;
4142 if (opts->list_properties) {
4143 property_print_help();
4144 opt_exit = 1;
4147 if (opt_exit)
4148 exit_player(mpctx, EXIT_NONE);
4150 if (!mpctx->filename && !opts->player_idle_mode) {
4151 // no file/vcd/dvd -> show HELP:
4152 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4153 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4156 /* Display what configure line was used */
4157 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4159 // Many users forget to include command line in bugreports...
4160 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4161 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4162 for (i = 1; i < argc; i++)
4163 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4164 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4167 //------ load global data first ------
4169 mpctx->osd = osd_create();
4171 // check font
4172 #ifdef CONFIG_FREETYPE
4173 init_freetype();
4174 #endif
4175 #ifdef CONFIG_FONTCONFIG
4176 if (font_fontconfig <= 0) {
4177 #endif
4178 #ifdef CONFIG_BITMAP_FONT
4179 if (font_name) {
4180 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4181 if (!vo_font)
4182 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4183 filename_recode(font_name));
4184 } else {
4185 // try default:
4186 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4187 font_factor, verbose > 1);
4188 free(mem_ptr); // release the buffer created by get_path()
4189 if (!vo_font)
4190 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4191 font_factor, verbose > 1);
4193 if (sub_font_name)
4194 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4195 verbose > 1);
4196 else
4197 mpctx->osd->sub_font = vo_font;
4198 #endif
4199 #ifdef CONFIG_FONTCONFIG
4201 #endif
4203 #ifdef CONFIG_ASS
4204 mpctx->ass_library = mp_ass_init(opts);
4205 mpctx->osd->ass_library = mpctx->ass_library;
4206 #endif
4208 #ifdef HAVE_RTC
4209 if (opts->rtc) {
4210 char *rtc_device = opts->rtc_device;
4211 // seteuid(0); /* Can't hurt to try to get root here */
4212 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4213 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4214 "(it should be readable by the user.)\n",
4215 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4216 else {
4217 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4219 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4220 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4221 "ioctl (rtc_irqp_set %lu): %s\n",
4222 irqp, strerror(errno));
4223 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4224 close(rtc_fd);
4225 rtc_fd = -1;
4226 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4227 /* variable only by the root */
4228 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4229 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4230 close(rtc_fd);
4231 rtc_fd = -1;
4232 } else
4233 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4234 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4237 if (rtc_fd < 0)
4238 #endif /* HAVE_RTC */
4239 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4240 opts->softsleep ? "software" : timer_name);
4242 #ifdef HAVE_TERMCAP
4243 load_termcap(NULL); // load key-codes
4244 #endif
4246 // ========== Init keyboard FIFO (connection to libvo) ============
4248 // Init input system
4249 current_module = "init_input";
4250 mpctx->input = mp_input_init(&opts->input);
4251 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4252 if (slave_mode)
4253 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4254 else if (opts->consolecontrols)
4255 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4256 // Set the libstream interrupt callback
4257 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4259 current_module = NULL;
4261 /// Catch signals
4262 #ifndef __MINGW32__
4263 signal(SIGCHLD, child_sighandler);
4264 #endif
4266 #ifdef CONFIG_CRASH_DEBUG
4267 prog_path = argv[0];
4268 #endif
4269 //========= Catch terminate signals: ================
4270 // terminate requests:
4271 signal(SIGTERM, exit_sighandler); // kill
4272 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4274 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4276 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4277 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4278 #ifdef CONFIG_SIGHANDLER
4279 // fatal errors:
4280 signal(SIGBUS, exit_sighandler); // bus error
4281 signal(SIGSEGV, exit_sighandler); // segfault
4282 signal(SIGILL, exit_sighandler); // illegal instruction
4283 signal(SIGFPE, exit_sighandler); // floating point exc.
4284 signal(SIGABRT, exit_sighandler); // abort()
4285 #ifdef CONFIG_CRASH_DEBUG
4286 if (crash_debug)
4287 signal(SIGTRAP, exit_sighandler);
4288 #endif
4289 #endif
4291 // ***************** Now, let's see the per-file stuff ******************
4293 play_next_file:
4295 // init global sub numbers
4296 mpctx->global_sub_size = 0;
4297 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4299 if (mpctx->filename) {
4300 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4301 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4302 load_per_file_config(mpctx->mconfig, mpctx->filename);
4305 if (opts->video_driver_list)
4306 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4307 opts->video_driver_list[0]);
4308 if (opts->audio_driver_list)
4309 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4310 opts->audio_driver_list[0]);
4312 // We must enable getch2 here to be able to interrupt network connection
4313 // or cache filling
4314 if (opts->consolecontrols && !slave_mode) {
4315 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4316 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4317 "WARNING: getch2_init called twice!\n");
4318 else
4319 getch2_enable(); // prepare stdin for hotkeys...
4320 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4321 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4324 // ================= GUI idle loop (STOP state) =========================
4325 while (opts->player_idle_mode && !mpctx->filename) {
4326 play_tree_t *entry = NULL;
4327 mp_cmd_t *cmd;
4328 if (mpctx->video_out && mpctx->video_out->config_ok)
4329 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4330 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4331 if (mpctx->video_out)
4332 vo_check_events(mpctx->video_out);
4333 usec_sleep(20000);
4335 switch (cmd->id) {
4336 case MP_CMD_LOADFILE:
4337 // prepare a tree entry with the new filename
4338 entry = play_tree_new();
4339 play_tree_add_file(entry, cmd->args[0].v.s);
4340 // The entry is added to the main playtree after the switch().
4341 break;
4342 case MP_CMD_LOADLIST:
4343 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4344 break;
4345 case MP_CMD_QUIT:
4346 exit_player_with_rc(mpctx, EXIT_QUIT,
4347 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4348 break;
4349 case MP_CMD_VO_FULLSCREEN:
4350 case MP_CMD_GET_PROPERTY:
4351 case MP_CMD_SET_PROPERTY:
4352 case MP_CMD_STEP_PROPERTY:
4353 run_command(mpctx, cmd);
4354 break;
4357 mp_cmd_free(cmd);
4359 if (entry) { // user entered a command that gave a valid entry
4360 if (mpctx->playtree)
4361 // the playtree is always a node with one child. let's clear it
4362 play_tree_free_list(mpctx->playtree->child, 1);
4363 else
4364 // .. or make a brand new playtree
4365 mpctx->playtree = play_tree_new();
4367 if (!mpctx->playtree)
4368 continue; // couldn't make playtree! wait for next command
4370 play_tree_set_child(mpctx->playtree, entry);
4372 /* Make iterator start at the top the of tree. */
4373 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4374 mpctx->mconfig);
4375 if (!mpctx->playtree_iter)
4376 continue;
4378 // find the first real item in the tree
4379 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4380 PLAY_TREE_ITER_ENTRY) {
4381 // no items!
4382 play_tree_iter_free(mpctx->playtree_iter);
4383 mpctx->playtree_iter = NULL;
4384 continue; // wait for next command
4386 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4390 #ifdef CONFIG_ASS
4391 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4392 #endif
4393 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4394 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4396 if (mpctx->filename) {
4397 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4398 filename_recode(mpctx->filename));
4399 if (use_filename_title && opts->vo_wintitle == NULL)
4400 opts->vo_wintitle = talloc_strdup(NULL,
4401 mp_basename(mpctx->filename));
4404 if (edl_filename) {
4405 if (edl_records)
4406 free_edl(edl_records);
4407 next_edl_record = edl_records = edl_parse_file();
4409 if (edl_output_filename) {
4410 if (edl_fd)
4411 fclose(edl_fd);
4412 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4413 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4414 "Can't open EDL file [%s] for writing.\n",
4415 filename_recode(edl_output_filename));
4419 //==================== Open VOB-Sub ============================
4421 current_module = "vobsub";
4422 if (opts->vobsub_name) {
4423 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4424 if (vo_vobsub == NULL)
4425 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4426 filename_recode(opts->vobsub_name));
4427 } else if (opts->sub_auto && mpctx->filename) {
4428 char **vob = find_vob_subtitles(opts, mpctx->filename);
4429 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4430 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4431 if (vo_vobsub)
4432 break;
4434 talloc_free(vob);
4436 if (vo_vobsub) {
4437 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4438 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4439 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4440 mpctx);
4442 // setup global sub numbering
4443 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4444 vobsub_get_indexes_count(vo_vobsub);
4447 //============ Open & Sync STREAM --- fork cache2 ====================
4449 mpctx->stream = NULL;
4450 mpctx->demuxer = NULL;
4451 mpctx->d_audio = NULL;
4452 mpctx->d_video = NULL;
4453 mpctx->d_sub = NULL;
4454 mpctx->sh_audio = NULL;
4455 mpctx->sh_video = NULL;
4457 current_module = "open_stream";
4458 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4459 if (!mpctx->stream) { // error...
4460 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4461 goto goto_next_file;
4463 mpctx->initialized_flags |= INITIALIZED_STREAM;
4465 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4466 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4467 "playlist support will not be used automatically.\n"
4468 "MPlayer's playlist code is unsafe and should only be used with "
4469 "trusted sources.\nPlayback will probably fail.\n\n");
4470 #if 0
4471 play_tree_t *entry;
4472 // Handle playlist
4473 current_module = "handle_playlist";
4474 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4475 filename_recode(mpctx->filename));
4476 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4477 mpctx->eof = playtree_add_playlist(mpctx, entry);
4478 goto goto_next_file;
4479 #endif
4481 mpctx->stream->start_pos += seek_to_byte;
4483 if (stream_dump_type == 5) {
4484 unsigned char buf[4096];
4485 int len;
4486 FILE *f;
4487 current_module = "dumpstream";
4488 stream_reset(mpctx->stream);
4489 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4490 f = fopen(opts->stream_dump_name, "wb");
4491 if (!f) {
4492 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4493 exit_player(mpctx, EXIT_ERROR);
4495 if (opts->chapterrange[0] > 1) {
4496 int chapter = opts->chapterrange[0] - 1;
4497 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4499 struct stream_dump_progress info;
4500 stream_dump_progress_start(&info);
4501 while (!mpctx->stream->eof && !async_quit_request) {
4502 len = stream_read(mpctx->stream, buf, 4096);
4503 if (len > 0) {
4504 if (fwrite(buf, len, 1, f) != 1) {
4505 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4506 exit_player(mpctx, EXIT_ERROR);
4509 stream_dump_progress(&info, len, mpctx->stream);
4510 if (opts->chapterrange[1] > 0) {
4511 int chapter = -1;
4512 if (stream_control(mpctx->stream,
4513 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4514 && chapter + 1 > opts->chapterrange[1])
4515 break;
4518 if (fclose(f)) {
4519 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4520 opts->stream_dump_name);
4521 exit_player(mpctx, EXIT_ERROR);
4523 stream_dump_progress_end(&info, opts->stream_dump_name);
4524 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4525 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4528 #ifdef CONFIG_DVDREAD
4529 if (mpctx->stream->type == STREAMTYPE_DVD) {
4530 current_module = "dvd lang->id";
4531 if (opts->audio_lang && opts->audio_id == -1)
4532 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4533 if (opts->sub_lang && opts->sub_id == -1)
4534 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4535 // setup global sub numbering
4536 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4537 current_module = NULL;
4539 #endif
4541 #ifdef CONFIG_DVDNAV
4542 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4543 current_module = "dvdnav lang->id";
4544 if (opts->audio_lang && opts->audio_id == -1)
4545 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4546 opts->audio_lang);
4547 dvdsub_lang_id = -3;
4548 if (opts->sub_lang && opts->sub_id == -1)
4549 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4550 mpctx->stream, opts->sub_lang);
4551 // setup global sub numbering
4552 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4553 mpctx->stream);
4554 current_module = NULL;
4556 #endif
4558 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4559 goto_enable_cache:
4560 if (stream_cache_size > 0) {
4561 int res;
4562 float stream_cache_min_percent = opts->stream_cache_min_percent;
4563 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4564 current_module = "enable_cache";
4565 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4566 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4567 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4568 if (res == 0)
4569 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4570 goto goto_next_file;
4573 //============ Open DEMUXERS --- DETECT file type =======================
4574 current_module = "demux_open";
4576 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4577 opts->audio_id, opts->video_id, opts->sub_id,
4578 mpctx->filename);
4580 // HACK to get MOV Reference Files working
4582 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4583 unsigned char *playlist_entry;
4584 play_tree_t *list = NULL, *entry = NULL;
4586 current_module = "handle_demux_playlist";
4587 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4588 char *temp;
4589 const char *bname;
4591 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4592 filename_recode(playlist_entry));
4594 bname = mp_basename(playlist_entry);
4595 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4596 !strncmp(bname + 3, "gateQT", 6))
4597 continue;
4599 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4600 continue;
4602 entry = play_tree_new();
4604 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4605 playlist_entry)) { // add reference path of current file
4606 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4607 mpctx->filename)) + strlen(playlist_entry) + 1));
4608 if (temp) {
4609 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4610 strlen(mp_basename(mpctx->filename)));
4611 temp[strlen(mpctx->filename) - strlen(mp_basename(
4612 mpctx->filename))] = '\0';
4613 strcat(temp, playlist_entry);
4614 if (!strcmp(temp, mpctx->filename)) {
4615 free(temp);
4616 continue;
4618 play_tree_add_file(entry, temp);
4619 mp_msg(MSGT_CPLAYER, MSGL_V,
4620 "Resolving reference to %s.\n", temp);
4621 free(temp);
4623 } else
4624 play_tree_add_file(entry, playlist_entry);
4626 if (!list)
4627 list = entry;
4628 else
4629 play_tree_append_entry(list, entry);
4631 free_demuxer(mpctx->demuxer);
4632 mpctx->demuxer = NULL;
4634 if (list) {
4635 entry = play_tree_new();
4636 play_tree_set_child(entry, list);
4637 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4638 goto goto_next_file;
4642 if (!mpctx->demuxer) {
4643 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4644 goto goto_next_file;
4647 if (mpctx->demuxer->matroska_data.ordered_chapters)
4648 build_ordered_chapter_timeline(mpctx);
4650 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4651 build_edl_timeline(mpctx);
4653 if (mpctx->timeline) {
4654 mpctx->timeline_part = 0;
4655 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4657 int part_count = mpctx->num_timeline_parts;
4658 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4659 "sources. Total length %.3f seconds.\n", part_count,
4660 mpctx->num_sources, mpctx->timeline[part_count].start);
4661 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4662 for (int i = 0; i < mpctx->num_sources; i++)
4663 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4664 filename_recode(mpctx->sources[i].demuxer->filename));
4665 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4666 "source_start, source):\n");
4667 for (int i = 0; i < part_count; i++) {
4668 struct timeline_part *p = mpctx->timeline + i;
4669 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4670 p->source_start, p->source - mpctx->sources);
4672 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4673 mpctx->timeline[part_count].start);
4676 if (!mpctx->sources) {
4677 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4678 *mpctx->sources = (struct content_source){
4679 .stream = mpctx->stream,
4680 .demuxer = mpctx->demuxer
4682 mpctx->num_sources = 1;
4685 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4687 #ifdef CONFIG_ASS
4688 if (opts->ass_enabled && mpctx->ass_library) {
4689 for (int j = 0; j < mpctx->num_sources; j++) {
4690 struct demuxer *d = mpctx->sources[j].demuxer;
4691 for (int i = 0; i < d->num_attachments; i++) {
4692 struct demux_attachment *att = d->attachments + i;
4693 if (opts->use_embedded_fonts && attachment_is_font(att))
4694 ass_add_font(mpctx->ass_library, att->name, att->data,
4695 att->data_size);
4699 #endif
4701 current_module = "demux_open2";
4703 mpctx->d_audio = mpctx->demuxer->audio;
4704 mpctx->d_video = mpctx->demuxer->video;
4705 mpctx->d_sub = mpctx->demuxer->sub;
4707 if (ts_prog) {
4708 int tmp = ts_prog;
4709 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4711 // select audio stream
4712 for (int i = 0; i < mpctx->num_sources; i++)
4713 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4714 opts->audio_lang);
4716 // DUMP STREAMS:
4717 if ((stream_dump_type) && (stream_dump_type < 4)) {
4718 FILE *f;
4719 demux_stream_t *ds = NULL;
4720 current_module = "dump";
4721 // select stream to dump
4722 switch (stream_dump_type) {
4723 case 1: ds = mpctx->d_audio;
4724 break;
4725 case 2: ds = mpctx->d_video;
4726 break;
4727 case 3: ds = mpctx->d_sub;
4728 break;
4730 if (!ds) {
4731 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4732 "dump: FATAL: Selected stream missing!\n");
4733 exit_player(mpctx, EXIT_ERROR);
4735 // disable other streams:
4736 if (mpctx->d_audio && mpctx->d_audio != ds) {
4737 ds_free_packs(mpctx->d_audio);
4738 mpctx->d_audio->id = -2;
4740 if (mpctx->d_video && mpctx->d_video != ds) {
4741 ds_free_packs(mpctx->d_video);
4742 mpctx->d_video->id = -2;
4744 if (mpctx->d_sub && mpctx->d_sub != ds) {
4745 ds_free_packs(mpctx->d_sub);
4746 mpctx->d_sub->id = -2;
4748 // let's dump it!
4749 f = fopen(opts->stream_dump_name, "wb");
4750 if (!f) {
4751 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4752 exit_player(mpctx, EXIT_ERROR);
4754 struct stream_dump_progress info;
4755 stream_dump_progress_start(&info);
4756 while (!ds->eof) {
4757 unsigned char *start;
4758 int in_size = ds_get_packet(ds, &start);
4759 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4760 && stream_dump_type == 2)
4761 fwrite(&in_size, 1, 4, f);
4762 if (in_size > 0) {
4763 fwrite(start, in_size, 1, f);
4764 stream_dump_progress(&info, in_size, mpctx->stream);
4766 if (opts->chapterrange[1] > 0) {
4767 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4768 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4769 break;
4772 fclose(f);
4773 stream_dump_progress_end(&info, opts->stream_dump_name);
4774 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4775 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4778 mpctx->sh_audio = mpctx->d_audio->sh;
4779 mpctx->sh_video = mpctx->d_video->sh;
4781 if (mpctx->sh_video) {
4782 current_module = "video_read_properties";
4783 if (!video_read_properties(mpctx->sh_video)) {
4784 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4785 mpctx->sh_video = mpctx->d_video->sh = NULL;
4786 } else {
4787 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4788 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4789 mpctx->demuxer->file_format, mpctx->sh_video->format,
4790 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4791 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4792 if (force_fps) {
4793 mpctx->sh_video->fps = force_fps;
4794 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4796 vo_fps = mpctx->sh_video->fps;
4798 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4799 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4800 "header or invalid, use the -fps option.\n");
4806 if (!mpctx->sh_video && !mpctx->sh_audio) {
4807 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4808 #ifdef CONFIG_DVBIN
4809 if (mpctx->stream->type == STREAMTYPE_DVB) {
4810 int dir;
4811 int v = mpctx->last_dvb_step;
4812 if (v > 0)
4813 dir = DVB_CHANNEL_HIGHER;
4814 else
4815 dir = DVB_CHANNEL_LOWER;
4817 if (dvb_step_channel(mpctx->stream, dir)) {
4818 mpctx->stop_play = PT_NEXT_ENTRY;
4819 mpctx->dvbin_reopen = 1;
4822 #endif
4823 goto goto_next_file; // exit_player(_("Fatal error"));
4826 /* display clip info */
4827 demux_info_print(mpctx->demuxer);
4829 //================= Read SUBTITLES (DVD & TEXT) =========================
4830 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4831 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4832 init_vo_spudec(mpctx);
4834 // after reading video params we should load subtitles because
4835 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4836 // check .sub
4837 current_module = "read_subtitles_file";
4838 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4839 if (opts->sub_name) {
4840 for (i = 0; opts->sub_name[i] != NULL; ++i)
4841 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4843 if (opts->sub_auto) { // auto load sub file ...
4844 char **tmp = find_text_subtitles(opts, mpctx->filename);
4845 int nsub = MP_TALLOC_ELEMS(tmp);
4846 for (int i = 0; i < nsub; i++)
4847 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4848 talloc_free(tmp);
4850 if (mpctx->set_of_sub_size > 0)
4851 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4853 if (select_subtitle(mpctx)) {
4854 if (mpctx->subdata)
4855 switch (stream_dump_type) {
4856 case 3: list_sub_file(mpctx->subdata);
4857 break;
4858 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4859 break;
4860 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4861 break;
4862 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4863 break;
4864 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4865 break;
4866 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4867 break;
4871 print_file_properties(mpctx, mpctx->filename);
4873 reinit_video_chain(mpctx);
4874 if (mpctx->sh_video) {
4875 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4876 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4877 #ifdef CONFIG_FREETYPE
4878 force_load_font = 1;
4879 #endif
4880 } else if (!mpctx->sh_audio)
4881 goto goto_next_file;
4883 //================== MAIN: ==========================
4884 current_module = "main";
4886 if (opts->playing_msg) {
4887 char *msg = property_expand_string(mpctx, opts->playing_msg);
4888 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4889 free(msg);
4893 // Disable the term OSD in verbose mode
4894 if (verbose)
4895 opts->term_osd = 0;
4897 // Make sure old OSD does not stay around,
4898 // e.g. with -fixed-vo and same-resolution files
4899 clear_osd_msgs();
4900 update_osd_msg(mpctx);
4902 //================ SETUP AUDIO ==========================
4904 if (mpctx->sh_audio) {
4905 reinit_audio_chain(mpctx);
4906 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4907 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4908 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4911 current_module = "av_init";
4913 if (mpctx->sh_video) {
4914 mpctx->sh_video->timer = 0;
4915 if (!ignore_start)
4916 audio_delay += mpctx->sh_video->stream_delay;
4918 if (mpctx->sh_audio) {
4919 if (start_volume >= 0)
4920 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4921 if (!ignore_start)
4922 audio_delay -= mpctx->sh_audio->stream_delay;
4923 mpctx->delay = -audio_delay;
4926 if (!mpctx->sh_audio) {
4927 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4928 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4929 mpctx->d_audio->packs);
4930 ds_free_packs(mpctx->d_audio); // free buffered chunks
4932 if (!mpctx->sh_video) {
4933 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4934 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4935 mpctx->d_video->packs);
4936 ds_free_packs(mpctx->d_video);
4937 mpctx->d_video->id = -2;
4940 if (!mpctx->sh_video && !mpctx->sh_audio)
4941 goto goto_next_file;
4943 if (force_fps && mpctx->sh_video) {
4944 vo_fps = mpctx->sh_video->fps = force_fps;
4945 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4946 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4947 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4948 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4951 mp_input_set_section(mpctx->input, NULL);
4952 //TODO: add desired (stream-based) sections here
4953 if (mpctx->stream->type == STREAMTYPE_TV)
4954 mp_input_set_section(mpctx->input, "tv");
4955 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4956 mp_input_set_section(mpctx->input, "dvdnav");
4958 //==================== START PLAYING =======================
4960 if (opts->loop_times > 1)
4961 opts->loop_times--;
4962 else if (opts->loop_times == 1)
4963 opts->loop_times = -1;
4965 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4967 total_time_usage_start = GetTimer();
4968 audio_time_usage = 0;
4969 video_time_usage = 0;
4970 vout_time_usage = 0;
4971 total_frame_cnt = 0;
4972 drop_frame_cnt = 0; // fix for multifile fps benchmark
4973 play_n_frames = play_n_frames_mf;
4975 if (play_n_frames == 0) {
4976 mpctx->stop_play = PT_NEXT_ENTRY;
4977 goto goto_next_file;
4980 mpctx->time_frame = 0;
4981 mpctx->drop_message_shown = 0;
4982 mpctx->restart_playback = true;
4983 mpctx->video_pts = 0;
4984 mpctx->last_seek_pts = 0;
4985 mpctx->hrseek_active = false;
4986 mpctx->hrseek_framedrop = false;
4987 mpctx->step_frames = 0;
4988 mpctx->total_avsync_change = 0;
4989 mpctx->last_chapter_seek = -2;
4991 // If there's a timeline force an absolute seek to initialize state
4992 if (opts->seek_to_sec || mpctx->timeline) {
4993 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4994 seek(mpctx, mpctx->seek, false);
4995 end_at.pos += opts->seek_to_sec;
4997 if (opts->chapterrange[0] > 0) {
4998 double pts;
4999 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
5000 && pts > -1.0) {
5001 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
5002 seek(mpctx, mpctx->seek, false);
5006 if (end_at.type == END_AT_SIZE) {
5007 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
5008 "Option -endpos in MPlayer does not yet support size units.\n");
5009 end_at.type = END_AT_NONE;
5012 #ifdef CONFIG_DVDNAV
5013 mp_dvdnav_context_free(mpctx);
5014 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
5015 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
5016 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
5018 #endif
5020 mpctx->seek = (struct seek_params){ 0 };
5021 get_relative_time(mpctx); // reset current delta
5022 // Make sure VO knows current pause state
5023 if (mpctx->sh_video)
5024 vo_control(mpctx->video_out,
5025 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
5027 while (!mpctx->stop_play)
5028 run_playloop(mpctx);
5030 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
5032 #ifdef CONFIG_DVBIN
5033 if (mpctx->dvbin_reopen) {
5034 mpctx->stop_play = 0;
5035 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
5036 cache_uninit(mpctx->stream);
5037 mpctx->dvbin_reopen = 0;
5038 goto goto_enable_cache;
5040 #endif
5042 goto_next_file: // don't jump here after ao/vo/getch initialization!
5044 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
5046 if (opts->benchmark) {
5047 double tot = video_time_usage + vout_time_usage + audio_time_usage;
5048 double total_time_usage;
5049 total_time_usage_start = GetTimer() - total_time_usage_start;
5050 total_time_usage = (float)total_time_usage_start * 0.000001;
5051 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
5052 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
5053 video_time_usage, vout_time_usage, audio_time_usage,
5054 total_time_usage - tot, total_time_usage);
5055 if (total_time_usage > 0.0)
5056 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
5057 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
5058 100.0 * video_time_usage / total_time_usage,
5059 100.0 * vout_time_usage / total_time_usage,
5060 100.0 * audio_time_usage / total_time_usage,
5061 100.0 * (total_time_usage - tot) / total_time_usage,
5062 100.0);
5063 if (total_frame_cnt && frame_dropping)
5064 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
5065 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
5066 total_frame_cnt - drop_frame_cnt,
5067 (total_time_usage > 0.5) ? ((total_frame_cnt -
5068 drop_frame_cnt) / total_time_usage) : 0,
5069 drop_frame_cnt,
5070 100 * drop_frame_cnt / total_frame_cnt,
5071 total_frame_cnt,
5072 (total_time_usage > 0.5) ?
5073 (total_frame_cnt / total_time_usage) : 0);
5076 // time to uninit all, except global stuff:
5077 int uninitialize_parts = INITIALIZED_ALL;
5078 if (opts->fixed_vo)
5079 uninitialize_parts -= INITIALIZED_VO;
5080 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
5081 uninitialize_parts -= INITIALIZED_AO;
5082 uninit_player(mpctx, uninitialize_parts);
5084 if (mpctx->set_of_sub_size > 0) {
5085 current_module = "sub_free";
5086 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5087 sub_free(mpctx->set_of_subtitles[i]);
5088 #ifdef CONFIG_ASS
5089 if (mpctx->set_of_ass_tracks[i])
5090 ass_free_track(mpctx->set_of_ass_tracks[i]);
5091 #endif
5093 mpctx->set_of_sub_size = 0;
5095 mpctx->vo_sub_last = vo_sub = NULL;
5096 mpctx->subdata = NULL;
5097 #ifdef CONFIG_ASS
5098 mpctx->osd->ass_track = NULL;
5099 if (mpctx->ass_library)
5100 ass_clear_fonts(mpctx->ass_library);
5101 #endif
5103 if (!mpctx->stop_play) // In case some goto jumped here...
5104 mpctx->stop_play = PT_NEXT_ENTRY;
5106 int playtree_direction = 1;
5108 if (mpctx->stop_play == PT_NEXT_ENTRY
5109 || mpctx->stop_play == PT_PREV_ENTRY) {
5110 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5111 != PLAY_TREE_ITER_ENTRY) {
5112 play_tree_iter_free(mpctx->playtree_iter);
5113 mpctx->playtree_iter = NULL;
5115 mpctx->play_tree_step = 1;
5116 } else if (mpctx->stop_play == PT_UP_NEXT ||
5117 mpctx->stop_play == PT_UP_PREV) {
5118 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5119 if (mpctx->playtree_iter) {
5120 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5121 PLAY_TREE_ITER_ENTRY) {
5122 play_tree_iter_free(mpctx->playtree_iter);
5123 mpctx->playtree_iter = NULL;
5126 } else if (mpctx->stop_play == PT_STOP) {
5127 play_tree_iter_free(mpctx->playtree_iter);
5128 mpctx->playtree_iter = NULL;
5129 } else // NEXT PREV SRC
5130 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5132 while (mpctx->playtree_iter != NULL) {
5133 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5134 playtree_direction);
5135 if (mpctx->filename == NULL) {
5136 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5137 0) != PLAY_TREE_ITER_ENTRY) {
5138 play_tree_iter_free(mpctx->playtree_iter);
5139 mpctx->playtree_iter = NULL;
5142 } else
5143 break;
5146 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5147 if (!mpctx->playtree_iter)
5148 mpctx->filename = NULL;
5149 mpctx->stop_play = 0;
5150 goto play_next_file;
5153 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5155 return 1;
5157 #endif /* DISABLE_MAIN */