cleanup: Silence compilation warnings on MinGW-w64
[mplayer.git] / mplayer.c
blobcdcd1d645e3b361288f78450c2be25aaca41a8d7
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 #include <windows.h>
32 #endif
33 #include <string.h>
34 #include <unistd.h>
36 // #include <sys/mman.h>
37 #include <sys/types.h>
38 #ifndef __MINGW32__
39 #include <sys/ioctl.h>
40 #include <sys/wait.h>
41 #else
42 #define SIGHUP 1 /* hangup */
43 #define SIGQUIT 3 /* quit */
44 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
45 #define SIGBUS 10 /* bus error */
46 #define SIGPIPE 13 /* broken pipe */
47 #endif
49 #include <sys/time.h>
50 #include <sys/stat.h>
52 #include <signal.h>
53 #include <time.h>
54 #include <fcntl.h>
55 #include <limits.h>
57 #include <errno.h>
59 #include "mp_msg.h"
60 #include "av_log.h"
63 #include "m_option.h"
64 #include "m_config.h"
65 #include "mplayer.h"
66 #include "m_property.h"
68 #include "sub/subreader.h"
69 #include "sub/find_subfiles.h"
70 #include "sub/dec_sub.h"
72 #include "mp_osd.h"
73 #include "libvo/video_out.h"
74 #include "screenshot.h"
76 #include "sub/font_load.h"
77 #include "sub/sub.h"
78 #include "sub/av_sub.h"
79 #include "libmpcodecs/dec_teletext.h"
80 #include "cpudetect.h"
81 #include "version.h"
83 #ifdef CONFIG_X11
84 #include "libvo/x11_common.h"
85 #endif
87 #include "libao2/audio_out.h"
89 #include "codec-cfg.h"
91 #include "edl.h"
93 #include "sub/spudec.h"
94 #include "sub/vobsub.h"
96 #include "osdep/getch2.h"
97 #include "osdep/timer.h"
99 #include "input/input.h"
101 int slave_mode = 0;
102 int enable_mouse_movements = 0;
103 float start_volume = -1;
105 #include "osdep/priority.h"
107 char *heartbeat_cmd;
109 #ifdef HAVE_RTC
110 #ifdef __linux__
111 #include <linux/rtc.h>
112 #else
113 #include <rtc.h>
114 #define RTC_IRQP_SET RTCIO_IRQP_SET
115 #define RTC_PIE_ON RTCIO_PIE_ON
116 #endif /* __linux__ */
117 #endif /* HAVE_RTC */
119 #include "stream/tv.h"
120 #include "stream/stream_radio.h"
121 #ifdef CONFIG_DVBIN
122 #include "stream/dvbin.h"
123 #endif
124 #include "stream/cache2.h"
126 //**************************************************************************//
127 // Playtree
128 //**************************************************************************//
129 #include "playtree.h"
130 #include "playtreeparser.h"
132 //**************************************************************************//
133 // Config
134 //**************************************************************************//
135 #include "parser-cfg.h"
136 #include "parser-mpcmd.h"
138 //**************************************************************************//
139 // Config file
140 //**************************************************************************//
142 static int cfg_inc_verbose(m_option_t *conf)
144 ++verbose;
145 return 0;
148 #include "path.h"
150 //**************************************************************************//
151 //**************************************************************************//
152 // Input media streaming & demultiplexer:
153 //**************************************************************************//
155 static int max_framesize = 0;
157 #include "stream/stream.h"
158 #include "libmpdemux/demuxer.h"
159 #include "libmpdemux/stheader.h"
161 #ifdef CONFIG_DVDREAD
162 #include "stream/stream_dvd.h"
163 #endif
164 #include "stream/stream_dvdnav.h"
166 #include "libmpcodecs/dec_audio.h"
167 #include "libmpcodecs/dec_video.h"
168 #include "libmpcodecs/mp_image.h"
169 #include "libmpcodecs/vf.h"
170 #include "libmpcodecs/vd.h"
172 #include "mixer.h"
174 #include "mp_core.h"
175 #include "options.h"
176 #include "defaultopts.h"
178 static const char help_text[] = _(
179 "Usage: mplayer [options] [url|path/]filename\n"
180 "\n"
181 "Basic options: (complete list in the man page)\n"
182 " -vo <drv> select video output driver ('-vo help' for a list)\n"
183 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
184 #ifdef CONFIG_VCD
185 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
186 #endif
187 #ifdef CONFIG_DVDREAD
188 " dvd://<titleno> play DVD title from device instead of plain file\n"
189 #endif
190 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
191 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
192 " -nosound do not play sound\n"
193 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
194 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
195 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
196 " -playlist <file> specify playlist file\n"
197 " -vid x -aid y select video (x) and audio (y) stream to play\n"
198 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
199 " -pp <quality> enable postprocessing filter (details in the man page)\n"
200 " -framedrop enable frame dropping (for slow machines)\n"
201 "\n"
202 "Basic keys: (complete list in the man page, also check input.conf)\n"
203 " <- or -> seek backward/forward 10 seconds\n"
204 " down or up seek backward/forward 1 minute\n"
205 " pgdown or pgup seek backward/forward 10 minutes\n"
206 " < or > step backward/forward in playlist\n"
207 " p or SPACE pause movie (press any key to continue)\n"
208 " q or ESC stop playing and quit program\n"
209 " + or - adjust audio delay by +/- 0.1 second\n"
210 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
211 " * or / increase or decrease PCM volume\n"
212 " x or z adjust subtitle delay by +/- 0.1 second\n"
213 " r or t adjust subtitle position up/down, also see -vf expand\n"
214 " double click toggle fullscreen\n"
215 " right click pause (press again to continue)\n"
216 "\n"
217 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
218 "\n");
221 #define Exit_SIGILL_RTCpuSel _(\
222 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
223 " It may be a bug in our new runtime CPU-detection code...\n"\
224 " Please read DOCS/HTML/en/bugreports.html.\n")
226 #define Exit_SIGILL _(\
227 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
228 " It usually happens when you run it on a CPU different than the one it was\n"\
229 " compiled/optimized for.\n"\
230 " Verify this!\n")
232 #define Exit_SIGSEGV_SIGFPE _(\
233 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
234 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
235 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
237 #define Exit_SIGCRASH _(\
238 "- MPlayer crashed. This shouldn't happen.\n"\
239 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
240 " gcc version. If you think it's MPlayer's fault, please read\n"\
241 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
242 " won't help unless you provide this information when reporting a possible bug.\n")
244 #define SystemTooSlow _("\n\n"\
245 " ************************************************\n"\
246 " **** Your system is too SLOW to play this! ****\n"\
247 " ************************************************\n\n"\
248 "Possible reasons, problems, workarounds:\n"\
249 "- Most common: broken/buggy _audio_ driver\n"\
250 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
251 " - Experiment with different values for -autosync, 30 is a good start.\n"\
252 "- Slow video output\n"\
253 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
254 "- Slow CPU\n"\
255 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
256 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
257 "- Broken file\n"\
258 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
259 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
260 " - Try -cache 8192.\n"\
261 "- Are you using -cache to play a non-interleaved AVI file?\n"\
262 " - Try -nocache.\n"\
263 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
264 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
267 //**************************************************************************//
268 //**************************************************************************//
270 #include "mp_fifo.h"
272 // benchmark:
273 double video_time_usage;
274 double vout_time_usage;
275 static double audio_time_usage;
276 static int total_time_usage_start;
277 static int total_frame_cnt;
278 static int drop_frame_cnt; // total number of dropped frames
280 // options:
281 static int output_quality;
283 // seek:
284 static off_t seek_to_byte;
285 static off_t step_sec;
287 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
289 // codecs:
290 char **audio_codec_list; // override audio codec
291 char **video_codec_list; // override video codec
292 char **audio_fm_list; // override audio codec family
293 char **video_fm_list; // override video codec family
295 // this dvdsub_id was selected via slang
296 // use this to allow dvdnav to follow -slang across stream resets,
297 // in particular the subtitle ID for a language changes
298 int dvdsub_lang_id;
299 int vobsub_id = -1;
300 static char *spudec_ifo = NULL;
301 int forced_subs_only = 0;
303 // cache2:
304 int stream_cache_size = -1;
306 // dump:
307 int stream_dump_type = 0;
309 // A-V sync:
310 static float default_max_pts_correction = -1;
311 float audio_delay = 0;
312 static int ignore_start = 0;
314 double force_fps = 0;
315 static int force_srate = 0;
316 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
317 static int play_n_frames = -1;
318 static int play_n_frames_mf = -1;
320 // sub:
321 char *font_name = NULL;
322 char *sub_font_name = NULL;
323 extern int font_fontconfig;
324 float font_factor = 0.75;
325 float sub_delay = 0;
326 float sub_fps = 0;
327 int subcc_enabled = 0;
328 int suboverlap_enabled = 1;
330 #include "sub/ass_mp.h"
332 char *current_module; // for debugging
335 // ---
337 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
338 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
339 FILE *edl_fd; // file to write to when in -edlout mode.
340 int use_filedir_conf;
341 int use_filename_title;
343 #include "mpcommon.h"
344 #include "command.h"
346 #include "metadata.h"
348 static float get_relative_time(struct MPContext *mpctx)
350 unsigned int new_time = GetTimer();
351 unsigned int delta = new_time - mpctx->last_time;
352 mpctx->last_time = new_time;
353 return delta * 0.000001;
356 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
358 switch (type) {
359 /* check for valid video stream */
360 case META_VIDEO_CODEC:
361 case META_VIDEO_BITRATE:
362 case META_VIDEO_RESOLUTION:
363 if (!mpctx->sh_video)
364 return 0;
365 break;
367 /* check for valid audio stream */
368 case META_AUDIO_CODEC:
369 case META_AUDIO_BITRATE:
370 case META_AUDIO_SAMPLES:
371 if (!mpctx->sh_audio)
372 return 0;
373 break;
375 /* check for valid demuxer */
376 case META_INFO_TITLE:
377 case META_INFO_ARTIST:
378 case META_INFO_ALBUM:
379 case META_INFO_YEAR:
380 case META_INFO_COMMENT:
381 case META_INFO_TRACK:
382 case META_INFO_GENRE:
383 if (!mpctx->demuxer)
384 return 0;
385 break;
387 default:
388 break;
391 return 1;
394 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
396 char **info = mpctx->demuxer->info;
397 int n;
399 if (!info || !tag)
400 return talloc_strdup(NULL, "");
402 for (n = 0; info[2 * n] != NULL; n++)
403 if (!strcasecmp(info[2 * n], tag))
404 break;
406 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
409 char *get_metadata(struct MPContext *mpctx, metadata_t type)
411 sh_audio_t * const sh_audio = mpctx->sh_audio;
412 sh_video_t * const sh_video = mpctx->sh_video;
414 if (!is_valid_metadata_type(mpctx, type))
415 return NULL;
417 switch (type) {
418 case META_NAME:
419 return talloc_strdup(NULL, mp_basename(mpctx->filename));
420 case META_VIDEO_CODEC:
421 if (sh_video->format == 0x10000001)
422 return talloc_strdup(NULL, "mpeg1");
423 else if (sh_video->format == 0x10000002)
424 return talloc_strdup(NULL, "mpeg2");
425 else if (sh_video->format == 0x10000004)
426 return talloc_strdup(NULL, "mpeg4");
427 else if (sh_video->format == 0x10000005)
428 return talloc_strdup(NULL, "h264");
429 else if (sh_video->format >= 0x20202020)
430 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
431 else
432 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
433 case META_VIDEO_BITRATE:
434 return talloc_asprintf(NULL, "%d kbps",
435 (int) (sh_video->i_bps * 8 / 1024));
436 case META_VIDEO_RESOLUTION:
437 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
438 sh_video->disp_h);
439 case META_AUDIO_CODEC:
440 if (sh_audio->codec && sh_audio->codec->name)
441 return talloc_strdup(NULL, sh_audio->codec->name);
442 return talloc_strdup(NULL, "");
443 case META_AUDIO_BITRATE:
444 return talloc_asprintf(NULL, "%d kbps",
445 (int) (sh_audio->i_bps * 8 / 1000));
446 case META_AUDIO_SAMPLES:
447 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
448 sh_audio->channels);
450 /* check for valid demuxer */
451 case META_INFO_TITLE:
452 return get_demuxer_info(mpctx, "Title");
454 case META_INFO_ARTIST:
455 return get_demuxer_info(mpctx, "Artist");
457 case META_INFO_ALBUM:
458 return get_demuxer_info(mpctx, "Album");
460 case META_INFO_YEAR:
461 return get_demuxer_info(mpctx, "Year");
463 case META_INFO_COMMENT:
464 return get_demuxer_info(mpctx, "Comment");
466 case META_INFO_TRACK:
467 return get_demuxer_info(mpctx, "Track");
469 case META_INFO_GENRE:
470 return get_demuxer_info(mpctx, "Genre");
472 default:
473 break;
476 return talloc_strdup(NULL, "");
479 static void print_file_properties(struct MPContext *mpctx, const char *filename)
481 double start_pts = MP_NOPTS_VALUE;
482 double video_start_pts = MP_NOPTS_VALUE;
483 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
484 filename_recode(filename));
485 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
486 mpctx->demuxer->desc->name);
487 if (mpctx->sh_video) {
488 /* Assume FOURCC if all bytes >= 0x20 (' ') */
489 if (mpctx->sh_video->format >= 0x20202020)
490 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
491 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
492 else
493 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
494 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
495 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
496 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
497 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
498 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
499 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
500 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
501 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
502 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
503 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
504 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
505 video_start_pts = ds_get_next_pts(mpctx->d_video);
507 if (mpctx->sh_audio) {
508 /* Assume FOURCC if all bytes >= 0x20 (' ') */
509 if (mpctx->sh_audio->format >= 0x20202020)
510 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
511 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
512 else
513 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
514 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
515 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
516 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
517 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
518 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
519 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
520 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
521 start_pts = ds_get_next_pts(mpctx->d_audio);
523 if (video_start_pts != MP_NOPTS_VALUE) {
524 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
525 (mpctx->sh_video && video_start_pts < start_pts))
526 start_pts = video_start_pts;
528 if (start_pts != MP_NOPTS_VALUE)
529 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
530 else
531 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
532 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
533 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
534 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
535 mpctx->stream->seek
536 && (!mpctx->demuxer || mpctx->demuxer->seekable));
537 if (mpctx->demuxer) {
538 int chapter_count = get_chapter_count(mpctx);
539 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
540 for (int i = 0; i < chapter_count; i++) {
541 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
542 // in milliseconds
543 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
544 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
545 char *name = chapter_name(mpctx, i);
546 if (name) {
547 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
548 name);
549 talloc_free(name);
555 /// step size of mixer changes
556 int volstep = 3;
558 #ifdef CONFIG_DVDNAV
559 static void mp_dvdnav_context_free(MPContext *ctx)
561 if (ctx->nav_smpi)
562 free_mp_image(ctx->nav_smpi);
563 ctx->nav_smpi = NULL;
564 free(ctx->nav_buffer);
565 ctx->nav_buffer = NULL;
566 ctx->nav_start = NULL;
567 ctx->nav_in_size = 0;
569 #endif
571 static void uninit_subs(struct demuxer *demuxer)
573 for (int i = 0; i < MAX_S_STREAMS; i++) {
574 struct sh_sub *sh = demuxer->s_streams[i];
575 if (sh && sh->initialized)
576 sub_uninit(sh);
580 void uninit_player(struct MPContext *mpctx, unsigned int mask)
582 mask &= mpctx->initialized_flags;
584 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
586 if (mask & INITIALIZED_ACODEC) {
587 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
588 current_module = "uninit_acodec";
589 if (mpctx->sh_audio)
590 uninit_audio(mpctx->sh_audio);
591 mpctx->sh_audio = NULL;
592 mpctx->mixer.afilter = NULL;
595 if (mask & INITIALIZED_SUB) {
596 mpctx->initialized_flags &= ~INITIALIZED_SUB;
597 if (mpctx->d_sub->sh)
598 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
601 if (mask & INITIALIZED_VCODEC) {
602 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
603 current_module = "uninit_vcodec";
604 if (mpctx->sh_video)
605 uninit_video(mpctx->sh_video);
606 mpctx->sh_video = NULL;
609 if (mask & INITIALIZED_DEMUXER) {
610 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
611 current_module = "free_demuxer";
612 if (mpctx->num_sources) {
613 mpctx->demuxer = mpctx->sources[0].demuxer;
614 for (int i = 1; i < mpctx->num_sources; i++) {
615 uninit_subs(mpctx->sources[i].demuxer);
616 free_stream(mpctx->sources[i].stream);
617 free_demuxer(mpctx->sources[i].demuxer);
620 talloc_free(mpctx->sources);
621 mpctx->sources = NULL;
622 mpctx->num_sources = 0;
623 talloc_free(mpctx->timeline);
624 mpctx->timeline = NULL;
625 mpctx->num_timeline_parts = 0;
626 talloc_free(mpctx->chapters);
627 mpctx->chapters = NULL;
628 mpctx->num_chapters = 0;
629 mpctx->video_offset = 0;
630 if (mpctx->demuxer) {
631 mpctx->stream = mpctx->demuxer->stream;
632 uninit_subs(mpctx->demuxer);
633 free_demuxer(mpctx->demuxer);
635 mpctx->demuxer = NULL;
638 // kill the cache process:
639 if (mask & INITIALIZED_STREAM) {
640 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
641 current_module = "uninit_stream";
642 if (mpctx->stream)
643 free_stream(mpctx->stream);
644 mpctx->stream = NULL;
647 if (mask & INITIALIZED_VO) {
648 mpctx->initialized_flags &= ~INITIALIZED_VO;
649 current_module = "uninit_vo";
650 vo_destroy(mpctx->video_out);
651 mpctx->video_out = NULL;
652 #ifdef CONFIG_DVDNAV
653 mp_dvdnav_context_free(mpctx);
654 #endif
657 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
658 if (mask & INITIALIZED_GETCH2) {
659 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
660 current_module = "uninit_getch2";
661 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
662 // restore terminal:
663 getch2_disable();
666 if (mask & INITIALIZED_VOBSUB) {
667 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
668 current_module = "uninit_vobsub";
669 if (vo_vobsub)
670 vobsub_close(vo_vobsub);
671 vo_vobsub = NULL;
674 if (mask & INITIALIZED_SPUDEC) {
675 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
676 current_module = "uninit_spudec";
677 spudec_free(vo_spudec);
678 vo_spudec = NULL;
681 if (mask & INITIALIZED_AO) {
682 mpctx->initialized_flags &= ~INITIALIZED_AO;
683 current_module = "uninit_ao";
684 if (mpctx->edl_muted)
685 mixer_mute(&mpctx->mixer);
686 if (mpctx->ao)
687 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
688 mpctx->ao = NULL;
691 current_module = NULL;
694 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
696 if (mpctx->user_muted && !mpctx->edl_muted)
697 mixer_mute(&mpctx->mixer);
698 uninit_player(mpctx, INITIALIZED_ALL);
699 #if defined(__MINGW32__) || defined(__CYGWIN__)
700 timeEndPeriod(1);
701 #endif
702 #ifdef CONFIG_X11
703 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
704 #endif
706 current_module = "uninit_input";
707 mp_input_uninit(mpctx->input);
709 #ifdef CONFIG_FREETYPE
710 current_module = "uninit_font";
711 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
712 free_font_desc(mpctx->osd->sub_font);
713 free_font_desc(vo_font);
714 vo_font = NULL;
715 done_freetype();
716 #endif
717 osd_free(mpctx->osd);
719 #ifdef CONFIG_ASS
720 ass_library_done(mpctx->ass_library);
721 mpctx->ass_library = NULL;
722 #endif
724 current_module = "exit_player";
726 if (mpctx->playtree_iter)
727 play_tree_iter_free(mpctx->playtree_iter);
728 mpctx->playtree_iter = NULL;
729 if (mpctx->playtree)
730 play_tree_free(mpctx->playtree, 1);
731 mpctx->playtree = NULL;
733 talloc_free(mpctx->key_fifo);
735 free(edl_records); // free mem allocated for EDL
736 edl_records = NULL;
737 switch (how) {
738 case EXIT_QUIT:
739 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
740 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
741 break;
742 case EXIT_EOF:
743 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
744 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
745 break;
746 case EXIT_ERROR:
747 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
748 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
749 break;
750 default:
751 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
753 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
754 "max framesize was %d bytes\n", max_framesize);
756 // must be last since e.g. mp_msg uses option values
757 // that will be freed by this.
758 if (mpctx->mconfig)
759 m_config_free(mpctx->mconfig);
760 mpctx->mconfig = NULL;
762 talloc_free(mpctx);
764 exit(rc);
767 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
769 exit_player_with_rc(mpctx, how, 1);
772 #ifndef __MINGW32__
773 static void child_sighandler(int x)
775 pid_t pid;
776 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
778 #endif
780 #ifdef CONFIG_CRASH_DEBUG
781 static char *prog_path;
782 static int crash_debug = 0;
783 #endif
785 static void exit_sighandler(int x)
787 static int sig_count = 0;
788 #ifdef CONFIG_CRASH_DEBUG
789 if (!crash_debug || x != SIGTRAP)
790 #endif
791 ++sig_count;
792 if (sig_count == 5) {
793 /* We're crashing bad and can't uninit cleanly :(
794 * by popular request, we make one last (dirty)
795 * effort to restore the user's
796 * terminal. */
797 getch2_disable();
798 exit(1);
800 if (sig_count == 6)
801 exit(1);
802 if (sig_count > 6) {
803 // can't stop :(
804 #ifndef __MINGW32__
805 kill(getpid(), SIGKILL);
806 #endif
808 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
809 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
810 "\nMPlayer interrupted by signal %d in module: %s\n", x,
811 current_module ? current_module : "unknown");
812 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
813 if (sig_count <= 1)
814 switch (x) {
815 case SIGINT:
816 case SIGPIPE:
817 case SIGQUIT:
818 case SIGTERM:
819 case SIGKILL:
820 async_quit_request = 1;
821 return; // killed from keyboard (^C) or killed [-9]
822 case SIGILL:
823 #if CONFIG_RUNTIME_CPUDETECT
824 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
825 #else
826 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
827 #endif
828 case SIGFPE:
829 case SIGSEGV:
830 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
831 default:
832 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
833 #ifdef CONFIG_CRASH_DEBUG
834 if (crash_debug) {
835 int gdb_pid;
836 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
837 gdb_pid = fork();
838 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
839 if (gdb_pid == 0) { // We are the child
840 char spid[20];
841 snprintf(spid, sizeof(spid), "%i", getppid());
842 getch2_disable(); // allow terminal to work properly with gdb
843 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
844 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
845 } else if (gdb_pid < 0)
846 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
847 else
848 waitpid(gdb_pid, NULL, 0);
849 if (x == SIGTRAP)
850 return;
852 #endif
854 getch2_disable();
855 exit(1);
858 #include "cfg-mplayer.h"
860 static int cfg_include(m_option_t *conf, char *filename)
862 return m_config_parse_config_file(conf->priv, filename);
865 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
867 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
869 struct MPOpts *opts = &mpctx->opts;
870 char *conffile;
871 int conffile_fd;
872 if (!(opts->noconfig & 2) &&
873 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
874 exit_player(mpctx, EXIT_NONE);
875 if ((conffile = get_path("")) == NULL)
876 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
877 else {
878 #ifdef __MINGW32__
879 mkdir(conffile);
880 #else
881 mkdir(conffile, 0777);
882 #endif
883 free(conffile);
884 if ((conffile = get_path("config")) == NULL)
885 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
886 else {
887 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
888 0666)) != -1) {
889 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
890 "Creating config file: %s\n", conffile);
891 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
892 close(conffile_fd);
894 if (!(opts->noconfig & 1) &&
895 m_config_parse_config_file(conf, conffile) < 0)
896 exit_player(mpctx, EXIT_NONE);
897 free(conffile);
902 #define PROFILE_CFG_PROTOCOL "protocol."
904 static void load_per_protocol_config(m_config_t *conf, const char * const file)
906 char *str;
907 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
908 m_profile_t *p;
910 /* does filename actually uses a protocol ? */
911 str = strstr(file, "://");
912 if (!str)
913 return;
915 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
916 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
917 p = m_config_get_profile(conf, protocol);
918 if (p) {
919 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
920 "Loading protocol-related profile '%s'\n", protocol);
921 m_config_set_profile(conf, p);
925 #define PROFILE_CFG_EXTENSION "extension."
927 static void load_per_extension_config(m_config_t *conf, const char * const file)
929 char *str;
930 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
931 m_profile_t *p;
933 /* does filename actually have an extension ? */
934 str = strrchr(file, '.');
935 if (!str)
936 return;
938 sprintf(extension, PROFILE_CFG_EXTENSION);
939 strncat(extension, ++str, 7);
940 p = m_config_get_profile(conf, extension);
941 if (p) {
942 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
943 "Loading extension-related profile '%s'\n", extension);
944 m_config_set_profile(conf, p);
948 #define PROFILE_CFG_VO "vo."
949 #define PROFILE_CFG_AO "ao."
951 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
953 char profile[strlen(cfg) + strlen(out) + 1];
954 m_profile_t *p;
956 sprintf(profile, "%s%s", cfg, out);
957 p = m_config_get_profile(conf, profile);
958 if (p) {
959 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
960 "Loading extension-related profile '%s'\n", profile);
961 m_config_set_profile(conf, p);
966 * Tries to load a config file
967 * @return 0 if file was not found, 1 otherwise
969 static int try_load_config(m_config_t *conf, const char *file)
971 struct stat st;
972 if (stat(file, &st))
973 return 0;
974 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
975 m_config_parse_config_file(conf, file);
976 return 1;
979 static void load_per_file_config(m_config_t *conf, const char * const file)
981 char *confpath;
982 char cfg[PATH_MAX];
983 const char *name;
985 if (strlen(file) > PATH_MAX - 14) {
986 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
987 "can not load file or directory specific config files\n");
988 return;
990 sprintf(cfg, "%s.conf", file);
992 name = mp_basename(cfg);
993 if (use_filedir_conf) {
994 char dircfg[PATH_MAX];
995 strcpy(dircfg, cfg);
996 strcpy(dircfg + (name - cfg), "mplayer.conf");
997 try_load_config(conf, dircfg);
999 if (try_load_config(conf, cfg))
1000 return;
1003 if ((confpath = get_path(name)) != NULL) {
1004 try_load_config(conf, confpath);
1006 free(confpath);
1010 /* When libmpdemux performs a blocking operation (network connection or
1011 * cache filling) if the operation fails we use this function to check
1012 * if it was interrupted by the user.
1013 * The function returns a new value for eof. */
1014 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1016 mp_cmd_t *cmd;
1017 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1018 switch (cmd->id) {
1019 case MP_CMD_QUIT:
1020 exit_player_with_rc(mpctx, EXIT_QUIT,
1021 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1022 case MP_CMD_PLAY_TREE_STEP: {
1023 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1024 mpctx->play_tree_step =
1025 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1026 } break;
1027 case MP_CMD_PLAY_TREE_UP_STEP: {
1028 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1029 } break;
1030 case MP_CMD_PLAY_ALT_SRC_STEP: {
1031 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1032 } break;
1034 mp_cmd_free(cmd);
1036 return stop_play;
1039 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1041 play_tree_add_bpf(entry, bstr(mpctx->filename));
1044 if (!entry) {
1045 entry = mpctx->playtree_iter->tree;
1046 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1047 != PLAY_TREE_ITER_ENTRY)
1048 return PT_NEXT_ENTRY;
1049 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1050 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1051 != PLAY_TREE_ITER_ENTRY)
1052 return PT_NEXT_ENTRY;
1054 play_tree_remove(entry, 1, 1);
1055 return PT_NEXT_SRC;
1057 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1058 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1059 entry = mpctx->playtree_iter->tree;
1060 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1061 != PLAY_TREE_ITER_ENTRY)
1062 return PT_NEXT_ENTRY;
1063 play_tree_remove(entry, 1, 1);
1065 return PT_NEXT_SRC;
1068 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1069 int noerr)
1071 struct MPOpts *opts = &mpctx->opts;
1072 sub_data *subd = NULL;
1073 struct ass_track *asst = NULL;
1074 bool is_native_ass = false;
1076 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1077 return;
1079 #ifdef CONFIG_ASS
1080 if (opts->ass_enabled) {
1081 #ifdef CONFIG_ICONV
1082 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1083 #else
1084 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1085 #endif
1086 is_native_ass = asst;
1087 if (!asst) {
1088 subd = sub_read_file(filename, fps, &mpctx->opts);
1089 if (subd) {
1090 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1091 sub_free(subd);
1092 subd = NULL;
1095 } else
1096 #endif
1097 subd = sub_read_file(filename, fps, &mpctx->opts);
1100 if (!asst && !subd) {
1101 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1102 "Cannot load subtitles: %s\n", filename_recode(filename));
1103 return;
1106 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1107 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1108 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1109 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1110 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1111 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1112 filename_recode(filename));
1113 ++mpctx->set_of_sub_size;
1114 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1115 mpctx->set_of_sub_size, filename_recode(filename));
1118 void init_vo_spudec(struct MPContext *mpctx)
1120 unsigned width, height;
1121 spudec_free(vo_spudec);
1122 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1123 vo_spudec = NULL;
1125 // we currently can't work without video stream
1126 if (!mpctx->sh_video)
1127 return;
1129 if (spudec_ifo) {
1130 unsigned int palette[16];
1131 current_module = "spudec_init_vobsub";
1132 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1133 1, -1, NULL) >= 0)
1134 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1137 width = mpctx->sh_video->disp_w;
1138 height = mpctx->sh_video->disp_h;
1140 #ifdef CONFIG_DVDREAD
1141 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1142 current_module = "spudec_init_dvdread";
1143 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1144 cur_pgc->palette, width, height, NULL, 0);
1146 #endif
1148 #ifdef CONFIG_DVDNAV
1149 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1150 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1151 current_module = "spudec_init_dvdnav";
1152 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1154 #endif
1156 if (vo_spudec == NULL) {
1157 sh_sub_t *sh = mpctx->d_sub->sh;
1158 current_module = "spudec_init_normal";
1159 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1160 sh->extradata_len);
1161 spudec_set_font_factor(vo_spudec, font_factor);
1164 if (vo_spudec != NULL) {
1165 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1166 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1167 mpctx);
1172 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1173 * make it all work is to use the builtin SDL-bootstrap code, which
1174 * will be done automatically by replacing our main() if we include SDL.h.
1176 #if defined(__APPLE__) && defined(CONFIG_SDL)
1177 #ifdef CONFIG_SDL_SDL_H
1178 #include <SDL/SDL.h>
1179 #else
1180 #include <SDL.h>
1181 #endif
1182 #endif
1185 * \brief append a formatted string
1186 * \param buf buffer to print into
1187 * \param pos position of terminating 0 in buf
1188 * \param len maximum number of characters in buf, not including terminating 0
1189 * \param format printf format string
1191 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1193 va_list va;
1194 va_start(va, format);
1195 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1196 va_end(va);
1197 if (*pos >= len) {
1198 buf[len] = 0;
1199 *pos = len;
1204 * \brief append time in the hh:mm:ss.f format
1205 * \param buf buffer to print into
1206 * \param pos position of terminating 0 in buf
1207 * \param len maximum number of characters in buf, not including terminating 0
1208 * \param time time value to convert/append
1210 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1212 int64_t tenths = 10 * time;
1213 int f1 = tenths % 10;
1214 int ss = (tenths / 10) % 60;
1215 int mm = (tenths / 600) % 60;
1216 int hh = tenths / 36000;
1217 if (time < 0) {
1218 saddf(buf, pos, len, "unknown");
1219 return;
1221 if (hh > 0)
1222 saddf(buf, pos, len, "%2d:", hh);
1223 if (hh > 0 || mm > 0)
1224 saddf(buf, pos, len, "%02d:", mm);
1225 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1228 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1230 struct MPOpts *opts = &mpctx->opts;
1231 sh_video_t * const sh_video = mpctx->sh_video;
1233 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1234 a_pos = playing_audio_pts(mpctx);
1235 if (mpctx->sh_audio && sh_video && at_frame) {
1236 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1237 if (mpctx->time_frame > 0)
1238 mpctx->last_av_difference +=
1239 mpctx->time_frame * opts->playback_speed;
1240 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1241 && !mpctx->drop_message_shown) {
1242 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1243 mpctx->drop_message_shown = true;
1246 if (opts->quiet)
1247 return;
1249 if (a_pos == MP_NOPTS_VALUE)
1250 a_pos = -9; // don't print a huge negative number
1252 int width;
1253 char *line;
1254 unsigned pos = 0;
1255 get_screen_size();
1256 if (screen_width > 0)
1257 width = screen_width;
1258 else
1259 width = 80;
1260 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1261 /* Windows command line is broken (MinGW's rxvt works, but we
1262 * should not depend on that). */
1263 width--;
1264 #endif
1265 line = malloc(width + 1); // one additional char for the terminating null
1267 // Audio time
1268 if (mpctx->sh_audio) {
1269 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1270 if (!sh_video) {
1271 float len = get_time_length(mpctx);
1272 saddf(line, &pos, width, "(");
1273 sadd_hhmmssf(line, &pos, width, a_pos);
1274 saddf(line, &pos, width, ") of %.1f (", len);
1275 sadd_hhmmssf(line, &pos, width, len);
1276 saddf(line, &pos, width, ") ");
1280 // Video time
1281 if (sh_video)
1282 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1284 // A-V sync
1285 if (mpctx->sh_audio && sh_video)
1286 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1287 mpctx->last_av_difference, mpctx->total_avsync_change);
1289 // Video stats
1290 if (sh_video)
1291 saddf(line, &pos, width, "%3d/%3d ",
1292 (int)sh_video->num_frames,
1293 (int)sh_video->num_frames_decoded);
1295 // CPU usage
1296 if (sh_video) {
1297 if (sh_video->timer > 0.5)
1298 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1299 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1300 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1301 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1302 else
1303 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1304 } else if (mpctx->sh_audio) {
1305 if (mpctx->delay > 0.5)
1306 saddf(line, &pos, width, "%4.1f%% ",
1307 100.0 * audio_time_usage / (double)mpctx->delay);
1308 else
1309 saddf(line, &pos, width, "??,?%% ");
1312 // VO stats
1313 if (sh_video)
1314 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1316 #ifdef CONFIG_STREAM_CACHE
1317 // cache stats
1318 if (stream_cache_size > 0)
1319 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1320 #endif
1322 // other
1323 if (opts->playback_speed != 1)
1324 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1326 // end
1327 if (erase_to_end_of_line) {
1328 line[pos] = 0;
1329 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1330 "%s%s\r", line, erase_to_end_of_line);
1331 } else {
1332 memset(&line[pos], ' ', width - pos);
1333 line[width] = 0;
1334 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1336 free(line);
1338 mpctx->status_printed = true;
1341 struct stream_dump_progress {
1342 uint64_t count;
1343 unsigned start_time;
1344 unsigned last_print_time;
1347 static void stream_dump_progress_start(struct stream_dump_progress *p)
1349 p->start_time = p->last_print_time = GetTimerMS();
1350 p->count = 0;
1353 static void stream_dump_progress(struct stream_dump_progress *p,
1354 uint64_t len, stream_t *stream)
1356 p->count += len;
1357 unsigned t = GetTimerMS();
1358 if (t - p->last_print_time < 1000)
1359 return;
1361 uint64_t start = stream->start_pos;
1362 uint64_t end = stream->end_pos;
1363 uint64_t pos = stream->pos;
1365 p->last_print_time = t;
1366 /* TODO: pretty print sizes; ETA */
1367 if (end > start && pos >= start && pos <= end) {
1368 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1369 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1370 p->count, 100.0 * (pos - start) / (end - start));
1371 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1372 } else {
1373 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1374 "dump: %"PRIu64 " bytes written", p->count);
1375 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1379 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1381 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1382 p->count, name);
1386 * \brief build a chain of audio filters that converts the input format
1387 * to the ao's format, taking into account the current playback_speed.
1388 * sh_audio describes the requested input format of the chain.
1389 * ao describes the requested output format of the chain.
1391 static int build_afilter_chain(struct MPContext *mpctx)
1393 struct sh_audio *sh_audio = mpctx->sh_audio;
1394 struct ao *ao = mpctx->ao;
1395 struct MPOpts *opts = &mpctx->opts;
1396 int new_srate;
1397 int result;
1398 if (!sh_audio) {
1399 mpctx->mixer.afilter = NULL;
1400 return 0;
1402 if (af_control_any_rev(sh_audio->afilter,
1403 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1404 &opts->playback_speed))
1405 new_srate = sh_audio->samplerate;
1406 else {
1407 new_srate = sh_audio->samplerate * opts->playback_speed;
1408 if (new_srate != ao->samplerate) {
1409 // limits are taken from libaf/af_resample.c
1410 if (new_srate < 8000)
1411 new_srate = 8000;
1412 if (new_srate > 192000)
1413 new_srate = 192000;
1414 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1417 result = init_audio_filters(sh_audio, new_srate,
1418 &ao->samplerate, &ao->channels, &ao->format);
1419 mpctx->mixer.afilter = sh_audio->afilter;
1420 return result;
1424 typedef struct mp_osd_msg mp_osd_msg_t;
1425 struct mp_osd_msg {
1426 /// Previous message on the stack.
1427 mp_osd_msg_t *prev;
1428 /// Message text.
1429 char *msg;
1430 int id, level, started;
1431 /// Display duration in ms.
1432 unsigned time;
1435 /// OSD message stack.
1436 static mp_osd_msg_t *osd_msg_stack = NULL;
1439 * \brief Add a message on the OSD message stack
1441 * If a message with the same id is already present in the stack
1442 * it is pulled on top of the stack, otherwise a new message is created.
1445 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1446 va_list ap)
1448 mp_osd_msg_t *msg, *last = NULL;
1450 // look if the id is already in the stack
1451 for (msg = osd_msg_stack; msg && msg->id != id;
1452 last = msg, msg = msg->prev) ;
1453 // not found: alloc it
1454 if (!msg) {
1455 msg = talloc_zero(NULL, mp_osd_msg_t);
1456 msg->prev = osd_msg_stack;
1457 osd_msg_stack = msg;
1458 } else if (last) { // found, but it's not on top of the stack
1459 last->prev = msg->prev;
1460 msg->prev = osd_msg_stack;
1461 osd_msg_stack = msg;
1463 talloc_free(msg->msg);
1464 // write the msg
1465 msg->msg = talloc_vasprintf(msg, fmt, ap);
1466 // set id and time
1467 msg->id = id;
1468 msg->level = level;
1469 msg->time = time;
1473 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1475 va_list ap;
1476 va_start(ap, fmt);
1477 set_osd_msg_va(id, level, time, fmt, ap);
1478 va_end(ap);
1481 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1483 va_list ap;
1484 va_start(ap, fmt);
1485 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1486 va_end(ap);
1490 * \brief Remove a message from the OSD stack
1492 * This function can be used to get rid of a message right away.
1496 void rm_osd_msg(int id)
1498 mp_osd_msg_t *msg, *last = NULL;
1500 // Search for the msg
1501 for (msg = osd_msg_stack; msg && msg->id != id;
1502 last = msg, msg = msg->prev) ;
1503 if (!msg)
1504 return;
1506 // Detach it from the stack and free it
1507 if (last)
1508 last->prev = msg->prev;
1509 else
1510 osd_msg_stack = msg->prev;
1511 talloc_free(msg);
1515 * \brief Remove all messages from the OSD stack
1519 static void clear_osd_msgs(void)
1521 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1522 while (msg) {
1523 prev = msg->prev;
1524 talloc_free(msg);
1525 msg = prev;
1527 osd_msg_stack = NULL;
1531 * \brief Get the current message from the OSD stack.
1533 * This function decrements the message timer and destroys the old ones.
1534 * The message that should be displayed is returned (if any).
1538 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1540 struct MPOpts *opts = &mpctx->opts;
1541 mp_osd_msg_t *msg, *prev, *last = NULL;
1542 static unsigned last_update = 0;
1543 unsigned now = GetTimerMS();
1544 unsigned diff;
1545 char hidden_dec_done = 0;
1547 if (mpctx->osd_visible) {
1548 // 36000000 means max timed visibility is 1 hour into the future, if
1549 // the difference is greater assume it's wrapped around from below 0
1550 if (mpctx->osd_visible - now > 36000000) {
1551 mpctx->osd_visible = 0;
1552 vo_osd_progbar_type = -1; // disable
1553 vo_osd_changed(OSDTYPE_PROGBAR);
1554 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1557 if (mpctx->osd_show_percentage_until - now > 36000000)
1558 mpctx->osd_show_percentage_until = 0;
1560 if (!last_update)
1561 last_update = now;
1562 diff = now >= last_update ? now - last_update : 0;
1564 last_update = now;
1566 // Look for the first message in the stack with high enough level.
1567 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1568 prev = msg->prev;
1569 if (msg->level > opts->osd_level && hidden_dec_done)
1570 continue;
1571 // The message has a high enough level or it is the first hidden one
1572 // in both cases we decrement the timer or kill it.
1573 if (!msg->started || msg->time > diff) {
1574 if (msg->started)
1575 msg->time -= diff;
1576 else
1577 msg->started = 1;
1578 // display it
1579 if (msg->level <= opts->osd_level)
1580 return msg;
1581 hidden_dec_done = 1;
1582 continue;
1584 // kill the message
1585 talloc_free(msg);
1586 if (last) {
1587 last->prev = prev;
1588 msg = last;
1589 } else {
1590 osd_msg_stack = prev;
1591 msg = NULL;
1594 // Nothing found
1595 return NULL;
1599 * \brief Display the OSD bar.
1601 * Display the OSD bar or fall back on a simple message.
1605 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1606 double min, double max, double val)
1608 struct MPOpts *opts = &mpctx->opts;
1609 if (opts->osd_level < 1)
1610 return;
1612 if (mpctx->sh_video) {
1613 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1614 vo_osd_progbar_type = type;
1615 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1616 vo_osd_changed(OSDTYPE_PROGBAR);
1617 return;
1620 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1621 name, ROUND(100 * (val - min) / (max - min)));
1625 * \brief Display text subtitles on the OSD
1627 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1629 int i;
1630 vo_sub = subs;
1631 vo_osd_changed(OSDTYPE_SUBTITLE);
1632 if (!mpctx->sh_video) {
1633 // reverse order, since newest set_osd_msg is displayed first
1634 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1635 if (!subs || i >= subs->lines || !subs->text[i])
1636 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1637 else {
1638 // HACK: currently display time for each sub line
1639 // except the last is set to 2 seconds.
1640 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1641 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1642 "%s", subs->text[i]);
1649 * \brief Update the OSD message line.
1651 * This function displays the current message on the vo OSD or on the term.
1652 * If the stack is empty and the OSD level is high enough the timer
1653 * is displayed (only on the vo OSD).
1657 static void update_osd_msg(struct MPContext *mpctx)
1659 struct MPOpts *opts = &mpctx->opts;
1660 mp_osd_msg_t *msg;
1661 struct osd_state *osd = mpctx->osd;
1662 char osd_text_timer[128];
1664 if (mpctx->add_osd_seek_info) {
1665 double percentage = get_percent_pos(mpctx);
1666 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1667 if (mpctx->sh_video)
1668 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1669 mpctx->add_osd_seek_info = false;
1672 // Look if we have a msg
1673 if ((msg = get_osd_msg(mpctx))) {
1674 if (strcmp(osd->osd_text, msg->msg)) {
1675 osd_set_text(osd, msg->msg);
1676 if (mpctx->sh_video)
1677 vo_osd_changed(OSDTYPE_OSD);
1678 else if (opts->term_osd)
1679 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1680 msg->msg);
1682 return;
1685 if (mpctx->sh_video) {
1686 // fallback on the timer
1687 if (opts->osd_level >= 2) {
1688 int len = get_time_length(mpctx);
1689 int percentage = -1;
1690 char percentage_text[10];
1691 char fractions_text[4];
1692 double fpts = get_current_time(mpctx);
1693 int pts = fpts;
1695 if (mpctx->osd_show_percentage_until)
1696 percentage = get_percent_pos(mpctx);
1698 if (percentage >= 0)
1699 snprintf(percentage_text, 9, " (%d%%)", percentage);
1700 else
1701 percentage_text[0] = 0;
1703 if (opts->osd_fractions == 1) {
1704 //print fractions as sub-second timestamp
1705 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1706 (int)((fpts - pts) * 100));
1707 } else if (opts->osd_fractions == 2) {
1708 /* Print fractions by estimating the frame count within the
1709 * second.
1711 * Rounding or cutting off numbers after the decimal point
1712 * causes problems because of float's precision and movies
1713 * whose first frame is not exactly at timestamp 0. Therefore,
1714 * we add 0.2 and cut off at the decimal point, which proved
1715 * to be good heuristic.
1717 double fps = mpctx->sh_video->fps;
1718 if (fps <= 1 || fps > 99)
1719 strcpy(fractions_text, ".??");
1720 else
1721 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1722 (int) ((fpts - pts) * fps + 0.2));
1723 } else {
1724 //do not print fractions
1725 fractions_text[0] = 0;
1728 if (opts->osd_level == 3)
1729 snprintf(osd_text_timer, sizeof(osd_text_timer),
1730 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1731 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1732 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1733 percentage_text);
1734 else
1735 snprintf(osd_text_timer, sizeof(osd_text_timer),
1736 "%c %02d:%02d:%02d%s%s",
1737 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1738 pts % 60, fractions_text, percentage_text);
1739 } else
1740 osd_text_timer[0] = 0;
1742 if (strcmp(osd->osd_text, osd_text_timer)) {
1743 osd_set_text(osd, osd_text_timer);
1744 vo_osd_changed(OSDTYPE_OSD);
1746 return;
1749 // Clear the term osd line
1750 if (opts->term_osd && osd->osd_text[0]) {
1751 osd->osd_text[0] = 0;
1752 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1757 void reinit_audio_chain(struct MPContext *mpctx)
1759 struct MPOpts *opts = &mpctx->opts;
1760 struct ao *ao;
1761 if (!mpctx->sh_audio)
1762 return;
1763 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1764 current_module = "init_audio_codec";
1765 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1766 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1767 goto init_error;
1768 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1769 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1773 current_module = "af_preinit";
1774 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1775 mpctx->initialized_flags |= INITIALIZED_AO;
1776 mpctx->ao = ao_create();
1777 mpctx->ao->samplerate = force_srate;
1778 mpctx->ao->format = opts->audio_output_format;
1780 ao = mpctx->ao;
1782 // first init to detect best values
1783 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1784 // input:
1785 mpctx->sh_audio->samplerate,
1786 // output:
1787 &ao->samplerate, &ao->channels, &ao->format)) {
1788 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1789 "pre-init!\n");
1790 exit_player(mpctx, EXIT_ERROR);
1792 if (!ao->initialized) {
1793 current_module = "ao2_init";
1794 ao->buffersize = opts->ao_buffersize;
1795 ao_init(ao, opts->audio_driver_list);
1796 if (!ao->initialized) {
1797 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1798 "Could not open/initialize audio device -> no sound.\n");
1799 goto init_error;
1801 ao->buffer.start = talloc_new(ao);
1802 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1803 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1804 ao->driver->info->short_name,
1805 ao->samplerate, ao->channels,
1806 af_fmt2str_short(ao->format),
1807 af_fmt2bits(ao->format) / 8);
1808 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1809 ao->driver->info->name, ao->driver->info->author);
1810 if (strlen(ao->driver->info->comment) > 0)
1811 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1812 ao->driver->info->comment);
1815 // init audio filters:
1816 current_module = "af_init";
1817 if (!build_afilter_chain(mpctx)) {
1818 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1819 "Couldn't find matching filter/ao format!\n");
1820 goto init_error;
1822 mpctx->mixer.ao = ao;
1823 mpctx->mixer.volstep = volstep;
1824 mpctx->syncing_audio = true;
1825 return;
1827 init_error:
1828 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1829 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1830 mpctx->d_audio->id = -2;
1834 // Return pts value corresponding to the end point of audio written to the
1835 // ao so far.
1836 static double written_audio_pts(struct MPContext *mpctx)
1838 sh_audio_t *sh_audio = mpctx->sh_audio;
1839 demux_stream_t *d_audio = mpctx->d_audio;
1840 // first calculate the end pts of audio that has been output by decoder
1841 double a_pts = sh_audio->pts;
1842 if (a_pts != MP_NOPTS_VALUE)
1843 // Good, decoder supports new way of calculating audio pts.
1844 // sh_audio->pts is the timestamp of the latest input packet with
1845 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1846 // the amount of bytes the decoder has written after that timestamp.
1847 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1848 else {
1849 // Decoder doesn't support new way of calculating pts (or we're
1850 // being called before it has decoded anything with known timestamp).
1851 // Use the old method of audio pts calculation: take the timestamp
1852 // of last packet with known pts the decoder has read data from,
1853 // and add amount of bytes read after the beginning of that packet
1854 // divided by input bps. This will be inaccurate if the input/output
1855 // ratio is not constant for every audio packet or if it is constant
1856 // but not accurately known in sh_audio->i_bps.
1858 a_pts = d_audio->pts;
1859 if (a_pts == MP_NOPTS_VALUE)
1860 return a_pts;
1862 // ds_tell_pts returns bytes read after last timestamp from
1863 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1864 // it has read but not decoded
1865 if (sh_audio->i_bps)
1866 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1867 (double)sh_audio->i_bps;
1869 // Now a_pts hopefully holds the pts for end of audio from decoder.
1870 // Substract data in buffers between decoder and audio out.
1872 // Decoded but not filtered
1873 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1875 // Data buffered in audio filters, measured in bytes of "missing" output
1876 double buffered_output = af_calc_delay(sh_audio->afilter);
1878 // Data that was ready for ao but was buffered because ao didn't fully
1879 // accept everything to internal buffers yet
1880 buffered_output += mpctx->ao->buffer.len;
1882 // Filters divide audio length by playback_speed, so multiply by it
1883 // to get the length in original units without speedup or slowdown
1884 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1886 return a_pts + mpctx->video_offset;
1889 // Return pts value corresponding to currently playing audio.
1890 double playing_audio_pts(struct MPContext *mpctx)
1892 double pts = written_audio_pts(mpctx);
1893 if (pts == MP_NOPTS_VALUE)
1894 return pts;
1895 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1898 static bool is_av_sub(int type)
1900 return type == 'b' || type == 'p' || type == 'x';
1903 void update_subtitles(struct MPContext *mpctx, double refpts,
1904 double sub_offset, bool reset)
1906 struct MPOpts *opts = &mpctx->opts;
1907 struct sh_video *sh_video = mpctx->sh_video;
1908 struct demux_stream *d_sub = mpctx->d_sub;
1909 double curpts = refpts + sub_delay;
1910 unsigned char *packet = NULL;
1911 int len;
1912 struct sh_sub *sh_sub = d_sub->sh;
1913 int type = sh_sub ? sh_sub->type : 'v';
1914 static subtitle subs;
1915 if (reset) {
1916 if (sh_sub)
1917 sub_reset(sh_sub, mpctx->osd);
1918 sub_clear_text(&subs, MP_NOPTS_VALUE);
1919 if (vo_sub)
1920 set_osd_subtitle(mpctx, NULL);
1921 if (vo_spudec) {
1922 spudec_reset(vo_spudec);
1923 vo_osd_changed(OSDTYPE_SPU);
1925 if (is_av_sub(type))
1926 reset_avsub(sh_sub);
1927 return;
1929 // find sub
1930 if (mpctx->subdata) {
1931 if (sub_fps == 0)
1932 sub_fps = sh_video ? sh_video->fps : 25;
1933 current_module = "find_sub";
1934 find_sub(mpctx, mpctx->subdata, curpts *
1935 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1936 if (vo_sub)
1937 mpctx->vo_sub_last = vo_sub;
1940 // DVD sub:
1941 if (vobsub_id >= 0 || type == 'v') {
1942 int timestamp;
1943 current_module = "spudec";
1944 /* Get a sub packet from the DVD or a vobsub */
1945 while (1) {
1946 // Vobsub
1947 len = 0;
1948 if (vo_vobsub) {
1949 if (curpts >= 0) {
1950 len = vobsub_get_packet(vo_vobsub, curpts,
1951 (void **)&packet, &timestamp);
1952 if (len > 0)
1953 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1954 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1955 len, refpts, sh_video->timer,
1956 timestamp / 90000.0, timestamp);
1958 } else {
1959 // DVD sub
1960 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1961 if (len > 0) {
1962 // XXX This is wrong, sh_video->pts can be arbitrarily
1963 // much behind demuxing position. Unfortunately using
1964 // d_video->pts which would have been the simplest
1965 // improvement doesn't work because mpeg specific hacks
1966 // in video.c set d_video->pts to 0.
1967 float x = d_sub->pts - refpts;
1968 if (x > -20 && x < 20) // prevent missing subs on pts reset
1969 timestamp = 90000 * d_sub->pts;
1970 else
1971 timestamp = 90000 * curpts;
1972 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1973 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1974 refpts, d_sub->pts, timestamp);
1977 if (len <= 0 || !packet)
1978 break;
1979 // create it only here, since with some broken demuxers we might
1980 // type = v but no DVD sub and we currently do not change the
1981 // "original frame size" ever after init, leading to wrong-sized
1982 // PGS subtitles.
1983 if (!vo_spudec)
1984 vo_spudec = spudec_new(NULL);
1985 if (vo_vobsub || timestamp >= 0)
1986 spudec_assemble(vo_spudec, packet, len, timestamp);
1988 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1989 if (type == 'd' && !d_sub->demuxer->teletext) {
1990 tt_stream_props tsp = { 0 };
1991 void *ptr = &tsp;
1992 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
1993 VBI_CONTROL_TRUE)
1994 d_sub->demuxer->teletext = ptr;
1996 if (d_sub->non_interleaved)
1997 ds_get_next_pts(d_sub);
1999 while (d_sub->first) {
2000 double subpts = ds_get_next_pts(d_sub) + sub_offset;
2001 if (subpts > curpts) {
2002 // Libass handled subs can be fed to it in advance
2003 if (!opts->ass_enabled || !is_text_sub(type))
2004 break;
2005 // Try to avoid demuxing whole file at once
2006 if (d_sub->non_interleaved && subpts > curpts + 1)
2007 break;
2009 double duration = d_sub->first->duration;
2010 len = ds_get_packet_sub(d_sub, &packet);
2011 if (is_av_sub(type)) {
2012 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2013 if (ret < 0)
2014 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2015 "subtitle\n");
2016 continue;
2018 if (type == 'm') {
2019 if (len < 2)
2020 continue;
2021 len = FFMIN(len - 2, AV_RB16(packet));
2022 packet += 2;
2024 if (type == 'd') {
2025 if (d_sub->demuxer->teletext) {
2026 uint8_t *p = packet;
2027 p++;
2028 len--;
2029 while (len >= 46) {
2030 int sublen = p[1];
2031 if (p[0] == 2 || p[0] == 3)
2032 teletext_control(d_sub->demuxer->teletext,
2033 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2034 p += sublen + 2;
2035 len -= sublen + 2;
2038 continue;
2040 if (sh_sub && sh_sub->active) {
2041 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2042 continue;
2044 if (subpts != MP_NOPTS_VALUE) {
2045 if (duration < 0)
2046 sub_clear_text(&subs, MP_NOPTS_VALUE);
2047 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2048 int i;
2049 unsigned char *p = packet;
2050 for (i = 0; i < 8 && *p != '\0'; p++)
2051 if (*p == ',')
2052 i++;
2053 if (*p == '\0') /* Broken line? */
2054 continue;
2055 len -= p - packet;
2056 packet = p;
2058 double endpts = MP_NOPTS_VALUE;
2059 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2060 endpts = subpts + duration;
2061 sub_add_text(&subs, packet, len, endpts);
2062 set_osd_subtitle(mpctx, &subs);
2064 if (d_sub->non_interleaved)
2065 ds_get_next_pts(d_sub);
2067 if (!opts->ass_enabled)
2068 if (sub_clear_text(&subs, curpts))
2069 set_osd_subtitle(mpctx, &subs);
2071 if (vo_spudec) {
2072 spudec_heartbeat(vo_spudec, 90000 * curpts);
2073 if (spudec_changed(vo_spudec))
2074 vo_osd_changed(OSDTYPE_SPU);
2077 current_module = NULL;
2080 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2082 int page_changed;
2084 if (!demuxer->teletext)
2085 return;
2087 //Also forcing page update when such ioctl is not supported or call error occured
2088 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2089 &page_changed) != VBI_CONTROL_TRUE)
2090 page_changed = 1;
2092 if (!page_changed)
2093 return;
2095 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2096 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2097 vo_osd_teletext_page = NULL;
2098 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2099 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2100 vo_osd_teletext_half = 0;
2101 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2102 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2103 vo_osd_teletext_mode = 0;
2104 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2105 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2106 vo_osd_teletext_format = 0;
2107 vo_osd_changed(OSDTYPE_TELETEXT);
2109 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2112 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2114 struct MPOpts *opts = &mpctx->opts;
2115 // check for frame-drop:
2116 current_module = "check_framedrop";
2117 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2118 static int dropped_frames;
2119 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2120 float d = delay - mpctx->delay;
2121 ++total_frame_cnt;
2122 // we should avoid dropping too many frames in sequence unless we
2123 // are too late. and we allow 100ms A-V delay here:
2124 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2125 && !mpctx->restart_playback) {
2126 ++drop_frame_cnt;
2127 ++dropped_frames;
2128 return frame_dropping;
2129 } else
2130 dropped_frames = 0;
2132 return 0;
2136 #ifdef HAVE_RTC
2137 int rtc_fd = -1;
2138 #endif
2140 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2142 #ifdef HAVE_RTC
2143 if (rtc_fd >= 0) {
2144 // -------- RTC -----------
2145 current_module = "sleep_rtc";
2146 while (time_frame > 0.000) {
2147 unsigned long rtc_ts;
2148 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2149 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2150 "Linux RTC read error: %s\n", strerror(errno));
2151 time_frame -= get_relative_time(mpctx);
2153 } else
2154 #endif
2156 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2157 // unnecessarily high CPU usage
2158 struct MPOpts *opts = &mpctx->opts;
2159 float margin = opts->softsleep ? 0.011 : 0;
2160 current_module = "sleep_timer";
2161 while (time_frame > margin) {
2162 usec_sleep(1000000 * (time_frame - margin));
2163 time_frame -= get_relative_time(mpctx);
2165 if (opts->softsleep) {
2166 current_module = "sleep_soft";
2167 if (time_frame < 0)
2168 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2169 "Warning! Softsleep underflow!\n");
2170 while (time_frame > 0)
2171 time_frame -= get_relative_time(mpctx); // burn the CPU
2174 return time_frame;
2177 static int select_subtitle(MPContext *mpctx)
2179 struct MPOpts *opts = &mpctx->opts;
2180 // find the best sub to use
2181 int id;
2182 int found = 0;
2183 mpctx->global_sub_pos = -1; // no subs by default
2184 if (vobsub_id >= 0) {
2185 // if user asks for a vobsub id, use that first.
2186 id = vobsub_id;
2187 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2188 M_PROPERTY_OK;
2191 if (!found && opts->sub_id >= 0) {
2192 // if user asks for a dvd sub id, use that next.
2193 id = opts->sub_id;
2194 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2195 M_PROPERTY_OK;
2198 if (!found) {
2199 // if there are text subs to use, use those. (autosubs come last here)
2200 id = 0;
2201 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2202 M_PROPERTY_OK;
2205 if (!found && opts->sub_id == -1) {
2206 // finally select subs by language and container hints
2207 if (opts->sub_id == -1)
2208 opts->sub_id =
2209 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2210 opts->sub_lang);
2211 if (opts->sub_id >= 0) {
2212 id = opts->sub_id;
2213 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2214 M_PROPERTY_OK;
2217 return found;
2220 #ifdef CONFIG_DVDNAV
2221 #ifndef FF_B_TYPE
2222 #define FF_B_TYPE 3
2223 #endif
2224 /// store decoded video image
2225 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2226 mp_image_t *from_mpi)
2228 mp_image_t *mpi;
2230 /// Do not store B-frames
2231 if (from_mpi->pict_type == FF_B_TYPE)
2232 return to_mpi;
2234 if (to_mpi &&
2235 to_mpi->w == from_mpi->w &&
2236 to_mpi->h == from_mpi->h &&
2237 to_mpi->imgfmt == from_mpi->imgfmt)
2238 mpi = to_mpi;
2239 else {
2240 if (to_mpi)
2241 free_mp_image(to_mpi);
2242 if (from_mpi->w == 0 || from_mpi->h == 0)
2243 return NULL;
2244 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2247 copy_mpi(mpi, from_mpi);
2248 return mpi;
2251 static void mp_dvdnav_reset_stream(MPContext *ctx)
2253 struct MPOpts *opts = &ctx->opts;
2254 if (ctx->sh_video) {
2255 /// clear video pts
2256 ctx->d_video->pts = 0.0f;
2257 ctx->sh_video->pts = 0.0f;
2258 ctx->sh_video->i_pts = 0.0f;
2259 ctx->sh_video->last_pts = 0.0f;
2260 ctx->sh_video->num_buffered_pts = 0;
2261 ctx->sh_video->num_frames = 0;
2262 ctx->sh_video->num_frames_decoded = 0;
2263 ctx->sh_video->timer = 0.0f;
2264 ctx->sh_video->stream_delay = 0.0f;
2265 ctx->sh_video->timer = 0;
2266 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2269 if (ctx->sh_audio) {
2270 /// free audio packets and reset
2271 ds_free_packs(ctx->d_audio);
2272 audio_delay -= ctx->sh_audio->stream_delay;
2273 ctx->delay = -audio_delay;
2274 ao_reset(ctx->ao);
2275 resync_audio_stream(ctx->sh_audio);
2278 audio_delay = 0.0f;
2279 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2280 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2281 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2282 if (dvdsub_lang_id != opts->sub_id) {
2283 opts->sub_id = dvdsub_lang_id;
2284 select_subtitle(ctx);
2288 /// clear all EOF related flags
2289 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2292 /// Restore last decoded DVDNAV (still frame)
2293 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2294 int *in_size,
2295 unsigned char **start,
2296 mp_image_t *decoded_frame)
2298 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2299 return decoded_frame;
2301 /// a change occurred in dvdnav stream
2302 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2303 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2304 mp_dvdnav_context_free(mpctx);
2305 mp_dvdnav_reset_stream(mpctx);
2306 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2307 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2310 if (*in_size < 0) {
2311 float len;
2313 /// Display still frame, if any
2314 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2315 decoded_frame = mpctx->nav_smpi;
2317 /// increment video frame : continue playing after still frame
2318 len = get_time_length(mpctx);
2319 if (mpctx->sh_video->pts >= len &&
2320 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2321 mp_dvdnav_skip_still(mpctx->stream);
2322 mp_dvdnav_skip_wait(mpctx->stream);
2324 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2326 if (mpctx->nav_buffer) {
2327 *start = mpctx->nav_start;
2328 *in_size = mpctx->nav_in_size;
2329 if (mpctx->nav_start)
2330 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2334 return decoded_frame;
2337 /// Save last decoded DVDNAV (still frame)
2338 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2339 unsigned char *start,
2340 mp_image_t *decoded_frame)
2342 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2343 return;
2345 free(mpctx->nav_buffer);
2346 mpctx->nav_buffer = NULL;
2347 mpctx->nav_start = NULL;
2348 mpctx->nav_in_size = -1;
2350 if (in_size > 0)
2351 mpctx->nav_buffer = malloc(in_size);
2352 if (mpctx->nav_buffer) {
2353 mpctx->nav_start = start;
2354 mpctx->nav_in_size = in_size;
2355 memcpy(mpctx->nav_buffer, start, in_size);
2358 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2359 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2361 #endif /* CONFIG_DVDNAV */
2363 /* Modify video timing to match the audio timeline. There are two main
2364 * reasons this is needed. First, video and audio can start from different
2365 * positions at beginning of file or after a seek (MPlayer starts both
2366 * immediately even if they have different pts). Second, the file can have
2367 * audio timestamps that are inconsistent with the duration of the audio
2368 * packets, for example two consecutive timestamp values differing by
2369 * one second but only a packet with enough samples for half a second
2370 * of playback between them.
2372 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2374 current_module = "av_sync";
2376 if (!mpctx->sh_audio || mpctx->syncing_audio)
2377 return;
2379 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2380 double v_pts = mpctx->sh_video->pts;
2381 double av_delay = a_pts - v_pts;
2382 // Try to sync vo_flip() so it will *finish* at given time
2383 av_delay += mpctx->last_vo_flip_duration;
2384 av_delay -= audio_delay; // This much pts difference is desired
2386 double change = av_delay * 0.1;
2387 double max_change = default_max_pts_correction >= 0 ?
2388 default_max_pts_correction : frame_time * 0.1;
2389 if (change < -max_change)
2390 change = -max_change;
2391 else if (change > max_change)
2392 change = max_change;
2393 mpctx->delay += change;
2394 mpctx->total_avsync_change += change;
2397 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2398 double pts)
2400 if (mpctx->paused)
2401 return 0;
2402 struct ao *ao = mpctx->ao;
2403 double bps = ao->bps / mpctx->opts.playback_speed;
2404 ao->pts = pts;
2405 // hack used by some mpeg-writing AOs
2406 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2407 mpctx->delay) * 90000.0;
2408 int played = ao_play(mpctx->ao, data, len, flags);
2409 if (played > 0) {
2410 mpctx->delay += played / bps;
2411 // Keep correct pts for remaining data - could be used to flush
2412 // remaining buffer when closing ao.
2413 ao->pts += played / bps;
2415 return played;
2418 #define ASYNC_PLAY_DONE -3
2419 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2421 struct ao *ao = mpctx->ao;
2422 struct MPOpts *opts = &mpctx->opts;
2423 sh_audio_t * const sh_audio = mpctx->sh_audio;
2424 int res;
2426 // Timing info may not be set without
2427 res = decode_audio(sh_audio, &ao->buffer, 1);
2428 if (res < 0)
2429 return res;
2431 int bytes;
2432 bool did_retry = false;
2433 double written_pts;
2434 double bps = ao->bps / opts->playback_speed;
2435 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2436 mpctx->hrseek_active = false;
2437 while (1) {
2438 written_pts = written_audio_pts(mpctx);
2439 double ptsdiff;
2440 if (hrseek)
2441 ptsdiff = written_pts - mpctx->hrseek_pts;
2442 else
2443 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2444 - audio_delay;
2445 bytes = ptsdiff * bps;
2446 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2448 // ogg demuxers give packets without timing
2449 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2450 if (!did_retry) {
2451 // Try to read more data to see packets that have pts
2452 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2453 if (res < 0)
2454 return res;
2455 did_retry = true;
2456 continue;
2458 bytes = 0;
2461 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2462 bytes = 0;
2464 if (bytes > 0)
2465 break;
2467 mpctx->syncing_audio = false;
2468 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2469 int res = decode_audio(sh_audio, &ao->buffer, a);
2470 bytes += ao->buffer.len;
2471 if (bytes >= 0) {
2472 memmove(ao->buffer.start,
2473 ao->buffer.start + ao->buffer.len - bytes, bytes);
2474 ao->buffer.len = bytes;
2475 if (res < 0)
2476 return res;
2477 return decode_audio(sh_audio, &ao->buffer, playsize);
2479 ao->buffer.len = 0;
2480 if (res < 0)
2481 return res;
2483 if (hrseek)
2484 // Don't add silence in audio-only case even if position is too late
2485 return 0;
2486 int fillbyte = 0;
2487 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2488 fillbyte = 0x80;
2489 if (bytes >= playsize) {
2490 /* This case could fall back to the one below with
2491 * bytes = playsize, but then silence would keep accumulating
2492 * in a_out_buffer if the AO accepts less data than it asks for
2493 * in playsize. */
2494 char *p = malloc(playsize);
2495 memset(p, fillbyte, playsize);
2496 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2497 free(p);
2498 return ASYNC_PLAY_DONE;
2500 mpctx->syncing_audio = false;
2501 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2502 return decode_audio(sh_audio, &ao->buffer, playsize);
2505 static int fill_audio_out_buffers(struct MPContext *mpctx)
2507 struct MPOpts *opts = &mpctx->opts;
2508 struct ao *ao = mpctx->ao;
2509 unsigned int t;
2510 double tt;
2511 int playsize;
2512 int playflags = 0;
2513 bool audio_eof = false;
2514 bool partial_fill = false;
2515 sh_audio_t * const sh_audio = mpctx->sh_audio;
2516 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2517 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2519 current_module = "play_audio";
2521 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2522 return 0;
2524 // hack used by some mpeg-writing AOs
2525 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2526 mpctx->delay) * 90000.0;
2528 if (mpctx->paused)
2529 playsize = 1; // just initialize things (audio pts at least)
2530 else
2531 playsize = ao_get_space(ao);
2533 // Fill buffer if needed:
2534 current_module = "decode_audio";
2535 t = GetTimer();
2537 // Coming here with hrseek_active still set means audio-only
2538 if (!mpctx->sh_video)
2539 mpctx->syncing_audio = false;
2540 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2541 mpctx->syncing_audio = false;
2542 mpctx->hrseek_active = false;
2545 int res;
2546 if (mpctx->syncing_audio || mpctx->hrseek_active)
2547 res = audio_start_sync(mpctx, playsize);
2548 else
2549 res = decode_audio(sh_audio, &ao->buffer, playsize);
2550 if (res < 0) { // EOF, error or format change
2551 if (res == -2) {
2552 /* The format change isn't handled too gracefully. A more precise
2553 * implementation would require draining buffered old-format audio
2554 * while displaying video, then doing the output format switch.
2556 uninit_player(mpctx, INITIALIZED_AO);
2557 reinit_audio_chain(mpctx);
2558 return -1;
2559 } else if (res == ASYNC_PLAY_DONE)
2560 return 0;
2561 else if (mpctx->d_audio->eof)
2562 audio_eof = true;
2564 t = GetTimer() - t;
2565 tt = t * 0.000001f;
2566 audio_time_usage += tt;
2567 if (mpctx->timeline && modifiable_audio_format) {
2568 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2569 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2570 * ao->bps / opts->playback_speed;
2571 if (playsize > bytes) {
2572 playsize = FFMAX(bytes, 0);
2573 playflags |= AOPLAY_FINAL_CHUNK;
2574 audio_eof = true;
2575 partial_fill = true;
2579 assert(ao->buffer.len % unitsize == 0);
2580 if (playsize > ao->buffer.len) {
2581 partial_fill = true;
2582 playsize = ao->buffer.len;
2583 if (audio_eof)
2584 playflags |= AOPLAY_FINAL_CHUNK;
2586 playsize -= playsize % unitsize;
2587 if (!playsize)
2588 return partial_fill && audio_eof ? -2 : -partial_fill;
2590 // play audio:
2591 current_module = "play_audio";
2593 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2594 written_audio_pts(mpctx));
2595 assert(played % unitsize == 0);
2596 ao->buffer_playable_size = playsize - played;
2598 if (played > 0) {
2599 ao->buffer.len -= played;
2600 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2601 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2602 // Sanity check to avoid hanging in case current ao doesn't output
2603 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2604 return -2;
2607 return -partial_fill;
2610 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2611 bool sync_to_audio, float *aq_sleep_time)
2613 struct MPOpts *opts = &mpctx->opts;
2614 double audio_limit = 2;
2615 current_module = "calc_sleep_time";
2617 if (mpctx->restart_playback)
2618 return 0;
2620 *time_frame -= get_relative_time(mpctx); // reset timer
2622 if (sync_to_audio) {
2623 float delay = ao_get_delay(mpctx->ao);
2624 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2626 if (opts->autosync) {
2628 * Adjust this raw delay value by calculating the expected
2629 * delay for this frame and generating a new value which is
2630 * weighted between the two. The higher autosync is, the
2631 * closer to the delay value gets to that which "-nosound"
2632 * would have used, and the longer it will take for A/V
2633 * sync to settle at the right value (but it eventually will.)
2634 * This settling time is very short for values below 100.
2636 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2637 float difference = delay - predicted;
2638 delay = predicted + difference / (float)opts->autosync;
2641 *time_frame = delay - mpctx->delay / opts->playback_speed;
2643 // delay = amount of audio buffered in soundcard/driver
2644 delay = FFMIN(delay, 0.5);
2645 delay = FFMAX(delay, 0.1);
2646 audio_limit = delay;
2647 } else {
2648 // If we're lagging more than 200 ms behind the right playback rate,
2649 // don't try to "catch up".
2650 // If benchmark is set always output frames as fast as possible
2651 // without sleeping.
2652 if (*time_frame < -0.2 || opts->benchmark)
2653 *time_frame = 0;
2656 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2658 if (t <= 0.05)
2659 return 0;
2661 t -= 0.05;
2662 if (t > audio_limit * 0.6)
2663 t = audio_limit * 0.5;
2664 *aq_sleep_time += t;
2665 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2666 return 1;
2669 int reinit_video_chain(struct MPContext *mpctx)
2671 struct MPOpts *opts = &mpctx->opts;
2672 sh_video_t * const sh_video = mpctx->sh_video;
2673 if (!sh_video)
2674 return 0;
2675 double ar = -1.0;
2676 //================== Init VIDEO (codec & libvo) ==========================
2677 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2678 current_module = "preinit_libvo";
2680 //shouldn't we set dvideo->id=-2 when we fail?
2681 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2682 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2683 mpctx->key_fifo,
2684 mpctx->input))) {
2685 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2686 "the selected video_out (-vo) device.\n");
2687 goto err_out;
2689 mpctx->initialized_flags |= INITIALIZED_VO;
2692 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2693 &ar) != STREAM_UNSUPPORTED)
2694 mpctx->sh_video->stream_aspect = ar;
2695 current_module = "init_video_filters";
2697 char *vf_arg[] = {
2698 "_oldargs_", (char *)mpctx->video_out, NULL
2700 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2703 #ifdef CONFIG_ASS
2704 if (opts->ass_enabled) {
2705 int i;
2706 int insert = 1;
2707 if (opts->vf_settings)
2708 for (i = 0; opts->vf_settings[i].name; ++i)
2709 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2710 insert = 0;
2711 break;
2713 if (insert) {
2714 extern vf_info_t vf_info_ass;
2715 const vf_info_t *libass_vfs[] = {
2716 &vf_info_ass, NULL
2718 char *vf_arg[] = {
2719 "auto", "1", NULL
2721 int retcode = 0;
2722 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2723 sh_video->vfilter,
2724 "ass", vf_arg,
2725 &retcode);
2726 if (vf_ass)
2727 sh_video->vfilter = vf_ass;
2728 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2729 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2730 else
2731 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2732 "ASS: cannot add video filter\n");
2735 #endif
2737 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2739 #ifdef CONFIG_ASS
2740 if (opts->ass_enabled)
2741 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2742 mpctx->ass_library);
2743 #endif
2745 current_module = "init_video_codec";
2747 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2748 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2749 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2751 if (!sh_video->initialized) {
2752 if (!opts->fixed_vo)
2753 uninit_player(mpctx, INITIALIZED_VO);
2754 goto err_out;
2757 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2759 if (sh_video->codec)
2760 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2761 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2763 sh_video->last_pts = MP_NOPTS_VALUE;
2764 sh_video->num_buffered_pts = 0;
2765 sh_video->next_frame_time = 0;
2767 if (opts->auto_quality > 0) {
2768 // Auto quality option enabled
2769 output_quality = get_video_quality_max(sh_video);
2770 if (opts->auto_quality > output_quality)
2771 opts->auto_quality = output_quality;
2772 else
2773 output_quality = opts->auto_quality;
2774 mp_msg(MSGT_CPLAYER, MSGL_V,
2775 "AutoQ: setting quality to %d.\n", output_quality);
2776 set_video_quality(sh_video, output_quality);
2779 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2781 current_module = "init_vo";
2783 return 1;
2785 err_out:
2786 mpctx->sh_video = mpctx->d_video->sh = NULL;
2787 return 0;
2790 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2792 struct sh_video *sh_video = mpctx->sh_video;
2793 double frame_time = 0;
2794 struct vo *video_out = mpctx->video_out;
2795 while (1) {
2796 current_module = "filter_video";
2797 // In nocorrect-pts mode there is no way to properly time these frames
2798 if (vo_get_buffered_frame(video_out, 0) >= 0)
2799 break;
2800 if (vf_output_queued_frame(sh_video->vfilter))
2801 break;
2802 unsigned char *packet = NULL;
2803 frame_time = sh_video->next_frame_time;
2804 if (mpctx->restart_playback)
2805 frame_time = 0;
2806 int in_size = 0;
2807 while (!in_size)
2808 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2809 &packet, force_fps);
2810 if (in_size < 0) {
2811 #ifdef CONFIG_DVDNAV
2812 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2813 if (mp_dvdnav_is_eof(mpctx->stream))
2814 return -1;
2815 if (mpctx->d_video)
2816 mpctx->d_video->eof = 0;
2817 if (mpctx->d_audio)
2818 mpctx->d_audio->eof = 0;
2819 mpctx->stream->eof = 0;
2820 } else
2821 #endif
2822 return -1;
2824 if (in_size > max_framesize)
2825 max_framesize = in_size;
2826 sh_video->timer += frame_time;
2827 if (mpctx->sh_audio)
2828 mpctx->delay -= frame_time;
2829 // video_read_frame can change fps (e.g. for ASF video)
2830 vo_fps = sh_video->fps;
2831 int framedrop_type = check_framedrop(mpctx, frame_time);
2832 current_module = "decode video";
2834 void *decoded_frame;
2835 #ifdef CONFIG_DVDNAV
2836 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2837 if (in_size >= 0 && !decoded_frame)
2838 #endif
2839 decoded_frame = decode_video(sh_video, NULL, packet, in_size,
2840 framedrop_type, sh_video->pts);
2841 #ifdef CONFIG_DVDNAV
2842 // Save last still frame for future display
2843 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2844 #endif
2845 if (decoded_frame) {
2846 current_module = "filter video";
2847 filter_video(sh_video, decoded_frame, sh_video->pts);
2849 break;
2851 return frame_time;
2854 static void determine_frame_pts(struct MPContext *mpctx)
2856 struct sh_video *sh_video = mpctx->sh_video;
2857 struct MPOpts *opts = &mpctx->opts;
2859 if (opts->user_pts_assoc_mode)
2860 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2861 else if (sh_video->pts_assoc_mode == 0) {
2862 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2863 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2864 sh_video->pts_assoc_mode = 1;
2865 else
2866 sh_video->pts_assoc_mode = 2;
2867 } else {
2868 int probcount1 = sh_video->num_reordered_pts_problems;
2869 int probcount2 = sh_video->num_sorted_pts_problems;
2870 if (sh_video->pts_assoc_mode == 2) {
2871 int tmp = probcount1;
2872 probcount1 = probcount2;
2873 probcount2 = tmp;
2875 if (probcount1 >= probcount2 * 1.5 + 2) {
2876 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2877 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2878 "%d.\n", sh_video->pts_assoc_mode);
2881 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2882 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2885 static double update_video(struct MPContext *mpctx)
2887 struct sh_video *sh_video = mpctx->sh_video;
2888 struct vo *video_out = mpctx->video_out;
2889 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2890 mpctx->osd); // hack for vf_expand
2891 if (!mpctx->opts.correct_pts)
2892 return update_video_nocorrect_pts(mpctx);
2894 double pts;
2896 while (1) {
2897 current_module = "filter_video";
2898 if (vo_get_buffered_frame(video_out, false) >= 0)
2899 break;
2900 // XXX Time used in this call is not counted in any performance
2901 // timer now
2902 if (vf_output_queued_frame(sh_video->vfilter))
2903 break;
2904 int in_size = 0;
2905 unsigned char *buf = NULL;
2906 pts = MP_NOPTS_VALUE;
2907 struct demux_packet *pkt;
2908 while (1) {
2909 pkt = ds_get_packet2(mpctx->d_video, false);
2910 if (!pkt || pkt->len)
2911 break;
2912 /* Packets with size 0 are assumed to not correspond to frames,
2913 * but to indicate the absence of a frame in formats like AVI
2914 * that must have packets at fixed timecode intervals. */
2916 if (pkt) {
2917 in_size = pkt->len;
2918 buf = pkt->buffer;
2919 pts = pkt->pts;
2921 if (pts != MP_NOPTS_VALUE)
2922 pts += mpctx->video_offset;
2923 if (in_size > max_framesize)
2924 max_framesize = in_size;
2925 current_module = "decode video";
2926 if (pts >= mpctx->hrseek_pts - .005)
2927 mpctx->hrseek_framedrop = false;
2928 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2929 check_framedrop(mpctx, sh_video->frametime);
2930 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2931 framedrop_type, pts);
2932 if (decoded_frame) {
2933 determine_frame_pts(mpctx);
2934 current_module = "filter video";
2935 filter_video(sh_video, decoded_frame, sh_video->pts);
2936 } else if (!pkt) {
2937 if (vo_get_buffered_frame(video_out, true) < 0)
2938 return -1;
2940 break;
2943 if (!video_out->frame_loaded)
2944 return 0;
2946 pts = video_out->next_pts;
2947 if (pts == MP_NOPTS_VALUE) {
2948 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2949 // Try to use decoder pts from before filters
2950 pts = sh_video->pts;
2951 if (pts == MP_NOPTS_VALUE)
2952 pts = sh_video->last_pts;
2954 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2955 vo_skip_frame(video_out);
2956 return 0;
2958 mpctx->hrseek_active = false;
2959 sh_video->pts = pts;
2960 if (sh_video->last_pts == MP_NOPTS_VALUE)
2961 sh_video->last_pts = sh_video->pts;
2962 else if (sh_video->last_pts > sh_video->pts) {
2963 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2964 sh_video->pts, sh_video->last_pts);
2965 /* If the difference in pts is small treat it as jitter around the
2966 * right value (possibly caused by incorrect timestamp ordering) and
2967 * just show this frame immediately after the last one.
2968 * Treat bigger differences as timestamp resets and start counting
2969 * timing of later frames from the position of this one. */
2970 if (sh_video->last_pts - sh_video->pts > 0.5)
2971 sh_video->last_pts = sh_video->pts;
2972 else
2973 sh_video->pts = sh_video->last_pts;
2975 double frame_time = sh_video->pts - sh_video->last_pts;
2976 sh_video->last_pts = sh_video->pts;
2977 sh_video->timer += frame_time;
2978 if (mpctx->sh_audio)
2979 mpctx->delay -= frame_time;
2980 return frame_time;
2983 static int get_cache_fill(struct MPContext *mpctx)
2985 #ifdef CONFIG_STREAM_CACHE
2986 if (stream_cache_size > 0)
2987 return cache_fill_status(mpctx->stream);
2988 #endif
2989 return -1;
2992 static void update_pause_message(struct MPContext *mpctx)
2994 struct MPOpts *opts = &mpctx->opts;
2996 if (opts->quiet)
2997 return;
2999 int cache_fill = get_cache_fill(mpctx);
3000 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
3002 if (!mpctx->status_printed && !cache_changed)
3003 return;
3005 char *msg = mp_gtext(" ===== PAUSE =====");
3006 char *tmpmem = NULL;
3007 if (cache_fill >= 0)
3008 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
3010 if (opts->term_osd && !mpctx->sh_video) {
3011 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
3012 update_osd_msg(mpctx);
3013 } else {
3014 if (mpctx->status_printed)
3015 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
3016 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
3019 mpctx->paused_cache_fill = cache_fill;
3020 mpctx->status_printed = false;
3022 talloc_free(tmpmem);
3025 void pause_player(struct MPContext *mpctx)
3027 if (mpctx->paused)
3028 return;
3029 mpctx->paused = 1;
3030 mpctx->step_frames = 0;
3031 mpctx->time_frame -= get_relative_time(mpctx);
3032 mpctx->osd_function = OSD_PAUSE;
3034 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3035 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3037 if (mpctx->ao && mpctx->sh_audio)
3038 ao_pause(mpctx->ao); // pause audio, keep data if possible
3040 mpctx->paused_cache_fill = get_cache_fill(mpctx);
3041 mpctx->status_printed = true;
3042 update_pause_message(mpctx);
3044 if (!mpctx->opts.quiet)
3045 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
3048 void unpause_player(struct MPContext *mpctx)
3050 if (!mpctx->paused)
3051 return;
3052 mpctx->paused = 0;
3053 if (!mpctx->step_frames)
3054 mpctx->osd_function = OSD_PLAY;
3056 if (mpctx->ao && mpctx->sh_audio)
3057 ao_resume(mpctx->ao);
3058 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3059 && !mpctx->step_frames)
3060 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3061 (void)get_relative_time(mpctx); // ignore time that passed during pause
3064 static int redraw_osd(struct MPContext *mpctx)
3066 struct sh_video *sh_video = mpctx->sh_video;
3067 struct vf_instance *vf = sh_video->vfilter;
3068 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3069 return -1;
3070 if (vo_redraw_frame(mpctx->video_out) < 0)
3071 return -1;
3072 mpctx->osd->pts = mpctx->video_pts;
3073 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3074 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3075 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3076 vo_flip_page(mpctx->video_out, 0, -1);
3077 return 0;
3080 void add_step_frame(struct MPContext *mpctx)
3082 mpctx->step_frames++;
3083 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3084 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3085 unpause_player(mpctx);
3088 static void pause_loop(struct MPContext *mpctx)
3090 mp_cmd_t *cmd;
3092 update_pause_message(mpctx);
3094 while ((cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
3095 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
3096 if (cmd) {
3097 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3098 run_command(mpctx, cmd);
3099 mp_cmd_free(cmd);
3100 continue;
3102 if (mpctx->sh_video && mpctx->video_out)
3103 vo_check_events(mpctx->video_out);
3104 update_osd_msg(mpctx);
3105 int hack = vo_osd_changed(0);
3106 vo_osd_changed(hack);
3107 if (hack || mpctx->sh_video && mpctx->video_out->want_redraw)
3108 break;
3109 update_pause_message(mpctx);
3114 // Find the right mute status and record position for new file position
3115 static void edl_seek_reset(MPContext *mpctx)
3117 mpctx->edl_muted = 0;
3118 next_edl_record = edl_records;
3120 while (next_edl_record) {
3121 if (next_edl_record->start_sec >= get_current_time(mpctx))
3122 break;
3124 if (next_edl_record->action == EDL_MUTE)
3125 mpctx->edl_muted = !mpctx->edl_muted;
3126 next_edl_record = next_edl_record->next;
3128 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3129 mixer_mute(&mpctx->mixer);
3133 // Execute EDL command for the current position if one exists
3134 static void edl_update(MPContext *mpctx)
3136 if (!next_edl_record)
3137 return;
3139 if (!mpctx->sh_video) {
3140 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
3141 "Cannot use EDL without video, disabling.\n");
3142 free_edl(edl_records);
3143 next_edl_record = NULL;
3144 edl_records = NULL;
3145 return;
3148 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3149 if (next_edl_record->action == EDL_SKIP) {
3150 mpctx->osd_function = OSD_FFW;
3151 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3152 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3153 "[%f], length [%f]\n", next_edl_record->start_sec,
3154 next_edl_record->stop_sec, next_edl_record->length_sec);
3155 } else if (next_edl_record->action == EDL_MUTE) {
3156 mpctx->edl_muted = !mpctx->edl_muted;
3157 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3158 mixer_mute(&mpctx->mixer);
3159 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3160 next_edl_record->start_sec);
3162 next_edl_record = next_edl_record->next;
3166 static void reinit_decoders(struct MPContext *mpctx)
3168 reinit_video_chain(mpctx);
3169 reinit_audio_chain(mpctx);
3170 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3173 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3175 if (mpctx->sh_video) {
3176 current_module = "seek_video_reset";
3177 resync_video_stream(mpctx->sh_video);
3178 mpctx->sh_video->timer = 0;
3179 vo_seek_reset(mpctx->video_out);
3180 mpctx->sh_video->timer = 0;
3181 mpctx->sh_video->num_buffered_pts = 0;
3182 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3183 mpctx->delay = 0;
3184 mpctx->time_frame = 0;
3185 mpctx->restart_playback = true;
3186 // Not all demuxers set d_video->pts during seek, so this value
3187 // (which is used by at least vobsub and edl code below) may
3188 // be completely wrong (probably 0).
3189 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3190 mpctx->video_pts = mpctx->sh_video->pts;
3191 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3192 true);
3193 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3196 if (mpctx->sh_audio) {
3197 current_module = "seek_audio_reset";
3198 resync_audio_stream(mpctx->sh_audio);
3199 if (reset_ao)
3200 ao_reset(mpctx->ao);
3201 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3202 mpctx->sh_audio->a_buffer_len = 0;
3203 if (!mpctx->sh_video)
3204 update_subtitles(mpctx, mpctx->sh_audio->pts,
3205 mpctx->video_offset, true);
3208 if (vo_vobsub && mpctx->sh_video) {
3209 current_module = "seek_vobsub_reset";
3210 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3213 edl_seek_reset(mpctx);
3215 mpctx->hrseek_active = false;
3216 mpctx->hrseek_framedrop = false;
3217 mpctx->total_avsync_change = 0;
3218 audio_time_usage = 0;
3219 video_time_usage = 0;
3220 vout_time_usage = 0;
3221 drop_frame_cnt = 0;
3223 current_module = NULL;
3226 static bool timeline_set_part(struct MPContext *mpctx, int i)
3228 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3229 struct timeline_part *n = mpctx->timeline + i;
3230 mpctx->timeline_part = i;
3231 mpctx->video_offset = n->start - n->source_start;
3232 if (n->source == p->source)
3233 return false;
3234 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3235 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3236 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3237 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3238 mpctx->stop_play = orig_stop_play;
3239 mpctx->demuxer = n->source->demuxer;
3240 mpctx->d_video = mpctx->demuxer->video;
3241 mpctx->d_audio = mpctx->demuxer->audio;
3242 mpctx->d_sub = mpctx->demuxer->sub;
3243 mpctx->sh_video = mpctx->d_video->sh;
3244 mpctx->sh_audio = mpctx->d_audio->sh;
3245 return true;
3248 // Given pts, switch playback to the corresponding part.
3249 // Return offset within that part.
3250 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3251 bool *need_reset)
3253 if (pts < 0)
3254 pts = 0;
3255 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3256 struct timeline_part *p = mpctx->timeline + i;
3257 if (pts < (p + 1)->start) {
3258 *need_reset = timeline_set_part(mpctx, i);
3259 return pts - p->start + p->source_start;
3262 return -1;
3266 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3267 static int seek(MPContext *mpctx, struct seek_params seek,
3268 bool timeline_fallthrough)
3270 struct MPOpts *opts = &mpctx->opts;
3272 current_module = "seek";
3273 if (mpctx->stop_play == AT_END_OF_FILE)
3274 mpctx->stop_play = KEEP_PLAYING;
3275 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3276 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3277 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3278 || opts->hr_seek > 0 || seek.exact > 0;
3279 if (seek.type == MPSEEK_FACTOR
3280 || seek.type == MPSEEK_ABSOLUTE
3281 && seek.amount < mpctx->last_chapter_pts
3282 || seek.amount < 0)
3283 mpctx->last_chapter_seek = -2;
3284 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3285 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3286 seek.type = MPSEEK_ABSOLUTE;
3288 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3289 && seek.type == MPSEEK_RELATIVE) {
3290 seek.type = MPSEEK_ABSOLUTE;
3291 seek.direction = seek.amount > 0 ? 1 : -1;
3292 seek.amount += get_current_time(mpctx);
3295 /* At least the liba52 decoder wants to read from the input stream
3296 * during initialization, so reinit must be done after the demux_seek()
3297 * call that clears possible stream EOF. */
3298 bool need_reset = false;
3299 double demuxer_amount = seek.amount;
3300 if (mpctx->timeline) {
3301 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3302 &need_reset);
3303 if (demuxer_amount == -1) {
3304 mpctx->stop_play = AT_END_OF_FILE;
3305 // Clear audio from current position
3306 if (mpctx->sh_audio) {
3307 ao_reset(mpctx->ao);
3308 mpctx->sh_audio->a_buffer_len = 0;
3310 return -1;
3313 int demuxer_style = 0;
3314 switch (seek.type) {
3315 case MPSEEK_FACTOR:
3316 demuxer_style |= SEEK_FACTOR; // fallthrough
3317 case MPSEEK_ABSOLUTE:
3318 demuxer_style |= SEEK_ABSOLUTE;
3320 if (hr_seek || seek.direction < 0)
3321 demuxer_style |= SEEK_BACKWARD;
3322 else if (seek.direction > 0)
3323 demuxer_style |= SEEK_FORWARD;
3325 if (hr_seek)
3326 demuxer_amount -= opts->hr_seek_demuxer_offset;
3327 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3328 demuxer_style);
3329 if (need_reset)
3330 reinit_decoders(mpctx);
3331 if (seekresult == 0)
3332 return -1;
3334 seek_reset(mpctx, !timeline_fallthrough);
3336 /* Use the target time as "current position" for further relative
3337 * seeks etc until a new video frame has been decoded */
3338 if (seek.type == MPSEEK_ABSOLUTE) {
3339 mpctx->video_pts = seek.amount;
3340 mpctx->last_seek_pts = seek.amount;
3341 } else
3342 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3344 if (hr_seek) {
3345 mpctx->hrseek_active = true;
3346 mpctx->hrseek_framedrop = true;
3347 mpctx->hrseek_pts = seek.amount;
3350 mpctx->start_timestamp = GetTimerMS();
3352 return 0;
3355 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3356 int exact)
3358 struct seek_params *seek = &mpctx->seek;
3359 switch (type) {
3360 case MPSEEK_RELATIVE:
3361 if (seek->type == MPSEEK_FACTOR)
3362 return; // Well... not common enough to bother doing better
3363 seek->amount += amount;
3364 seek->exact = FFMAX(seek->exact, exact);
3365 if (seek->type == MPSEEK_NONE)
3366 seek->exact = exact;
3367 if (seek->type == MPSEEK_ABSOLUTE)
3368 return;
3369 if (seek->amount == 0) {
3370 *seek = (struct seek_params){ 0 };
3371 return;
3373 seek->type = MPSEEK_RELATIVE;
3374 return;
3375 case MPSEEK_ABSOLUTE:
3376 case MPSEEK_FACTOR:
3377 *seek = (struct seek_params) {
3378 .type = type,
3379 .amount = amount,
3380 .exact = exact,
3382 return;
3383 case MPSEEK_NONE:
3384 *seek = (struct seek_params){ 0 };
3385 return;
3387 abort();
3391 double get_time_length(struct MPContext *mpctx)
3393 if (mpctx->timeline)
3394 return mpctx->timeline[mpctx->num_timeline_parts].start;
3396 struct demuxer *demuxer = mpctx->demuxer;
3397 double get_time_ans;
3398 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3399 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3400 (void *) &get_time_ans) > 0)
3401 return get_time_ans;
3403 struct sh_video *sh_video = mpctx->d_video->sh;
3404 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3405 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3406 return (double) (demuxer->movi_end - demuxer->movi_start) /
3407 (sh_video->i_bps + sh_audio->i_bps);
3408 if (sh_video && sh_video->i_bps)
3409 return (double) (demuxer->movi_end - demuxer->movi_start) /
3410 sh_video->i_bps;
3411 if (sh_audio && sh_audio->i_bps)
3412 return (double) (demuxer->movi_end - demuxer->movi_start) /
3413 sh_audio->i_bps;
3414 return 0;
3417 /* If there are timestamps from stream level then use those (for example
3418 * DVDs can have consistent times there while the MPEG-level timestamps
3419 * reset). */
3420 double get_current_time(struct MPContext *mpctx)
3422 struct demuxer *demuxer = mpctx->demuxer;
3423 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3424 return demuxer->stream_pts;
3425 struct sh_video *sh_video = demuxer->video->sh;
3426 if (sh_video)
3427 return mpctx->video_pts;
3428 double apts = playing_audio_pts(mpctx);
3429 if (apts != MP_NOPTS_VALUE)
3430 return apts;
3431 return mpctx->last_seek_pts;
3434 int get_percent_pos(struct MPContext *mpctx)
3436 struct demuxer *demuxer = mpctx->demuxer;
3437 int ans = 0;
3438 if (mpctx->timeline)
3439 ans = get_current_time(mpctx) * 100 /
3440 mpctx->timeline[mpctx->num_timeline_parts].start;
3441 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3443 else {
3444 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3445 off_t pos = demuxer->filepos > 0 ?
3446 demuxer->filepos : stream_tell(demuxer->stream);
3447 if (len > 0)
3448 ans = (pos - demuxer->movi_start) / len;
3449 else
3450 ans = 0;
3452 if (ans < 0)
3453 ans = 0;
3454 if (ans > 100)
3455 ans = 100;
3456 return ans;
3459 // -2 is no chapters, -1 is before first chapter
3460 int get_current_chapter(struct MPContext *mpctx)
3462 double current_pts = get_current_time(mpctx);
3463 if (!mpctx->chapters)
3464 return FFMAX(mpctx->last_chapter_seek,
3465 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3467 int i;
3468 for (i = 1; i < mpctx->num_chapters; i++)
3469 if (current_pts < mpctx->chapters[i].start)
3470 break;
3471 return FFMAX(mpctx->last_chapter_seek, i - 1);
3474 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3476 char *name = chapter_name(mpctx, chapter);
3477 if (name) {
3478 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3479 } else {
3480 int chapter_count = get_chapter_count(mpctx);
3481 if (chapter_count <= 0)
3482 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3483 else
3484 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3485 chapter_count);
3487 return name;
3490 // returns NULL if chapter name unavailable
3491 char *chapter_name(struct MPContext *mpctx, int chapter)
3493 if (!mpctx->chapters)
3494 return demuxer_chapter_name(mpctx->demuxer, chapter);
3495 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3498 // returns the start of the chapter in seconds
3499 double chapter_start_time(struct MPContext *mpctx, int chapter)
3501 if (!mpctx->chapters)
3502 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3503 return mpctx->chapters[chapter].start;
3506 int get_chapter_count(struct MPContext *mpctx)
3508 if (!mpctx->chapters)
3509 return demuxer_chapter_count(mpctx->demuxer);
3510 return mpctx->num_chapters;
3513 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3515 mpctx->last_chapter_seek = -2;
3516 if (!mpctx->chapters) {
3517 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3518 if (res >= 0) {
3519 if (*seek_pts == -1)
3520 seek_reset(mpctx, true);
3521 else {
3522 mpctx->last_chapter_seek = res;
3523 mpctx->last_chapter_pts = *seek_pts;
3526 return res;
3529 if (chapter >= mpctx->num_chapters)
3530 return -1;
3531 if (chapter < 0)
3532 chapter = 0;
3533 *seek_pts = mpctx->chapters[chapter].start;
3534 mpctx->last_chapter_seek = chapter;
3535 mpctx->last_chapter_pts = *seek_pts;
3536 return chapter;
3540 static void run_playloop(struct MPContext *mpctx)
3542 struct MPOpts *opts = &mpctx->opts;
3543 float aq_sleep_time = 0;
3544 bool full_audio_buffers = false;
3546 if (opts->chapterrange[1] > 0) {
3547 int cur_chapter = get_current_chapter(mpctx);
3548 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3549 mpctx->stop_play = PT_NEXT_ENTRY;
3552 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3553 mpctx->sh_audio = mpctx->d_audio->sh;
3554 mpctx->sh_audio->ds = mpctx->d_audio;
3555 reinit_audio_chain(mpctx);
3558 /*========================== PLAY AUDIO ============================*/
3560 if (!mpctx->sh_video)
3561 mpctx->restart_playback = false;
3563 if (mpctx->sh_audio && !mpctx->restart_playback) {
3564 int status = fill_audio_out_buffers(mpctx);
3565 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3566 if (status == -2)
3567 // at eof, all audio at least written to ao
3568 if (!mpctx->sh_video)
3569 mpctx->stop_play = AT_END_OF_FILE;
3573 if (!mpctx->sh_video) {
3574 if (mpctx->step_frames) {
3575 mpctx->step_frames = 0;
3576 pause_player(mpctx);
3578 // handle audio-only case:
3579 double a_pos = 0, a_buf = 0;
3580 // sh_audio can be NULL due to video stream switching
3581 // TODO: handle this better
3582 if (mpctx->sh_audio) {
3583 a_buf = ao_get_delay(mpctx->ao);
3584 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3585 a_buf;
3588 print_status(mpctx, a_pos, false);
3590 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3591 update_osd_msg(mpctx);
3592 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3593 mpctx->stop_play = AT_END_OF_FILE;
3594 else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3595 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3596 && mpctx->sh_audio) {
3597 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3598 if (!opts->gapless_audio && p->source != (p + 1)->source
3599 && a_buf > 0.05) {
3600 mpctx->stop_play = KEEP_PLAYING;
3601 mp_input_get_cmd(mpctx->input, (a_buf - .05) * 1000, true);
3602 } else {
3603 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3604 .amount = (p + 1)->start },
3605 true);
3607 } else if (!mpctx->stop_play) {
3608 int sleep_time = 100;
3609 if (mpctx->sh_audio) {
3610 if (mpctx->ao->untimed)
3611 sleep_time = 0;
3612 else if (full_audio_buffers)
3613 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3614 else
3615 sleep_time = 20;
3616 sleep_time = FFMIN(sleep_time, 100);
3618 mp_input_get_cmd(mpctx->input, sleep_time, true);
3620 } else {
3622 /*========================== PLAY VIDEO ============================*/
3624 vo_pts = mpctx->sh_video->timer * 90000.0;
3625 vo_fps = mpctx->sh_video->fps;
3627 bool blit_frame = mpctx->video_out->frame_loaded;
3628 if (!blit_frame) {
3629 double frame_time = update_video(mpctx);
3630 blit_frame = mpctx->video_out->frame_loaded;
3631 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3632 if (mpctx->sh_video->vf_initialized < 0) {
3633 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3634 "\nFATAL: Could not initialize video filters (-vf) "
3635 "or video output (-vo).\n");
3636 mpctx->stop_play = PT_NEXT_ENTRY;
3637 return;
3639 if (frame_time < 0)
3640 mpctx->stop_play = AT_END_OF_FILE;
3641 else if (!mpctx->restart_playback) {
3642 mpctx->time_frame += frame_time / opts->playback_speed;
3643 adjust_sync(mpctx, frame_time);
3646 if (mpctx->timeline) {
3647 struct timeline_part *next =
3648 mpctx->timeline + mpctx->timeline_part + 1;
3649 if (mpctx->sh_video->pts >= next->start
3650 || mpctx->stop_play == AT_END_OF_FILE
3651 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3652 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3653 .amount = next->start },
3654 true);
3655 return;
3659 // ================================================================
3661 current_module = "vo_check_events";
3662 vo_check_events(mpctx->video_out);
3664 #ifdef CONFIG_X11
3665 if (stop_xscreensaver) {
3666 current_module = "stop_xscreensaver";
3667 xscreensaver_heartbeat(mpctx->x11_state);
3669 #endif
3670 if (heartbeat_cmd) {
3671 static unsigned last_heartbeat;
3672 unsigned now = GetTimerMS();
3673 if (now - last_heartbeat > 30000) {
3674 last_heartbeat = now;
3675 system(heartbeat_cmd);
3679 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3680 &mpctx->time_frame,
3681 full_audio_buffers,
3682 &aq_sleep_time);
3684 //=================== FLIP PAGE (VIDEO BLT): ======================
3686 current_module = "flip_page";
3687 if (!frame_time_remaining && blit_frame) {
3688 vo_new_frame_imminent(mpctx->video_out);
3689 struct sh_video *sh_video = mpctx->sh_video;
3690 mpctx->video_pts = sh_video->pts;
3691 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3692 update_teletext(sh_video, mpctx->demuxer, 0);
3693 update_osd_msg(mpctx);
3694 struct vf_instance *vf = sh_video->vfilter;
3695 mpctx->osd->pts = mpctx->video_pts;
3696 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3697 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3698 vo_osd_changed(0);
3700 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3701 aq_sleep_time += mpctx->time_frame;
3702 // flag 256 means: libvo driver does its timing (dvb card)
3703 if (mpctx->time_frame > 0.001
3704 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3705 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3706 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3708 unsigned int t2 = GetTimer();
3709 /* Playing with playback speed it's possible to get pathological
3710 * cases with mpctx->time_frame negative enough to cause an
3711 * overflow in pts_us calculation, thus the FFMAX. */
3712 double time_frame = FFMAX(mpctx->time_frame, -1);
3713 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3714 int duration = -1;
3715 double pts2 = mpctx->video_out->next_pts2;
3716 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3717 && !mpctx->restart_playback) {
3718 // expected A/V sync correction is ignored
3719 double diff = (pts2 - mpctx->video_pts);
3720 diff /= opts->playback_speed;
3721 if (mpctx->time_frame < 0)
3722 diff += mpctx->time_frame;
3723 if (diff < 0)
3724 diff = 0;
3725 if (diff > 10)
3726 diff = 10;
3727 duration = diff * 1e6;
3729 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3731 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3732 vout_time_usage += mpctx->last_vo_flip_duration;
3733 if (mpctx->video_out->driver->flip_page_timed) {
3734 // No need to adjust sync based on flip speed
3735 mpctx->last_vo_flip_duration = 0;
3736 // For print_status - VO call finishing early is OK for sync
3737 mpctx->time_frame -= get_relative_time(mpctx);
3739 if (mpctx->restart_playback) {
3740 mpctx->syncing_audio = true;
3741 if (mpctx->sh_audio)
3742 fill_audio_out_buffers(mpctx);
3743 mpctx->restart_playback = false;
3744 mpctx->time_frame = 0;
3745 get_relative_time(mpctx);
3747 print_status(mpctx, MP_NOPTS_VALUE, true);
3748 screenshot_flip(mpctx);
3749 } else
3750 print_status(mpctx, MP_NOPTS_VALUE, false);
3752 if (opts->auto_quality > 0) {
3753 current_module = "autoq";
3754 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3755 ++output_quality;
3756 else if (output_quality > 1 && aq_sleep_time < 0)
3757 --output_quality;
3758 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3759 output_quality = 0;
3760 set_video_quality(mpctx->sh_video, output_quality);
3763 if (!frame_time_remaining && blit_frame) {
3764 if (play_n_frames >= 0) {
3765 --play_n_frames;
3766 if (play_n_frames <= 0)
3767 mpctx->stop_play = PT_NEXT_ENTRY;
3769 if (mpctx->step_frames > 0) {
3770 mpctx->step_frames--;
3771 if (mpctx->step_frames == 0)
3772 pause_player(mpctx);
3776 // FIXME: add size based support for -endpos
3777 if (end_at.type == END_AT_TIME &&
3778 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3779 mpctx->stop_play = PT_NEXT_ENTRY;
3781 } // end if(mpctx->sh_video)
3783 #ifdef CONFIG_DVDNAV
3784 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3785 nav_highlight_t hl;
3786 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3787 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3788 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3789 vo_osd_changed(OSDTYPE_DVDNAV);
3790 } else {
3791 osd_set_nav_box(0, 0, 0, 0);
3792 vo_osd_changed(OSDTYPE_DVDNAV);
3793 vo_osd_changed(OSDTYPE_SPU);
3796 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3797 double ar = -1.0;
3798 if (mpctx->sh_video &&
3799 stream_control(mpctx->demuxer->stream,
3800 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3801 != STREAM_UNSUPPORTED)
3802 mpctx->sh_video->stream_aspect = ar;
3805 #endif
3807 //================= Keyboard events, SEEKing ====================
3809 current_module = "key_events";
3811 while (1) {
3812 mp_cmd_t *cmd;
3813 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3814 /* Allow running consecutive seek commands to combine them,
3815 * but execute the seek before running other commands.
3816 * If the user seeks continuously (keeps arrow key down)
3817 * try to finish showing a frame from one location before doing
3818 * another seek (which could lead to unchanging display). */
3819 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3820 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3821 && GetTimerMS() - mpctx->start_timestamp < 300)
3822 break;
3823 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3824 run_command(mpctx, cmd);
3825 mp_cmd_free(cmd);
3826 if (mpctx->stop_play)
3827 break;
3829 bool slow_video = mpctx->sh_video && mpctx->video_out->frame_loaded;
3830 if (!(mpctx->paused || slow_video) || mpctx->stop_play
3831 || mpctx->seek.type || mpctx->restart_playback)
3832 break;
3833 if (mpctx->sh_video) {
3834 update_osd_msg(mpctx);
3835 int hack = vo_osd_changed(0);
3836 vo_osd_changed(hack);
3837 if (hack || mpctx->video_out->want_redraw) {
3838 if (redraw_osd(mpctx) < 0) {
3839 if (mpctx->paused)
3840 add_step_frame(mpctx);
3841 break;
3842 } else
3843 vo_osd_changed(0);
3846 if (!mpctx->paused)
3847 break;
3848 pause_loop(mpctx);
3851 // handle -sstep
3852 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3853 mpctx->osd_function = OSD_FFW;
3854 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3857 edl_update(mpctx);
3859 /* Looping. */
3860 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3861 mpctx->stop_play == PT_NEXT_ENTRY)) {
3862 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3864 if (opts->loop_times > 1)
3865 opts->loop_times--;
3866 else if (opts->loop_times == 1)
3867 opts->loop_times = -1;
3868 play_n_frames = play_n_frames_mf;
3869 mpctx->stop_play = 0;
3870 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3873 if (mpctx->seek.type) {
3874 seek(mpctx, mpctx->seek, false);
3875 mpctx->seek = (struct seek_params){ 0 };
3880 static int read_keys(void *ctx, int fd)
3882 getch2(ctx);
3883 return MP_INPUT_NOTHING;
3886 static bool attachment_is_font(struct demux_attachment *att)
3888 if (!att->name || !att->type || !att->data || !att->data_size)
3889 return false;
3890 // match against MIME types
3891 if (strcmp(att->type, "application/x-truetype-font") == 0
3892 || strcmp(att->type, "application/x-font") == 0)
3893 return true;
3894 // fallback: match against file extension
3895 if (strlen(att->name) > 4) {
3896 char *ext = att->name + strlen(att->name) - 4;
3897 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3898 || strcasecmp(ext, ".otf") == 0)
3899 return true;
3901 return false;
3904 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3906 if (audio_id == -1)
3907 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3908 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3909 demuxer_switch_audio(demuxer, audio_id);
3910 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3911 demuxer->audio->id = -2;
3912 demuxer->audio->sh = NULL;
3914 return demuxer->audio->id;
3917 static void print_version(const char *name)
3919 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3921 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3922 GetCpuCaps(&gCpuCaps);
3923 #if ARCH_X86
3924 mp_msg(MSGT_CPLAYER, MSGL_V,
3925 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3926 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3927 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3928 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3929 #if CONFIG_RUNTIME_CPUDETECT
3930 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3931 #else
3932 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3933 if (HAVE_MMX)
3934 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3935 if (HAVE_MMX2)
3936 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3937 if (HAVE_AMD3DNOW)
3938 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3939 if (HAVE_AMD3DNOWEXT)
3940 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3941 if (HAVE_SSE)
3942 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3943 if (HAVE_SSE2)
3944 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3945 if (HAVE_SSSE3)
3946 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3947 if (HAVE_CMOV)
3948 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3949 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3950 #endif /* CONFIG_RUNTIME_CPUDETECT */
3951 #endif /* ARCH_X86 */
3952 print_libav_versions();
3955 #ifdef PTW32_STATIC_LIB
3956 static void detach_ptw32(void)
3958 pthread_win32_thread_detach_np();
3959 pthread_win32_process_detach_np();
3961 #endif
3963 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3964 * file for some tools to link against. */
3965 #ifndef DISABLE_MAIN
3966 int main(int argc, char *argv[])
3968 #ifdef PTW32_STATIC_LIB
3969 pthread_win32_process_attach_np();
3970 pthread_win32_thread_attach_np();
3971 atexit(detach_ptw32);
3972 #endif
3973 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3974 || !strcmp(argv[1], "--leak-report")))
3975 talloc_enable_leak_report();
3977 char *mem_ptr;
3979 // movie info:
3981 /* Flag indicating whether MPlayer should exit without playing anything. */
3982 int opt_exit = 0;
3983 int i;
3985 struct MPContext *mpctx = talloc(NULL, MPContext);
3986 *mpctx = (struct MPContext){
3987 .osd_function = OSD_PLAY,
3988 .begin_skip = MP_NOPTS_VALUE,
3989 .play_tree_step = 1,
3990 .global_sub_pos = -1,
3991 .set_of_sub_pos = -1,
3992 .file_format = DEMUXER_TYPE_UNKNOWN,
3993 .last_dvb_step = 1,
3994 .paused_cache_fill = -1,
3997 InitTimer();
3998 srand(GetTimerMS());
4000 mp_msg_init();
4001 init_libav();
4003 #ifdef CONFIG_X11
4004 mpctx->x11_state = vo_x11_init_state();
4005 #endif
4006 struct MPOpts *opts = &mpctx->opts;
4007 set_default_mplayer_options(opts);
4008 // Create the config context and register the options
4009 mpctx->mconfig = m_config_new(opts, cfg_include);
4010 m_config_register_options(mpctx->mconfig, mplayer_opts);
4011 m_config_register_options(mpctx->mconfig, common_opts);
4012 mp_input_register_options(mpctx->mconfig);
4014 // Preparse the command line
4015 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
4017 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
4018 set_path_env();
4019 #endif
4021 #ifdef CONFIG_TV
4022 stream_tv_defaults.immediate = 1;
4023 #endif
4025 parse_cfgfiles(mpctx, mpctx->mconfig);
4027 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
4028 if (mpctx->playtree == NULL)
4029 opt_exit = 1;
4030 else {
4031 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
4032 if (mpctx->playtree) {
4033 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4034 mpctx->mconfig);
4035 if (mpctx->playtree_iter) {
4036 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4037 PLAY_TREE_ITER_ENTRY) {
4038 play_tree_iter_free(mpctx->playtree_iter);
4039 mpctx->playtree_iter = NULL;
4041 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
4047 print_version("MPlayer2");
4049 #if defined(__MINGW32__) || defined(__CYGWIN__)
4051 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
4052 BOOL WINAPI (*setDEP)(DWORD) = NULL;
4053 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
4054 if (kernel32) {
4055 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
4056 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
4058 if (setDEP)
4059 setDEP(3);
4060 if (setDllDir)
4061 setDllDir("");
4063 // stop Windows from showing all kinds of annoying error dialogs
4064 SetErrorMode(0x8003);
4065 // request 1ms timer resolution
4066 timeBeginPeriod(1);
4067 #endif
4069 #ifdef CONFIG_PRIORITY
4070 set_priority();
4071 #endif
4073 if (opts->video_driver_list &&
4074 strcmp(opts->video_driver_list[0], "help") == 0) {
4075 list_video_out();
4076 opt_exit = 1;
4079 if (opts->audio_driver_list &&
4080 strcmp(opts->audio_driver_list[0], "help") == 0) {
4081 list_audio_out();
4082 opt_exit = 1;
4085 /* Check codecs.conf. */
4086 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4087 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4088 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4089 if (!parse_codec_cfg(NULL))
4090 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4091 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4092 "Using built-in default codecs.conf.\n");
4095 free(mem_ptr); // release the buffer created by get_path()
4098 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4099 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4100 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4101 list_codecs(1);
4102 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4103 opt_exit = 1;
4105 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4106 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4107 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4108 list_codecs(0);
4109 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4110 opt_exit = 1;
4112 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4113 vfm_help();
4114 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4115 opt_exit = 1;
4117 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4118 afm_help();
4119 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4120 opt_exit = 1;
4122 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4123 af_help();
4124 printf("\n");
4125 opt_exit = 1;
4127 #ifdef CONFIG_X11
4128 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4129 fstype_help();
4130 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4131 opt_exit = 1;
4133 #endif
4134 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4135 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4136 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4137 demuxer_help();
4138 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4139 opt_exit = 1;
4141 if (opts->list_properties) {
4142 property_print_help();
4143 opt_exit = 1;
4146 if (opt_exit)
4147 exit_player(mpctx, EXIT_NONE);
4149 if (!mpctx->filename && !opts->player_idle_mode) {
4150 // no file/vcd/dvd -> show HELP:
4151 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4152 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4155 /* Display what configure line was used */
4156 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4158 // Many users forget to include command line in bugreports...
4159 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4160 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4161 for (i = 1; i < argc; i++)
4162 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4163 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4166 //------ load global data first ------
4168 mpctx->osd = osd_create();
4170 // check font
4171 #ifdef CONFIG_FREETYPE
4172 init_freetype();
4173 #endif
4174 #ifdef CONFIG_FONTCONFIG
4175 if (font_fontconfig <= 0) {
4176 #endif
4177 #ifdef CONFIG_BITMAP_FONT
4178 if (font_name) {
4179 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4180 if (!vo_font)
4181 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4182 filename_recode(font_name));
4183 } else {
4184 // try default:
4185 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4186 font_factor, verbose > 1);
4187 free(mem_ptr); // release the buffer created by get_path()
4188 if (!vo_font)
4189 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4190 font_factor, verbose > 1);
4192 if (sub_font_name)
4193 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4194 verbose > 1);
4195 else
4196 mpctx->osd->sub_font = vo_font;
4197 #endif
4198 #ifdef CONFIG_FONTCONFIG
4200 #endif
4202 #ifdef CONFIG_ASS
4203 mpctx->ass_library = mp_ass_init(opts);
4204 mpctx->osd->ass_library = mpctx->ass_library;
4205 #endif
4207 #ifdef HAVE_RTC
4208 if (opts->rtc) {
4209 char *rtc_device = opts->rtc_device;
4210 // seteuid(0); /* Can't hurt to try to get root here */
4211 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4212 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4213 "(it should be readable by the user.)\n",
4214 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4215 else {
4216 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4218 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4219 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4220 "ioctl (rtc_irqp_set %lu): %s\n",
4221 irqp, strerror(errno));
4222 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4223 close(rtc_fd);
4224 rtc_fd = -1;
4225 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4226 /* variable only by the root */
4227 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4228 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4229 close(rtc_fd);
4230 rtc_fd = -1;
4231 } else
4232 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4233 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4236 if (rtc_fd < 0)
4237 #endif /* HAVE_RTC */
4238 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4239 opts->softsleep ? "software" : timer_name);
4241 #ifdef HAVE_TERMCAP
4242 load_termcap(NULL); // load key-codes
4243 #endif
4245 // ========== Init keyboard FIFO (connection to libvo) ============
4247 // Init input system
4248 current_module = "init_input";
4249 mpctx->input = mp_input_init(&opts->input);
4250 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4251 if (slave_mode)
4252 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4253 else if (opts->consolecontrols)
4254 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4255 // Set the libstream interrupt callback
4256 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4258 current_module = NULL;
4260 /// Catch signals
4261 #ifndef __MINGW32__
4262 signal(SIGCHLD, child_sighandler);
4263 #endif
4265 #ifdef CONFIG_CRASH_DEBUG
4266 prog_path = argv[0];
4267 #endif
4268 //========= Catch terminate signals: ================
4269 // terminate requests:
4270 signal(SIGTERM, exit_sighandler); // kill
4271 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4273 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4275 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4276 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4277 #ifdef CONFIG_SIGHANDLER
4278 // fatal errors:
4279 signal(SIGBUS, exit_sighandler); // bus error
4280 signal(SIGSEGV, exit_sighandler); // segfault
4281 signal(SIGILL, exit_sighandler); // illegal instruction
4282 signal(SIGFPE, exit_sighandler); // floating point exc.
4283 signal(SIGABRT, exit_sighandler); // abort()
4284 #ifdef CONFIG_CRASH_DEBUG
4285 if (crash_debug)
4286 signal(SIGTRAP, exit_sighandler);
4287 #endif
4288 #endif
4290 // ***************** Now, let's see the per-file stuff ******************
4292 play_next_file:
4294 // init global sub numbers
4295 mpctx->global_sub_size = 0;
4296 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4298 if (mpctx->filename) {
4299 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4300 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4301 load_per_file_config(mpctx->mconfig, mpctx->filename);
4304 if (opts->video_driver_list)
4305 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4306 opts->video_driver_list[0]);
4307 if (opts->audio_driver_list)
4308 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4309 opts->audio_driver_list[0]);
4311 // We must enable getch2 here to be able to interrupt network connection
4312 // or cache filling
4313 if (opts->consolecontrols && !slave_mode) {
4314 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4315 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4316 "WARNING: getch2_init called twice!\n");
4317 else
4318 getch2_enable(); // prepare stdin for hotkeys...
4319 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4320 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4323 // ================= GUI idle loop (STOP state) =========================
4324 while (opts->player_idle_mode && !mpctx->filename) {
4325 play_tree_t *entry = NULL;
4326 mp_cmd_t *cmd;
4327 if (mpctx->video_out && mpctx->video_out->config_ok)
4328 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4329 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4330 if (mpctx->video_out)
4331 vo_check_events(mpctx->video_out);
4332 usec_sleep(20000);
4334 switch (cmd->id) {
4335 case MP_CMD_LOADFILE:
4336 // prepare a tree entry with the new filename
4337 entry = play_tree_new();
4338 play_tree_add_file(entry, cmd->args[0].v.s);
4339 // The entry is added to the main playtree after the switch().
4340 break;
4341 case MP_CMD_LOADLIST:
4342 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4343 break;
4344 case MP_CMD_QUIT:
4345 exit_player_with_rc(mpctx, EXIT_QUIT,
4346 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4347 break;
4348 case MP_CMD_VO_FULLSCREEN:
4349 case MP_CMD_GET_PROPERTY:
4350 case MP_CMD_SET_PROPERTY:
4351 case MP_CMD_STEP_PROPERTY:
4352 run_command(mpctx, cmd);
4353 break;
4356 mp_cmd_free(cmd);
4358 if (entry) { // user entered a command that gave a valid entry
4359 if (mpctx->playtree)
4360 // the playtree is always a node with one child. let's clear it
4361 play_tree_free_list(mpctx->playtree->child, 1);
4362 else
4363 // .. or make a brand new playtree
4364 mpctx->playtree = play_tree_new();
4366 if (!mpctx->playtree)
4367 continue; // couldn't make playtree! wait for next command
4369 play_tree_set_child(mpctx->playtree, entry);
4371 /* Make iterator start at the top the of tree. */
4372 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4373 mpctx->mconfig);
4374 if (!mpctx->playtree_iter)
4375 continue;
4377 // find the first real item in the tree
4378 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4379 PLAY_TREE_ITER_ENTRY) {
4380 // no items!
4381 play_tree_iter_free(mpctx->playtree_iter);
4382 mpctx->playtree_iter = NULL;
4383 continue; // wait for next command
4385 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4389 #ifdef CONFIG_ASS
4390 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4391 #endif
4392 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4393 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4395 if (mpctx->filename) {
4396 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4397 filename_recode(mpctx->filename));
4398 if (use_filename_title && opts->vo_wintitle == NULL)
4399 opts->vo_wintitle = talloc_strdup(NULL,
4400 mp_basename(mpctx->filename));
4403 if (edl_filename) {
4404 if (edl_records)
4405 free_edl(edl_records);
4406 next_edl_record = edl_records = edl_parse_file();
4408 if (edl_output_filename) {
4409 if (edl_fd)
4410 fclose(edl_fd);
4411 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4412 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4413 "Can't open EDL file [%s] for writing.\n",
4414 filename_recode(edl_output_filename));
4418 //==================== Open VOB-Sub ============================
4420 current_module = "vobsub";
4421 if (opts->vobsub_name) {
4422 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4423 if (vo_vobsub == NULL)
4424 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4425 filename_recode(opts->vobsub_name));
4426 } else if (opts->sub_auto && mpctx->filename) {
4427 char **vob = find_vob_subtitles(opts, mpctx->filename);
4428 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4429 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4430 if (vo_vobsub)
4431 break;
4433 talloc_free(vob);
4435 if (vo_vobsub) {
4436 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4437 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4438 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4439 mpctx);
4441 // setup global sub numbering
4442 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4443 vobsub_get_indexes_count(vo_vobsub);
4446 //============ Open & Sync STREAM --- fork cache2 ====================
4448 mpctx->stream = NULL;
4449 mpctx->demuxer = NULL;
4450 mpctx->d_audio = NULL;
4451 mpctx->d_video = NULL;
4452 mpctx->d_sub = NULL;
4453 mpctx->sh_audio = NULL;
4454 mpctx->sh_video = NULL;
4456 current_module = "open_stream";
4457 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4458 if (!mpctx->stream) { // error...
4459 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4460 goto goto_next_file;
4462 mpctx->initialized_flags |= INITIALIZED_STREAM;
4464 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4465 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4466 "playlist support will not be used automatically.\n"
4467 "MPlayer's playlist code is unsafe and should only be used with "
4468 "trusted sources.\nPlayback will probably fail.\n\n");
4469 #if 0
4470 play_tree_t *entry;
4471 // Handle playlist
4472 current_module = "handle_playlist";
4473 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4474 filename_recode(mpctx->filename));
4475 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4476 mpctx->eof = playtree_add_playlist(mpctx, entry);
4477 goto goto_next_file;
4478 #endif
4480 mpctx->stream->start_pos += seek_to_byte;
4482 if (stream_dump_type == 5) {
4483 unsigned char buf[4096];
4484 int len;
4485 FILE *f;
4486 current_module = "dumpstream";
4487 stream_reset(mpctx->stream);
4488 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4489 f = fopen(opts->stream_dump_name, "wb");
4490 if (!f) {
4491 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4492 exit_player(mpctx, EXIT_ERROR);
4494 if (opts->chapterrange[0] > 1) {
4495 int chapter = opts->chapterrange[0] - 1;
4496 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4498 struct stream_dump_progress info;
4499 stream_dump_progress_start(&info);
4500 while (!mpctx->stream->eof && !async_quit_request) {
4501 len = stream_read(mpctx->stream, buf, 4096);
4502 if (len > 0) {
4503 if (fwrite(buf, len, 1, f) != 1) {
4504 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4505 exit_player(mpctx, EXIT_ERROR);
4508 stream_dump_progress(&info, len, mpctx->stream);
4509 if (opts->chapterrange[1] > 0) {
4510 int chapter = -1;
4511 if (stream_control(mpctx->stream,
4512 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4513 && chapter + 1 > opts->chapterrange[1])
4514 break;
4517 if (fclose(f)) {
4518 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4519 opts->stream_dump_name);
4520 exit_player(mpctx, EXIT_ERROR);
4522 stream_dump_progress_end(&info, opts->stream_dump_name);
4523 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4524 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4527 #ifdef CONFIG_DVDREAD
4528 if (mpctx->stream->type == STREAMTYPE_DVD) {
4529 current_module = "dvd lang->id";
4530 if (opts->audio_lang && opts->audio_id == -1)
4531 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4532 if (opts->sub_lang && opts->sub_id == -1)
4533 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4534 // setup global sub numbering
4535 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4536 current_module = NULL;
4538 #endif
4540 #ifdef CONFIG_DVDNAV
4541 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4542 current_module = "dvdnav lang->id";
4543 if (opts->audio_lang && opts->audio_id == -1)
4544 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4545 opts->audio_lang);
4546 dvdsub_lang_id = -3;
4547 if (opts->sub_lang && opts->sub_id == -1)
4548 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4549 mpctx->stream, opts->sub_lang);
4550 // setup global sub numbering
4551 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4552 mpctx->stream);
4553 current_module = NULL;
4555 #endif
4557 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4558 goto_enable_cache:
4559 if (stream_cache_size > 0) {
4560 int res;
4561 float stream_cache_min_percent = opts->stream_cache_min_percent;
4562 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4563 current_module = "enable_cache";
4564 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4565 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4566 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4567 if (res == 0)
4568 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4569 goto goto_next_file;
4572 //============ Open DEMUXERS --- DETECT file type =======================
4573 current_module = "demux_open";
4575 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4576 opts->audio_id, opts->video_id, opts->sub_id,
4577 mpctx->filename);
4579 // HACK to get MOV Reference Files working
4581 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4582 unsigned char *playlist_entry;
4583 play_tree_t *list = NULL, *entry = NULL;
4585 current_module = "handle_demux_playlist";
4586 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4587 char *temp;
4588 const char *bname;
4590 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4591 filename_recode(playlist_entry));
4593 bname = mp_basename(playlist_entry);
4594 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4595 !strncmp(bname + 3, "gateQT", 6))
4596 continue;
4598 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4599 continue;
4601 entry = play_tree_new();
4603 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4604 playlist_entry)) { // add reference path of current file
4605 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4606 mpctx->filename)) + strlen(playlist_entry) + 1));
4607 if (temp) {
4608 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4609 strlen(mp_basename(mpctx->filename)));
4610 temp[strlen(mpctx->filename) - strlen(mp_basename(
4611 mpctx->filename))] = '\0';
4612 strcat(temp, playlist_entry);
4613 if (!strcmp(temp, mpctx->filename)) {
4614 free(temp);
4615 continue;
4617 play_tree_add_file(entry, temp);
4618 mp_msg(MSGT_CPLAYER, MSGL_V,
4619 "Resolving reference to %s.\n", temp);
4620 free(temp);
4622 } else
4623 play_tree_add_file(entry, playlist_entry);
4625 if (!list)
4626 list = entry;
4627 else
4628 play_tree_append_entry(list, entry);
4630 free_demuxer(mpctx->demuxer);
4631 mpctx->demuxer = NULL;
4633 if (list) {
4634 entry = play_tree_new();
4635 play_tree_set_child(entry, list);
4636 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4637 goto goto_next_file;
4641 if (!mpctx->demuxer) {
4642 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4643 goto goto_next_file;
4646 if (mpctx->demuxer->matroska_data.ordered_chapters)
4647 build_ordered_chapter_timeline(mpctx);
4649 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4650 build_edl_timeline(mpctx);
4652 if (mpctx->timeline) {
4653 mpctx->timeline_part = 0;
4654 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4656 int part_count = mpctx->num_timeline_parts;
4657 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4658 "sources. Total length %.3f seconds.\n", part_count,
4659 mpctx->num_sources, mpctx->timeline[part_count].start);
4660 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4661 for (int i = 0; i < mpctx->num_sources; i++)
4662 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4663 filename_recode(mpctx->sources[i].demuxer->filename));
4664 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4665 "source_start, source):\n");
4666 for (int i = 0; i < part_count; i++) {
4667 struct timeline_part *p = mpctx->timeline + i;
4668 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4669 p->source_start, p->source - mpctx->sources);
4671 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4672 mpctx->timeline[part_count].start);
4675 if (!mpctx->sources) {
4676 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4677 *mpctx->sources = (struct content_source){
4678 .stream = mpctx->stream,
4679 .demuxer = mpctx->demuxer
4681 mpctx->num_sources = 1;
4684 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4686 #ifdef CONFIG_ASS
4687 if (opts->ass_enabled && mpctx->ass_library) {
4688 for (int j = 0; j < mpctx->num_sources; j++) {
4689 struct demuxer *d = mpctx->sources[j].demuxer;
4690 for (int i = 0; i < d->num_attachments; i++) {
4691 struct demux_attachment *att = d->attachments + i;
4692 if (opts->use_embedded_fonts && attachment_is_font(att))
4693 ass_add_font(mpctx->ass_library, att->name, att->data,
4694 att->data_size);
4698 #endif
4700 current_module = "demux_open2";
4702 mpctx->d_audio = mpctx->demuxer->audio;
4703 mpctx->d_video = mpctx->demuxer->video;
4704 mpctx->d_sub = mpctx->demuxer->sub;
4706 if (ts_prog) {
4707 int tmp = ts_prog;
4708 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4710 // select audio stream
4711 for (int i = 0; i < mpctx->num_sources; i++)
4712 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4713 opts->audio_lang);
4715 // DUMP STREAMS:
4716 if ((stream_dump_type) && (stream_dump_type < 4)) {
4717 FILE *f;
4718 demux_stream_t *ds = NULL;
4719 current_module = "dump";
4720 // select stream to dump
4721 switch (stream_dump_type) {
4722 case 1: ds = mpctx->d_audio;
4723 break;
4724 case 2: ds = mpctx->d_video;
4725 break;
4726 case 3: ds = mpctx->d_sub;
4727 break;
4729 if (!ds) {
4730 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4731 "dump: FATAL: Selected stream missing!\n");
4732 exit_player(mpctx, EXIT_ERROR);
4734 // disable other streams:
4735 if (mpctx->d_audio && mpctx->d_audio != ds) {
4736 ds_free_packs(mpctx->d_audio);
4737 mpctx->d_audio->id = -2;
4739 if (mpctx->d_video && mpctx->d_video != ds) {
4740 ds_free_packs(mpctx->d_video);
4741 mpctx->d_video->id = -2;
4743 if (mpctx->d_sub && mpctx->d_sub != ds) {
4744 ds_free_packs(mpctx->d_sub);
4745 mpctx->d_sub->id = -2;
4747 // let's dump it!
4748 f = fopen(opts->stream_dump_name, "wb");
4749 if (!f) {
4750 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4751 exit_player(mpctx, EXIT_ERROR);
4753 struct stream_dump_progress info;
4754 stream_dump_progress_start(&info);
4755 while (!ds->eof) {
4756 unsigned char *start;
4757 int in_size = ds_get_packet(ds, &start);
4758 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4759 && stream_dump_type == 2)
4760 fwrite(&in_size, 1, 4, f);
4761 if (in_size > 0) {
4762 fwrite(start, in_size, 1, f);
4763 stream_dump_progress(&info, in_size, mpctx->stream);
4765 if (opts->chapterrange[1] > 0) {
4766 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4767 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4768 break;
4771 fclose(f);
4772 stream_dump_progress_end(&info, opts->stream_dump_name);
4773 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4774 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4777 mpctx->sh_audio = mpctx->d_audio->sh;
4778 mpctx->sh_video = mpctx->d_video->sh;
4780 if (mpctx->sh_video) {
4781 current_module = "video_read_properties";
4782 if (!video_read_properties(mpctx->sh_video)) {
4783 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4784 mpctx->sh_video = mpctx->d_video->sh = NULL;
4785 } else {
4786 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4787 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4788 mpctx->demuxer->file_format, mpctx->sh_video->format,
4789 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4790 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4791 if (force_fps) {
4792 mpctx->sh_video->fps = force_fps;
4793 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4795 vo_fps = mpctx->sh_video->fps;
4797 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4798 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4799 "header or invalid, use the -fps option.\n");
4805 if (!mpctx->sh_video && !mpctx->sh_audio) {
4806 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4807 #ifdef CONFIG_DVBIN
4808 if (mpctx->stream->type == STREAMTYPE_DVB) {
4809 int dir;
4810 int v = mpctx->last_dvb_step;
4811 if (v > 0)
4812 dir = DVB_CHANNEL_HIGHER;
4813 else
4814 dir = DVB_CHANNEL_LOWER;
4816 if (dvb_step_channel(mpctx->stream, dir)) {
4817 mpctx->stop_play = PT_NEXT_ENTRY;
4818 mpctx->dvbin_reopen = 1;
4821 #endif
4822 goto goto_next_file; // exit_player(_("Fatal error"));
4825 /* display clip info */
4826 demux_info_print(mpctx->demuxer);
4828 //================= Read SUBTITLES (DVD & TEXT) =========================
4829 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4830 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4831 init_vo_spudec(mpctx);
4833 // after reading video params we should load subtitles because
4834 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4835 // check .sub
4836 current_module = "read_subtitles_file";
4837 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4838 if (opts->sub_name) {
4839 for (i = 0; opts->sub_name[i] != NULL; ++i)
4840 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4842 if (opts->sub_auto) { // auto load sub file ...
4843 char **tmp = find_text_subtitles(opts, mpctx->filename);
4844 int nsub = MP_TALLOC_ELEMS(tmp);
4845 for (int i = 0; i < nsub; i++)
4846 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4847 talloc_free(tmp);
4849 if (mpctx->set_of_sub_size > 0)
4850 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4852 if (select_subtitle(mpctx)) {
4853 if (mpctx->subdata)
4854 switch (stream_dump_type) {
4855 case 3: list_sub_file(mpctx->subdata);
4856 break;
4857 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4858 break;
4859 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4860 break;
4861 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4862 break;
4863 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4864 break;
4865 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4866 break;
4870 print_file_properties(mpctx, mpctx->filename);
4872 reinit_video_chain(mpctx);
4873 if (mpctx->sh_video) {
4874 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4875 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4876 #ifdef CONFIG_FREETYPE
4877 force_load_font = 1;
4878 #endif
4879 } else if (!mpctx->sh_audio)
4880 goto goto_next_file;
4882 //================== MAIN: ==========================
4883 current_module = "main";
4885 if (opts->playing_msg) {
4886 char *msg = property_expand_string(mpctx, opts->playing_msg);
4887 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4888 free(msg);
4892 // Disable the term OSD in verbose mode
4893 if (verbose)
4894 opts->term_osd = 0;
4896 // Make sure old OSD does not stay around,
4897 // e.g. with -fixed-vo and same-resolution files
4898 clear_osd_msgs();
4899 update_osd_msg(mpctx);
4901 //================ SETUP AUDIO ==========================
4903 if (mpctx->sh_audio) {
4904 reinit_audio_chain(mpctx);
4905 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4906 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4907 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4910 current_module = "av_init";
4912 if (mpctx->sh_video) {
4913 mpctx->sh_video->timer = 0;
4914 if (!ignore_start)
4915 audio_delay += mpctx->sh_video->stream_delay;
4917 if (mpctx->sh_audio) {
4918 if (start_volume >= 0)
4919 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4920 if (!ignore_start)
4921 audio_delay -= mpctx->sh_audio->stream_delay;
4922 mpctx->delay = -audio_delay;
4925 if (!mpctx->sh_audio) {
4926 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4927 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4928 mpctx->d_audio->packs);
4929 ds_free_packs(mpctx->d_audio); // free buffered chunks
4931 if (!mpctx->sh_video) {
4932 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4933 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4934 mpctx->d_video->packs);
4935 ds_free_packs(mpctx->d_video);
4936 mpctx->d_video->id = -2;
4939 if (!mpctx->sh_video && !mpctx->sh_audio)
4940 goto goto_next_file;
4942 if (force_fps && mpctx->sh_video) {
4943 vo_fps = mpctx->sh_video->fps = force_fps;
4944 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4945 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4946 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4947 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4950 mp_input_set_section(mpctx->input, NULL);
4951 //TODO: add desired (stream-based) sections here
4952 if (mpctx->stream->type == STREAMTYPE_TV)
4953 mp_input_set_section(mpctx->input, "tv");
4954 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4955 mp_input_set_section(mpctx->input, "dvdnav");
4957 //==================== START PLAYING =======================
4959 if (opts->loop_times > 1)
4960 opts->loop_times--;
4961 else if (opts->loop_times == 1)
4962 opts->loop_times = -1;
4964 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4966 total_time_usage_start = GetTimer();
4967 audio_time_usage = 0;
4968 video_time_usage = 0;
4969 vout_time_usage = 0;
4970 total_frame_cnt = 0;
4971 drop_frame_cnt = 0; // fix for multifile fps benchmark
4972 play_n_frames = play_n_frames_mf;
4974 if (play_n_frames == 0) {
4975 mpctx->stop_play = PT_NEXT_ENTRY;
4976 goto goto_next_file;
4979 mpctx->time_frame = 0;
4980 mpctx->drop_message_shown = 0;
4981 mpctx->restart_playback = true;
4982 mpctx->video_pts = 0;
4983 mpctx->last_seek_pts = 0;
4984 mpctx->hrseek_active = false;
4985 mpctx->hrseek_framedrop = false;
4986 mpctx->step_frames = 0;
4987 mpctx->total_avsync_change = 0;
4988 mpctx->last_chapter_seek = -2;
4990 // If there's a timeline force an absolute seek to initialize state
4991 if (opts->seek_to_sec || mpctx->timeline) {
4992 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4993 seek(mpctx, mpctx->seek, false);
4994 end_at.pos += opts->seek_to_sec;
4996 if (opts->chapterrange[0] > 0) {
4997 double pts;
4998 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4999 && pts > -1.0) {
5000 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
5001 seek(mpctx, mpctx->seek, false);
5005 if (end_at.type == END_AT_SIZE) {
5006 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
5007 "Option -endpos in MPlayer does not yet support size units.\n");
5008 end_at.type = END_AT_NONE;
5011 #ifdef CONFIG_DVDNAV
5012 mp_dvdnav_context_free(mpctx);
5013 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
5014 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
5015 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
5017 #endif
5019 mpctx->seek = (struct seek_params){ 0 };
5020 get_relative_time(mpctx); // reset current delta
5021 // Make sure VO knows current pause state
5022 if (mpctx->sh_video)
5023 vo_control(mpctx->video_out,
5024 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
5026 while (!mpctx->stop_play)
5027 run_playloop(mpctx);
5029 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
5031 #ifdef CONFIG_DVBIN
5032 if (mpctx->dvbin_reopen) {
5033 mpctx->stop_play = 0;
5034 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
5035 cache_uninit(mpctx->stream);
5036 mpctx->dvbin_reopen = 0;
5037 goto goto_enable_cache;
5039 #endif
5041 goto_next_file: // don't jump here after ao/vo/getch initialization!
5043 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
5045 if (opts->benchmark) {
5046 double tot = video_time_usage + vout_time_usage + audio_time_usage;
5047 double total_time_usage;
5048 total_time_usage_start = GetTimer() - total_time_usage_start;
5049 total_time_usage = (float)total_time_usage_start * 0.000001;
5050 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
5051 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
5052 video_time_usage, vout_time_usage, audio_time_usage,
5053 total_time_usage - tot, total_time_usage);
5054 if (total_time_usage > 0.0)
5055 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
5056 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
5057 100.0 * video_time_usage / total_time_usage,
5058 100.0 * vout_time_usage / total_time_usage,
5059 100.0 * audio_time_usage / total_time_usage,
5060 100.0 * (total_time_usage - tot) / total_time_usage,
5061 100.0);
5062 if (total_frame_cnt && frame_dropping)
5063 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
5064 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
5065 total_frame_cnt - drop_frame_cnt,
5066 (total_time_usage > 0.5) ? ((total_frame_cnt -
5067 drop_frame_cnt) / total_time_usage) : 0,
5068 drop_frame_cnt,
5069 100 * drop_frame_cnt / total_frame_cnt,
5070 total_frame_cnt,
5071 (total_time_usage > 0.5) ?
5072 (total_frame_cnt / total_time_usage) : 0);
5075 // time to uninit all, except global stuff:
5076 int uninitialize_parts = INITIALIZED_ALL;
5077 if (opts->fixed_vo)
5078 uninitialize_parts -= INITIALIZED_VO;
5079 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
5080 uninitialize_parts -= INITIALIZED_AO;
5081 uninit_player(mpctx, uninitialize_parts);
5083 if (mpctx->set_of_sub_size > 0) {
5084 current_module = "sub_free";
5085 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5086 sub_free(mpctx->set_of_subtitles[i]);
5087 #ifdef CONFIG_ASS
5088 if (mpctx->set_of_ass_tracks[i])
5089 ass_free_track(mpctx->set_of_ass_tracks[i]);
5090 #endif
5092 mpctx->set_of_sub_size = 0;
5094 mpctx->vo_sub_last = vo_sub = NULL;
5095 mpctx->subdata = NULL;
5096 #ifdef CONFIG_ASS
5097 mpctx->osd->ass_track = NULL;
5098 if (mpctx->ass_library)
5099 ass_clear_fonts(mpctx->ass_library);
5100 #endif
5102 if (!mpctx->stop_play) // In case some goto jumped here...
5103 mpctx->stop_play = PT_NEXT_ENTRY;
5105 int playtree_direction = 1;
5107 if (mpctx->stop_play == PT_NEXT_ENTRY
5108 || mpctx->stop_play == PT_PREV_ENTRY) {
5109 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5110 != PLAY_TREE_ITER_ENTRY) {
5111 play_tree_iter_free(mpctx->playtree_iter);
5112 mpctx->playtree_iter = NULL;
5114 mpctx->play_tree_step = 1;
5115 } else if (mpctx->stop_play == PT_UP_NEXT ||
5116 mpctx->stop_play == PT_UP_PREV) {
5117 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5118 if (mpctx->playtree_iter) {
5119 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5120 PLAY_TREE_ITER_ENTRY) {
5121 play_tree_iter_free(mpctx->playtree_iter);
5122 mpctx->playtree_iter = NULL;
5125 } else if (mpctx->stop_play == PT_STOP) {
5126 play_tree_iter_free(mpctx->playtree_iter);
5127 mpctx->playtree_iter = NULL;
5128 } else // NEXT PREV SRC
5129 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5131 while (mpctx->playtree_iter != NULL) {
5132 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5133 playtree_direction);
5134 if (mpctx->filename == NULL) {
5135 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5136 0) != PLAY_TREE_ITER_ENTRY) {
5137 play_tree_iter_free(mpctx->playtree_iter);
5138 mpctx->playtree_iter = NULL;
5141 } else
5142 break;
5145 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5146 if (!mpctx->playtree_iter)
5147 mpctx->filename = NULL;
5148 mpctx->stop_play = 0;
5149 goto play_next_file;
5152 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5154 return 1;
5156 #endif /* DISABLE_MAIN */