stream_netstream: Remove netstream support
[mplayer.git] / mplayer.c
blob9feca0a5ebd9b7ec504ac0d0369e72e213b94ceb
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>
24 #ifdef PTW32_STATIC_LIB
25 #include <pthread.h>
26 #endif
28 #include <libavutil/intreadwrite.h>
30 #include "config.h"
31 #include "talloc.h"
33 #include "osdep/io.h"
35 #if defined(__MINGW32__) || defined(__CYGWIN__)
36 #include <windows.h>
37 // No proper file descriptor event handling; keep waking up to poll input
38 #define WAKEUP_PERIOD 0.02
39 #else
40 /* Even if we can immediately wake up in response to most input events,
41 * there are some timers which are not registered to the event loop
42 * and need to be checked periodically (like automatic mouse cursor hiding).
43 * OSD content updates behave similarly. Also some uncommon input devices
44 * may not have proper FD event support.
46 #define WAKEUP_PERIOD 0.5
47 #endif
48 #include <string.h>
49 #include <unistd.h>
51 // #include <sys/mman.h>
52 #include <sys/types.h>
53 #ifndef __MINGW32__
54 #include <sys/ioctl.h>
55 #include <sys/wait.h>
56 #else
57 #define SIGHUP 1 /* hangup */
58 #define SIGQUIT 3 /* quit */
59 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
60 #define SIGBUS 10 /* bus error */
61 #define SIGPIPE 13 /* broken pipe */
62 #endif
64 #include <sys/time.h>
65 #include <sys/stat.h>
67 #include <signal.h>
68 #include <time.h>
69 #include <fcntl.h>
70 #include <limits.h>
72 #include <errno.h>
74 #include "mp_msg.h"
75 #include "av_log.h"
78 #include "m_option.h"
79 #include "m_config.h"
80 #include "mplayer.h"
81 #include "m_property.h"
83 #include "sub/subreader.h"
84 #include "sub/find_subfiles.h"
85 #include "sub/dec_sub.h"
86 #include "sub/sub_cc.h"
88 #include "mp_osd.h"
89 #include "libvo/video_out.h"
90 #include "screenshot.h"
92 #include "sub/sub.h"
93 #include "libmpcodecs/dec_teletext.h"
94 #include "cpudetect.h"
95 #include "version.h"
97 #ifdef CONFIG_X11
98 #include "libvo/x11_common.h"
99 #endif
101 #include "libao2/audio_out.h"
103 #include "codec-cfg.h"
105 #include "sub/spudec.h"
106 #include "sub/vobsub.h"
108 #include "osdep/getch2.h"
109 #include "osdep/timer.h"
111 #include "input/input.h"
113 int slave_mode = 0;
114 int enable_mouse_movements = 0;
115 float start_volume = -1;
117 #include "osdep/priority.h"
119 char *heartbeat_cmd;
121 #ifdef HAVE_RTC
122 #ifdef __linux__
123 #include <linux/rtc.h>
124 #else
125 #include <rtc.h>
126 #define RTC_IRQP_SET RTCIO_IRQP_SET
127 #define RTC_PIE_ON RTCIO_PIE_ON
128 #endif /* __linux__ */
129 #endif /* HAVE_RTC */
131 #include "stream/tv.h"
132 #include "stream/stream_radio.h"
133 #ifdef CONFIG_DVBIN
134 #include "stream/dvbin.h"
135 #endif
136 #include "stream/cache2.h"
138 //**************************************************************************//
139 // Playtree
140 //**************************************************************************//
141 #include "playtree.h"
142 #include "playtreeparser.h"
144 //**************************************************************************//
145 // Config
146 //**************************************************************************//
147 #include "parser-cfg.h"
148 #include "parser-mpcmd.h"
150 //**************************************************************************//
151 // Config file
152 //**************************************************************************//
154 #include "path.h"
156 //**************************************************************************//
157 //**************************************************************************//
158 // Input media streaming & demultiplexer:
159 //**************************************************************************//
161 static int max_framesize = 0;
163 #include "stream/stream.h"
164 #include "libmpdemux/demuxer.h"
165 #include "libmpdemux/stheader.h"
167 #ifdef CONFIG_DVDREAD
168 #include "stream/stream_dvd.h"
169 #endif
170 #include "stream/stream_dvdnav.h"
172 #include "libmpcodecs/dec_audio.h"
173 #include "libmpcodecs/dec_video.h"
174 #include "libmpcodecs/mp_image.h"
175 #include "libmpcodecs/vf.h"
176 #include "libmpcodecs/vd.h"
178 #include "mixer.h"
180 #include "mp_core.h"
181 #include "options.h"
182 #include "defaultopts.h"
184 static const char help_text[] = _(
185 "Usage: mplayer [options] [url|path/]filename\n"
186 "\n"
187 "Basic options: (complete list in the man page)\n"
188 " -vo <drv> select video output driver ('-vo help' for a list)\n"
189 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
190 #ifdef CONFIG_VCD
191 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
192 #endif
193 #ifdef CONFIG_DVDREAD
194 " dvd://<titleno> play DVD title from device instead of plain file\n"
195 #endif
196 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
197 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
198 " -nosound do not play sound\n"
199 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
200 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
201 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
202 " -playlist <file> specify playlist file\n"
203 " -vid x -aid y select video (x) and audio (y) stream to play\n"
204 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
205 " -pp <quality> enable postprocessing filter (details in the man page)\n"
206 " -framedrop enable frame dropping (for slow machines)\n"
207 "\n"
208 "Basic keys: (complete list in the man page, also check input.conf)\n"
209 " <- or -> seek backward/forward 10 seconds\n"
210 " down or up seek backward/forward 1 minute\n"
211 " pgdown or pgup seek backward/forward 10 minutes\n"
212 " < or > step backward/forward in playlist\n"
213 " p or SPACE pause movie (press any key to continue)\n"
214 " q or ESC stop playing and quit program\n"
215 " + or - adjust audio delay by +/- 0.1 second\n"
216 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
217 " * or / increase or decrease PCM volume\n"
218 " x or z adjust subtitle delay by +/- 0.1 second\n"
219 " r or t adjust subtitle position up/down, also see -vf expand\n"
220 " double click toggle fullscreen\n"
221 " right click pause (press again to continue)\n"
222 "\n"
223 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
224 "\n");
227 #define Exit_SIGILL_RTCpuSel _(\
228 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
229 " It may be a bug in our new runtime CPU-detection code...\n"\
230 " Please read DOCS/HTML/en/bugreports.html.\n")
232 #define Exit_SIGILL _(\
233 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
234 " It usually happens when you run it on a CPU different than the one it was\n"\
235 " compiled/optimized for.\n"\
236 " Verify this!\n")
238 #define Exit_SIGSEGV_SIGFPE _(\
239 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
240 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
241 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
243 #define Exit_SIGCRASH _(\
244 "- MPlayer crashed. This shouldn't happen.\n"\
245 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
246 " gcc version. If you think it's MPlayer's fault, please read\n"\
247 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
248 " won't help unless you provide this information when reporting a possible bug.\n")
250 #define SystemTooSlow _("\n\n"\
251 " ************************************************\n"\
252 " **** Your system is too SLOW to play this! ****\n"\
253 " ************************************************\n\n"\
254 "Possible reasons, problems, workarounds:\n"\
255 "- Most common: broken/buggy _audio_ driver\n"\
256 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
257 " - Experiment with different values for -autosync, 30 is a good start.\n"\
258 "- Slow video output\n"\
259 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
260 "- Slow CPU\n"\
261 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
262 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
263 "- Broken file\n"\
264 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
265 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
266 " - Try -cache 8192.\n"\
267 "- Are you using -cache to play a non-interleaved AVI file?\n"\
268 " - Try -nocache.\n"\
269 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
270 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
273 //**************************************************************************//
274 //**************************************************************************//
276 #include "mp_fifo.h"
278 // benchmark:
279 double video_time_usage;
280 double vout_time_usage;
281 static double audio_time_usage;
282 static int total_time_usage_start;
283 static int total_frame_cnt;
284 static int drop_frame_cnt; // total number of dropped frames
286 // options:
287 static int output_quality;
289 // seek:
290 static off_t seek_to_byte;
291 static off_t step_sec;
293 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
295 // codecs:
296 char **audio_codec_list; // override audio codec
297 char **video_codec_list; // override video codec
298 char **audio_fm_list; // override audio codec family
299 char **video_fm_list; // override video codec family
301 // this dvdsub_id was selected via slang
302 // use this to allow dvdnav to follow -slang across stream resets,
303 // in particular the subtitle ID for a language changes
304 int dvdsub_lang_id;
305 int vobsub_id = -1;
306 static char *spudec_ifo = NULL;
307 int forced_subs_only = 0;
309 // dump:
310 int stream_dump_type = 0;
312 // A-V sync:
313 static float default_max_pts_correction = -1;
314 float audio_delay = 0;
315 static int ignore_start = 0;
317 double force_fps = 0;
318 static int force_srate = 0;
319 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
320 static int play_n_frames = -1;
321 static int play_n_frames_mf = -1;
323 #include "sub/ass_mp.h"
325 char *current_module; // for debugging
328 // ---
330 FILE *edl_fd; // file to write to when in -edlout mode.
331 char *edl_output_filename; // file to put EDL entries in (-edlout)
333 int use_filedir_conf;
334 int use_filename_title;
336 #include "mpcommon.h"
337 #include "command.h"
339 #include "metadata.h"
341 static float get_relative_time(struct MPContext *mpctx)
343 unsigned int new_time = GetTimer();
344 unsigned int delta = new_time - mpctx->last_time;
345 mpctx->last_time = new_time;
346 return delta * 0.000001;
349 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
351 switch (type) {
352 /* check for valid video stream */
353 case META_VIDEO_CODEC:
354 case META_VIDEO_BITRATE:
355 case META_VIDEO_RESOLUTION:
356 if (!mpctx->sh_video)
357 return 0;
358 break;
360 /* check for valid audio stream */
361 case META_AUDIO_CODEC:
362 case META_AUDIO_BITRATE:
363 case META_AUDIO_SAMPLES:
364 if (!mpctx->sh_audio)
365 return 0;
366 break;
368 /* check for valid demuxer */
369 case META_INFO_TITLE:
370 case META_INFO_ARTIST:
371 case META_INFO_ALBUM:
372 case META_INFO_YEAR:
373 case META_INFO_COMMENT:
374 case META_INFO_TRACK:
375 case META_INFO_GENRE:
376 if (!mpctx->demuxer)
377 return 0;
378 break;
380 default:
381 break;
384 return 1;
387 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
389 char **info = mpctx->demuxer->info;
390 int n;
392 if (!info || !tag)
393 return talloc_strdup(NULL, "");
395 for (n = 0; info[2 * n] != NULL; n++)
396 if (!strcasecmp(info[2 * n], tag))
397 break;
399 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
402 char *get_metadata(struct MPContext *mpctx, metadata_t type)
404 sh_audio_t * const sh_audio = mpctx->sh_audio;
405 sh_video_t * const sh_video = mpctx->sh_video;
407 if (!is_valid_metadata_type(mpctx, type))
408 return NULL;
410 switch (type) {
411 case META_NAME:
412 return talloc_strdup(NULL, mp_basename(mpctx->filename));
413 case META_VIDEO_CODEC:
414 if (sh_video->format == 0x10000001)
415 return talloc_strdup(NULL, "mpeg1");
416 else if (sh_video->format == 0x10000002)
417 return talloc_strdup(NULL, "mpeg2");
418 else if (sh_video->format == 0x10000004)
419 return talloc_strdup(NULL, "mpeg4");
420 else if (sh_video->format == 0x10000005)
421 return talloc_strdup(NULL, "h264");
422 else if (sh_video->format >= 0x20202020)
423 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
424 else
425 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
426 case META_VIDEO_BITRATE:
427 return talloc_asprintf(NULL, "%d kbps",
428 (int) (sh_video->i_bps * 8 / 1024));
429 case META_VIDEO_RESOLUTION:
430 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
431 sh_video->disp_h);
432 case META_AUDIO_CODEC:
433 if (sh_audio->codec && sh_audio->codec->name)
434 return talloc_strdup(NULL, sh_audio->codec->name);
435 return talloc_strdup(NULL, "");
436 case META_AUDIO_BITRATE:
437 return talloc_asprintf(NULL, "%d kbps",
438 (int) (sh_audio->i_bps * 8 / 1000));
439 case META_AUDIO_SAMPLES:
440 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
441 sh_audio->channels);
443 /* check for valid demuxer */
444 case META_INFO_TITLE:
445 return get_demuxer_info(mpctx, "Title");
447 case META_INFO_ARTIST:
448 return get_demuxer_info(mpctx, "Artist");
450 case META_INFO_ALBUM:
451 return get_demuxer_info(mpctx, "Album");
453 case META_INFO_YEAR:
454 return get_demuxer_info(mpctx, "Year");
456 case META_INFO_COMMENT:
457 return get_demuxer_info(mpctx, "Comment");
459 case META_INFO_TRACK:
460 return get_demuxer_info(mpctx, "Track");
462 case META_INFO_GENRE:
463 return get_demuxer_info(mpctx, "Genre");
465 default:
466 break;
469 return talloc_strdup(NULL, "");
472 static void print_file_properties(struct MPContext *mpctx, const char *filename)
474 double start_pts = MP_NOPTS_VALUE;
475 double video_start_pts = MP_NOPTS_VALUE;
476 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
477 filename_recode(filename));
478 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
479 mpctx->demuxer->desc->name);
480 if (mpctx->sh_video) {
481 /* Assume FOURCC if all bytes >= 0x20 (' ') */
482 if (mpctx->sh_video->format >= 0x20202020)
483 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
484 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
485 else
486 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
487 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
488 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
489 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
490 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
491 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
492 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
493 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
494 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
495 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
496 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
497 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
498 video_start_pts = ds_get_next_pts(mpctx->d_video);
500 if (mpctx->sh_audio) {
501 /* Assume FOURCC if all bytes >= 0x20 (' ') */
502 if (mpctx->sh_audio->format >= 0x20202020)
503 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
504 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
505 else
506 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
507 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
508 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
509 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
510 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
511 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
512 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
513 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
514 start_pts = ds_get_next_pts(mpctx->d_audio);
516 if (video_start_pts != MP_NOPTS_VALUE) {
517 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
518 (mpctx->sh_video && video_start_pts < start_pts))
519 start_pts = video_start_pts;
521 if (start_pts != MP_NOPTS_VALUE)
522 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
523 else
524 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
525 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
526 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
527 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
528 mpctx->stream->seek
529 && (!mpctx->demuxer || mpctx->demuxer->seekable));
530 if (mpctx->demuxer) {
531 int chapter_count = get_chapter_count(mpctx);
532 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
533 for (int i = 0; i < chapter_count; i++) {
534 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
535 // in milliseconds
536 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
537 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
538 char *name = chapter_name(mpctx, i);
539 if (name) {
540 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
541 name);
542 talloc_free(name);
548 /// step size of mixer changes
549 int volstep = 3;
551 #ifdef CONFIG_DVDNAV
552 static void mp_dvdnav_context_free(MPContext *ctx)
554 if (ctx->nav_smpi)
555 free_mp_image(ctx->nav_smpi);
556 ctx->nav_smpi = NULL;
557 free(ctx->nav_buffer);
558 ctx->nav_buffer = NULL;
559 ctx->nav_start = NULL;
560 ctx->nav_in_size = 0;
562 #endif
564 static void uninit_subs(struct demuxer *demuxer)
566 for (int i = 0; i < MAX_S_STREAMS; i++) {
567 struct sh_sub *sh = demuxer->s_streams[i];
568 if (sh && sh->initialized)
569 sub_uninit(sh);
573 void uninit_player(struct MPContext *mpctx, unsigned int mask)
575 mask &= mpctx->initialized_flags;
577 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
579 if (mask & INITIALIZED_ACODEC) {
580 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
581 current_module = "uninit_acodec";
582 if (mpctx->sh_audio)
583 uninit_audio(mpctx->sh_audio);
584 mpctx->sh_audio = NULL;
585 mpctx->mixer.afilter = NULL;
588 if (mask & INITIALIZED_SUB) {
589 mpctx->initialized_flags &= ~INITIALIZED_SUB;
590 if (mpctx->osd->sh_sub)
591 sub_switchoff(mpctx->osd->sh_sub, mpctx->osd);
594 if (mask & INITIALIZED_VCODEC) {
595 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
596 current_module = "uninit_vcodec";
597 if (mpctx->sh_video)
598 uninit_video(mpctx->sh_video);
599 mpctx->sh_video = NULL;
602 if (mask & INITIALIZED_DEMUXER) {
603 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
604 current_module = "free_demuxer";
605 if (mpctx->num_sources) {
606 mpctx->demuxer = mpctx->sources[0].demuxer;
607 for (int i = 1; i < mpctx->num_sources; i++) {
608 uninit_subs(mpctx->sources[i].demuxer);
609 free_stream(mpctx->sources[i].stream);
610 free_demuxer(mpctx->sources[i].demuxer);
613 talloc_free(mpctx->sources);
614 mpctx->sources = NULL;
615 mpctx->num_sources = 0;
616 talloc_free(mpctx->timeline);
617 mpctx->timeline = NULL;
618 mpctx->num_timeline_parts = 0;
619 talloc_free(mpctx->chapters);
620 mpctx->chapters = NULL;
621 mpctx->num_chapters = 0;
622 mpctx->video_offset = 0;
623 if (mpctx->demuxer) {
624 mpctx->stream = mpctx->demuxer->stream;
625 uninit_subs(mpctx->demuxer);
626 free_demuxer(mpctx->demuxer);
628 mpctx->demuxer = NULL;
631 // kill the cache process:
632 if (mask & INITIALIZED_STREAM) {
633 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
634 current_module = "uninit_stream";
635 if (mpctx->stream)
636 free_stream(mpctx->stream);
637 mpctx->stream = NULL;
640 if (mask & INITIALIZED_VO) {
641 mpctx->initialized_flags &= ~INITIALIZED_VO;
642 current_module = "uninit_vo";
643 vo_destroy(mpctx->video_out);
644 mpctx->video_out = NULL;
645 #ifdef CONFIG_DVDNAV
646 mp_dvdnav_context_free(mpctx);
647 #endif
650 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
651 if (mask & INITIALIZED_GETCH2) {
652 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
653 current_module = "uninit_getch2";
654 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
655 // restore terminal:
656 getch2_disable();
659 if (mask & INITIALIZED_VOBSUB) {
660 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
661 current_module = "uninit_vobsub";
662 if (vo_vobsub)
663 vobsub_close(vo_vobsub);
664 vo_vobsub = NULL;
667 if (mask & INITIALIZED_SPUDEC) {
668 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
669 current_module = "uninit_spudec";
670 spudec_free(vo_spudec);
671 vo_spudec = NULL;
674 if (mask & INITIALIZED_AO) {
675 mpctx->initialized_flags &= ~INITIALIZED_AO;
676 current_module = "uninit_ao";
677 mixer_uninit(&mpctx->mixer);
678 if (mpctx->ao)
679 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
680 mpctx->ao = NULL;
683 current_module = NULL;
686 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
688 uninit_player(mpctx, INITIALIZED_ALL);
689 #if defined(__MINGW32__) || defined(__CYGWIN__)
690 timeEndPeriod(1);
691 #endif
693 current_module = "uninit_input";
694 mp_input_uninit(mpctx->input);
696 osd_free(mpctx->osd);
698 #ifdef CONFIG_ASS
699 ass_library_done(mpctx->ass_library);
700 mpctx->ass_library = NULL;
701 #endif
703 current_module = "exit_player";
705 if (mpctx->playtree_iter)
706 play_tree_iter_free(mpctx->playtree_iter);
707 mpctx->playtree_iter = NULL;
708 if (mpctx->playtree)
709 play_tree_free(mpctx->playtree, 1);
710 mpctx->playtree = NULL;
712 talloc_free(mpctx->key_fifo);
714 switch (how) {
715 case EXIT_QUIT:
716 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
717 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
718 break;
719 case EXIT_EOF:
720 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
721 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
722 break;
723 case EXIT_ERROR:
724 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
725 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
726 break;
727 default:
728 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
730 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
731 "max framesize was %d bytes\n", max_framesize);
733 // must be last since e.g. mp_msg uses option values
734 // that will be freed by this.
735 if (mpctx->mconfig)
736 m_config_free(mpctx->mconfig);
737 mpctx->mconfig = NULL;
739 talloc_free(mpctx);
741 exit(rc);
744 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
746 exit_player_with_rc(mpctx, how, 1);
749 #ifndef __MINGW32__
750 static void child_sighandler(int x)
752 pid_t pid;
753 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
755 #endif
757 #ifdef CONFIG_CRASH_DEBUG
758 static char *prog_path;
759 static int crash_debug = 0;
760 #endif
762 static void exit_sighandler(int x)
764 static int sig_count = 0;
765 #ifdef CONFIG_CRASH_DEBUG
766 if (!crash_debug || x != SIGTRAP)
767 #endif
768 ++sig_count;
769 if (sig_count == 5) {
770 /* We're crashing bad and can't uninit cleanly :(
771 * by popular request, we make one last (dirty)
772 * effort to restore the user's
773 * terminal. */
774 getch2_disable();
775 exit(1);
777 if (sig_count == 6)
778 exit(1);
779 if (sig_count > 6) {
780 // can't stop :(
781 #ifndef __MINGW32__
782 kill(getpid(), SIGKILL);
783 #endif
785 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
786 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
787 "\nMPlayer interrupted by signal %d in module: %s\n", x,
788 current_module ? current_module : "unknown");
789 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
790 if (sig_count <= 1)
791 switch (x) {
792 case SIGINT:
793 case SIGPIPE:
794 case SIGQUIT:
795 case SIGTERM:
796 case SIGKILL:
797 async_quit_request = 1;
798 return; // killed from keyboard (^C) or killed [-9]
799 case SIGILL:
800 #if CONFIG_RUNTIME_CPUDETECT
801 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
802 #else
803 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
804 #endif
805 case SIGFPE:
806 case SIGSEGV:
807 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
808 default:
809 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
810 #ifdef CONFIG_CRASH_DEBUG
811 if (crash_debug) {
812 int gdb_pid;
813 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
814 gdb_pid = fork();
815 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
816 if (gdb_pid == 0) { // We are the child
817 char spid[20];
818 snprintf(spid, sizeof(spid), "%i", getppid());
819 getch2_disable(); // allow terminal to work properly with gdb
820 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
821 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
822 } else if (gdb_pid < 0)
823 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
824 else
825 waitpid(gdb_pid, NULL, 0);
826 if (x == SIGTRAP)
827 return;
829 #endif
831 getch2_disable();
832 exit(1);
835 #include "cfg-mplayer.h"
837 static int cfg_include(struct m_config *conf, char *filename)
839 return m_config_parse_config_file(conf, filename);
842 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
844 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
846 struct MPOpts *opts = &mpctx->opts;
847 char *conffile;
848 int conffile_fd;
849 if (!(opts->noconfig & 2) &&
850 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
851 exit_player(mpctx, EXIT_NONE);
852 if ((conffile = get_path("")) == NULL)
853 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
854 else {
855 mkdir(conffile, 0777);
856 free(conffile);
857 if ((conffile = get_path("config")) == NULL)
858 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
859 else {
860 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
861 0666)) != -1) {
862 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
863 "Creating config file: %s\n", conffile);
864 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
865 close(conffile_fd);
867 if (!(opts->noconfig & 1) &&
868 m_config_parse_config_file(conf, conffile) < 0)
869 exit_player(mpctx, EXIT_NONE);
870 free(conffile);
875 #define PROFILE_CFG_PROTOCOL "protocol."
877 static void load_per_protocol_config(m_config_t *conf, const char * const file)
879 char *str;
880 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
881 m_profile_t *p;
883 /* does filename actually uses a protocol ? */
884 str = strstr(file, "://");
885 if (!str)
886 return;
888 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
889 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
890 p = m_config_get_profile(conf, protocol);
891 if (p) {
892 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
893 "Loading protocol-related profile '%s'\n", protocol);
894 m_config_set_profile(conf, p);
898 #define PROFILE_CFG_EXTENSION "extension."
900 static void load_per_extension_config(m_config_t *conf, const char * const file)
902 char *str;
903 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
904 m_profile_t *p;
906 /* does filename actually have an extension ? */
907 str = strrchr(file, '.');
908 if (!str)
909 return;
911 sprintf(extension, PROFILE_CFG_EXTENSION);
912 strncat(extension, ++str, 7);
913 p = m_config_get_profile(conf, extension);
914 if (p) {
915 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
916 "Loading extension-related profile '%s'\n", extension);
917 m_config_set_profile(conf, p);
921 #define PROFILE_CFG_VO "vo."
922 #define PROFILE_CFG_AO "ao."
924 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
926 char profile[strlen(cfg) + strlen(out) + 1];
927 m_profile_t *p;
929 sprintf(profile, "%s%s", cfg, out);
930 p = m_config_get_profile(conf, profile);
931 if (p) {
932 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
933 "Loading extension-related profile '%s'\n", profile);
934 m_config_set_profile(conf, p);
939 * Tries to load a config file
940 * @return 0 if file was not found, 1 otherwise
942 static int try_load_config(m_config_t *conf, const char *file)
944 if (!mp_path_exists(file))
945 return 0;
946 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
947 m_config_parse_config_file(conf, file);
948 return 1;
951 static void load_per_file_config(m_config_t *conf, const char * const file)
953 char *confpath;
954 char cfg[MP_PATH_MAX];
955 const char *name;
957 if (strlen(file) > MP_PATH_MAX - 14) {
958 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
959 "can not load file or directory specific config files\n");
960 return;
962 sprintf(cfg, "%s.conf", file);
964 name = mp_basename(cfg);
965 if (use_filedir_conf) {
966 char dircfg[MP_PATH_MAX];
967 strcpy(dircfg, cfg);
968 strcpy(dircfg + (name - cfg), "mplayer.conf");
969 try_load_config(conf, dircfg);
971 if (try_load_config(conf, cfg))
972 return;
975 if ((confpath = get_path(name)) != NULL) {
976 try_load_config(conf, confpath);
978 free(confpath);
982 /* When libmpdemux performs a blocking operation (network connection or
983 * cache filling) if the operation fails we use this function to check
984 * if it was interrupted by the user.
985 * The function returns a new value for eof. */
986 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
988 mp_cmd_t *cmd;
989 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
990 switch (cmd->id) {
991 case MP_CMD_QUIT:
992 exit_player_with_rc(mpctx, EXIT_QUIT,
993 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
994 case MP_CMD_PLAY_TREE_STEP: {
995 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
996 mpctx->play_tree_step =
997 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
998 } break;
999 case MP_CMD_PLAY_TREE_UP_STEP: {
1000 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1001 } break;
1002 case MP_CMD_PLAY_ALT_SRC_STEP: {
1003 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1004 } break;
1006 mp_cmd_free(cmd);
1008 return stop_play;
1011 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1013 play_tree_add_bpf(entry, bstr(mpctx->filename));
1016 if (!entry) {
1017 entry = mpctx->playtree_iter->tree;
1018 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1019 != PLAY_TREE_ITER_ENTRY)
1020 return PT_NEXT_ENTRY;
1021 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1022 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1023 != PLAY_TREE_ITER_ENTRY)
1024 return PT_NEXT_ENTRY;
1026 play_tree_remove(entry, 1, 1);
1027 return PT_NEXT_SRC;
1029 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1030 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1031 entry = mpctx->playtree_iter->tree;
1032 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1033 != PLAY_TREE_ITER_ENTRY)
1034 return PT_NEXT_ENTRY;
1035 play_tree_remove(entry, 1, 1);
1037 return PT_NEXT_SRC;
1040 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1041 int noerr)
1043 struct MPOpts *opts = &mpctx->opts;
1044 sub_data *subd = NULL;
1045 struct sh_sub *sh = NULL;
1047 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1048 return;
1050 if (opts->ass_enabled) {
1051 #ifdef CONFIG_ASS
1052 struct ass_track *asst;
1053 #ifdef CONFIG_ICONV
1054 asst = mp_ass_read_stream(mpctx->ass_library, opts, filename, sub_cp);
1055 #else
1056 asst = mp_ass_read_stream(mpctx->ass_library, opts, filename, 0);
1057 #endif
1058 bool is_native_ass = asst;
1059 if (!asst) {
1060 subd = sub_read_file(filename, fps, &mpctx->opts);
1061 if (subd) {
1062 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1063 sub_free(subd);
1064 subd = NULL;
1067 if (asst)
1068 sh = sd_ass_create_from_track(asst, is_native_ass, opts);
1069 #endif
1070 } else
1071 subd = sub_read_file(filename, fps, &mpctx->opts);
1074 if (!sh && !subd) {
1075 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1076 "Cannot load subtitles: %s\n", filename_recode(filename));
1077 return;
1080 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = sh;
1081 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1082 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1083 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1084 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1085 filename_recode(filename));
1086 ++mpctx->set_of_sub_size;
1087 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1088 mpctx->set_of_sub_size, filename_recode(filename));
1091 void init_vo_spudec(struct MPContext *mpctx)
1093 unsigned width, height;
1094 spudec_free(vo_spudec);
1095 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1096 vo_spudec = NULL;
1098 // we currently can't work without video stream
1099 if (!mpctx->sh_video)
1100 return;
1102 if (spudec_ifo) {
1103 unsigned int palette[16];
1104 current_module = "spudec_init_vobsub";
1105 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1106 1, -1, NULL) >= 0)
1107 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1110 width = mpctx->sh_video->disp_w;
1111 height = mpctx->sh_video->disp_h;
1113 #ifdef CONFIG_DVDREAD
1114 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1115 current_module = "spudec_init_dvdread";
1116 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1117 cur_pgc->palette, width, height, NULL, 0);
1119 #endif
1121 #ifdef CONFIG_DVDNAV
1122 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1123 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1124 current_module = "spudec_init_dvdnav";
1125 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1127 #endif
1129 if (vo_spudec == NULL) {
1130 sh_sub_t *sh = mpctx->d_sub->sh;
1131 current_module = "spudec_init_normal";
1132 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1133 sh->extradata_len);
1134 spudec_set_font_factor(vo_spudec, font_factor);
1137 if (vo_spudec != NULL) {
1138 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1139 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1140 mpctx);
1145 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1146 * make it all work is to use the builtin SDL-bootstrap code, which
1147 * will be done automatically by replacing our main() if we include SDL.h.
1149 #if defined(__APPLE__) && defined(CONFIG_SDL)
1150 #ifdef CONFIG_SDL_SDL_H
1151 #include <SDL/SDL.h>
1152 #else
1153 #include <SDL.h>
1154 #endif
1155 #endif
1158 * \brief append a formatted string
1159 * \param buf buffer to print into
1160 * \param pos position of terminating 0 in buf
1161 * \param len maximum number of characters in buf, not including terminating 0
1162 * \param format printf format string
1164 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1166 va_list va;
1167 va_start(va, format);
1168 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1169 va_end(va);
1170 if (*pos >= len) {
1171 buf[len] = 0;
1172 *pos = len;
1177 * \brief append time in the hh:mm:ss.f format
1178 * \param buf buffer to print into
1179 * \param pos position of terminating 0 in buf
1180 * \param len maximum number of characters in buf, not including terminating 0
1181 * \param time time value to convert/append
1183 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1185 int64_t tenths = 10 * time;
1186 int f1 = tenths % 10;
1187 int ss = (tenths / 10) % 60;
1188 int mm = (tenths / 600) % 60;
1189 int hh = tenths / 36000;
1190 if (time < 0) {
1191 saddf(buf, pos, len, "unknown");
1192 return;
1194 if (hh > 0)
1195 saddf(buf, pos, len, "%2d:", hh);
1196 if (hh > 0 || mm > 0)
1197 saddf(buf, pos, len, "%02d:", mm);
1198 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1201 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1203 struct MPOpts *opts = &mpctx->opts;
1204 sh_video_t * const sh_video = mpctx->sh_video;
1206 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1207 a_pos = playing_audio_pts(mpctx);
1208 if (mpctx->sh_audio && sh_video && at_frame) {
1209 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1210 if (mpctx->time_frame > 0)
1211 mpctx->last_av_difference +=
1212 mpctx->time_frame * opts->playback_speed;
1213 if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
1214 mpctx->last_av_difference = MP_NOPTS_VALUE;
1215 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1216 && !mpctx->drop_message_shown) {
1217 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1218 mpctx->drop_message_shown = true;
1221 if (opts->quiet)
1222 return;
1224 int width;
1225 char *line;
1226 unsigned pos = 0;
1227 get_screen_size();
1228 if (screen_width > 0)
1229 width = screen_width;
1230 else
1231 width = 80;
1232 #if defined(__MINGW32__) || defined(__CYGWIN__)
1233 /* Windows command line is broken (MinGW's rxvt works, but we
1234 * should not depend on that). */
1235 width--;
1236 #endif
1237 line = malloc(width + 1); // one additional char for the terminating null
1239 // Audio time
1240 if (mpctx->sh_audio) {
1241 if (a_pos != MP_NOPTS_VALUE)
1242 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1243 else
1244 saddf(line, &pos, width, "A: ??? ");
1245 if (!sh_video && a_pos != MP_NOPTS_VALUE) {
1246 float len = get_time_length(mpctx);
1247 saddf(line, &pos, width, "(");
1248 sadd_hhmmssf(line, &pos, width, a_pos);
1249 saddf(line, &pos, width, ") of %.1f (", len);
1250 sadd_hhmmssf(line, &pos, width, len);
1251 saddf(line, &pos, width, ") ");
1255 // Video time
1256 if (sh_video) {
1257 if (mpctx->video_pts != MP_NOPTS_VALUE)
1258 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1259 else
1260 saddf(line, &pos, width, "V: ??? ", mpctx->video_pts);
1263 // A-V sync
1264 if (mpctx->sh_audio && sh_video) {
1265 if (mpctx->last_av_difference != MP_NOPTS_VALUE)
1266 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1267 mpctx->last_av_difference, mpctx->total_avsync_change);
1268 else
1269 saddf(line, &pos, width, "A-V: ??? ct:%7.3f ",
1270 mpctx->total_avsync_change);
1273 // Video stats
1274 if (sh_video)
1275 saddf(line, &pos, width, "%3d/%3d ",
1276 (int)sh_video->num_frames,
1277 (int)sh_video->num_frames_decoded);
1279 // CPU usage
1280 if (sh_video) {
1281 if (sh_video->timer > 0.5)
1282 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1283 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1284 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1285 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1286 else
1287 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1288 } else if (mpctx->sh_audio) {
1289 if (mpctx->delay > 0.5)
1290 saddf(line, &pos, width, "%4.1f%% ",
1291 100.0 * audio_time_usage / (double)mpctx->delay);
1292 else
1293 saddf(line, &pos, width, "??,?%% ");
1296 // VO stats
1297 if (sh_video)
1298 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1300 #ifdef CONFIG_STREAM_CACHE
1301 // cache stats
1302 if (mpctx->stream->cached)
1303 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1304 #endif
1306 // other
1307 if (opts->playback_speed != 1)
1308 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1310 // end
1311 if (erase_to_end_of_line) {
1312 line[pos] = 0;
1313 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1314 "%s%s\r", line, erase_to_end_of_line);
1315 } else {
1316 memset(&line[pos], ' ', width - pos);
1317 line[width] = 0;
1318 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1320 free(line);
1322 mpctx->status_printed = true;
1325 struct stream_dump_progress {
1326 uint64_t count;
1327 unsigned start_time;
1328 unsigned last_print_time;
1331 static void stream_dump_progress_start(struct stream_dump_progress *p)
1333 p->start_time = p->last_print_time = GetTimerMS();
1334 p->count = 0;
1337 static void stream_dump_progress(struct stream_dump_progress *p,
1338 uint64_t len, stream_t *stream)
1340 p->count += len;
1341 unsigned t = GetTimerMS();
1342 if (t - p->last_print_time < 1000)
1343 return;
1345 uint64_t start = stream->start_pos;
1346 uint64_t end = stream->end_pos;
1347 uint64_t pos = stream->pos;
1349 p->last_print_time = t;
1350 /* TODO: pretty print sizes; ETA */
1351 if (end > start && pos >= start && pos <= end) {
1352 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1353 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1354 p->count, 100.0 * (pos - start) / (end - start));
1355 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1356 } else {
1357 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1358 "dump: %"PRIu64 " bytes written", p->count);
1359 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1363 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1365 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1366 p->count, name);
1370 * \brief build a chain of audio filters that converts the input format
1371 * to the ao's format, taking into account the current playback_speed.
1372 * sh_audio describes the requested input format of the chain.
1373 * ao describes the requested output format of the chain.
1375 static int build_afilter_chain(struct MPContext *mpctx)
1377 struct sh_audio *sh_audio = mpctx->sh_audio;
1378 struct ao *ao = mpctx->ao;
1379 struct MPOpts *opts = &mpctx->opts;
1380 int new_srate;
1381 int result;
1382 if (!sh_audio) {
1383 mpctx->mixer.afilter = NULL;
1384 return 0;
1386 if (af_control_any_rev(sh_audio->afilter,
1387 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1388 &opts->playback_speed))
1389 new_srate = sh_audio->samplerate;
1390 else {
1391 new_srate = sh_audio->samplerate * opts->playback_speed;
1392 if (new_srate != ao->samplerate) {
1393 // limits are taken from libaf/af_resample.c
1394 if (new_srate < 8000)
1395 new_srate = 8000;
1396 if (new_srate > 192000)
1397 new_srate = 192000;
1398 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1401 result = init_audio_filters(sh_audio, new_srate,
1402 &ao->samplerate, &ao->channels, &ao->format);
1403 mpctx->mixer.afilter = sh_audio->afilter;
1404 return result;
1408 typedef struct mp_osd_msg mp_osd_msg_t;
1409 struct mp_osd_msg {
1410 /// Previous message on the stack.
1411 mp_osd_msg_t *prev;
1412 /// Message text.
1413 char *msg;
1414 int id, level, started;
1415 /// Display duration in ms.
1416 unsigned time;
1417 // Show full OSD for duration of message instead of static text ('P' key)
1418 bool show_position;
1421 /// OSD message stack.
1422 static mp_osd_msg_t *osd_msg_stack = NULL;
1425 * \brief Add a message on the OSD message stack
1427 * If a message with the same id is already present in the stack
1428 * it is pulled on top of the stack, otherwise a new message is created.
1431 static void set_osd_msg_va(int id, int level, int time, bool show_position,
1432 const char *fmt, va_list ap)
1434 mp_osd_msg_t *msg, *last = NULL;
1436 // look if the id is already in the stack
1437 for (msg = osd_msg_stack; msg && msg->id != id;
1438 last = msg, msg = msg->prev) ;
1439 // not found: alloc it
1440 if (!msg) {
1441 msg = talloc_zero(NULL, mp_osd_msg_t);
1442 msg->prev = osd_msg_stack;
1443 osd_msg_stack = msg;
1444 } else if (last) { // found, but it's not on top of the stack
1445 last->prev = msg->prev;
1446 msg->prev = osd_msg_stack;
1447 osd_msg_stack = msg;
1449 talloc_free(msg->msg);
1450 // write the msg
1451 msg->msg = talloc_vasprintf(msg, fmt, ap);
1452 // set id and time
1453 msg->id = id;
1454 msg->level = level;
1455 msg->time = time;
1456 msg->show_position = show_position;
1459 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1461 va_list ap;
1462 va_start(ap, fmt);
1463 set_osd_msg_va(id, level, time, false, fmt, ap);
1464 va_end(ap);
1467 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1469 va_list ap;
1470 va_start(ap, fmt);
1471 set_osd_msg_va(id, level, time, false, mp_gtext(fmt), ap);
1472 va_end(ap);
1475 void set_osd_progressmsg(int id, int level, int time, ...)
1477 va_list ap;
1478 va_start(ap, time);
1479 set_osd_msg_va(id, level, time, true, "", ap);
1480 va_end(ap);
1484 * \brief Remove a message from the OSD stack
1486 * This function can be used to get rid of a message right away.
1490 void rm_osd_msg(int id)
1492 mp_osd_msg_t *msg, *last = NULL;
1494 // Search for the msg
1495 for (msg = osd_msg_stack; msg && msg->id != id;
1496 last = msg, msg = msg->prev) ;
1497 if (!msg)
1498 return;
1500 // Detach it from the stack and free it
1501 if (last)
1502 last->prev = msg->prev;
1503 else
1504 osd_msg_stack = msg->prev;
1505 talloc_free(msg);
1509 * \brief Remove all messages from the OSD stack
1513 static void clear_osd_msgs(void)
1515 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1516 while (msg) {
1517 prev = msg->prev;
1518 talloc_free(msg);
1519 msg = prev;
1521 osd_msg_stack = NULL;
1525 * \brief Get the current message from the OSD stack.
1527 * This function decrements the message timer and destroys the old ones.
1528 * The message that should be displayed is returned (if any).
1532 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1534 struct MPOpts *opts = &mpctx->opts;
1535 mp_osd_msg_t *msg, *prev, *last = NULL;
1536 static unsigned last_update = 0;
1537 unsigned now = GetTimerMS();
1538 unsigned diff;
1539 char hidden_dec_done = 0;
1541 if (mpctx->osd_visible) {
1542 // 36000000 means max timed visibility is 1 hour into the future, if
1543 // the difference is greater assume it's wrapped around from below 0
1544 if (mpctx->osd_visible - now > 36000000) {
1545 mpctx->osd_visible = 0;
1546 vo_osd_progbar_type = -1; // disable
1547 vo_osd_changed(OSDTYPE_PROGBAR);
1548 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1551 if (mpctx->osd_show_percentage_until - now > 36000000)
1552 mpctx->osd_show_percentage_until = 0;
1554 if (!last_update)
1555 last_update = now;
1556 diff = now >= last_update ? now - last_update : 0;
1558 last_update = now;
1560 // Look for the first message in the stack with high enough level.
1561 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1562 prev = msg->prev;
1563 if (msg->level > opts->osd_level && hidden_dec_done)
1564 continue;
1565 // The message has a high enough level or it is the first hidden one
1566 // in both cases we decrement the timer or kill it.
1567 if (!msg->started || msg->time > diff) {
1568 if (msg->started)
1569 msg->time -= diff;
1570 else
1571 msg->started = 1;
1572 // display it
1573 if (msg->level <= opts->osd_level)
1574 return msg;
1575 hidden_dec_done = 1;
1576 continue;
1578 // kill the message
1579 talloc_free(msg);
1580 if (last) {
1581 last->prev = prev;
1582 msg = last;
1583 } else {
1584 osd_msg_stack = prev;
1585 msg = NULL;
1588 // Nothing found
1589 return NULL;
1593 * \brief Display the OSD bar.
1595 * Display the OSD bar or fall back on a simple message.
1599 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1600 double min, double max, double val)
1602 struct MPOpts *opts = &mpctx->opts;
1603 if (opts->osd_level < 1)
1604 return;
1606 if (mpctx->sh_video) {
1607 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1608 vo_osd_progbar_type = type;
1609 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1610 vo_osd_changed(OSDTYPE_PROGBAR);
1611 return;
1614 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1615 name, ROUND(100 * (val - min) / (max - min)));
1619 * \brief Display text subtitles on the OSD
1621 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1623 int i;
1624 vo_sub = subs;
1625 vo_osd_changed(OSDTYPE_SUBTITLE);
1626 if (!mpctx->sh_video) {
1627 // reverse order, since newest set_osd_msg is displayed first
1628 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1629 if (!subs || i >= subs->lines || !subs->text[i])
1630 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1631 else {
1632 // HACK: currently display time for each sub line
1633 // except the last is set to 2 seconds.
1634 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1635 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1636 "%s", subs->text[i]);
1643 * \brief Update the OSD message line.
1645 * This function displays the current message on the vo OSD or on the term.
1646 * If the stack is empty and the OSD level is high enough the timer
1647 * is displayed (only on the vo OSD).
1651 static void update_osd_msg(struct MPContext *mpctx)
1653 struct MPOpts *opts = &mpctx->opts;
1654 mp_osd_msg_t *msg;
1655 struct osd_state *osd = mpctx->osd;
1657 if (mpctx->add_osd_seek_info) {
1658 double percentage = get_percent_pos(mpctx);
1659 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1660 if (mpctx->sh_video)
1661 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1662 mpctx->add_osd_seek_info = false;
1665 // Look if we have a msg
1666 if ((msg = get_osd_msg(mpctx)) && !msg->show_position) {
1667 if (strcmp(osd->osd_text, msg->msg)) {
1668 osd_set_text(osd, msg->msg);
1669 if (mpctx->sh_video)
1670 vo_osd_changed(OSDTYPE_OSD);
1671 else if (opts->term_osd)
1672 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1673 msg->msg);
1675 return;
1678 int osdlevel = opts->osd_level;
1679 if (msg && msg->show_position)
1680 osdlevel = 3;
1682 if (mpctx->sh_video) {
1683 // fallback on the timer
1684 char osd_text_timer[128] = {0};
1685 if (osdlevel >= 2) {
1686 int len = get_time_length(mpctx);
1687 int percentage = -1;
1688 char percentage_text[10];
1689 char fractions_text[4];
1690 double fpts = get_current_time(mpctx);
1691 int pts = fpts;
1693 if (mpctx->osd_show_percentage_until)
1694 percentage = get_percent_pos(mpctx);
1696 if (percentage >= 0)
1697 snprintf(percentage_text, 9, " (%d%%)", percentage);
1698 else
1699 percentage_text[0] = 0;
1701 if (opts->osd_fractions == 1) {
1702 //print fractions as sub-second timestamp
1703 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1704 (int)((fpts - pts) * 100));
1705 } else if (opts->osd_fractions == 2) {
1706 /* Print fractions by estimating the frame count within the
1707 * second.
1709 * Rounding or cutting off numbers after the decimal point
1710 * causes problems because of float's precision and movies
1711 * whose first frame is not exactly at timestamp 0. Therefore,
1712 * we add 0.2 and cut off at the decimal point, which proved
1713 * to be good heuristic.
1715 double fps = mpctx->sh_video->fps;
1716 if (fps <= 1 || fps > 99)
1717 strcpy(fractions_text, ".??");
1718 else
1719 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1720 (int) ((fpts - pts) * fps + 0.2));
1721 } else {
1722 //do not print fractions
1723 fractions_text[0] = 0;
1726 osd_get_function_sym(osd_text_timer, sizeof(osd_text_timer),
1727 mpctx->osd_function);
1728 size_t blen = strlen(osd_text_timer);
1730 if (osdlevel == 3)
1731 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1732 " %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1733 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1734 len / 3600, (len / 60) % 60, len % 60,
1735 percentage_text);
1736 else
1737 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1738 " %02d:%02d:%02d%s%s",
1739 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1740 percentage_text);
1743 if (strcmp(osd->osd_text, osd_text_timer)) {
1744 osd_set_text(osd, osd_text_timer);
1745 vo_osd_changed(OSDTYPE_OSD);
1747 return;
1750 // Clear the term osd line
1751 if (opts->term_osd && osd->osd_text[0]) {
1752 osd->osd_text[0] = 0;
1753 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1758 void reinit_audio_chain(struct MPContext *mpctx)
1760 struct MPOpts *opts = &mpctx->opts;
1761 struct ao *ao;
1762 if (!mpctx->sh_audio) {
1763 uninit_player(mpctx, INITIALIZED_AO);
1764 return;
1766 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1767 current_module = "init_audio_codec";
1768 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1769 goto init_error;
1770 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1773 current_module = "af_preinit";
1774 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1775 mpctx->initialized_flags |= INITIALIZED_AO;
1776 mpctx->ao = ao_create(opts, mpctx->input);
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.volstep = volstep;
1823 mpctx->mixer.softvol = opts->softvol;
1824 mpctx->mixer.softvol_max = opts->softvol_max;
1825 mixer_reinit(&mpctx->mixer, ao);
1826 mpctx->syncing_audio = true;
1827 return;
1829 init_error:
1830 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1831 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1832 mpctx->d_audio->id = -2;
1836 // Return pts value corresponding to the end point of audio written to the
1837 // ao so far.
1838 static double written_audio_pts(struct MPContext *mpctx)
1840 sh_audio_t *sh_audio = mpctx->sh_audio;
1841 if (!sh_audio)
1842 return MP_NOPTS_VALUE;
1843 demux_stream_t *d_audio = mpctx->d_audio;
1844 // first calculate the end pts of audio that has been output by decoder
1845 double a_pts = sh_audio->pts;
1846 if (a_pts != MP_NOPTS_VALUE)
1847 // Good, decoder supports new way of calculating audio pts.
1848 // sh_audio->pts is the timestamp of the latest input packet with
1849 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1850 // the amount of bytes the decoder has written after that timestamp.
1851 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1852 else {
1853 // Decoder doesn't support new way of calculating pts (or we're
1854 // being called before it has decoded anything with known timestamp).
1855 // Use the old method of audio pts calculation: take the timestamp
1856 // of last packet with known pts the decoder has read data from,
1857 // and add amount of bytes read after the beginning of that packet
1858 // divided by input bps. This will be inaccurate if the input/output
1859 // ratio is not constant for every audio packet or if it is constant
1860 // but not accurately known in sh_audio->i_bps.
1862 a_pts = d_audio->pts;
1863 if (a_pts == MP_NOPTS_VALUE)
1864 return a_pts;
1866 // ds_tell_pts returns bytes read after last timestamp from
1867 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1868 // it has read but not decoded
1869 if (sh_audio->i_bps)
1870 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1871 (double)sh_audio->i_bps;
1873 // Now a_pts hopefully holds the pts for end of audio from decoder.
1874 // Substract data in buffers between decoder and audio out.
1876 // Decoded but not filtered
1877 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1879 // Data buffered in audio filters, measured in bytes of "missing" output
1880 double buffered_output = af_calc_delay(sh_audio->afilter);
1882 // Data that was ready for ao but was buffered because ao didn't fully
1883 // accept everything to internal buffers yet
1884 buffered_output += mpctx->ao->buffer.len;
1886 // Filters divide audio length by playback_speed, so multiply by it
1887 // to get the length in original units without speedup or slowdown
1888 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1890 return a_pts + mpctx->video_offset;
1893 // Return pts value corresponding to currently playing audio.
1894 double playing_audio_pts(struct MPContext *mpctx)
1896 double pts = written_audio_pts(mpctx);
1897 if (pts == MP_NOPTS_VALUE)
1898 return pts;
1899 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1902 static bool is_av_sub(int type)
1904 return type == 'b' || type == 'p' || type == 'x';
1907 void update_subtitles(struct MPContext *mpctx, double refpts_tl, bool reset)
1909 mpctx->osd->sub_offset = mpctx->video_offset;
1910 struct MPOpts *opts = &mpctx->opts;
1911 struct sh_video *sh_video = mpctx->sh_video;
1912 struct demux_stream *d_sub = mpctx->d_sub;
1913 double refpts_s = refpts_tl - mpctx->osd->sub_offset;
1914 double curpts_s = refpts_s + opts->sub_delay;
1915 unsigned char *packet = NULL;
1916 int len;
1917 struct sh_sub *sh_sub = d_sub->sh;
1918 int type = sh_sub ? sh_sub->type : 'v';
1919 static subtitle subs;
1920 if (reset) {
1921 if (sh_sub)
1922 sub_reset(sh_sub, mpctx->osd);
1923 sub_clear_text(&subs, MP_NOPTS_VALUE);
1924 if (vo_sub)
1925 set_osd_subtitle(mpctx, NULL);
1926 if (vo_spudec) {
1927 spudec_reset(vo_spudec);
1928 vo_osd_changed(OSDTYPE_SPU);
1930 return;
1932 // find sub
1933 if (mpctx->subdata) {
1934 if (sub_fps == 0)
1935 sub_fps = sh_video ? sh_video->fps : 25;
1936 current_module = "find_sub";
1937 find_sub(mpctx, mpctx->subdata, curpts_s *
1938 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1939 if (vo_sub)
1940 mpctx->vo_sub_last = vo_sub;
1943 // DVD sub:
1944 if (vobsub_id >= 0 || type == 'v') {
1945 int timestamp;
1946 current_module = "spudec";
1947 /* Get a sub packet from the DVD or a vobsub */
1948 while (1) {
1949 // Vobsub
1950 len = 0;
1951 if (vo_vobsub) {
1952 if (curpts_s >= 0) {
1953 len = vobsub_get_packet(vo_vobsub, curpts_s,
1954 (void **)&packet, &timestamp);
1955 if (len > 0)
1956 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1957 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1958 len, refpts_s, sh_video->timer,
1959 timestamp / 90000.0, timestamp);
1961 } else {
1962 // DVD sub
1963 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1964 if (len > 0) {
1965 // XXX This is wrong, sh_video->pts can be arbitrarily
1966 // much behind demuxing position. Unfortunately using
1967 // d_video->pts which would have been the simplest
1968 // improvement doesn't work because mpeg specific hacks
1969 // in video.c set d_video->pts to 0.
1970 float x = d_sub->pts - refpts_s;
1971 if (x > -20 && x < 20) // prevent missing subs on pts reset
1972 timestamp = 90000 * d_sub->pts;
1973 else
1974 timestamp = 90000 * curpts_s;
1975 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1976 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1977 refpts_s, d_sub->pts, timestamp);
1980 if (len <= 0 || !packet)
1981 break;
1982 // create it only here, since with some broken demuxers we might
1983 // type = v but no DVD sub and we currently do not change the
1984 // "original frame size" ever after init, leading to wrong-sized
1985 // PGS subtitles.
1986 if (!vo_spudec)
1987 vo_spudec = spudec_new(NULL);
1988 if (vo_vobsub || timestamp >= 0)
1989 spudec_assemble(vo_spudec, packet, len, timestamp);
1991 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1992 if (type == 'd' && !d_sub->demuxer->teletext) {
1993 tt_stream_props tsp = { 0 };
1994 void *ptr = &tsp;
1995 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
1996 VBI_CONTROL_TRUE)
1997 d_sub->demuxer->teletext = ptr;
1999 if (d_sub->non_interleaved)
2000 ds_get_next_pts(d_sub);
2002 while (d_sub->first) {
2003 double subpts_s = ds_get_next_pts(d_sub);
2004 if (subpts_s > curpts_s) {
2005 // Libass handled subs can be fed to it in advance
2006 if (!opts->ass_enabled || !is_text_sub(type))
2007 break;
2008 // Try to avoid demuxing whole file at once
2009 if (d_sub->non_interleaved && subpts_s > curpts_s + 1)
2010 break;
2012 double duration = d_sub->first->duration;
2013 len = ds_get_packet_sub(d_sub, &packet);
2014 if (type == 'm') {
2015 if (len < 2)
2016 continue;
2017 len = FFMIN(len - 2, AV_RB16(packet));
2018 packet += 2;
2020 if (type == 'd') {
2021 if (d_sub->demuxer->teletext) {
2022 uint8_t *p = packet;
2023 p++;
2024 len--;
2025 while (len >= 46) {
2026 int sublen = p[1];
2027 if (p[0] == 2 || p[0] == 3)
2028 teletext_control(d_sub->demuxer->teletext,
2029 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2030 p += sublen + 2;
2031 len -= sublen + 2;
2034 continue;
2036 if (sh_sub && sh_sub->active) {
2037 sub_decode(sh_sub, mpctx->osd, packet, len, subpts_s, duration);
2038 continue;
2040 if (subpts_s != MP_NOPTS_VALUE) {
2041 if (duration < 0)
2042 sub_clear_text(&subs, MP_NOPTS_VALUE);
2043 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2044 int i;
2045 unsigned char *p = packet;
2046 for (i = 0; i < 8 && *p != '\0'; p++)
2047 if (*p == ',')
2048 i++;
2049 if (*p == '\0') /* Broken line? */
2050 continue;
2051 len -= p - packet;
2052 packet = p;
2054 double endpts_s = MP_NOPTS_VALUE;
2055 if (subpts_s != MP_NOPTS_VALUE && duration >= 0)
2056 endpts_s = subpts_s + duration;
2057 sub_add_text(&subs, packet, len, endpts_s);
2058 set_osd_subtitle(mpctx, &subs);
2060 if (d_sub->non_interleaved)
2061 ds_get_next_pts(d_sub);
2063 if (!opts->ass_enabled)
2064 if (sub_clear_text(&subs, curpts_s))
2065 set_osd_subtitle(mpctx, &subs);
2067 if (vo_spudec) {
2068 spudec_heartbeat(vo_spudec, 90000 * curpts_s);
2069 if (spudec_changed(vo_spudec))
2070 vo_osd_changed(OSDTYPE_SPU);
2073 current_module = NULL;
2076 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2078 int page_changed;
2080 if (!demuxer->teletext)
2081 return;
2083 //Also forcing page update when such ioctl is not supported or call error occured
2084 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2085 &page_changed) != VBI_CONTROL_TRUE)
2086 page_changed = 1;
2088 if (!page_changed)
2089 return;
2091 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2092 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2093 vo_osd_teletext_page = NULL;
2094 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2095 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2096 vo_osd_teletext_half = 0;
2097 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2098 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2099 vo_osd_teletext_mode = 0;
2100 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2101 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2102 vo_osd_teletext_format = 0;
2103 vo_osd_changed(OSDTYPE_TELETEXT);
2105 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2108 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2110 struct MPOpts *opts = &mpctx->opts;
2111 // check for frame-drop:
2112 current_module = "check_framedrop";
2113 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2114 static int dropped_frames;
2115 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2116 float d = delay - mpctx->delay;
2117 ++total_frame_cnt;
2118 // we should avoid dropping too many frames in sequence unless we
2119 // are too late. and we allow 100ms A-V delay here:
2120 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2121 && !mpctx->restart_playback) {
2122 ++drop_frame_cnt;
2123 ++dropped_frames;
2124 return frame_dropping;
2125 } else
2126 dropped_frames = 0;
2128 return 0;
2132 #ifdef HAVE_RTC
2133 int rtc_fd = -1;
2134 #endif
2136 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2138 #ifdef HAVE_RTC
2139 if (rtc_fd >= 0) {
2140 // -------- RTC -----------
2141 current_module = "sleep_rtc";
2142 while (time_frame > 0.000) {
2143 unsigned long rtc_ts;
2144 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2145 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2146 "Linux RTC read error: %s\n", strerror(errno));
2147 time_frame -= get_relative_time(mpctx);
2149 } else
2150 #endif
2152 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2153 // unnecessarily high CPU usage
2154 struct MPOpts *opts = &mpctx->opts;
2155 float margin = opts->softsleep ? 0.011 : 0;
2156 current_module = "sleep_timer";
2157 while (time_frame > margin) {
2158 usec_sleep(1000000 * (time_frame - margin));
2159 time_frame -= get_relative_time(mpctx);
2161 if (opts->softsleep) {
2162 current_module = "sleep_soft";
2163 if (time_frame < 0)
2164 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2165 "Warning! Softsleep underflow!\n");
2166 while (time_frame > 0)
2167 time_frame -= get_relative_time(mpctx); // burn the CPU
2170 return time_frame;
2173 static int select_subtitle(MPContext *mpctx)
2175 struct MPOpts *opts = &mpctx->opts;
2176 // find the best sub to use
2177 int id;
2178 int found = 0;
2179 mpctx->global_sub_pos = -1; // no subs by default
2180 if (vobsub_id >= 0) {
2181 // if user asks for a vobsub id, use that first.
2182 id = vobsub_id;
2183 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2184 M_PROPERTY_OK;
2187 if (!found && opts->sub_id >= 0) {
2188 // if user asks for a dvd sub id, use that next.
2189 id = opts->sub_id;
2190 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2191 M_PROPERTY_OK;
2194 if (!found) {
2195 // if there are text subs to use, use those. (autosubs come last here)
2196 id = 0;
2197 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2198 M_PROPERTY_OK;
2201 if (!found && opts->sub_id == -1) {
2202 // finally select subs by language and container hints
2203 if (opts->sub_id == -1)
2204 opts->sub_id =
2205 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2206 opts->sub_lang);
2207 if (opts->sub_id >= 0) {
2208 id = opts->sub_id;
2209 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2210 M_PROPERTY_OK;
2213 return found;
2216 #ifdef CONFIG_DVDNAV
2217 #ifndef FF_B_TYPE
2218 #define FF_B_TYPE 3
2219 #endif
2220 /// store decoded video image
2221 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2222 mp_image_t *from_mpi)
2224 mp_image_t *mpi;
2226 /// Do not store B-frames
2227 if (from_mpi->pict_type == FF_B_TYPE)
2228 return to_mpi;
2230 if (to_mpi &&
2231 to_mpi->w == from_mpi->w &&
2232 to_mpi->h == from_mpi->h &&
2233 to_mpi->imgfmt == from_mpi->imgfmt)
2234 mpi = to_mpi;
2235 else {
2236 if (to_mpi)
2237 free_mp_image(to_mpi);
2238 if (from_mpi->w == 0 || from_mpi->h == 0)
2239 return NULL;
2240 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2243 copy_mpi(mpi, from_mpi);
2244 return mpi;
2247 static void mp_dvdnav_reset_stream(MPContext *ctx)
2249 struct MPOpts *opts = &ctx->opts;
2250 if (ctx->sh_video) {
2251 /// clear video pts
2252 ctx->d_video->pts = 0.0f;
2253 ctx->sh_video->pts = 0.0f;
2254 ctx->sh_video->i_pts = 0.0f;
2255 ctx->sh_video->last_pts = 0.0f;
2256 ctx->sh_video->num_buffered_pts = 0;
2257 ctx->sh_video->num_frames = 0;
2258 ctx->sh_video->num_frames_decoded = 0;
2259 ctx->sh_video->timer = 0.0f;
2260 ctx->sh_video->stream_delay = 0.0f;
2261 ctx->sh_video->timer = 0;
2262 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2265 if (ctx->sh_audio) {
2266 /// free audio packets and reset
2267 ds_free_packs(ctx->d_audio);
2268 audio_delay -= ctx->sh_audio->stream_delay;
2269 ctx->delay = -audio_delay;
2270 ao_reset(ctx->ao);
2271 resync_audio_stream(ctx->sh_audio);
2274 audio_delay = 0.0f;
2275 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2276 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2277 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2278 if (dvdsub_lang_id != opts->sub_id) {
2279 opts->sub_id = dvdsub_lang_id;
2280 select_subtitle(ctx);
2284 /// clear all EOF related flags
2285 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2288 /// Restore last decoded DVDNAV (still frame)
2289 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2290 int *in_size,
2291 unsigned char **start,
2292 mp_image_t *decoded_frame)
2294 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2295 return decoded_frame;
2297 /// a change occurred in dvdnav stream
2298 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2299 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2300 mp_dvdnav_context_free(mpctx);
2301 mp_dvdnav_reset_stream(mpctx);
2302 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2303 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2306 if (*in_size < 0) {
2307 float len;
2309 /// Display still frame, if any
2310 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2311 decoded_frame = mpctx->nav_smpi;
2313 /// increment video frame : continue playing after still frame
2314 len = get_time_length(mpctx);
2315 if (mpctx->sh_video->pts >= len &&
2316 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2317 mp_dvdnav_skip_still(mpctx->stream);
2318 mp_dvdnav_skip_wait(mpctx->stream);
2320 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2322 if (mpctx->nav_buffer) {
2323 *start = mpctx->nav_start;
2324 *in_size = mpctx->nav_in_size;
2325 if (mpctx->nav_start)
2326 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2330 return decoded_frame;
2333 /// Save last decoded DVDNAV (still frame)
2334 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2335 unsigned char *start,
2336 mp_image_t *decoded_frame)
2338 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2339 return;
2341 free(mpctx->nav_buffer);
2342 mpctx->nav_buffer = NULL;
2343 mpctx->nav_start = NULL;
2344 mpctx->nav_in_size = -1;
2346 if (in_size > 0)
2347 mpctx->nav_buffer = malloc(in_size);
2348 if (mpctx->nav_buffer) {
2349 mpctx->nav_start = start;
2350 mpctx->nav_in_size = in_size;
2351 memcpy(mpctx->nav_buffer, start, in_size);
2354 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2355 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2357 #endif /* CONFIG_DVDNAV */
2359 /* Modify video timing to match the audio timeline. There are two main
2360 * reasons this is needed. First, video and audio can start from different
2361 * positions at beginning of file or after a seek (MPlayer starts both
2362 * immediately even if they have different pts). Second, the file can have
2363 * audio timestamps that are inconsistent with the duration of the audio
2364 * packets, for example two consecutive timestamp values differing by
2365 * one second but only a packet with enough samples for half a second
2366 * of playback between them.
2368 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2370 current_module = "av_sync";
2372 if (!mpctx->sh_audio || mpctx->syncing_audio)
2373 return;
2375 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2376 double v_pts = mpctx->sh_video->pts;
2377 double av_delay = a_pts - v_pts;
2378 // Try to sync vo_flip() so it will *finish* at given time
2379 av_delay += mpctx->last_vo_flip_duration;
2380 av_delay -= audio_delay; // This much pts difference is desired
2382 double change = av_delay * 0.1;
2383 double max_change = default_max_pts_correction >= 0 ?
2384 default_max_pts_correction : frame_time * 0.1;
2385 if (change < -max_change)
2386 change = -max_change;
2387 else if (change > max_change)
2388 change = max_change;
2389 mpctx->delay += change;
2390 mpctx->total_avsync_change += change;
2393 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2394 double pts)
2396 if (mpctx->paused)
2397 return 0;
2398 struct ao *ao = mpctx->ao;
2399 double bps = ao->bps / mpctx->opts.playback_speed;
2400 ao->pts = pts;
2401 // hack used by some mpeg-writing AOs
2402 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2403 mpctx->delay) * 90000.0;
2404 int played = ao_play(mpctx->ao, data, len, flags);
2405 if (played > 0) {
2406 mpctx->delay += played / bps;
2407 // Keep correct pts for remaining data - could be used to flush
2408 // remaining buffer when closing ao.
2409 ao->pts += played / bps;
2411 return played;
2414 #define ASYNC_PLAY_DONE -3
2415 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2417 struct ao *ao = mpctx->ao;
2418 struct MPOpts *opts = &mpctx->opts;
2419 sh_audio_t * const sh_audio = mpctx->sh_audio;
2420 int res;
2422 // Timing info may not be set without
2423 res = decode_audio(sh_audio, &ao->buffer, 1);
2424 if (res < 0)
2425 return res;
2427 int bytes;
2428 bool did_retry = false;
2429 double written_pts;
2430 double bps = ao->bps / opts->playback_speed;
2431 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2432 mpctx->hrseek_active = false;
2433 while (1) {
2434 written_pts = written_audio_pts(mpctx);
2435 double ptsdiff;
2436 if (hrseek)
2437 ptsdiff = written_pts - mpctx->hrseek_pts;
2438 else
2439 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2440 - audio_delay;
2441 bytes = ptsdiff * bps;
2442 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2444 // ogg demuxers give packets without timing
2445 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2446 if (!did_retry) {
2447 // Try to read more data to see packets that have pts
2448 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2449 if (res < 0)
2450 return res;
2451 did_retry = true;
2452 continue;
2454 bytes = 0;
2457 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2458 bytes = 0;
2460 if (bytes > 0)
2461 break;
2463 mpctx->syncing_audio = false;
2464 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2465 int res = decode_audio(sh_audio, &ao->buffer, a);
2466 bytes += ao->buffer.len;
2467 if (bytes >= 0) {
2468 memmove(ao->buffer.start,
2469 ao->buffer.start + ao->buffer.len - bytes, bytes);
2470 ao->buffer.len = bytes;
2471 if (res < 0)
2472 return res;
2473 return decode_audio(sh_audio, &ao->buffer, playsize);
2475 ao->buffer.len = 0;
2476 if (res < 0)
2477 return res;
2479 if (hrseek)
2480 // Don't add silence in audio-only case even if position is too late
2481 return 0;
2482 int fillbyte = 0;
2483 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2484 fillbyte = 0x80;
2485 if (bytes >= playsize) {
2486 /* This case could fall back to the one below with
2487 * bytes = playsize, but then silence would keep accumulating
2488 * in a_out_buffer if the AO accepts less data than it asks for
2489 * in playsize. */
2490 char *p = malloc(playsize);
2491 memset(p, fillbyte, playsize);
2492 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2493 free(p);
2494 return ASYNC_PLAY_DONE;
2496 mpctx->syncing_audio = false;
2497 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2498 return decode_audio(sh_audio, &ao->buffer, playsize);
2501 static int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
2503 struct MPOpts *opts = &mpctx->opts;
2504 struct ao *ao = mpctx->ao;
2505 unsigned int t;
2506 double tt;
2507 int playsize;
2508 int playflags = 0;
2509 bool audio_eof = false;
2510 bool partial_fill = false;
2511 sh_audio_t * const sh_audio = mpctx->sh_audio;
2512 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2513 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2515 current_module = "play_audio";
2517 // hack used by some mpeg-writing AOs
2518 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2519 mpctx->delay) * 90000.0;
2521 if (mpctx->paused)
2522 playsize = 1; // just initialize things (audio pts at least)
2523 else
2524 playsize = ao_get_space(ao);
2526 // Fill buffer if needed:
2527 current_module = "decode_audio";
2528 t = GetTimer();
2530 // Coming here with hrseek_active still set means audio-only
2531 if (!mpctx->sh_video)
2532 mpctx->syncing_audio = false;
2533 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2534 mpctx->syncing_audio = false;
2535 mpctx->hrseek_active = false;
2538 int res;
2539 if (mpctx->syncing_audio || mpctx->hrseek_active)
2540 res = audio_start_sync(mpctx, playsize);
2541 else
2542 res = decode_audio(sh_audio, &ao->buffer, playsize);
2543 if (res < 0) { // EOF, error or format change
2544 if (res == -2) {
2545 /* The format change isn't handled too gracefully. A more precise
2546 * implementation would require draining buffered old-format audio
2547 * while displaying video, then doing the output format switch.
2549 uninit_player(mpctx, INITIALIZED_AO);
2550 reinit_audio_chain(mpctx);
2551 return -1;
2552 } else if (res == ASYNC_PLAY_DONE)
2553 return 0;
2554 else if (mpctx->d_audio->eof)
2555 audio_eof = true;
2557 t = GetTimer() - t;
2558 tt = t * 0.000001f;
2559 audio_time_usage += tt;
2560 if (endpts != MP_NOPTS_VALUE && modifiable_audio_format) {
2561 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2562 * ao->bps / opts->playback_speed;
2563 if (playsize > bytes) {
2564 playsize = FFMAX(bytes, 0);
2565 playflags |= AOPLAY_FINAL_CHUNK;
2566 audio_eof = true;
2567 partial_fill = true;
2571 assert(ao->buffer.len % unitsize == 0);
2572 if (playsize > ao->buffer.len) {
2573 partial_fill = true;
2574 playsize = ao->buffer.len;
2575 if (audio_eof)
2576 playflags |= AOPLAY_FINAL_CHUNK;
2578 playsize -= playsize % unitsize;
2579 if (!playsize)
2580 return partial_fill && audio_eof ? -2 : -partial_fill;
2582 // play audio:
2583 current_module = "play_audio";
2585 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2586 written_audio_pts(mpctx));
2587 assert(played % unitsize == 0);
2588 ao->buffer_playable_size = playsize - played;
2590 if (played > 0) {
2591 ao->buffer.len -= played;
2592 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2593 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2594 // Sanity check to avoid hanging in case current ao doesn't output
2595 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2596 return -2;
2599 return -partial_fill;
2602 int reinit_video_chain(struct MPContext *mpctx)
2604 struct MPOpts *opts = &mpctx->opts;
2605 sh_video_t * const sh_video = mpctx->sh_video;
2606 if (!sh_video) {
2607 uninit_player(mpctx, INITIALIZED_VO);
2608 return 0;
2610 double ar = -1.0;
2611 //================== Init VIDEO (codec & libvo) ==========================
2612 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2613 current_module = "preinit_libvo";
2615 //shouldn't we set dvideo->id=-2 when we fail?
2616 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2617 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->key_fifo,
2618 mpctx->input))) {
2619 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2620 "the selected video_out (-vo) device.\n");
2621 goto err_out;
2623 mpctx->initialized_flags |= INITIALIZED_VO;
2626 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2627 &ar) != STREAM_UNSUPPORTED)
2628 mpctx->sh_video->stream_aspect = ar;
2629 current_module = "init_video_filters";
2631 char *vf_arg[] = {
2632 "_oldargs_", (char *)mpctx->video_out, NULL
2634 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2637 #ifdef CONFIG_ASS
2638 if (opts->ass_enabled) {
2639 int i;
2640 int insert = 1;
2641 if (opts->vf_settings)
2642 for (i = 0; opts->vf_settings[i].name; ++i)
2643 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2644 insert = 0;
2645 break;
2647 if (insert) {
2648 extern vf_info_t vf_info_ass;
2649 const vf_info_t *libass_vfs[] = {
2650 &vf_info_ass, NULL
2652 char *vf_arg[] = {
2653 "auto", "1", NULL
2655 int retcode = 0;
2656 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2657 sh_video->vfilter,
2658 "ass", vf_arg,
2659 &retcode);
2660 if (vf_ass)
2661 sh_video->vfilter = vf_ass;
2662 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2663 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2664 else
2665 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2666 "ASS: cannot add video filter\n");
2669 #endif
2671 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2673 if (opts->ass_enabled)
2674 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2675 mpctx->ass_library);
2677 current_module = "init_video_codec";
2679 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2681 if (!sh_video->initialized) {
2682 if (!opts->fixed_vo)
2683 uninit_player(mpctx, INITIALIZED_VO);
2684 goto err_out;
2687 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2689 if (sh_video->codec)
2690 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2691 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2693 sh_video->last_pts = MP_NOPTS_VALUE;
2694 sh_video->num_buffered_pts = 0;
2695 sh_video->next_frame_time = 0;
2696 mpctx->restart_playback = true;
2697 mpctx->delay = 0;
2699 if (opts->auto_quality > 0) {
2700 // Auto quality option enabled
2701 output_quality = get_video_quality_max(sh_video);
2702 if (opts->auto_quality > output_quality)
2703 opts->auto_quality = output_quality;
2704 else
2705 output_quality = opts->auto_quality;
2706 mp_msg(MSGT_CPLAYER, MSGL_V,
2707 "AutoQ: setting quality to %d.\n", output_quality);
2708 set_video_quality(sh_video, output_quality);
2711 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2713 current_module = "init_vo";
2715 return 1;
2717 err_out:
2718 mpctx->sh_video = mpctx->d_video->sh = NULL;
2719 return 0;
2722 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2724 struct sh_video *sh_video = mpctx->sh_video;
2725 double frame_time = 0;
2726 struct vo *video_out = mpctx->video_out;
2727 while (1) {
2728 current_module = "filter_video";
2729 // In nocorrect-pts mode there is no way to properly time these frames
2730 if (vo_get_buffered_frame(video_out, 0) >= 0)
2731 break;
2732 if (vf_output_queued_frame(sh_video->vfilter))
2733 break;
2734 unsigned char *packet = NULL;
2735 frame_time = sh_video->next_frame_time;
2736 if (mpctx->restart_playback)
2737 frame_time = 0;
2738 int in_size = 0;
2739 while (!in_size)
2740 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2741 &packet, force_fps);
2742 if (in_size < 0) {
2743 #ifdef CONFIG_DVDNAV
2744 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2745 if (mp_dvdnav_is_eof(mpctx->stream))
2746 return -1;
2747 if (mpctx->d_video)
2748 mpctx->d_video->eof = 0;
2749 if (mpctx->d_audio)
2750 mpctx->d_audio->eof = 0;
2751 mpctx->stream->eof = 0;
2752 } else
2753 #endif
2754 return -1;
2756 if (in_size > max_framesize)
2757 max_framesize = in_size;
2758 sh_video->timer += frame_time;
2759 if (mpctx->sh_audio)
2760 mpctx->delay -= frame_time;
2761 // video_read_frame can change fps (e.g. for ASF video)
2762 vo_fps = sh_video->fps;
2763 int framedrop_type = check_framedrop(mpctx, frame_time);
2764 current_module = "decode video";
2766 void *decoded_frame;
2767 #ifdef CONFIG_DVDNAV
2768 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2769 if (in_size >= 0 && !decoded_frame)
2770 #endif
2771 decoded_frame = decode_video(sh_video, sh_video->ds->current, packet,
2772 in_size, framedrop_type, sh_video->pts);
2773 #ifdef CONFIG_DVDNAV
2774 // Save last still frame for future display
2775 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2776 #endif
2777 if (decoded_frame) {
2778 current_module = "filter video";
2779 filter_video(sh_video, decoded_frame, sh_video->pts);
2781 break;
2783 return frame_time;
2786 static void determine_frame_pts(struct MPContext *mpctx)
2788 struct sh_video *sh_video = mpctx->sh_video;
2789 struct MPOpts *opts = &mpctx->opts;
2791 if (opts->user_pts_assoc_mode)
2792 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2793 else if (sh_video->pts_assoc_mode == 0) {
2794 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2795 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2796 sh_video->pts_assoc_mode = 1;
2797 else
2798 sh_video->pts_assoc_mode = 2;
2799 } else {
2800 int probcount1 = sh_video->num_reordered_pts_problems;
2801 int probcount2 = sh_video->num_sorted_pts_problems;
2802 if (sh_video->pts_assoc_mode == 2) {
2803 int tmp = probcount1;
2804 probcount1 = probcount2;
2805 probcount2 = tmp;
2807 if (probcount1 >= probcount2 * 1.5 + 2) {
2808 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2809 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2810 "%d.\n", sh_video->pts_assoc_mode);
2813 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2814 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2817 static double update_video(struct MPContext *mpctx)
2819 struct sh_video *sh_video = mpctx->sh_video;
2820 struct vo *video_out = mpctx->video_out;
2821 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2822 mpctx->osd); // hack for vf_expand
2823 if (!mpctx->opts.correct_pts)
2824 return update_video_nocorrect_pts(mpctx);
2826 double pts;
2828 while (1) {
2829 current_module = "filter_video";
2830 if (vo_get_buffered_frame(video_out, false) >= 0)
2831 break;
2832 // XXX Time used in this call is not counted in any performance
2833 // timer now
2834 if (vf_output_queued_frame(sh_video->vfilter))
2835 break;
2836 int in_size = 0;
2837 unsigned char *buf = NULL;
2838 pts = MP_NOPTS_VALUE;
2839 struct demux_packet *pkt;
2840 while (1) {
2841 pkt = ds_get_packet2(mpctx->d_video, false);
2842 if (!pkt || pkt->len)
2843 break;
2844 /* Packets with size 0 are assumed to not correspond to frames,
2845 * but to indicate the absence of a frame in formats like AVI
2846 * that must have packets at fixed timecode intervals. */
2848 if (pkt) {
2849 in_size = pkt->len;
2850 buf = pkt->buffer;
2851 pts = pkt->pts;
2853 if (pts != MP_NOPTS_VALUE)
2854 pts += mpctx->video_offset;
2855 if (in_size > max_framesize)
2856 max_framesize = in_size;
2857 current_module = "decode video";
2858 if (pts >= mpctx->hrseek_pts - .005)
2859 mpctx->hrseek_framedrop = false;
2860 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2861 check_framedrop(mpctx, sh_video->frametime);
2862 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2863 framedrop_type, pts);
2864 if (decoded_frame) {
2865 determine_frame_pts(mpctx);
2866 current_module = "filter video";
2867 filter_video(sh_video, decoded_frame, sh_video->pts);
2868 } else if (!pkt) {
2869 if (vo_get_buffered_frame(video_out, true) < 0)
2870 return -1;
2872 break;
2875 if (!video_out->frame_loaded)
2876 return 0;
2878 pts = video_out->next_pts;
2879 if (pts == MP_NOPTS_VALUE) {
2880 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2881 // Try to use decoder pts from before filters
2882 pts = sh_video->pts;
2883 if (pts == MP_NOPTS_VALUE)
2884 pts = sh_video->last_pts;
2886 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2887 vo_skip_frame(video_out);
2888 return 0;
2890 mpctx->hrseek_active = false;
2891 sh_video->pts = pts;
2892 if (sh_video->last_pts == MP_NOPTS_VALUE)
2893 sh_video->last_pts = sh_video->pts;
2894 else if (sh_video->last_pts > sh_video->pts) {
2895 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2896 sh_video->pts, sh_video->last_pts);
2897 /* If the difference in pts is small treat it as jitter around the
2898 * right value (possibly caused by incorrect timestamp ordering) and
2899 * just show this frame immediately after the last one.
2900 * Treat bigger differences as timestamp resets and start counting
2901 * timing of later frames from the position of this one. */
2902 if (sh_video->last_pts - sh_video->pts > 0.5)
2903 sh_video->last_pts = sh_video->pts;
2904 else
2905 sh_video->pts = sh_video->last_pts;
2907 double frame_time = sh_video->pts - sh_video->last_pts;
2908 sh_video->last_pts = sh_video->pts;
2909 sh_video->timer += frame_time;
2910 if (mpctx->sh_audio)
2911 mpctx->delay -= frame_time;
2912 return frame_time;
2915 static int get_cache_fill(struct MPContext *mpctx)
2917 #ifdef CONFIG_STREAM_CACHE
2918 if (mpctx->stream && mpctx->stream->cached)
2919 return cache_fill_status(mpctx->stream);
2920 #endif
2921 return -1;
2924 static void update_pause_message(struct MPContext *mpctx)
2926 struct MPOpts *opts = &mpctx->opts;
2928 if (opts->quiet)
2929 return;
2931 int cache_fill = get_cache_fill(mpctx);
2932 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2934 if (!mpctx->status_printed && !cache_changed)
2935 return;
2937 char *msg = mp_gtext(" ===== PAUSE =====");
2938 char *tmpmem = NULL;
2939 if (cache_fill >= 0)
2940 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
2942 if (opts->term_osd && !mpctx->sh_video) {
2943 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
2944 update_osd_msg(mpctx);
2945 } else {
2946 if (mpctx->status_printed)
2947 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n");
2948 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s\r", msg);
2951 mpctx->paused_cache_fill = cache_fill;
2952 mpctx->status_printed = false;
2954 talloc_free(tmpmem);
2957 void pause_player(struct MPContext *mpctx)
2959 if (mpctx->paused)
2960 return;
2961 mpctx->paused = 1;
2962 mpctx->step_frames = 0;
2963 mpctx->time_frame -= get_relative_time(mpctx);
2964 mpctx->osd_function = OSD_PAUSE;
2966 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2967 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2969 if (mpctx->ao && mpctx->sh_audio)
2970 ao_pause(mpctx->ao); // pause audio, keep data if possible
2972 mpctx->paused_cache_fill = get_cache_fill(mpctx);
2973 mpctx->status_printed = true;
2974 update_pause_message(mpctx);
2976 if (!mpctx->opts.quiet)
2977 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2980 void unpause_player(struct MPContext *mpctx)
2982 if (!mpctx->paused)
2983 return;
2984 mpctx->paused = 0;
2985 if (!mpctx->step_frames)
2986 mpctx->osd_function = OSD_PLAY;
2988 if (mpctx->ao && mpctx->sh_audio)
2989 ao_resume(mpctx->ao);
2990 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2991 && !mpctx->step_frames)
2992 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2993 (void)get_relative_time(mpctx); // ignore time that passed during pause
2996 static int redraw_osd(struct MPContext *mpctx)
2998 struct MPOpts *opts = &mpctx->opts;
2999 struct sh_video *sh_video = mpctx->sh_video;
3000 struct vf_instance *vf = sh_video->vfilter;
3001 if (sh_video->output_flags & VFCAP_OSD_FILTER)
3002 return -1;
3003 if (vo_redraw_frame(mpctx->video_out) < 0)
3004 return -1;
3005 mpctx->osd->sub_pts = mpctx->video_pts;
3006 if (mpctx->osd->sub_pts != MP_NOPTS_VALUE)
3007 mpctx->osd->sub_pts += opts->sub_delay - mpctx->osd->sub_offset;
3009 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
3010 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3011 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3012 vo_flip_page(mpctx->video_out, 0, -1);
3013 return 0;
3016 void add_step_frame(struct MPContext *mpctx)
3018 mpctx->step_frames++;
3019 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3020 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3021 unpause_player(mpctx);
3024 static void seek_reset(struct MPContext *mpctx, bool reset_ao, bool reset_ac)
3026 if (mpctx->sh_video) {
3027 current_module = "seek_video_reset";
3028 resync_video_stream(mpctx->sh_video);
3029 mpctx->sh_video->timer = 0;
3030 vo_seek_reset(mpctx->video_out);
3031 mpctx->sh_video->timer = 0;
3032 mpctx->sh_video->num_buffered_pts = 0;
3033 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3034 mpctx->delay = 0;
3035 mpctx->time_frame = 0;
3036 // Not all demuxers set d_video->pts during seek, so this value
3037 // (which is used by at least vobsub code below) may be completely
3038 // wrong (probably 0).
3039 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3040 mpctx->video_pts = mpctx->sh_video->pts;
3041 update_subtitles(mpctx, mpctx->sh_video->pts, true);
3042 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3045 if (mpctx->sh_audio && reset_ac) {
3046 current_module = "seek_audio_reset";
3047 resync_audio_stream(mpctx->sh_audio);
3048 if (reset_ao)
3049 ao_reset(mpctx->ao);
3050 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3051 mpctx->sh_audio->a_buffer_len = 0;
3052 if (!mpctx->sh_video)
3053 update_subtitles(mpctx, mpctx->sh_audio->pts, true);
3056 if (vo_vobsub && mpctx->sh_video) {
3057 current_module = "seek_vobsub_reset";
3058 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3061 mpctx->restart_playback = true;
3062 mpctx->hrseek_active = false;
3063 mpctx->hrseek_framedrop = false;
3064 mpctx->total_avsync_change = 0;
3065 audio_time_usage = 0;
3066 video_time_usage = 0;
3067 vout_time_usage = 0;
3068 drop_frame_cnt = 0;
3070 current_module = NULL;
3073 static bool timeline_set_part(struct MPContext *mpctx, int i)
3075 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3076 struct timeline_part *n = mpctx->timeline + i;
3077 mpctx->timeline_part = i;
3078 mpctx->video_offset = n->start - n->source_start;
3079 if (n->source == p->source)
3080 return false;
3081 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3082 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3083 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3084 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3085 mpctx->stop_play = orig_stop_play;
3086 mpctx->demuxer = n->source->demuxer;
3087 mpctx->d_video = mpctx->demuxer->video;
3088 mpctx->d_audio = mpctx->demuxer->audio;
3089 mpctx->d_sub = mpctx->demuxer->sub;
3090 mpctx->sh_video = mpctx->d_video->sh;
3091 mpctx->sh_audio = mpctx->d_audio->sh;
3092 return true;
3095 // Given pts, switch playback to the corresponding part.
3096 // Return offset within that part.
3097 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3098 bool *need_reset)
3100 if (pts < 0)
3101 pts = 0;
3102 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3103 struct timeline_part *p = mpctx->timeline + i;
3104 if (pts < (p + 1)->start) {
3105 *need_reset = timeline_set_part(mpctx, i);
3106 return pts - p->start + p->source_start;
3109 return -1;
3113 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3114 static int seek(MPContext *mpctx, struct seek_params seek,
3115 bool timeline_fallthrough)
3117 struct MPOpts *opts = &mpctx->opts;
3119 current_module = "seek";
3120 if (mpctx->stop_play == AT_END_OF_FILE)
3121 mpctx->stop_play = KEEP_PLAYING;
3122 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3123 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3124 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3125 || opts->hr_seek > 0 || seek.exact > 0;
3126 if (seek.type == MPSEEK_FACTOR
3127 || seek.type == MPSEEK_ABSOLUTE
3128 && seek.amount < mpctx->last_chapter_pts
3129 || seek.amount < 0)
3130 mpctx->last_chapter_seek = -2;
3131 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3132 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3133 seek.type = MPSEEK_ABSOLUTE;
3135 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3136 && seek.type == MPSEEK_RELATIVE) {
3137 seek.type = MPSEEK_ABSOLUTE;
3138 seek.direction = seek.amount > 0 ? 1 : -1;
3139 seek.amount += get_current_time(mpctx);
3142 /* At least the liba52 decoder wants to read from the input stream
3143 * during initialization, so reinit must be done after the demux_seek()
3144 * call that clears possible stream EOF. */
3145 bool need_reset = false;
3146 double demuxer_amount = seek.amount;
3147 if (mpctx->timeline) {
3148 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3149 &need_reset);
3150 if (demuxer_amount == -1) {
3151 mpctx->stop_play = AT_END_OF_FILE;
3152 // Clear audio from current position
3153 if (mpctx->sh_audio && !timeline_fallthrough) {
3154 ao_reset(mpctx->ao);
3155 mpctx->sh_audio->a_buffer_len = 0;
3157 return -1;
3160 if (need_reset) {
3161 reinit_video_chain(mpctx);
3162 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos},
3163 mpctx);
3166 int demuxer_style = 0;
3167 switch (seek.type) {
3168 case MPSEEK_FACTOR:
3169 demuxer_style |= SEEK_FACTOR; // fallthrough
3170 case MPSEEK_ABSOLUTE:
3171 demuxer_style |= SEEK_ABSOLUTE;
3173 if (hr_seek || seek.direction < 0)
3174 demuxer_style |= SEEK_BACKWARD;
3175 else if (seek.direction > 0)
3176 demuxer_style |= SEEK_FORWARD;
3178 if (hr_seek)
3179 demuxer_amount -= opts->hr_seek_demuxer_offset;
3180 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3181 demuxer_style);
3182 if (seekresult == 0) {
3183 if (need_reset) {
3184 reinit_audio_chain(mpctx);
3185 seek_reset(mpctx, !timeline_fallthrough, false);
3187 return -1;
3190 if (need_reset)
3191 reinit_audio_chain(mpctx);
3192 /* If we just reinitialized audio it doesn't need to be reset,
3193 * and resetting could lose audio some decoders produce during init. */
3194 seek_reset(mpctx, !timeline_fallthrough, !need_reset);
3196 /* Use the target time as "current position" for further relative
3197 * seeks etc until a new video frame has been decoded */
3198 if (seek.type == MPSEEK_ABSOLUTE) {
3199 mpctx->video_pts = seek.amount;
3200 mpctx->last_seek_pts = seek.amount;
3201 } else
3202 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3204 if (hr_seek || mpctx->timeline) {
3205 mpctx->hrseek_active = true;
3206 mpctx->hrseek_framedrop = true;
3207 mpctx->hrseek_pts = hr_seek ? seek.amount
3208 : mpctx->timeline[mpctx->timeline_part].start;
3211 mpctx->start_timestamp = GetTimerMS();
3213 return 0;
3216 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3217 int exact)
3219 struct seek_params *seek = &mpctx->seek;
3220 switch (type) {
3221 case MPSEEK_RELATIVE:
3222 if (seek->type == MPSEEK_FACTOR)
3223 return; // Well... not common enough to bother doing better
3224 seek->amount += amount;
3225 seek->exact = FFMAX(seek->exact, exact);
3226 if (seek->type == MPSEEK_NONE)
3227 seek->exact = exact;
3228 if (seek->type == MPSEEK_ABSOLUTE)
3229 return;
3230 if (seek->amount == 0) {
3231 *seek = (struct seek_params){ 0 };
3232 return;
3234 seek->type = MPSEEK_RELATIVE;
3235 return;
3236 case MPSEEK_ABSOLUTE:
3237 case MPSEEK_FACTOR:
3238 *seek = (struct seek_params) {
3239 .type = type,
3240 .amount = amount,
3241 .exact = exact,
3243 return;
3244 case MPSEEK_NONE:
3245 *seek = (struct seek_params){ 0 };
3246 return;
3248 abort();
3252 double get_time_length(struct MPContext *mpctx)
3254 if (mpctx->timeline)
3255 return mpctx->timeline[mpctx->num_timeline_parts].start;
3257 struct demuxer *demuxer = mpctx->demuxer;
3258 double get_time_ans;
3259 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3260 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3261 (void *) &get_time_ans) > 0)
3262 return get_time_ans;
3264 struct sh_video *sh_video = mpctx->d_video->sh;
3265 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3266 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3267 return (double) (demuxer->movi_end - demuxer->movi_start) /
3268 (sh_video->i_bps + sh_audio->i_bps);
3269 if (sh_video && sh_video->i_bps)
3270 return (double) (demuxer->movi_end - demuxer->movi_start) /
3271 sh_video->i_bps;
3272 if (sh_audio && sh_audio->i_bps)
3273 return (double) (demuxer->movi_end - demuxer->movi_start) /
3274 sh_audio->i_bps;
3275 return 0;
3278 /* If there are timestamps from stream level then use those (for example
3279 * DVDs can have consistent times there while the MPEG-level timestamps
3280 * reset). */
3281 double get_current_time(struct MPContext *mpctx)
3283 struct demuxer *demuxer = mpctx->demuxer;
3284 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3285 return demuxer->stream_pts;
3286 if (mpctx->sh_video) {
3287 double pts = mpctx->video_pts;
3288 if (pts != MP_NOPTS_VALUE)
3289 return pts;
3291 double apts = playing_audio_pts(mpctx);
3292 if (apts != MP_NOPTS_VALUE)
3293 return apts;
3294 return mpctx->last_seek_pts;
3297 int get_percent_pos(struct MPContext *mpctx)
3299 struct demuxer *demuxer = mpctx->demuxer;
3300 int ans = 0;
3301 if (mpctx->timeline)
3302 ans = get_current_time(mpctx) * 100 /
3303 mpctx->timeline[mpctx->num_timeline_parts].start;
3304 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3306 else {
3307 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3308 off_t pos = demuxer->filepos > 0 ?
3309 demuxer->filepos : stream_tell(demuxer->stream);
3310 if (len > 0)
3311 ans = (pos - demuxer->movi_start) / len;
3312 else
3313 ans = 0;
3315 if (ans < 0)
3316 ans = 0;
3317 if (ans > 100)
3318 ans = 100;
3319 return ans;
3322 // -2 is no chapters, -1 is before first chapter
3323 int get_current_chapter(struct MPContext *mpctx)
3325 double current_pts = get_current_time(mpctx);
3326 if (!mpctx->chapters)
3327 return FFMAX(mpctx->last_chapter_seek,
3328 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3330 int i;
3331 for (i = 1; i < mpctx->num_chapters; i++)
3332 if (current_pts < mpctx->chapters[i].start)
3333 break;
3334 return FFMAX(mpctx->last_chapter_seek, i - 1);
3337 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3339 char *name = chapter_name(mpctx, chapter);
3340 if (name) {
3341 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3342 } else {
3343 int chapter_count = get_chapter_count(mpctx);
3344 if (chapter_count <= 0)
3345 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3346 else
3347 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3348 chapter_count);
3350 return name;
3353 // returns NULL if chapter name unavailable
3354 char *chapter_name(struct MPContext *mpctx, int chapter)
3356 if (!mpctx->chapters)
3357 return demuxer_chapter_name(mpctx->demuxer, chapter);
3358 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3361 // returns the start of the chapter in seconds
3362 double chapter_start_time(struct MPContext *mpctx, int chapter)
3364 if (!mpctx->chapters)
3365 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3366 return mpctx->chapters[chapter].start;
3369 int get_chapter_count(struct MPContext *mpctx)
3371 if (!mpctx->chapters)
3372 return demuxer_chapter_count(mpctx->demuxer);
3373 return mpctx->num_chapters;
3376 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3378 mpctx->last_chapter_seek = -2;
3379 if (!mpctx->chapters) {
3380 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3381 if (res >= 0) {
3382 if (*seek_pts == -1)
3383 seek_reset(mpctx, true, true);
3384 else {
3385 mpctx->last_chapter_seek = res;
3386 mpctx->last_chapter_pts = *seek_pts;
3389 return res;
3392 if (chapter >= mpctx->num_chapters)
3393 return -1;
3394 if (chapter < 0)
3395 chapter = 0;
3396 *seek_pts = mpctx->chapters[chapter].start;
3397 mpctx->last_chapter_seek = chapter;
3398 mpctx->last_chapter_pts = *seek_pts;
3399 return chapter;
3403 static void run_playloop(struct MPContext *mpctx)
3405 struct MPOpts *opts = &mpctx->opts;
3406 bool full_audio_buffers = false;
3407 bool audio_left = false, video_left = false;
3408 double endpts = end_at.type == END_AT_TIME ? end_at.pos : MP_NOPTS_VALUE;
3409 bool end_is_chapter = false;
3410 double sleeptime = WAKEUP_PERIOD;
3411 bool was_restart = mpctx->restart_playback;
3413 if (mpctx->timeline) {
3414 double end = mpctx->timeline[mpctx->timeline_part + 1].start;
3415 if (endpts == MP_NOPTS_VALUE || end < endpts) {
3416 endpts = end;
3417 end_is_chapter = true;
3421 if (opts->chapterrange[1] > 0) {
3422 int cur_chapter = get_current_chapter(mpctx);
3423 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3424 mpctx->stop_play = PT_NEXT_ENTRY;
3427 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3428 mpctx->sh_audio = mpctx->d_audio->sh;
3429 mpctx->sh_audio->ds = mpctx->d_audio;
3430 reinit_audio_chain(mpctx);
3433 if (mpctx->step_frames && !mpctx->sh_video) {
3434 mpctx->step_frames = 0;
3435 pause_player(mpctx);
3438 if (mpctx->sh_audio && !mpctx->restart_playback && !mpctx->ao->untimed) {
3439 int status = fill_audio_out_buffers(mpctx, endpts);
3440 full_audio_buffers = status >= 0;
3441 // Not at audio stream EOF yet
3442 audio_left = status > -2;
3445 double buffered_audio = -1;
3446 while (mpctx->sh_video) { // never loops, for "break;" only
3447 struct vo *vo = mpctx->video_out;
3448 vo_pts = mpctx->sh_video->timer * 90000.0;
3449 vo_fps = mpctx->sh_video->fps;
3451 video_left = vo->hasframe || vo->frame_loaded;
3452 if (!vo->frame_loaded && (!mpctx->paused || mpctx->restart_playback)) {
3453 double frame_time = update_video(mpctx);
3454 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3455 if (mpctx->sh_video->vf_initialized < 0) {
3456 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3457 "\nFATAL: Could not initialize video filters (-vf) "
3458 "or video output (-vo).\n");
3459 mpctx->stop_play = PT_NEXT_ENTRY;
3460 return;
3462 video_left = frame_time >= 0;
3463 if (video_left && !mpctx->restart_playback) {
3464 mpctx->time_frame += frame_time / opts->playback_speed;
3465 adjust_sync(mpctx, frame_time);
3469 if (endpts != MP_NOPTS_VALUE)
3470 video_left &= mpctx->sh_video->pts < endpts;
3472 // ================================================================
3474 current_module = "vo_check_events";
3475 vo_check_events(vo);
3477 #ifdef CONFIG_X11
3478 if (stop_xscreensaver && vo->x11)
3479 xscreensaver_heartbeat(vo->x11);
3480 #endif
3481 if (heartbeat_cmd) {
3482 static unsigned last_heartbeat;
3483 unsigned now = GetTimerMS();
3484 if (now - last_heartbeat > 30000) {
3485 last_heartbeat = now;
3486 system(heartbeat_cmd);
3490 if (!video_left || (mpctx->paused && !mpctx->restart_playback))
3491 break;
3492 if (!vo->frame_loaded) {
3493 sleeptime = 0;
3494 break;
3497 mpctx->time_frame -= get_relative_time(mpctx);
3498 if (full_audio_buffers && !mpctx->restart_playback) {
3499 buffered_audio = ao_get_delay(mpctx->ao);
3500 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", buffered_audio);
3502 if (opts->autosync) {
3503 /* Smooth reported playback position from AO by averaging
3504 * it with the value expected based on previus value and
3505 * time elapsed since then. May help smooth video timing
3506 * with audio output that have inaccurate position reporting.
3507 * This is badly implemented; the behavior of the smoothing
3508 * now undesirably depends on how often this code runs
3509 * (mainly depends on video frame rate). */
3510 float predicted = (mpctx->delay / opts->playback_speed +
3511 mpctx->time_frame);
3512 float difference = buffered_audio - predicted;
3513 buffered_audio = predicted + difference / opts->autosync;
3516 mpctx->time_frame = (buffered_audio -
3517 mpctx->delay / opts->playback_speed);
3518 } else {
3519 /* If we're more than 200 ms behind the right playback
3520 * position, don't try to speed up display of following
3521 * frames to catch up; continue with default speed from
3522 * the current frame instead.
3523 * If benchmark is set always output frames immediately
3524 * without sleeping.
3526 if (mpctx->time_frame < -0.2 || opts->benchmark)
3527 mpctx->time_frame = 0;
3530 double vsleep = mpctx->time_frame - vo->flip_queue_offset;
3531 if (vsleep > 0.050) {
3532 sleeptime = FFMIN(sleeptime, vsleep - 0.040);
3533 break;
3535 sleeptime = 0;
3537 //=================== FLIP PAGE (VIDEO BLT): ======================
3539 current_module = "flip_page";
3540 vo_new_frame_imminent(vo);
3541 struct sh_video *sh_video = mpctx->sh_video;
3542 mpctx->video_pts = sh_video->pts;
3543 update_subtitles(mpctx, sh_video->pts, false);
3544 update_teletext(sh_video, mpctx->demuxer, 0);
3545 update_osd_msg(mpctx);
3546 struct vf_instance *vf = sh_video->vfilter;
3547 mpctx->osd->sub_pts = mpctx->video_pts;
3548 if (mpctx->osd->sub_pts != MP_NOPTS_VALUE)
3549 mpctx->osd->sub_pts += opts->sub_delay - mpctx->osd->sub_offset;
3550 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3551 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3552 vo_osd_changed(0);
3554 mpctx->time_frame -= get_relative_time(mpctx);
3555 mpctx->time_frame -= vo->flip_queue_offset;
3556 float aq_sleep_time = mpctx->time_frame;
3557 if (mpctx->time_frame > 0.001
3558 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3559 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3560 mpctx->time_frame += vo->flip_queue_offset;
3562 unsigned int t2 = GetTimer();
3563 /* Playing with playback speed it's possible to get pathological
3564 * cases with mpctx->time_frame negative enough to cause an
3565 * overflow in pts_us calculation, thus the FFMAX. */
3566 double time_frame = FFMAX(mpctx->time_frame, -1);
3567 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3568 int duration = -1;
3569 double pts2 = vo->next_pts2;
3570 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts &&
3571 !mpctx->restart_playback) {
3572 // expected A/V sync correction is ignored
3573 double diff = (pts2 - mpctx->video_pts);
3574 diff /= opts->playback_speed;
3575 if (mpctx->time_frame < 0)
3576 diff += mpctx->time_frame;
3577 if (diff < 0)
3578 diff = 0;
3579 if (diff > 10)
3580 diff = 10;
3581 duration = diff * 1e6;
3583 vo_flip_page(vo, pts_us | 1, duration);
3585 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3586 vout_time_usage += mpctx->last_vo_flip_duration;
3587 if (vo->driver->flip_page_timed) {
3588 // No need to adjust sync based on flip speed
3589 mpctx->last_vo_flip_duration = 0;
3590 // For print_status - VO call finishing early is OK for sync
3591 mpctx->time_frame -= get_relative_time(mpctx);
3593 if (mpctx->restart_playback) {
3594 mpctx->syncing_audio = true;
3595 if (mpctx->sh_audio)
3596 fill_audio_out_buffers(mpctx, endpts);
3597 mpctx->restart_playback = false;
3598 mpctx->time_frame = 0;
3599 get_relative_time(mpctx);
3601 print_status(mpctx, MP_NOPTS_VALUE, true);
3602 screenshot_flip(mpctx);
3604 if (opts->auto_quality > 0) {
3605 current_module = "autoq";
3606 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3607 ++output_quality;
3608 else if (output_quality > 1 && aq_sleep_time < 0)
3609 --output_quality;
3610 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3611 output_quality = 0;
3612 set_video_quality(mpctx->sh_video, output_quality);
3615 if (play_n_frames >= 0) {
3616 --play_n_frames;
3617 if (play_n_frames <= 0)
3618 mpctx->stop_play = PT_NEXT_ENTRY;
3620 if (mpctx->step_frames > 0) {
3621 mpctx->step_frames--;
3622 if (mpctx->step_frames == 0)
3623 pause_player(mpctx);
3625 break;
3626 } // video
3628 #ifdef CONFIG_DVDNAV
3629 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3630 nav_highlight_t hl;
3631 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3632 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3633 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3634 vo_osd_changed(OSDTYPE_DVDNAV);
3635 } else {
3636 osd_set_nav_box(0, 0, 0, 0);
3637 vo_osd_changed(OSDTYPE_DVDNAV);
3638 vo_osd_changed(OSDTYPE_SPU);
3641 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3642 double ar = -1.0;
3643 if (mpctx->sh_video &&
3644 stream_control(mpctx->demuxer->stream,
3645 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3646 != STREAM_UNSUPPORTED)
3647 mpctx->sh_video->stream_aspect = ar;
3650 #endif
3652 if (mpctx->sh_audio && (mpctx->restart_playback ? !video_left :
3653 mpctx->ao->untimed && (mpctx->delay <= 0 ||
3654 !video_left))) {
3655 int status = fill_audio_out_buffers(mpctx, endpts);
3656 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3657 // Not at audio stream EOF yet
3658 audio_left = status > -2;
3660 if (!video_left)
3661 mpctx->restart_playback = false;
3662 if (mpctx->sh_audio && buffered_audio == -1)
3663 buffered_audio = mpctx->paused ? 0 : ao_get_delay(mpctx->ao);
3665 update_osd_msg(mpctx);
3666 if (mpctx->paused)
3667 update_pause_message(mpctx);
3668 if (!video_left && (!mpctx->paused || was_restart)) {
3669 double a_pos = 0;
3670 if (mpctx->sh_audio) {
3671 a_pos = (written_audio_pts(mpctx) -
3672 mpctx->opts.playback_speed * buffered_audio);
3674 print_status(mpctx, a_pos, false);
3676 if (!mpctx->sh_video)
3677 update_subtitles(mpctx, a_pos, false);
3680 /* It's possible for the user to simultaneously switch both audio
3681 * and video streams to "disabled" at runtime. Handle this by waiting
3682 * rather than immediately stopping playback due to EOF.
3684 * When all audio has been written to output driver, stay in the
3685 * main loop handling commands until it has been mostly consumed,
3686 * except in the gapless case, where the next file will be started
3687 * while audio from the current one still remains to be played.
3689 * We want this check to trigger if we seeked to this position,
3690 * but not if we paused at it with audio possibly still buffered in
3691 * the AO. There's currently no working way to check buffered audio
3692 * inside AO while paused. Thus the "was_restart" check below, which
3693 * should trigger after seek only, when we know there's no audio
3694 * buffered.
3696 if ((mpctx->sh_audio || mpctx->sh_video) && !audio_left && !video_left
3697 && (opts->gapless_audio || buffered_audio < 0.05)
3698 && (!mpctx->paused || was_restart)) {
3699 if (end_is_chapter) {
3700 seek(mpctx, (struct seek_params){
3701 .type = MPSEEK_ABSOLUTE,
3702 .amount = mpctx->timeline[mpctx->timeline_part+1].start
3703 }, true);
3704 } else
3705 mpctx->stop_play = AT_END_OF_FILE;
3706 } else if (!mpctx->stop_play) {
3707 double audio_sleep = 9;
3708 if (mpctx->sh_audio && !mpctx->paused) {
3709 if (mpctx->ao->untimed) {
3710 if (!video_left)
3711 audio_sleep = 0;
3712 } else if (full_audio_buffers) {
3713 audio_sleep = buffered_audio - 0.050;
3714 // Keep extra safety margin if the buffers are large
3715 if (audio_sleep > 0.100)
3716 audio_sleep = FFMAX(audio_sleep - 0.200, 0.100);
3717 else
3718 audio_sleep = FFMAX(audio_sleep, 0.020);
3719 } else
3720 audio_sleep = 0.020;
3722 sleeptime = FFMIN(sleeptime, audio_sleep);
3723 if (sleeptime > 0) {
3724 if (!mpctx->sh_video)
3725 goto novideo;
3726 int hack = vo_osd_changed(0);
3727 vo_osd_changed(hack);
3728 if (hack || mpctx->video_out->want_redraw) {
3729 if (redraw_osd(mpctx) < 0) {
3730 if (mpctx->paused && video_left)
3731 add_step_frame(mpctx);
3732 else
3733 goto novideo;
3734 } else
3735 vo_osd_changed(0);
3736 } else {
3737 novideo:
3738 mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
3743 //================= Keyboard events, SEEKing ====================
3745 current_module = "key_events";
3747 mp_cmd_t *cmd;
3748 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3749 /* Allow running consecutive seek commands to combine them,
3750 * but execute the seek before running other commands.
3751 * If the user seeks continuously (keeps arrow key down)
3752 * try to finish showing a frame from one location before doing
3753 * another seek (which could lead to unchanging display). */
3754 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3755 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3756 && GetTimerMS() - mpctx->start_timestamp < 300)
3757 break;
3758 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3759 run_command(mpctx, cmd);
3760 mp_cmd_free(cmd);
3761 if (mpctx->stop_play)
3762 break;
3765 // handle -sstep
3766 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3767 mpctx->osd_function = OSD_FFW;
3768 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3771 /* Looping. */
3772 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3773 mpctx->stop_play == PT_NEXT_ENTRY)) {
3774 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3776 if (opts->loop_times > 1)
3777 opts->loop_times--;
3778 else if (opts->loop_times == 1)
3779 opts->loop_times = -1;
3780 play_n_frames = play_n_frames_mf;
3781 mpctx->stop_play = 0;
3782 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3785 if (mpctx->seek.type) {
3786 seek(mpctx, mpctx->seek, false);
3787 mpctx->seek = (struct seek_params){ 0 };
3792 static int read_keys(void *ctx, int fd)
3794 if (getch2(ctx))
3795 return MP_INPUT_NOTHING;
3796 return MP_INPUT_DEAD;
3799 static bool attachment_is_font(struct demux_attachment *att)
3801 if (!att->name || !att->type || !att->data || !att->data_size)
3802 return false;
3803 // match against MIME types
3804 if (strcmp(att->type, "application/x-truetype-font") == 0
3805 || strcmp(att->type, "application/x-font") == 0)
3806 return true;
3807 // fallback: match against file extension
3808 if (strlen(att->name) > 4) {
3809 char *ext = att->name + strlen(att->name) - 4;
3810 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3811 || strcasecmp(ext, ".otf") == 0)
3812 return true;
3814 return false;
3817 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3819 if (audio_id == -1)
3820 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3821 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3822 demuxer_switch_audio(demuxer, audio_id);
3823 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3824 demuxer->audio->id = -2;
3825 demuxer->audio->sh = NULL;
3827 return demuxer->audio->id;
3830 static void print_version(const char *name)
3832 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3834 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3835 GetCpuCaps(&gCpuCaps);
3836 #if ARCH_X86
3837 mp_msg(MSGT_CPLAYER, MSGL_V,
3838 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3839 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3840 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3841 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3842 #if CONFIG_RUNTIME_CPUDETECT
3843 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3844 #else
3845 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3846 if (HAVE_MMX)
3847 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3848 if (HAVE_MMX2)
3849 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3850 if (HAVE_AMD3DNOW)
3851 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3852 if (HAVE_AMD3DNOWEXT)
3853 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3854 if (HAVE_SSE)
3855 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3856 if (HAVE_SSE2)
3857 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3858 if (HAVE_SSSE3)
3859 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3860 if (HAVE_CMOV)
3861 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3862 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3863 #endif /* CONFIG_RUNTIME_CPUDETECT */
3864 #endif /* ARCH_X86 */
3865 print_libav_versions();
3868 #ifdef PTW32_STATIC_LIB
3869 static void detach_ptw32(void)
3871 pthread_win32_thread_detach_np();
3872 pthread_win32_process_detach_np();
3874 #endif
3876 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3877 * file for some tools to link against. */
3878 #ifndef DISABLE_MAIN
3879 int main(int argc, char *argv[])
3881 #ifdef PTW32_STATIC_LIB
3882 pthread_win32_process_attach_np();
3883 pthread_win32_thread_attach_np();
3884 atexit(detach_ptw32);
3885 #endif
3886 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3887 || !strcmp(argv[1], "--leak-report")))
3888 talloc_enable_leak_report();
3890 #ifdef __MINGW32__
3891 mp_get_converted_argv(&argc, &argv);
3892 #endif
3894 char *mem_ptr;
3896 // movie info:
3898 /* Flag indicating whether MPlayer should exit without playing anything. */
3899 int opt_exit = 0;
3900 int i;
3902 struct MPContext *mpctx = talloc(NULL, MPContext);
3903 *mpctx = (struct MPContext){
3904 .osd_function = OSD_PLAY,
3905 .begin_skip = MP_NOPTS_VALUE,
3906 .play_tree_step = 1,
3907 .global_sub_pos = -1,
3908 .set_of_sub_pos = -1,
3909 .file_format = DEMUXER_TYPE_UNKNOWN,
3910 .last_dvb_step = 1,
3911 .paused_cache_fill = -1,
3914 InitTimer();
3915 srand(GetTimerMS());
3917 mp_msg_init();
3918 init_libav();
3920 struct MPOpts *opts = &mpctx->opts;
3921 set_default_mplayer_options(opts);
3922 // Create the config context and register the options
3923 mpctx->mconfig = m_config_new(opts, cfg_include);
3924 m_config_register_options(mpctx->mconfig, mplayer_opts);
3925 m_config_register_options(mpctx->mconfig, common_opts);
3926 mp_input_register_options(mpctx->mconfig);
3927 m_config_initialize(mpctx->mconfig, opts);
3929 // Preparse the command line
3930 m_config_preparse_command_line(mpctx->mconfig, argc, argv, &verbose);
3932 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3933 set_path_env();
3934 #endif
3936 #ifdef CONFIG_TV
3937 stream_tv_defaults.immediate = 1;
3938 #endif
3940 parse_cfgfiles(mpctx, mpctx->mconfig);
3942 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3943 if (mpctx->playtree == NULL)
3944 opt_exit = 1;
3945 else {
3946 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3947 if (mpctx->playtree) {
3948 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3949 mpctx->mconfig);
3950 if (mpctx->playtree_iter) {
3951 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3952 PLAY_TREE_ITER_ENTRY) {
3953 play_tree_iter_free(mpctx->playtree_iter);
3954 mpctx->playtree_iter = NULL;
3956 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3962 print_version("MPlayer2");
3964 #if defined(__MINGW32__) || defined(__CYGWIN__)
3966 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3967 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3968 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3969 if (kernel32) {
3970 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3971 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3973 if (setDEP)
3974 setDEP(3);
3975 if (setDllDir)
3976 setDllDir("");
3978 // stop Windows from showing all kinds of annoying error dialogs
3979 SetErrorMode(0x8003);
3980 // request 1ms timer resolution
3981 timeBeginPeriod(1);
3982 #endif
3984 #ifdef CONFIG_PRIORITY
3985 set_priority();
3986 #endif
3988 if (opts->video_driver_list &&
3989 strcmp(opts->video_driver_list[0], "help") == 0) {
3990 list_video_out();
3991 opt_exit = 1;
3994 if (opts->audio_driver_list &&
3995 strcmp(opts->audio_driver_list[0], "help") == 0) {
3996 list_audio_out();
3997 opt_exit = 1;
4000 /* Check codecs.conf. */
4001 if (!codecs_file || !parse_codec_cfg(codecs_file, opts)) {
4002 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"), opts)) {
4003 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf", opts)) {
4004 if (!parse_codec_cfg(NULL, opts))
4005 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4006 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4007 "Using built-in default codecs.conf.\n");
4010 free(mem_ptr); // release the buffer created by get_path()
4013 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4014 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4015 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4016 list_codecs(1);
4017 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4018 opt_exit = 1;
4020 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4021 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4022 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4023 list_codecs(0);
4024 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4025 opt_exit = 1;
4027 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4028 vfm_help();
4029 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4030 opt_exit = 1;
4032 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4033 afm_help();
4034 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4035 opt_exit = 1;
4037 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4038 af_help();
4039 printf("\n");
4040 opt_exit = 1;
4042 #ifdef CONFIG_X11
4043 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4044 fstype_help();
4045 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4046 opt_exit = 1;
4048 #endif
4049 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4050 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4051 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4052 demuxer_help();
4053 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4054 opt_exit = 1;
4056 if (opts->list_properties) {
4057 property_print_help();
4058 opt_exit = 1;
4061 if (opt_exit)
4062 exit_player(mpctx, EXIT_NONE);
4064 if (!mpctx->filename && !opts->player_idle_mode) {
4065 // no file/vcd/dvd -> show HELP:
4066 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4067 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4070 /* Display what configure line was used */
4071 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4073 // Many users forget to include command line in bugreports...
4074 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4075 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4076 for (i = 1; i < argc; i++)
4077 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4078 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4081 //------ load global data first ------
4083 #ifdef CONFIG_ASS
4084 mpctx->ass_library = mp_ass_init(opts);
4085 #endif
4087 mpctx->osd = osd_create(opts, mpctx->ass_library);
4089 #ifdef HAVE_RTC
4090 if (opts->rtc) {
4091 char *rtc_device = opts->rtc_device;
4092 // seteuid(0); /* Can't hurt to try to get root here */
4093 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4094 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4095 "(it should be readable by the user.)\n",
4096 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4097 else {
4098 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4100 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4101 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4102 "ioctl (rtc_irqp_set %lu): %s\n",
4103 irqp, strerror(errno));
4104 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4105 close(rtc_fd);
4106 rtc_fd = -1;
4107 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4108 /* variable only by the root */
4109 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4110 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4111 close(rtc_fd);
4112 rtc_fd = -1;
4113 } else
4114 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4115 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4118 if (rtc_fd < 0)
4119 #endif /* HAVE_RTC */
4120 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4121 opts->softsleep ? "software" : timer_name);
4123 #ifdef HAVE_TERMCAP
4124 load_termcap(NULL); // load key-codes
4125 #endif
4127 // ========== Init keyboard FIFO (connection to libvo) ============
4129 // Init input system
4130 current_module = "init_input";
4131 mpctx->input = mp_input_init(opts);
4132 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4133 if (slave_mode)
4134 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4135 else if (opts->consolecontrols)
4136 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4137 // Set the libstream interrupt callback
4138 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4140 current_module = NULL;
4142 /// Catch signals
4143 #ifndef __MINGW32__
4144 signal(SIGCHLD, child_sighandler);
4145 #endif
4147 #ifdef CONFIG_CRASH_DEBUG
4148 prog_path = argv[0];
4149 #endif
4150 //========= Catch terminate signals: ================
4151 // terminate requests:
4152 signal(SIGTERM, exit_sighandler); // kill
4153 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4155 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4157 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4158 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4159 #ifdef CONFIG_SIGHANDLER
4160 // fatal errors:
4161 signal(SIGBUS, exit_sighandler); // bus error
4162 signal(SIGSEGV, exit_sighandler); // segfault
4163 signal(SIGILL, exit_sighandler); // illegal instruction
4164 signal(SIGFPE, exit_sighandler); // floating point exc.
4165 signal(SIGABRT, exit_sighandler); // abort()
4166 #ifdef CONFIG_CRASH_DEBUG
4167 if (crash_debug)
4168 signal(SIGTRAP, exit_sighandler);
4169 #endif
4170 #endif
4172 // ***************** Now, let's see the per-file stuff ******************
4174 play_next_file:
4176 // init global sub numbers
4177 mpctx->global_sub_size = 0;
4178 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4180 if (mpctx->filename) {
4181 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4182 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4183 load_per_file_config(mpctx->mconfig, mpctx->filename);
4186 if (opts->video_driver_list)
4187 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4188 opts->video_driver_list[0]);
4189 if (opts->audio_driver_list)
4190 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4191 opts->audio_driver_list[0]);
4193 // We must enable getch2 here to be able to interrupt network connection
4194 // or cache filling
4195 if (opts->consolecontrols && !slave_mode) {
4196 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4197 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4198 "WARNING: getch2_init called twice!\n");
4199 else
4200 getch2_enable(); // prepare stdin for hotkeys...
4201 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4202 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4205 // ================= idle loop (STOP state) =========================
4206 while (opts->player_idle_mode && !mpctx->filename) {
4207 uninit_player(mpctx, INITIALIZED_AO | INITIALIZED_VO);
4208 play_tree_t *entry = NULL;
4209 mp_cmd_t *cmd;
4210 while (!(cmd = mp_input_get_cmd(mpctx->input, WAKEUP_PERIOD * 1000,
4211 false)));
4212 switch (cmd->id) {
4213 case MP_CMD_LOADFILE:
4214 // prepare a tree entry with the new filename
4215 entry = play_tree_new();
4216 play_tree_add_file(entry, cmd->args[0].v.s);
4217 // The entry is added to the main playtree after the switch().
4218 break;
4219 case MP_CMD_LOADLIST:
4220 entry = parse_playlist_file(&mpctx->opts, bstr(cmd->args[0].v.s));
4221 break;
4222 case MP_CMD_QUIT:
4223 exit_player_with_rc(mpctx, EXIT_QUIT,
4224 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4225 break;
4226 case MP_CMD_VO_FULLSCREEN:
4227 case MP_CMD_GET_PROPERTY:
4228 case MP_CMD_SET_PROPERTY:
4229 case MP_CMD_STEP_PROPERTY:
4230 run_command(mpctx, cmd);
4231 break;
4234 mp_cmd_free(cmd);
4236 if (entry) { // user entered a command that gave a valid entry
4237 if (mpctx->playtree)
4238 // the playtree is always a node with one child. let's clear it
4239 play_tree_free_list(mpctx->playtree->child, 1);
4240 else
4241 // .. or make a brand new playtree
4242 mpctx->playtree = play_tree_new();
4244 if (!mpctx->playtree)
4245 continue; // couldn't make playtree! wait for next command
4247 play_tree_set_child(mpctx->playtree, entry);
4249 /* Make iterator start at the top the of tree. */
4250 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4251 mpctx->mconfig);
4252 if (!mpctx->playtree_iter)
4253 continue;
4255 // find the first real item in the tree
4256 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4257 PLAY_TREE_ITER_ENTRY) {
4258 // no items!
4259 play_tree_iter_free(mpctx->playtree_iter);
4260 mpctx->playtree_iter = NULL;
4261 continue; // wait for next command
4263 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4267 #ifdef CONFIG_ASS
4268 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4269 #endif
4270 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4271 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4273 if (mpctx->filename) {
4274 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4275 filename_recode(mpctx->filename));
4276 if (use_filename_title && opts->vo_wintitle == NULL)
4277 opts->vo_wintitle = talloc_strdup(NULL,
4278 mp_basename(mpctx->filename));
4281 if (edl_output_filename) {
4282 if (edl_fd)
4283 fclose(edl_fd);
4284 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4285 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4286 "Can't open EDL file [%s] for writing.\n",
4287 filename_recode(edl_output_filename));
4291 //==================== Open VOB-Sub ============================
4293 current_module = "vobsub";
4294 if (opts->vobsub_name) {
4295 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4296 if (vo_vobsub == NULL)
4297 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4298 filename_recode(opts->vobsub_name));
4299 } else if (opts->sub_auto && mpctx->filename) {
4300 char **vob = find_vob_subtitles(opts, mpctx->filename);
4301 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4302 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4303 if (vo_vobsub)
4304 break;
4306 talloc_free(vob);
4308 if (vo_vobsub) {
4309 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4310 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4311 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4312 mpctx);
4314 // setup global sub numbering
4315 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4316 vobsub_get_indexes_count(vo_vobsub);
4319 //============ Open & Sync STREAM --- fork cache2 ====================
4321 mpctx->stream = NULL;
4322 mpctx->demuxer = NULL;
4323 mpctx->d_audio = NULL;
4324 mpctx->d_video = NULL;
4325 mpctx->d_sub = NULL;
4326 mpctx->sh_audio = NULL;
4327 mpctx->sh_video = NULL;
4329 current_module = "open_stream";
4330 char *stream_filename = mpctx->filename;
4331 #ifdef CONFIG_LIBQUVI
4332 mpctx->resolve_result = mp_resolve_quvi(stream_filename, opts);
4333 #endif
4334 if (mpctx->resolve_result)
4335 stream_filename = mpctx->resolve_result->url;
4336 mpctx->stream = open_stream(stream_filename, opts, &mpctx->file_format);
4337 if (!mpctx->stream) { // error...
4338 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4339 goto goto_next_file;
4341 mpctx->initialized_flags |= INITIALIZED_STREAM;
4343 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4344 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4345 "playlist support will not be used automatically.\n"
4346 "MPlayer's playlist code is unsafe and should only be used with "
4347 "trusted sources.\nPlayback will probably fail.\n\n");
4348 #if 0
4349 play_tree_t *entry;
4350 // Handle playlist
4351 current_module = "handle_playlist";
4352 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4353 filename_recode(mpctx->filename));
4354 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4355 mpctx->eof = playtree_add_playlist(mpctx, entry);
4356 goto goto_next_file;
4357 #endif
4359 mpctx->stream->start_pos += seek_to_byte;
4361 if (stream_dump_type == 5) {
4362 unsigned char buf[4096];
4363 int len;
4364 FILE *f;
4365 current_module = "dumpstream";
4366 stream_reset(mpctx->stream);
4367 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4368 f = fopen(opts->stream_dump_name, "wb");
4369 if (!f) {
4370 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4371 exit_player(mpctx, EXIT_ERROR);
4373 if (opts->chapterrange[0] > 1) {
4374 int chapter = opts->chapterrange[0] - 1;
4375 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4377 struct stream_dump_progress info;
4378 stream_dump_progress_start(&info);
4379 while (!mpctx->stream->eof && !async_quit_request) {
4380 len = stream_read(mpctx->stream, buf, 4096);
4381 if (len > 0) {
4382 if (fwrite(buf, len, 1, f) != 1) {
4383 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4384 exit_player(mpctx, EXIT_ERROR);
4387 stream_dump_progress(&info, len, mpctx->stream);
4388 if (opts->chapterrange[1] > 0) {
4389 int chapter = -1;
4390 if (stream_control(mpctx->stream,
4391 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4392 && chapter + 1 > opts->chapterrange[1])
4393 break;
4396 if (fclose(f)) {
4397 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4398 opts->stream_dump_name);
4399 exit_player(mpctx, EXIT_ERROR);
4401 stream_dump_progress_end(&info, opts->stream_dump_name);
4402 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4403 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4406 #ifdef CONFIG_DVDREAD
4407 if (mpctx->stream->type == STREAMTYPE_DVD) {
4408 current_module = "dvd lang->id";
4409 if (opts->audio_lang && opts->audio_id == -1)
4410 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4411 if (opts->sub_lang && opts->sub_id == -1)
4412 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4413 // setup global sub numbering
4414 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4415 current_module = NULL;
4417 #endif
4419 #ifdef CONFIG_DVDNAV
4420 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4421 current_module = "dvdnav lang->id";
4422 if (opts->audio_lang && opts->audio_id == -1)
4423 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4424 opts->audio_lang);
4425 dvdsub_lang_id = -3;
4426 if (opts->sub_lang && opts->sub_id == -1)
4427 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4428 mpctx->stream, opts->sub_lang);
4429 // setup global sub numbering
4430 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4431 mpctx->stream);
4432 current_module = NULL;
4434 #endif
4436 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4437 goto_enable_cache:
4438 current_module = "enable_cache";
4439 int res = stream_enable_cache_percent(mpctx->stream,
4440 opts->stream_cache_size,
4441 opts->stream_cache_min_percent,
4442 opts->stream_cache_seek_min_percent);
4443 if (res == 0)
4444 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx,
4445 PT_NEXT_ENTRY)))
4446 goto goto_next_file;
4449 //============ Open DEMUXERS --- DETECT file type =======================
4450 current_module = "demux_open";
4452 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4453 opts->audio_id, opts->video_id, opts->sub_id,
4454 mpctx->filename);
4456 // HACK to get MOV Reference Files working
4458 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4459 unsigned char *playlist_entry;
4460 play_tree_t *list = NULL, *entry = NULL;
4462 current_module = "handle_demux_playlist";
4463 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4464 char *temp;
4465 const char *bname;
4467 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4468 filename_recode(playlist_entry));
4470 bname = mp_basename(playlist_entry);
4471 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4472 !strncmp(bname + 3, "gateQT", 6))
4473 continue;
4475 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4476 continue;
4478 entry = play_tree_new();
4480 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4481 playlist_entry)) { // add reference path of current file
4482 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4483 mpctx->filename)) + strlen(playlist_entry) + 1));
4484 if (temp) {
4485 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4486 strlen(mp_basename(mpctx->filename)));
4487 temp[strlen(mpctx->filename) - strlen(mp_basename(
4488 mpctx->filename))] = '\0';
4489 strcat(temp, playlist_entry);
4490 if (!strcmp(temp, mpctx->filename)) {
4491 free(temp);
4492 continue;
4494 play_tree_add_file(entry, temp);
4495 mp_msg(MSGT_CPLAYER, MSGL_V,
4496 "Resolving reference to %s.\n", temp);
4497 free(temp);
4499 } else
4500 play_tree_add_file(entry, playlist_entry);
4502 if (!list)
4503 list = entry;
4504 else
4505 play_tree_append_entry(list, entry);
4507 free_demuxer(mpctx->demuxer);
4508 mpctx->demuxer = NULL;
4510 if (list) {
4511 entry = play_tree_new();
4512 play_tree_set_child(entry, list);
4513 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4514 goto goto_next_file;
4518 if (!mpctx->demuxer) {
4519 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4520 goto goto_next_file;
4523 if (mpctx->demuxer->matroska_data.ordered_chapters)
4524 build_ordered_chapter_timeline(mpctx);
4526 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4527 build_edl_timeline(mpctx);
4529 if (mpctx->timeline) {
4530 mpctx->timeline_part = 0;
4531 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4533 int part_count = mpctx->num_timeline_parts;
4534 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4535 "sources. Total length %.3f seconds.\n", part_count,
4536 mpctx->num_sources, mpctx->timeline[part_count].start);
4537 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4538 for (int i = 0; i < mpctx->num_sources; i++)
4539 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4540 filename_recode(mpctx->sources[i].demuxer->filename));
4541 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4542 "source_start, source):\n");
4543 for (int i = 0; i < part_count; i++) {
4544 struct timeline_part *p = mpctx->timeline + i;
4545 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4546 p->source_start, p->source - mpctx->sources);
4548 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4549 mpctx->timeline[part_count].start);
4552 if (!mpctx->sources) {
4553 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4554 *mpctx->sources = (struct content_source){
4555 .stream = mpctx->stream,
4556 .demuxer = mpctx->demuxer
4558 mpctx->num_sources = 1;
4561 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4563 #ifdef CONFIG_ASS
4564 if (opts->ass_enabled) {
4565 for (int j = 0; j < mpctx->num_sources; j++) {
4566 struct demuxer *d = mpctx->sources[j].demuxer;
4567 for (int i = 0; i < d->num_attachments; i++) {
4568 struct demux_attachment *att = d->attachments + i;
4569 if (opts->use_embedded_fonts && attachment_is_font(att))
4570 ass_add_font(mpctx->ass_library, att->name, att->data,
4571 att->data_size);
4575 /* libass seems to misbehave if fonts are changed while a renderer
4576 * exists, so we (re)create the renderer after fonts are set.
4578 assert(!mpctx->osd->ass_renderer);
4579 mpctx->osd->ass_renderer = ass_renderer_init(mpctx->osd->ass_library);
4580 if (!mpctx->osd->ass_renderer) {
4581 mp_msg(MSGT_OSD, MSGL_FATAL, "Failed to create libass renderer\n");
4582 exit_player(mpctx, EXIT_ERROR);
4584 mp_ass_configure_fonts(mpctx->osd->ass_renderer);
4585 #endif
4587 current_module = "demux_open2";
4589 mpctx->d_audio = mpctx->demuxer->audio;
4590 mpctx->d_video = mpctx->demuxer->video;
4591 mpctx->d_sub = mpctx->demuxer->sub;
4593 if (ts_prog) {
4594 int tmp = ts_prog;
4595 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4597 // select audio stream
4598 for (int i = 0; i < mpctx->num_sources; i++)
4599 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4600 opts->audio_lang);
4602 // DUMP STREAMS:
4603 if ((stream_dump_type) && (stream_dump_type < 4)) {
4604 FILE *f;
4605 demux_stream_t *ds = NULL;
4606 current_module = "dump";
4607 // select stream to dump
4608 switch (stream_dump_type) {
4609 case 1: ds = mpctx->d_audio;
4610 break;
4611 case 2: ds = mpctx->d_video;
4612 break;
4613 case 3: ds = mpctx->d_sub;
4614 break;
4616 if (!ds) {
4617 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4618 "dump: FATAL: Selected stream missing!\n");
4619 exit_player(mpctx, EXIT_ERROR);
4621 // disable other streams:
4622 if (mpctx->d_audio && mpctx->d_audio != ds) {
4623 ds_free_packs(mpctx->d_audio);
4624 mpctx->d_audio->id = -2;
4626 if (mpctx->d_video && mpctx->d_video != ds) {
4627 ds_free_packs(mpctx->d_video);
4628 mpctx->d_video->id = -2;
4630 if (mpctx->d_sub && mpctx->d_sub != ds) {
4631 ds_free_packs(mpctx->d_sub);
4632 mpctx->d_sub->id = -2;
4634 // let's dump it!
4635 f = fopen(opts->stream_dump_name, "wb");
4636 if (!f) {
4637 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4638 exit_player(mpctx, EXIT_ERROR);
4640 struct stream_dump_progress info;
4641 stream_dump_progress_start(&info);
4642 while (!ds->eof) {
4643 unsigned char *start;
4644 int in_size = ds_get_packet(ds, &start);
4645 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4646 && stream_dump_type == 2)
4647 fwrite(&in_size, 1, 4, f);
4648 if (in_size > 0) {
4649 fwrite(start, in_size, 1, f);
4650 stream_dump_progress(&info, in_size, mpctx->stream);
4652 if (opts->chapterrange[1] > 0) {
4653 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4654 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4655 break;
4658 fclose(f);
4659 stream_dump_progress_end(&info, opts->stream_dump_name);
4660 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4661 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4664 mpctx->sh_audio = mpctx->d_audio->sh;
4665 mpctx->sh_video = mpctx->d_video->sh;
4667 if (mpctx->sh_video) {
4668 current_module = "video_read_properties";
4669 if (!video_read_properties(mpctx->sh_video)) {
4670 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4671 mpctx->sh_video = mpctx->d_video->sh = NULL;
4672 } else {
4673 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4674 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4675 mpctx->demuxer->file_format, mpctx->sh_video->format,
4676 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4677 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4678 if (force_fps) {
4679 mpctx->sh_video->fps = force_fps;
4680 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4682 vo_fps = mpctx->sh_video->fps;
4684 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4685 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4686 "header or invalid, use the -fps option.\n");
4692 if (!mpctx->sh_video && !mpctx->sh_audio) {
4693 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4694 #ifdef CONFIG_DVBIN
4695 if (mpctx->stream->type == STREAMTYPE_DVB) {
4696 int dir;
4697 int v = mpctx->last_dvb_step;
4698 if (v > 0)
4699 dir = DVB_CHANNEL_HIGHER;
4700 else
4701 dir = DVB_CHANNEL_LOWER;
4703 if (dvb_step_channel(mpctx->stream, dir)) {
4704 mpctx->stop_play = PT_NEXT_ENTRY;
4705 mpctx->dvbin_reopen = 1;
4708 #endif
4709 goto goto_next_file; // exit_player(_("Fatal error"));
4712 /* display clip info */
4713 demux_info_print(mpctx->demuxer);
4715 //================= Read SUBTITLES (DVD & TEXT) =========================
4716 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4717 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4718 init_vo_spudec(mpctx);
4720 // after reading video params we should load subtitles because
4721 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4722 // check .sub
4723 current_module = "read_subtitles_file";
4724 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4725 if (opts->sub_name) {
4726 for (i = 0; opts->sub_name[i] != NULL; ++i)
4727 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4729 if (opts->sub_auto) { // auto load sub file ...
4730 char **tmp = find_text_subtitles(opts, mpctx->filename);
4731 int nsub = MP_TALLOC_ELEMS(tmp);
4732 for (int i = 0; i < nsub; i++)
4733 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4734 talloc_free(tmp);
4736 if (mpctx->set_of_sub_size > 0)
4737 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4739 if (select_subtitle(mpctx)) {
4740 if (mpctx->subdata)
4741 switch (stream_dump_type) {
4742 case 3: list_sub_file(mpctx->subdata);
4743 break;
4744 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4745 break;
4746 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4747 break;
4748 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4749 break;
4750 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4751 break;
4752 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4753 break;
4757 print_file_properties(mpctx, mpctx->filename);
4759 reinit_video_chain(mpctx);
4760 if (!mpctx->sh_video && !mpctx->sh_audio)
4761 goto goto_next_file;
4763 //================== MAIN: ==========================
4764 current_module = "main";
4766 if (opts->playing_msg) {
4767 char *msg = property_expand_string(mpctx, opts->playing_msg);
4768 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4769 free(msg);
4773 // Disable the term OSD in verbose mode
4774 if (verbose)
4775 opts->term_osd = 0;
4777 // Make sure old OSD does not stay around
4778 clear_osd_msgs();
4780 //================ SETUP AUDIO ==========================
4782 if (mpctx->sh_audio) {
4783 reinit_audio_chain(mpctx);
4784 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4785 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4786 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4789 current_module = "av_init";
4791 if (mpctx->sh_video) {
4792 mpctx->sh_video->timer = 0;
4793 if (!ignore_start)
4794 audio_delay += mpctx->sh_video->stream_delay;
4796 if (mpctx->sh_audio) {
4797 if (start_volume >= 0)
4798 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4799 if (!ignore_start)
4800 audio_delay -= mpctx->sh_audio->stream_delay;
4803 if (!mpctx->sh_audio) {
4804 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4805 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4806 mpctx->d_audio->packs);
4807 ds_free_packs(mpctx->d_audio); // free buffered chunks
4809 if (!mpctx->sh_video) {
4810 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4811 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4812 mpctx->d_video->packs);
4813 ds_free_packs(mpctx->d_video);
4814 mpctx->d_video->id = -2;
4817 if (!mpctx->sh_video && !mpctx->sh_audio)
4818 goto goto_next_file;
4820 if (force_fps && mpctx->sh_video) {
4821 vo_fps = mpctx->sh_video->fps = force_fps;
4822 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4823 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4824 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4825 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4828 mp_input_set_section(mpctx->input, NULL);
4829 //TODO: add desired (stream-based) sections here
4830 if (mpctx->stream->type == STREAMTYPE_TV)
4831 mp_input_set_section(mpctx->input, "tv");
4832 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4833 mp_input_set_section(mpctx->input, "dvdnav");
4835 //==================== START PLAYING =======================
4837 if (opts->loop_times > 1)
4838 opts->loop_times--;
4839 else if (opts->loop_times == 1)
4840 opts->loop_times = -1;
4842 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4844 total_time_usage_start = GetTimer();
4845 audio_time_usage = 0;
4846 video_time_usage = 0;
4847 vout_time_usage = 0;
4848 total_frame_cnt = 0;
4849 drop_frame_cnt = 0; // fix for multifile fps benchmark
4850 play_n_frames = play_n_frames_mf;
4852 if (play_n_frames == 0) {
4853 mpctx->stop_play = PT_NEXT_ENTRY;
4854 goto goto_next_file;
4857 mpctx->time_frame = 0;
4858 mpctx->drop_message_shown = 0;
4859 mpctx->restart_playback = true;
4860 mpctx->video_pts = 0;
4861 mpctx->last_seek_pts = 0;
4862 mpctx->hrseek_active = false;
4863 mpctx->hrseek_framedrop = false;
4864 mpctx->step_frames = 0;
4865 mpctx->total_avsync_change = 0;
4866 mpctx->last_chapter_seek = -2;
4868 // If there's a timeline force an absolute seek to initialize state
4869 if (opts->seek_to_sec || mpctx->timeline) {
4870 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4871 seek(mpctx, mpctx->seek, false);
4872 end_at.pos += opts->seek_to_sec;
4874 if (opts->chapterrange[0] > 0) {
4875 double pts;
4876 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4877 && pts > -1.0) {
4878 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4879 seek(mpctx, mpctx->seek, false);
4883 if (end_at.type == END_AT_SIZE) {
4884 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4885 "Option -endpos in MPlayer does not yet support size units.\n");
4886 end_at.type = END_AT_NONE;
4889 #ifdef CONFIG_DVDNAV
4890 mp_dvdnav_context_free(mpctx);
4891 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4892 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4893 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4895 #endif
4897 mpctx->seek = (struct seek_params){ 0 };
4898 get_relative_time(mpctx); // reset current delta
4899 // Make sure VO knows current pause state
4900 if (mpctx->sh_video)
4901 vo_control(mpctx->video_out,
4902 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4904 while (!mpctx->stop_play)
4905 run_playloop(mpctx);
4907 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4909 #ifdef CONFIG_DVBIN
4910 if (mpctx->dvbin_reopen) {
4911 mpctx->stop_play = 0;
4912 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4913 cache_uninit(mpctx->stream);
4914 mpctx->dvbin_reopen = 0;
4915 goto goto_enable_cache;
4917 #endif
4919 goto_next_file: // don't jump here after ao/vo/getch initialization!
4921 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4923 if (opts->benchmark) {
4924 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4925 double total_time_usage;
4926 total_time_usage_start = GetTimer() - total_time_usage_start;
4927 total_time_usage = (float)total_time_usage_start * 0.000001;
4928 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4929 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4930 video_time_usage, vout_time_usage, audio_time_usage,
4931 total_time_usage - tot, total_time_usage);
4932 if (total_time_usage > 0.0)
4933 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4934 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4935 100.0 * video_time_usage / total_time_usage,
4936 100.0 * vout_time_usage / total_time_usage,
4937 100.0 * audio_time_usage / total_time_usage,
4938 100.0 * (total_time_usage - tot) / total_time_usage,
4939 100.0);
4940 if (total_frame_cnt && frame_dropping)
4941 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4942 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4943 total_frame_cnt - drop_frame_cnt,
4944 (total_time_usage > 0.5) ? ((total_frame_cnt -
4945 drop_frame_cnt) / total_time_usage) : 0,
4946 drop_frame_cnt,
4947 100 * drop_frame_cnt / total_frame_cnt,
4948 total_frame_cnt,
4949 (total_time_usage > 0.5) ?
4950 (total_frame_cnt / total_time_usage) : 0);
4953 // time to uninit all, except global stuff:
4954 int uninitialize_parts = INITIALIZED_ALL;
4955 if (opts->fixed_vo)
4956 uninitialize_parts -= INITIALIZED_VO;
4957 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4958 uninitialize_parts -= INITIALIZED_AO;
4959 uninit_player(mpctx, uninitialize_parts);
4961 mpctx->file_format = DEMUXER_TYPE_UNKNOWN;
4962 talloc_free(mpctx->resolve_result);
4963 mpctx->resolve_result = NULL;
4965 if (mpctx->set_of_sub_size > 0) {
4966 current_module = "sub_free";
4967 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
4968 sub_free(mpctx->set_of_subtitles[i]);
4969 if (mpctx->set_of_ass_tracks[i])
4970 sub_uninit(mpctx->set_of_ass_tracks[i]);
4971 talloc_free(mpctx->set_of_ass_tracks[i]);
4973 mpctx->set_of_sub_size = 0;
4975 mpctx->vo_sub_last = vo_sub = NULL;
4976 mpctx->subdata = NULL;
4977 #ifdef CONFIG_ASS
4978 if (mpctx->osd->ass_renderer)
4979 ass_renderer_done(mpctx->osd->ass_renderer);
4980 mpctx->osd->ass_renderer = NULL;
4981 ass_clear_fonts(mpctx->ass_library);
4982 #endif
4984 if (!mpctx->stop_play) // In case some goto jumped here...
4985 mpctx->stop_play = PT_NEXT_ENTRY;
4987 int playtree_direction = 1;
4989 if (mpctx->stop_play == PT_NEXT_ENTRY
4990 || mpctx->stop_play == PT_PREV_ENTRY) {
4991 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
4992 != PLAY_TREE_ITER_ENTRY) {
4993 play_tree_iter_free(mpctx->playtree_iter);
4994 mpctx->playtree_iter = NULL;
4996 mpctx->play_tree_step = 1;
4997 } else if (mpctx->stop_play == PT_UP_NEXT ||
4998 mpctx->stop_play == PT_UP_PREV) {
4999 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5000 if (mpctx->playtree_iter) {
5001 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5002 PLAY_TREE_ITER_ENTRY) {
5003 play_tree_iter_free(mpctx->playtree_iter);
5004 mpctx->playtree_iter = NULL;
5007 } else if (mpctx->stop_play == PT_STOP) {
5008 play_tree_iter_free(mpctx->playtree_iter);
5009 mpctx->playtree_iter = NULL;
5010 } else // NEXT PREV SRC
5011 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5013 while (mpctx->playtree_iter != NULL) {
5014 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5015 playtree_direction);
5016 if (mpctx->filename == NULL) {
5017 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5018 0) != PLAY_TREE_ITER_ENTRY) {
5019 play_tree_iter_free(mpctx->playtree_iter);
5020 mpctx->playtree_iter = NULL;
5023 } else
5024 break;
5027 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5028 if (!mpctx->playtree_iter)
5029 mpctx->filename = NULL;
5030 mpctx->stop_play = 0;
5031 goto play_next_file;
5034 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5036 return 1;
5038 #endif /* DISABLE_MAIN */