stream_dvd: fix dvd_get_current_time()
[mplayer.git] / mplayer.c
blob80e7a8d20e8cb5b6bf2e13446e520b027d956fc2
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 /// \file
20 /// \ingroup Properties Command2Property OSDMsgStack
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdbool.h>
25 #include <math.h>
26 #include <assert.h>
28 #include "config.h"
29 #include "talloc.h"
31 #if defined(__MINGW32__) || defined(__CYGWIN__)
32 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
33 #include <windows.h>
34 #endif
35 #include <string.h>
36 #include <unistd.h>
38 // #include <sys/mman.h>
39 #include <sys/types.h>
40 #ifndef __MINGW32__
41 #include <sys/ioctl.h>
42 #include <sys/wait.h>
43 #else
44 #define SIGHUP 1 /* hangup */
45 #define SIGQUIT 3 /* quit */
46 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
47 #define SIGBUS 10 /* bus error */
48 #define SIGPIPE 13 /* broken pipe */
49 #endif
51 #include <sys/time.h>
52 #include <sys/stat.h>
54 #include <signal.h>
55 #include <time.h>
56 #include <fcntl.h>
57 #include <limits.h>
59 #include <errno.h>
61 #include "mp_msg.h"
62 #include "av_log.h"
65 #include "m_option.h"
66 #include "m_config.h"
67 #include "mplayer.h"
68 #include "access_mpcontext.h"
69 #include "m_property.h"
71 #include "libavutil/avstring.h"
73 #include "sub/subreader.h"
74 #include "sub/find_subfiles.h"
75 #include "sub/dec_sub.h"
77 #include "mp_osd.h"
78 #include "libvo/video_out.h"
80 #include "sub/font_load.h"
81 #include "sub/sub.h"
82 #include "ffmpeg_files/intreadwrite.h"
83 #include "sub/av_sub.h"
84 #include "libmpcodecs/dec_teletext.h"
85 #include "cpudetect.h"
86 #include "version.h"
88 #ifdef CONFIG_X11
89 #include "libvo/x11_common.h"
90 #endif
92 #include "libao2/audio_out.h"
94 #include "codec-cfg.h"
96 #include "edl.h"
98 #include "sub/spudec.h"
99 #include "sub/vobsub.h"
101 #include "osdep/getch2.h"
102 #include "osdep/timer.h"
104 #include "input/input.h"
106 int slave_mode=0;
107 int enable_mouse_movements=0;
108 float start_volume = -1;
110 #include "osdep/priority.h"
112 char *heartbeat_cmd;
114 #ifdef HAVE_RTC
115 #ifdef __linux__
116 #include <linux/rtc.h>
117 #else
118 #include <rtc.h>
119 #define RTC_IRQP_SET RTCIO_IRQP_SET
120 #define RTC_PIE_ON RTCIO_PIE_ON
121 #endif /* __linux__ */
122 #endif /* HAVE_RTC */
124 #include "stream/tv.h"
125 #include "stream/stream_radio.h"
126 #ifdef CONFIG_DVBIN
127 #include "stream/dvbin.h"
128 #endif
129 #include "stream/cache2.h"
131 //**************************************************************************//
132 // Playtree
133 //**************************************************************************//
134 #include "playtree.h"
135 #include "playtreeparser.h"
137 //**************************************************************************//
138 // Config
139 //**************************************************************************//
140 #include "parser-cfg.h"
141 #include "parser-mpcmd.h"
143 //**************************************************************************//
144 // Config file
145 //**************************************************************************//
147 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
149 #include "path.h"
151 //**************************************************************************//
152 //**************************************************************************//
153 // Input media streaming & demultiplexer:
154 //**************************************************************************//
156 static int max_framesize=0;
158 #include "stream/stream.h"
159 #include "libmpdemux/demuxer.h"
160 #include "libmpdemux/stheader.h"
162 #ifdef CONFIG_DVDREAD
163 #include "stream/stream_dvd.h"
164 #endif
165 #include "stream/stream_dvdnav.h"
167 #include "libmpcodecs/dec_audio.h"
168 #include "libmpcodecs/dec_video.h"
169 #include "libmpcodecs/mp_image.h"
170 #include "libmpcodecs/vf.h"
171 #include "libmpcodecs/vd.h"
173 #include "mixer.h"
175 #include "mp_core.h"
176 #include "options.h"
177 #include "defaultopts.h"
179 static const char help_text[]=_(
180 "Usage: mplayer [options] [url|path/]filename\n"
181 "\n"
182 "Basic options: (complete list in the man page)\n"
183 " -vo <drv> select video output driver ('-vo help' for a list)\n"
184 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
185 #ifdef CONFIG_VCD
186 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
187 #endif
188 #ifdef CONFIG_DVDREAD
189 " dvd://<titleno> play DVD title from device instead of plain file\n"
190 #endif
191 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
192 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
193 " -nosound do not play sound\n"
194 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
195 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
196 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
197 " -playlist <file> specify playlist file\n"
198 " -vid x -aid y select video (x) and audio (y) stream to play\n"
199 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
200 " -pp <quality> enable postprocessing filter (details in the man page)\n"
201 " -framedrop enable frame dropping (for slow machines)\n"
202 "\n"
203 "Basic keys: (complete list in the man page, also check input.conf)\n"
204 " <- or -> seek backward/forward 10 seconds\n"
205 " down or up seek backward/forward 1 minute\n"
206 " pgdown or pgup seek backward/forward 10 minutes\n"
207 " < or > step backward/forward in playlist\n"
208 " p or SPACE pause movie (press any key to continue)\n"
209 " q or ESC stop playing and quit program\n"
210 " + or - adjust audio delay by +/- 0.1 second\n"
211 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
212 " * or / increase or decrease PCM volume\n"
213 " x or z adjust subtitle delay by +/- 0.1 second\n"
214 " r or t adjust subtitle position up/down, also see -vf expand\n"
215 " double click toggle fullscreen\n"
216 " right click pause (press again to continue)\n"
217 "\n"
218 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
219 "\n");
222 #define Exit_SIGILL_RTCpuSel _(\
223 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
224 " It may be a bug in our new runtime CPU-detection code...\n"\
225 " Please read DOCS/HTML/en/bugreports.html.\n")
227 #define Exit_SIGILL _(\
228 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
229 " It usually happens when you run it on a CPU different than the one it was\n"\
230 " compiled/optimized for.\n"\
231 " Verify this!\n")
233 #define Exit_SIGSEGV_SIGFPE _(\
234 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
235 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
236 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
238 #define Exit_SIGCRASH _(\
239 "- MPlayer crashed. This shouldn't happen.\n"\
240 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
241 " gcc version. If you think it's MPlayer's fault, please read\n"\
242 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
243 " won't help unless you provide this information when reporting a possible bug.\n")
245 #define SystemTooSlow _("\n\n"\
246 " ************************************************\n"\
247 " **** Your system is too SLOW to play this! ****\n"\
248 " ************************************************\n\n"\
249 "Possible reasons, problems, workarounds:\n"\
250 "- Most common: broken/buggy _audio_ driver\n"\
251 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
252 " - Experiment with different values for -autosync, 30 is a good start.\n"\
253 "- Slow video output\n"\
254 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
255 "- Slow CPU\n"\
256 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
257 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
258 "- Broken file\n"\
259 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
260 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
261 " - Try -cache 8192.\n"\
262 "- Are you using -cache to play a non-interleaved AVI file?\n"\
263 " - Try -nocache.\n"\
264 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
265 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
268 //**************************************************************************//
269 //**************************************************************************//
271 #include "mp_fifo.h"
273 // benchmark:
274 double video_time_usage=0;
275 double vout_time_usage=0;
276 static double audio_time_usage=0;
277 static int total_time_usage_start=0;
278 static int total_frame_cnt=0;
279 static int drop_frame_cnt=0; // total number of dropped frames
281 // options:
282 static int output_quality=0;
284 // seek:
285 static double seek_to_sec;
286 static off_t seek_to_byte=0;
287 static off_t step_sec=0;
289 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
291 // codecs:
292 char **audio_codec_list=NULL; // override audio codec
293 char **video_codec_list=NULL; // override video codec
294 char **audio_fm_list=NULL; // override audio codec family
295 char **video_fm_list=NULL; // override video codec family
297 // this dvdsub_id was selected via slang
298 // use this to allow dvdnav to follow -slang across stream resets,
299 // in particular the subtitle ID for a language changes
300 int dvdsub_lang_id;
301 int vobsub_id=-1;
302 static char* spudec_ifo=NULL;
303 int forced_subs_only=0;
304 int file_filter=1;
306 // cache2:
307 int stream_cache_size=-1;
309 // dump:
310 int stream_dump_type=0;
312 // A-V sync:
313 static float default_max_pts_correction=-1;//0.01f;
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 // sub:
324 char *font_name=NULL;
325 char *sub_font_name=NULL;
326 extern int font_fontconfig;
327 float font_factor=0.75;
328 float sub_delay=0;
329 float sub_fps=0;
330 int subcc_enabled=0;
331 int suboverlap_enabled = 1;
333 #include "sub/ass_mp.h"
335 char* current_module=NULL; // for debugging
338 // ---
340 #ifdef CONFIG_MENU
341 #include "m_struct.h"
342 #include "libmenu/menu.h"
343 static const vf_info_t* const libmenu_vfs[] = {
344 &vf_info_menu,
345 NULL
347 static vf_instance_t* vf_menu = NULL;
348 int use_menu = 0;
349 static char* menu_cfg = NULL;
350 static char* menu_root = "main";
351 #endif
354 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
355 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
356 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
357 int use_filedir_conf;
358 int use_filename_title;
360 #include "mpcommon.h"
361 #include "command.h"
363 #include "metadata.h"
365 void *mpctx_get_video_out(MPContext *mpctx)
367 return mpctx->video_out;
370 void *mpctx_get_demuxer(MPContext *mpctx)
372 return mpctx->demuxer;
375 void *mpctx_get_playtree_iter(MPContext *mpctx)
377 return mpctx->playtree_iter;
380 void *mpctx_get_mixer(MPContext *mpctx)
382 return &mpctx->mixer;
385 int mpctx_get_global_sub_size(MPContext *mpctx)
387 return mpctx->global_sub_size;
390 int mpctx_get_osd_function(MPContext *mpctx)
392 return mpctx->osd_function;
395 static float get_relative_time(struct MPContext *mpctx)
397 unsigned int new_time = GetTimer();
398 unsigned int delta = new_time - mpctx->last_time;
399 mpctx->last_time = new_time;
400 return delta * 0.000001;
403 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
404 switch (type)
406 /* check for valid video stream */
407 case META_VIDEO_CODEC:
408 case META_VIDEO_BITRATE:
409 case META_VIDEO_RESOLUTION:
411 if (!mpctx->sh_video)
412 return 0;
413 break;
416 /* check for valid audio stream */
417 case META_AUDIO_CODEC:
418 case META_AUDIO_BITRATE:
419 case META_AUDIO_SAMPLES:
421 if (!mpctx->sh_audio)
422 return 0;
423 break;
426 /* check for valid demuxer */
427 case META_INFO_TITLE:
428 case META_INFO_ARTIST:
429 case META_INFO_ALBUM:
430 case META_INFO_YEAR:
431 case META_INFO_COMMENT:
432 case META_INFO_TRACK:
433 case META_INFO_GENRE:
435 if (!mpctx->demuxer)
436 return 0;
437 break;
440 default:
441 break;
444 return 1;
447 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
448 char **info = mpctx->demuxer->info;
449 int n;
451 if (!info || !tag)
452 return talloc_strdup(NULL, "");
454 for (n = 0; info[2*n] != NULL ; n++)
455 if (!strcasecmp (info[2*n], tag))
456 break;
458 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
461 char *get_metadata(struct MPContext *mpctx, metadata_t type)
463 sh_audio_t * const sh_audio = mpctx->sh_audio;
464 sh_video_t * const sh_video = mpctx->sh_video;
466 if (!is_valid_metadata_type(mpctx, type))
467 return NULL;
469 switch (type) {
470 case META_NAME:
471 return talloc_strdup(NULL, mp_basename(mpctx->filename));
472 case META_VIDEO_CODEC:
473 if (sh_video->format == 0x10000001)
474 return talloc_strdup(NULL, "mpeg1");
475 else if (sh_video->format == 0x10000002)
476 return talloc_strdup(NULL, "mpeg2");
477 else if (sh_video->format == 0x10000004)
478 return talloc_strdup(NULL, "mpeg4");
479 else if (sh_video->format == 0x10000005)
480 return talloc_strdup(NULL, "h264");
481 else if (sh_video->format >= 0x20202020)
482 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
483 else
484 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
485 case META_VIDEO_BITRATE:
486 return talloc_asprintf(NULL, "%d kbps",
487 (int) (sh_video->i_bps * 8 / 1024));
488 case META_VIDEO_RESOLUTION:
489 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
490 sh_video->disp_h);
491 case META_AUDIO_CODEC:
492 if (sh_audio->codec && sh_audio->codec->name)
493 return talloc_strdup(NULL, sh_audio->codec->name);
494 return talloc_strdup(NULL, "");
495 case META_AUDIO_BITRATE:
496 return talloc_asprintf(NULL, "%d kbps",
497 (int) (sh_audio->i_bps * 8/1000));
498 case META_AUDIO_SAMPLES:
499 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
500 sh_audio->channels);
502 /* check for valid demuxer */
503 case META_INFO_TITLE:
504 return get_demuxer_info(mpctx, "Title");
506 case META_INFO_ARTIST:
507 return get_demuxer_info(mpctx, "Artist");
509 case META_INFO_ALBUM:
510 return get_demuxer_info(mpctx, "Album");
512 case META_INFO_YEAR:
513 return get_demuxer_info(mpctx, "Year");
515 case META_INFO_COMMENT:
516 return get_demuxer_info(mpctx, "Comment");
518 case META_INFO_TRACK:
519 return get_demuxer_info(mpctx, "Track");
521 case META_INFO_GENRE:
522 return get_demuxer_info(mpctx, "Genre");
524 default:
525 break;
528 return talloc_strdup(NULL, "");
531 static void print_file_properties(struct MPContext *mpctx, const char *filename)
533 double start_pts = MP_NOPTS_VALUE;
534 double video_start_pts = MP_NOPTS_VALUE;
535 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
536 filename_recode(filename));
537 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
538 if (mpctx->sh_video) {
539 /* Assume FOURCC if all bytes >= 0x20 (' ') */
540 if (mpctx->sh_video->format >= 0x20202020)
541 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
542 else
543 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
544 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
545 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
546 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
547 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
548 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
549 video_start_pts = ds_get_next_pts(mpctx->d_video);
551 if (mpctx->sh_audio) {
552 /* Assume FOURCC if all bytes >= 0x20 (' ') */
553 if (mpctx->sh_audio->format >= 0x20202020)
554 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
555 else
556 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
557 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
558 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
559 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
560 start_pts = ds_get_next_pts(mpctx->d_audio);
562 if (video_start_pts != MP_NOPTS_VALUE) {
563 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
564 (mpctx->sh_video && video_start_pts < start_pts))
565 start_pts = video_start_pts;
567 if (start_pts != MP_NOPTS_VALUE)
568 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
569 else
570 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
571 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
572 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
573 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
574 if (mpctx->demuxer) {
575 if (mpctx->demuxer->num_chapters == 0)
576 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
577 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
581 /// step size of mixer changes
582 int volstep = 3;
584 #ifdef CONFIG_DVDNAV
585 static void mp_dvdnav_context_free(MPContext *ctx){
586 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
587 ctx->nav_smpi = NULL;
588 free(ctx->nav_buffer);
589 ctx->nav_buffer = NULL;
590 ctx->nav_start = NULL;
591 ctx->nav_in_size = 0;
593 #endif
595 static void uninit_subs(struct demuxer *demuxer)
597 for (int i = 0; i < MAX_S_STREAMS; i++) {
598 struct sh_sub *sh = demuxer->s_streams[i];
599 if (sh && sh->initialized)
600 sub_uninit(sh);
604 void uninit_player(struct MPContext *mpctx, unsigned int mask){
605 mask &= mpctx->initialized_flags;
607 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
609 if(mask&INITIALIZED_ACODEC){
610 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
611 current_module="uninit_acodec";
612 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
613 mpctx->sh_audio=NULL;
614 mpctx->mixer.afilter = NULL;
617 if (mask & INITIALIZED_SUB) {
618 mpctx->initialized_flags &= ~INITIALIZED_SUB;
619 if (mpctx->d_sub->sh)
620 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
623 if(mask&INITIALIZED_VCODEC){
624 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
625 current_module="uninit_vcodec";
626 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
627 mpctx->sh_video=NULL;
628 #ifdef CONFIG_MENU
629 vf_menu=NULL;
630 #endif
633 if(mask&INITIALIZED_DEMUXER){
634 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
635 current_module="free_demuxer";
636 if (mpctx->num_sources) {
637 mpctx->demuxer = mpctx->sources[0].demuxer;
638 for (int i = 1; i < mpctx->num_sources; i++) {
639 uninit_subs(mpctx->sources[i].demuxer);
640 free_stream(mpctx->sources[i].stream);
641 free_demuxer(mpctx->sources[i].demuxer);
644 talloc_free(mpctx->sources);
645 mpctx->sources = NULL;
646 mpctx->num_sources = 0;
647 talloc_free(mpctx->timeline);
648 mpctx->timeline = NULL;
649 mpctx->num_timeline_parts = 0;
650 talloc_free(mpctx->chapters);
651 mpctx->chapters = NULL;
652 mpctx->num_chapters = 0;
653 mpctx->video_offset = 0;
654 if(mpctx->demuxer){
655 mpctx->stream=mpctx->demuxer->stream;
656 uninit_subs(mpctx->demuxer);
657 free_demuxer(mpctx->demuxer);
659 mpctx->demuxer=NULL;
662 // kill the cache process:
663 if(mask&INITIALIZED_STREAM){
664 mpctx->initialized_flags&=~INITIALIZED_STREAM;
665 current_module="uninit_stream";
666 if(mpctx->stream) free_stream(mpctx->stream);
667 mpctx->stream=NULL;
670 if(mask&INITIALIZED_VO){
671 mpctx->initialized_flags&=~INITIALIZED_VO;
672 current_module="uninit_vo";
673 vo_destroy(mpctx->video_out);
674 mpctx->video_out=NULL;
675 #ifdef CONFIG_DVDNAV
676 mp_dvdnav_context_free(mpctx);
677 #endif
680 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
681 if(mask&INITIALIZED_GETCH2){
682 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
683 current_module="uninit_getch2";
684 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
685 // restore terminal:
686 getch2_disable();
689 if(mask&INITIALIZED_VOBSUB){
690 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
691 current_module="uninit_vobsub";
692 if(vo_vobsub) vobsub_close(vo_vobsub);
693 vo_vobsub=NULL;
696 if (mask&INITIALIZED_SPUDEC){
697 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
698 current_module="uninit_spudec";
699 spudec_free(vo_spudec);
700 vo_spudec=NULL;
703 if(mask&INITIALIZED_AO){
704 mpctx->initialized_flags&=~INITIALIZED_AO;
705 current_module="uninit_ao";
706 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
707 if (mpctx->ao)
708 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
709 mpctx->ao = NULL;
712 current_module=NULL;
715 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
717 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
718 uninit_player(mpctx, INITIALIZED_ALL);
719 #if defined(__MINGW32__) || defined(__CYGWIN__)
720 timeEndPeriod(1);
721 #endif
722 #ifdef CONFIG_X11
723 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
724 #endif
726 current_module="uninit_input";
727 mp_input_uninit(mpctx->input);
728 #ifdef CONFIG_MENU
729 if (use_menu)
730 menu_uninit();
731 #endif
733 #ifdef CONFIG_FREETYPE
734 current_module="uninit_font";
735 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
736 free_font_desc(mpctx->osd->sub_font);
737 free_font_desc(vo_font);
738 vo_font = NULL;
739 done_freetype();
740 #endif
741 osd_free(mpctx->osd);
743 #ifdef CONFIG_ASS
744 ass_library_done(ass_library);
745 ass_library = NULL;
746 #endif
748 current_module="exit_player";
750 if(mpctx->playtree_iter)
751 play_tree_iter_free(mpctx->playtree_iter);
752 mpctx->playtree_iter = NULL;
753 if(mpctx->playtree)
754 play_tree_free(mpctx->playtree, 1);
755 mpctx->playtree = NULL;
757 talloc_free(mpctx->key_fifo);
759 free(edl_records); // free mem allocated for EDL
760 edl_records = NULL;
761 switch(how) {
762 case EXIT_QUIT:
763 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
764 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
765 break;
766 case EXIT_EOF:
767 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
768 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
769 break;
770 case EXIT_ERROR:
771 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
772 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
773 break;
774 default:
775 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
777 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
779 // must be last since e.g. mp_msg uses option values
780 // that will be freed by this.
781 if (mpctx->mconfig)
782 m_config_free(mpctx->mconfig);
783 mpctx->mconfig = NULL;
785 exit(rc);
788 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
790 exit_player_with_rc(mpctx, how, 1);
793 #ifndef __MINGW32__
794 static void child_sighandler(int x){
795 pid_t pid;
796 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
798 #endif
800 #ifdef CONFIG_CRASH_DEBUG
801 static char *prog_path;
802 static int crash_debug = 0;
803 #endif
805 static void exit_sighandler(int x){
806 static int sig_count=0;
807 #ifdef CONFIG_CRASH_DEBUG
808 if (!crash_debug || x != SIGTRAP)
809 #endif
810 ++sig_count;
811 if(sig_count==5)
813 /* We're crashing bad and can't uninit cleanly :(
814 * by popular request, we make one last (dirty)
815 * effort to restore the user's
816 * terminal. */
817 getch2_disable();
818 exit(1);
820 if(sig_count==6) exit(1);
821 if(sig_count>6){
822 // can't stop :(
823 #ifndef __MINGW32__
824 kill(getpid(),SIGKILL);
825 #endif
827 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
828 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
829 "\nMPlayer interrupted by signal %d in module: %s\n", x,
830 current_module ? current_module : "unknown");
831 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
832 if(sig_count<=1)
833 switch(x){
834 case SIGINT:
835 case SIGPIPE:
836 case SIGQUIT:
837 case SIGTERM:
838 case SIGKILL:
839 async_quit_request = 1;
840 return; // killed from keyboard (^C) or killed [-9]
841 case SIGILL:
842 #if CONFIG_RUNTIME_CPUDETECT
843 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
844 #else
845 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
846 #endif
847 case SIGFPE:
848 case SIGSEGV:
849 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
850 default:
851 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
852 #ifdef CONFIG_CRASH_DEBUG
853 if (crash_debug) {
854 int gdb_pid;
855 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
856 gdb_pid = fork();
857 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
858 if (gdb_pid == 0) { // We are the child
859 char spid[20];
860 snprintf(spid, sizeof(spid), "%i", getppid());
861 getch2_disable(); // allow terminal to work properly with gdb
862 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
863 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
864 } else if (gdb_pid < 0)
865 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
866 else {
867 waitpid(gdb_pid, NULL, 0);
869 if (x == SIGTRAP) return;
871 #endif
873 getch2_disable();
874 exit(1);
877 #include "cfg-mplayer.h"
879 static int cfg_include(m_option_t *conf, char *filename)
881 return m_config_parse_config_file(conf->priv, filename);
884 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
886 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
888 struct MPOpts *opts = &mpctx->opts;
889 char *conffile;
890 int conffile_fd;
891 if (!(opts->noconfig & 2) &&
892 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
893 exit_player(mpctx, EXIT_NONE);
894 if ((conffile = get_path("")) == NULL) {
895 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
896 } else {
897 #ifdef __MINGW32__
898 mkdir(conffile);
899 #else
900 mkdir(conffile, 0777);
901 #endif
902 free(conffile);
903 if ((conffile = get_path("config")) == NULL) {
904 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
905 } else {
906 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
907 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
908 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
909 close(conffile_fd);
911 if (!(opts->noconfig & 1) &&
912 m_config_parse_config_file(conf, conffile) < 0)
913 exit_player(mpctx, EXIT_NONE);
914 free(conffile);
919 #define PROFILE_CFG_PROTOCOL "protocol."
921 static void load_per_protocol_config (m_config_t* conf, const char *const file)
923 char *str;
924 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
925 m_profile_t *p;
927 /* does filename actually uses a protocol ? */
928 str = strstr (file, "://");
929 if (!str)
930 return;
932 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
933 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
934 p = m_config_get_profile (conf, protocol);
935 if (p)
937 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
938 m_config_set_profile(conf,p);
942 #define PROFILE_CFG_EXTENSION "extension."
944 static void load_per_extension_config (m_config_t* conf, const char *const file)
946 char *str;
947 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
948 m_profile_t *p;
950 /* does filename actually have an extension ? */
951 str = strrchr (file, '.');
952 if (!str)
953 return;
955 sprintf (extension, PROFILE_CFG_EXTENSION);
956 strncat (extension, ++str, 7);
957 p = m_config_get_profile (conf, extension);
958 if (p)
960 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
961 m_config_set_profile(conf,p);
965 #define PROFILE_CFG_VO "vo."
966 #define PROFILE_CFG_AO "ao."
968 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
970 char profile[strlen (cfg) + strlen (out) + 1];
971 m_profile_t *p;
973 sprintf (profile, "%s%s", cfg, out);
974 p = m_config_get_profile (conf, profile);
975 if (p)
977 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
978 m_config_set_profile(conf,p);
983 * Tries to load a config file
984 * @return 0 if file was not found, 1 otherwise
986 static int try_load_config(m_config_t *conf, const char *file)
988 struct stat st;
989 if (stat(file, &st))
990 return 0;
991 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
992 m_config_parse_config_file (conf, file);
993 return 1;
996 static void load_per_file_config (m_config_t* conf, const char *const file)
998 char *confpath;
999 char cfg[PATH_MAX];
1000 const char *name;
1002 if (strlen(file) > PATH_MAX - 14) {
1003 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1004 return;
1006 sprintf (cfg, "%s.conf", file);
1008 name = mp_basename(cfg);
1009 if (use_filedir_conf) {
1010 char dircfg[PATH_MAX];
1011 strcpy(dircfg, cfg);
1012 strcpy(dircfg + (name - cfg), "mplayer.conf");
1013 try_load_config(conf, dircfg);
1015 if (try_load_config(conf, cfg))
1016 return;
1019 if ((confpath = get_path (name)) != NULL)
1021 try_load_config(conf, confpath);
1023 free (confpath);
1027 /* When libmpdemux performs a blocking operation (network connection or
1028 * cache filling) if the operation fails we use this function to check
1029 * if it was interrupted by the user.
1030 * The function returns a new value for eof. */
1031 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1033 mp_cmd_t* cmd;
1034 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1035 switch(cmd->id) {
1036 case MP_CMD_QUIT:
1037 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1038 case MP_CMD_PLAY_TREE_STEP: {
1039 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1040 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1041 } break;
1042 case MP_CMD_PLAY_TREE_UP_STEP: {
1043 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1044 } break;
1045 case MP_CMD_PLAY_ALT_SRC_STEP: {
1046 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1047 } break;
1049 mp_cmd_free(cmd);
1051 return stop_play;
1054 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1056 play_tree_add_bpf(entry,mpctx->filename);
1059 if(!entry) {
1060 entry = mpctx->playtree_iter->tree;
1061 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1062 return PT_NEXT_ENTRY;
1064 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1065 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1066 return PT_NEXT_ENTRY;
1069 play_tree_remove(entry,1,1);
1070 return PT_NEXT_SRC;
1072 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1073 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1074 entry = mpctx->playtree_iter->tree;
1075 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1076 return PT_NEXT_ENTRY;
1078 play_tree_remove(entry,1,1);
1080 return PT_NEXT_SRC;
1083 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1085 struct MPOpts *opts = &mpctx->opts;
1086 sub_data *subd = NULL;
1087 struct ass_track *asst = NULL;
1088 bool is_native_ass = false;
1090 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1091 return;
1093 #ifdef CONFIG_ASS
1094 if (opts->ass_enabled) {
1095 #ifdef CONFIG_ICONV
1096 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1097 #else
1098 asst = mp_ass_read_stream(ass_library, filename, 0);
1099 #endif
1100 is_native_ass = asst;
1101 if (!asst) {
1102 subd = sub_read_file(filename, fps, &mpctx->opts);
1103 if (subd) {
1104 asst = mp_ass_read_subdata(ass_library, subd, fps);
1105 sub_free(subd);
1106 subd = NULL;
1109 } else
1110 #endif
1111 subd = sub_read_file(filename, fps, &mpctx->opts);
1114 if (!asst && !subd) {
1115 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1116 "Cannot load subtitles: %s\n", filename_recode(filename));
1117 return;
1120 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1121 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1122 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1123 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1124 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1125 filename_recode(filename));
1126 ++mpctx->set_of_sub_size;
1127 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1128 filename_recode(filename));
1131 void init_vo_spudec(struct MPContext *mpctx)
1133 spudec_free(vo_spudec);
1134 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1135 vo_spudec = NULL;
1137 // we currently can't work without video stream
1138 if (!mpctx->sh_video)
1139 return;
1141 if (spudec_ifo) {
1142 unsigned int palette[16], width, height;
1143 current_module="spudec_init_vobsub";
1144 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1145 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1148 #ifdef CONFIG_DVDREAD
1149 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1150 current_module="spudec_init_dvdread";
1151 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1152 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1153 NULL, 0);
1155 #endif
1157 #ifdef CONFIG_DVDNAV
1158 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1159 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1160 current_module="spudec_init_dvdnav";
1161 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1163 #endif
1165 if (vo_spudec==NULL) {
1166 sh_sub_t *sh = mpctx->d_sub->sh;
1167 current_module="spudec_init_normal";
1168 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1169 spudec_set_font_factor(vo_spudec,font_factor);
1172 if (vo_spudec!=NULL) {
1173 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1174 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1179 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1180 * make it all work is to use the builtin SDL-bootstrap code, which
1181 * will be done automatically by replacing our main() if we include SDL.h.
1183 #if defined(__APPLE__) && defined(CONFIG_SDL)
1184 #ifdef CONFIG_SDL_SDL_H
1185 #include <SDL/SDL.h>
1186 #else
1187 #include <SDL.h>
1188 #endif
1189 #endif
1192 * \brief append a formatted string
1193 * \param buf buffer to print into
1194 * \param pos position of terminating 0 in buf
1195 * \param len maximum number of characters in buf, not including terminating 0
1196 * \param format printf format string
1198 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1200 va_list va;
1201 va_start(va, format);
1202 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1203 va_end(va);
1204 if (*pos >= len ) {
1205 buf[len] = 0;
1206 *pos = len;
1211 * \brief append time in the hh:mm:ss.f format
1212 * \param buf buffer to print into
1213 * \param pos position of terminating 0 in buf
1214 * \param len maximum number of characters in buf, not including terminating 0
1215 * \param time time value to convert/append
1217 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1218 int64_t tenths = 10 * time;
1219 int f1 = tenths % 10;
1220 int ss = (tenths / 10) % 60;
1221 int mm = (tenths / 600) % 60;
1222 int hh = tenths / 36000;
1223 if (time <= 0) {
1224 saddf(buf, pos, len, "unknown");
1225 return;
1227 if (hh > 0)
1228 saddf(buf, pos, len, "%2d:", hh);
1229 if (hh > 0 || mm > 0)
1230 saddf(buf, pos, len, "%02d:", mm);
1231 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1234 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1236 struct MPOpts *opts = &mpctx->opts;
1237 sh_video_t * const sh_video = mpctx->sh_video;
1239 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1240 a_pos = playing_audio_pts(mpctx);
1241 if (mpctx->sh_audio && sh_video && at_frame) {
1242 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1243 if (mpctx->time_frame > 0)
1244 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1245 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1246 && !mpctx->drop_message_shown) {
1247 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1248 mpctx->drop_message_shown = true;
1251 if (opts->quiet)
1252 return;
1255 int width;
1256 char *line;
1257 unsigned pos = 0;
1258 get_screen_size();
1259 if (screen_width > 0)
1260 width = screen_width;
1261 else
1262 width = 80;
1263 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1264 /* Windows command line is broken (MinGW's rxvt works, but we
1265 * should not depend on that). */
1266 width--;
1267 #endif
1268 line = malloc(width + 1); // one additional char for the terminating null
1270 // Audio time
1271 if (mpctx->sh_audio) {
1272 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1273 if (!sh_video) {
1274 float len = get_time_length(mpctx);
1275 saddf(line, &pos, width, "(");
1276 sadd_hhmmssf(line, &pos, width, a_pos);
1277 saddf(line, &pos, width, ") of %.1f (", len);
1278 sadd_hhmmssf(line, &pos, width, len);
1279 saddf(line, &pos, width, ") ");
1283 // Video time
1284 if (sh_video)
1285 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1287 // A-V sync
1288 if (mpctx->sh_audio && sh_video)
1289 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1290 mpctx->last_av_difference, mpctx->total_avsync_change);
1292 // Video stats
1293 if (sh_video)
1294 saddf(line, &pos, width, "%3d/%3d ",
1295 (int)sh_video->num_frames,
1296 (int)sh_video->num_frames_decoded);
1298 // CPU usage
1299 if (sh_video) {
1300 if (sh_video->timer > 0.5)
1301 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1302 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1303 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1304 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1305 else
1306 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1307 } else if (mpctx->sh_audio) {
1308 if (mpctx->delay > 0.5)
1309 saddf(line, &pos, width, "%4.1f%% ",
1310 100.0*audio_time_usage/(double)mpctx->delay);
1311 else
1312 saddf(line, &pos, width, "??,?%% ");
1315 // VO stats
1316 if (sh_video)
1317 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1319 #ifdef CONFIG_STREAM_CACHE
1320 // cache stats
1321 if (stream_cache_size > 0)
1322 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1323 #endif
1325 // other
1326 if (opts->playback_speed != 1)
1327 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1329 // end
1330 if (erase_to_end_of_line) {
1331 line[pos] = 0;
1332 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1333 } else {
1334 memset(&line[pos], ' ', width - pos);
1335 line[width] = 0;
1336 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1338 free(line);
1341 struct stream_dump_progress {
1342 uint64_t count;
1343 unsigned start_time;
1344 unsigned last_print_time;
1347 static void stream_dump_progress_start(struct stream_dump_progress *p)
1349 p->start_time = p->last_print_time = GetTimerMS();
1350 p->count = 0;
1353 static void stream_dump_progress(struct stream_dump_progress *p,
1354 uint64_t len, stream_t *stream)
1356 p->count += len;
1357 unsigned t = GetTimerMS();
1358 if (t - p->last_print_time < 1000)
1359 return;
1361 uint64_t start = stream->start_pos;
1362 uint64_t end = stream->end_pos;
1363 uint64_t pos = stream->pos;
1365 p->last_print_time = t;
1366 /* TODO: pretty print sizes; ETA */
1367 if (end > start && pos >= start && pos <= end) {
1368 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1369 "dump: %"PRIu64" bytes written (~%.1f%%)",
1370 p->count, 100.0 * (pos - start) / (end - start));
1371 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1372 } else {
1373 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1374 "dump: %"PRIu64" bytes written", p->count);
1375 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1379 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1381 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64" bytes written to '%s'.\n",
1382 p->count, name);
1386 * \brief build a chain of audio filters that converts the input format
1387 * to the ao's format, taking into account the current playback_speed.
1388 * sh_audio describes the requested input format of the chain.
1389 * ao describes the requested output format of the chain.
1391 static int build_afilter_chain(struct MPContext *mpctx)
1393 struct sh_audio *sh_audio = mpctx->sh_audio;
1394 struct ao *ao = mpctx->ao;
1395 struct MPOpts *opts = &mpctx->opts;
1396 int new_srate;
1397 int result;
1398 if (!sh_audio)
1400 mpctx->mixer.afilter = NULL;
1401 return 0;
1403 if(af_control_any_rev(sh_audio->afilter,
1404 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1405 &opts->playback_speed)) {
1406 new_srate = sh_audio->samplerate;
1407 } else {
1408 new_srate = sh_audio->samplerate * opts->playback_speed;
1409 if (new_srate != ao->samplerate) {
1410 // limits are taken from libaf/af_resample.c
1411 if (new_srate < 8000)
1412 new_srate = 8000;
1413 if (new_srate > 192000)
1414 new_srate = 192000;
1415 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1418 result = init_audio_filters(sh_audio, new_srate,
1419 &ao->samplerate, &ao->channels, &ao->format);
1420 mpctx->mixer.afilter = sh_audio->afilter;
1421 return result;
1425 typedef struct mp_osd_msg mp_osd_msg_t;
1426 struct mp_osd_msg {
1427 /// Previous message on the stack.
1428 mp_osd_msg_t* prev;
1429 /// Message text.
1430 char msg[128];
1431 int id,level,started;
1432 /// Display duration in ms.
1433 unsigned time;
1436 /// OSD message stack.
1437 static mp_osd_msg_t* osd_msg_stack = NULL;
1440 * \brief Add a message on the OSD message stack
1442 * If a message with the same id is already present in the stack
1443 * it is pulled on top of the stack, otherwise a new message is created.
1446 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1447 va_list ap)
1449 mp_osd_msg_t *msg,*last=NULL;
1450 int r;
1452 // look if the id is already in the stack
1453 for(msg = osd_msg_stack ; msg && msg->id != id ;
1454 last = msg, msg = msg->prev);
1455 // not found: alloc it
1456 if(!msg) {
1457 msg = calloc(1,sizeof(mp_osd_msg_t));
1458 msg->prev = osd_msg_stack;
1459 osd_msg_stack = msg;
1460 } else if(last) { // found, but it's not on top of the stack
1461 last->prev = msg->prev;
1462 msg->prev = osd_msg_stack;
1463 osd_msg_stack = msg;
1465 // write the msg
1466 r = vsnprintf(msg->msg, 128, fmt, ap);
1467 if(r >= 128) msg->msg[127] = 0;
1468 // set id and time
1469 msg->id = id;
1470 msg->level = level;
1471 msg->time = time;
1475 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1477 va_list ap;
1478 va_start(ap, fmt);
1479 set_osd_msg_va(id, level, time, fmt, ap);
1480 va_end(ap);
1483 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1485 va_list ap;
1486 va_start(ap, fmt);
1487 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1488 va_end(ap);
1493 * \brief Remove a message from the OSD stack
1495 * This function can be used to get rid of a message right away.
1499 void rm_osd_msg(int id) {
1500 mp_osd_msg_t *msg,*last=NULL;
1502 // Search for the msg
1503 for(msg = osd_msg_stack ; msg && msg->id != id ;
1504 last = msg, msg = msg->prev);
1505 if(!msg) return;
1507 // Detach it from the stack and free it
1508 if(last)
1509 last->prev = msg->prev;
1510 else
1511 osd_msg_stack = msg->prev;
1512 free(msg);
1516 * \brief Remove all messages from the OSD stack
1520 static void clear_osd_msgs(void) {
1521 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1522 while(msg) {
1523 prev = msg->prev;
1524 free(msg);
1525 msg = prev;
1527 osd_msg_stack = NULL;
1531 * \brief Get the current message from the OSD stack.
1533 * This function decrements the message timer and destroys the old ones.
1534 * The message that should be displayed is returned (if any).
1538 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1540 struct MPOpts *opts = &mpctx->opts;
1541 mp_osd_msg_t *msg,*prev,*last = NULL;
1542 static unsigned last_update = 0;
1543 unsigned now = GetTimerMS();
1544 unsigned diff;
1545 char hidden_dec_done = 0;
1547 if (mpctx->osd_visible) {
1548 // 36000000 means max timed visibility is 1 hour into the future, if
1549 // the difference is greater assume it's wrapped around from below 0
1550 if (mpctx->osd_visible - now > 36000000) {
1551 mpctx->osd_visible = 0;
1552 vo_osd_progbar_type = -1; // disable
1553 vo_osd_changed(OSDTYPE_PROGBAR);
1554 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1557 if (mpctx->osd_show_percentage_until - now > 36000000)
1558 mpctx->osd_show_percentage_until = 0;
1560 if(!last_update) last_update = now;
1561 diff = now >= last_update ? now - last_update : 0;
1563 last_update = now;
1565 // Look for the first message in the stack with high enough level.
1566 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1567 prev = msg->prev;
1568 if (msg->level > opts->osd_level && hidden_dec_done)
1569 continue;
1570 // The message has a high enough level or it is the first hidden one
1571 // in both cases we decrement the timer or kill it.
1572 if(!msg->started || msg->time > diff) {
1573 if(msg->started) msg->time -= diff;
1574 else msg->started = 1;
1575 // display it
1576 if (msg->level <= opts->osd_level)
1577 return msg;
1578 hidden_dec_done = 1;
1579 continue;
1581 // kill the message
1582 free(msg);
1583 if(last) {
1584 last->prev = prev;
1585 msg = last;
1586 } else {
1587 osd_msg_stack = prev;
1588 msg = NULL;
1591 // Nothing found
1592 return NULL;
1596 * \brief Display the OSD bar.
1598 * Display the OSD bar or fall back on a simple message.
1602 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1603 struct MPOpts *opts = &mpctx->opts;
1604 if (opts->osd_level < 1)
1605 return;
1607 if(mpctx->sh_video) {
1608 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1609 vo_osd_progbar_type = type;
1610 vo_osd_progbar_value = 256*(val-min)/(max-min);
1611 vo_osd_changed(OSDTYPE_PROGBAR);
1612 return;
1615 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1616 name, ROUND(100*(val-min)/(max-min)));
1620 * \brief Display text subtitles on the OSD
1622 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1624 int i;
1625 vo_sub = subs;
1626 vo_osd_changed(OSDTYPE_SUBTITLE);
1627 if (!mpctx->sh_video) {
1628 // reverse order, since newest set_osd_msg is displayed first
1629 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1630 if (!subs || i >= subs->lines || !subs->text[i])
1631 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1632 else {
1633 // HACK: currently display time for each sub line 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, "%s", subs->text[i]);
1642 * \brief Update the OSD message line.
1644 * This function displays the current message on the vo OSD or on the term.
1645 * If the stack is empty and the OSD level is high enough the timer
1646 * is displayed (only on the vo OSD).
1650 static void update_osd_msg(struct MPContext *mpctx)
1652 struct MPOpts *opts = &mpctx->opts;
1653 mp_osd_msg_t *msg;
1654 struct osd_state *osd = mpctx->osd;
1655 char osd_text_timer[128];
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))) {
1667 if (strcmp(osd->osd_text, msg->msg)) {
1668 strncpy(osd->osd_text, msg->msg, 127);
1669 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1670 if(opts->term_osd)
1671 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1672 msg->msg);
1674 return;
1677 if(mpctx->sh_video) {
1678 // fallback on the timer
1679 if (opts->osd_level >= 2) {
1680 int len = get_time_length(mpctx);
1681 int percentage = -1;
1682 char percentage_text[10];
1683 char fractions_text[4];
1684 double fpts = get_current_time(mpctx);
1685 int pts = fpts;
1687 if (mpctx->osd_show_percentage_until)
1688 percentage = get_percent_pos(mpctx);
1690 if (percentage >= 0)
1691 snprintf(percentage_text, 9, " (%d%%)", percentage);
1692 else
1693 percentage_text[0] = 0;
1695 if (opts->osd_fractions == 1) {
1696 //print fractions as sub-second timestamp
1697 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1698 (int)((fpts - pts) * 100));
1699 } else if (opts->osd_fractions == 2) {
1700 /* Print fractions by estimating the frame count within the
1701 * second.
1703 * Rounding or cutting off numbers after the decimal point
1704 * causes problems because of float's precision and movies
1705 * whose first frame is not exactly at timestamp 0. Therefore,
1706 * we add 0.2 and cut off at the decimal point, which proved
1707 * to be good heuristic.
1709 double fps = mpctx->sh_video->fps;
1710 if (fps <= 1 || fps > 99)
1711 strcpy(fractions_text, ".??");
1712 else
1713 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1714 (int) ( (fpts - pts) * fps + 0.2 ) );
1715 } else {
1716 //do not print fractions
1717 fractions_text[0] = 0;
1720 if (opts->osd_level == 3)
1721 snprintf(osd_text_timer, 63,
1722 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1723 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1724 fractions_text, len/3600, (len/60)%60, len%60,
1725 percentage_text);
1726 else
1727 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s%s",
1728 mpctx->osd_function,pts/3600,(pts/60)%60,
1729 pts%60, fractions_text, percentage_text);
1730 } else
1731 osd_text_timer[0]=0;
1733 if (strcmp(osd->osd_text, osd_text_timer)) {
1734 strncpy(osd->osd_text, osd_text_timer, 63);
1735 vo_osd_changed(OSDTYPE_OSD);
1737 return;
1740 // Clear the term osd line
1741 if (opts->term_osd && osd->osd_text[0]) {
1742 osd->osd_text[0] = 0;
1743 printf("%s\n", opts->term_osd_esc);
1747 ///@}
1748 // OSDMsgStack
1751 void reinit_audio_chain(struct MPContext *mpctx)
1753 struct MPOpts *opts = &mpctx->opts;
1754 struct ao *ao;
1755 if (!mpctx->sh_audio)
1756 return;
1757 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1758 current_module="init_audio_codec";
1759 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1760 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1761 goto init_error;
1763 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1764 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1768 current_module="af_preinit";
1769 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1770 mpctx->initialized_flags |= INITIALIZED_AO;
1771 mpctx->ao = ao_create();
1772 mpctx->ao->samplerate = force_srate;
1773 mpctx->ao->format = opts->audio_output_format;
1775 ao = mpctx->ao;
1777 // first init to detect best values
1778 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1779 // input:
1780 mpctx->sh_audio->samplerate,
1781 // output:
1782 &ao->samplerate, &ao->channels, &ao->format)) {
1783 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1784 "pre-init!\n");
1785 exit_player(mpctx, EXIT_ERROR);
1787 if (!ao->initialized) {
1788 current_module="ao2_init";
1789 ao->buffersize = opts->ao_buffersize;
1790 ao_init(ao, opts->audio_driver_list);
1791 if (!ao->initialized) {
1792 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1793 goto init_error;
1795 ao->buffer.start = talloc_new(ao);
1796 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1797 ao->driver->info->short_name,
1798 ao->samplerate, ao->channels,
1799 af_fmt2str_short(ao->format),
1800 af_fmt2bits(ao->format)/8 );
1801 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1802 ao->driver->info->name, ao->driver->info->author);
1803 if (strlen(ao->driver->info->comment) > 0)
1804 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1805 ao->driver->info->comment);
1808 // init audio filters:
1809 current_module="af_init";
1810 if (!build_afilter_chain(mpctx)) {
1811 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1812 goto init_error;
1814 mpctx->mixer.ao = ao;
1815 mpctx->mixer.volstep = volstep;
1816 mpctx->syncing_audio = true;
1817 return;
1819 init_error:
1820 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1821 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1822 mpctx->d_audio->id = -2;
1826 ///@}
1827 // Command2Property
1830 // Return pts value corresponding to the end point of audio written to the
1831 // ao so far.
1832 static double written_audio_pts(struct MPContext *mpctx)
1834 sh_audio_t *sh_audio = mpctx->sh_audio;
1835 demux_stream_t *d_audio = mpctx->d_audio;
1836 // first calculate the end pts of audio that has been output by decoder
1837 double a_pts = sh_audio->pts;
1838 if (a_pts != MP_NOPTS_VALUE)
1839 // Good, decoder supports new way of calculating audio pts.
1840 // sh_audio->pts is the timestamp of the latest input packet with
1841 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1842 // the amount of bytes the decoder has written after that timestamp.
1843 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1844 else {
1845 // Decoder doesn't support new way of calculating pts (or we're
1846 // being called before it has decoded anything with known timestamp).
1847 // Use the old method of audio pts calculation: take the timestamp
1848 // of last packet with known pts the decoder has read data from,
1849 // and add amount of bytes read after the beginning of that packet
1850 // divided by input bps. This will be inaccurate if the input/output
1851 // ratio is not constant for every audio packet or if it is constant
1852 // but not accurately known in sh_audio->i_bps.
1854 a_pts = d_audio->pts;
1855 // ds_tell_pts returns bytes read after last timestamp from
1856 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1857 // it has read but not decoded
1858 if (sh_audio->i_bps)
1859 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1860 (double)sh_audio->i_bps;
1862 // Now a_pts hopefully holds the pts for end of audio from decoder.
1863 // Substract data in buffers between decoder and audio out.
1865 // Decoded but not filtered
1866 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1868 // Data buffered in audio filters, measured in bytes of "missing" output
1869 double buffered_output = af_calc_delay(sh_audio->afilter);
1871 // Data that was ready for ao but was buffered because ao didn't fully
1872 // accept everything to internal buffers yet
1873 buffered_output += mpctx->ao->buffer.len;
1875 // Filters divide audio length by playback_speed, so multiply by it
1876 // to get the length in original units without speedup or slowdown
1877 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1879 return a_pts + mpctx->video_offset;
1882 // Return pts value corresponding to currently playing audio.
1883 double playing_audio_pts(struct MPContext *mpctx)
1885 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1886 ao_get_delay(mpctx->ao);
1889 static bool is_av_sub(int type)
1891 return type == 'b' || type == 'p' || type == 'x';
1894 void update_subtitles(struct MPContext *mpctx, double refpts,
1895 double sub_offset, bool reset)
1897 struct MPOpts *opts = &mpctx->opts;
1898 struct sh_video *sh_video = mpctx->sh_video;
1899 struct demux_stream *d_sub = mpctx->d_sub;
1900 double curpts = refpts + sub_delay;
1901 unsigned char *packet=NULL;
1902 int len;
1903 struct sh_sub *sh_sub = d_sub->sh;
1904 int type = sh_sub ? sh_sub->type : 'v';
1905 static subtitle subs;
1906 if (reset) {
1907 if (sh_sub)
1908 sub_reset(sh_sub, mpctx->osd);
1909 sub_clear_text(&subs, MP_NOPTS_VALUE);
1910 if (vo_sub)
1911 set_osd_subtitle(mpctx, NULL);
1912 if (vo_spudec) {
1913 spudec_reset(vo_spudec);
1914 vo_osd_changed(OSDTYPE_SPU);
1916 #ifdef CONFIG_FFMPEG
1917 if (is_av_sub(type))
1918 reset_avsub(sh_sub);
1919 #endif
1920 return;
1922 // find sub
1923 if (mpctx->subdata) {
1924 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1925 current_module = "find_sub";
1926 find_sub(mpctx, mpctx->subdata, curpts *
1927 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1928 if (vo_sub)
1929 mpctx->vo_sub_last = vo_sub;
1932 // DVD sub:
1933 if (vobsub_id >= 0 || type == 'v') {
1934 int timestamp;
1935 current_module = "spudec";
1936 /* Get a sub packet from the DVD or a vobsub */
1937 while(1) {
1938 // Vobsub
1939 len = 0;
1940 if (vo_vobsub) {
1941 if (curpts >= 0) {
1942 len = vobsub_get_packet(vo_vobsub, curpts,
1943 (void**)&packet, &timestamp);
1944 if (len > 0) {
1945 mp_dbg(MSGT_CPLAYER,MSGL_V,"\rVOB sub: len=%d v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",len,refpts,sh_video->timer,timestamp / 90000.0,timestamp);
1948 } else {
1949 // DVD sub
1950 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1951 if (len > 0) {
1952 // XXX This is wrong, sh_video->pts can be arbitrarily
1953 // much behind demuxing position. Unfortunately using
1954 // d_video->pts which would have been the simplest
1955 // improvement doesn't work because mpeg specific hacks
1956 // in video.c set d_video->pts to 0.
1957 float x = d_sub->pts - refpts;
1958 if (x > -20 && x < 20) // prevent missing subs on pts reset
1959 timestamp = 90000*d_sub->pts;
1960 else timestamp = 90000*curpts;
1961 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1962 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1963 refpts, d_sub->pts, timestamp);
1966 if (len<=0 || !packet) break;
1967 // create it only here, since with some broken demuxers we might
1968 // type = v but no DVD sub and we currently do not change the
1969 // "original frame size" ever after init, leading to wrong-sized
1970 // PGS subtitles.
1971 if (!vo_spudec)
1972 vo_spudec = spudec_new(NULL);
1973 if (vo_vobsub || timestamp >= 0)
1974 spudec_assemble(vo_spudec, packet, len, timestamp);
1976 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1977 if (type == 'd' && !d_sub->demuxer->teletext) {
1978 tt_stream_props tsp = {0};
1979 void *ptr = &tsp;
1980 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1981 d_sub->demuxer->teletext = ptr;
1983 if (d_sub->non_interleaved)
1984 ds_get_next_pts(d_sub);
1986 while (d_sub->first) {
1987 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1988 if (subpts > curpts) {
1989 // Libass handled subs can be fed to it in advance
1990 if (!opts->ass_enabled || !is_text_sub(type))
1991 break;
1992 // Try to avoid demuxing whole file at once
1993 if (d_sub->non_interleaved && subpts > curpts + 1)
1994 break;
1996 double duration = d_sub->first->duration;
1997 len = ds_get_packet_sub(d_sub, &packet);
1998 if (is_av_sub(type)) {
1999 #ifdef CONFIG_FFMPEG
2000 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2001 if (ret < 0)
2002 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2003 "subtitle\n");
2004 #endif
2005 continue;
2007 if (type == 'm') {
2008 if (len < 2) continue;
2009 len = FFMIN(len - 2, AV_RB16(packet));
2010 packet += 2;
2012 if (type == 'd') {
2013 if (d_sub->demuxer->teletext) {
2014 uint8_t *p = packet;
2015 p++;
2016 len--;
2017 while (len >= 46) {
2018 int sublen = p[1];
2019 if (p[0] == 2 || p[0] == 3)
2020 teletext_control(d_sub->demuxer->teletext,
2021 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2022 p += sublen + 2;
2023 len -= sublen + 2;
2026 continue;
2028 if (sh_sub && sh_sub->active) {
2029 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2030 continue;
2032 if (subpts != MP_NOPTS_VALUE) {
2033 if (duration < 0)
2034 sub_clear_text(&subs, MP_NOPTS_VALUE);
2035 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2036 int i;
2037 unsigned char* p = packet;
2038 for (i=0; i < 8 && *p != '\0'; p++)
2039 if (*p == ',')
2040 i++;
2041 if (*p == '\0') /* Broken line? */
2042 continue;
2043 len -= p - packet;
2044 packet = p;
2046 double endpts = MP_NOPTS_VALUE;
2047 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2048 endpts = subpts + duration;
2049 sub_add_text(&subs, packet, len, endpts);
2050 set_osd_subtitle(mpctx, &subs);
2052 if (d_sub->non_interleaved)
2053 ds_get_next_pts(d_sub);
2055 if (!opts->ass_enabled)
2056 if (sub_clear_text(&subs, curpts))
2057 set_osd_subtitle(mpctx, &subs);
2059 if (vo_spudec) {
2060 spudec_heartbeat(vo_spudec, 90000*curpts);
2061 if (spudec_changed(vo_spudec))
2062 vo_osd_changed(OSDTYPE_SPU);
2065 current_module=NULL;
2068 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2070 int page_changed;
2072 if (!demuxer->teletext)
2073 return;
2075 //Also forcing page update when such ioctl is not supported or call error occured
2076 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2077 page_changed=1;
2079 if(!page_changed)
2080 return;
2082 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2083 vo_osd_teletext_page=NULL;
2084 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2085 vo_osd_teletext_half=0;
2086 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2087 vo_osd_teletext_mode=0;
2088 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2089 vo_osd_teletext_format=0;
2090 vo_osd_changed(OSDTYPE_TELETEXT);
2092 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2095 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2096 struct MPOpts *opts = &mpctx->opts;
2097 // check for frame-drop:
2098 current_module = "check_framedrop";
2099 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2100 static int dropped_frames;
2101 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2102 float d = delay-mpctx->delay;
2103 ++total_frame_cnt;
2104 // we should avoid dropping too many frames in sequence unless we
2105 // are too late. and we allow 100ms A-V delay here:
2106 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2107 && !mpctx->restart_playback) {
2108 ++drop_frame_cnt;
2109 ++dropped_frames;
2110 return frame_dropping;
2111 } else
2112 dropped_frames = 0;
2114 return 0;
2118 #ifdef HAVE_RTC
2119 int rtc_fd = -1;
2120 #endif
2122 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2124 #ifdef HAVE_RTC
2125 if (rtc_fd >= 0){
2126 // -------- RTC -----------
2127 current_module="sleep_rtc";
2128 while (time_frame > 0.000) {
2129 unsigned long rtc_ts;
2130 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2131 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2132 time_frame -= get_relative_time(mpctx);
2134 } else
2135 #endif
2137 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2138 // unnecessarily high CPU usage
2139 struct MPOpts *opts = &mpctx->opts;
2140 float margin = opts->softsleep ? 0.011 : 0;
2141 current_module = "sleep_timer";
2142 while (time_frame > margin) {
2143 usec_sleep(1000000 * (time_frame - margin));
2144 time_frame -= get_relative_time(mpctx);
2146 if (opts->softsleep){
2147 current_module = "sleep_soft";
2148 if (time_frame < 0)
2149 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2150 while (time_frame > 0)
2151 time_frame -= get_relative_time(mpctx); // burn the CPU
2154 return time_frame;
2157 static int select_subtitle(MPContext *mpctx)
2159 struct MPOpts *opts = &mpctx->opts;
2160 // find the best sub to use
2161 int id;
2162 int found = 0;
2163 mpctx->global_sub_pos = -1; // no subs by default
2164 if (vobsub_id >= 0) {
2165 // if user asks for a vobsub id, use that first.
2166 id = vobsub_id;
2167 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2170 if (!found && opts->sub_id >= 0) {
2171 // if user asks for a dvd sub id, use that next.
2172 id = opts->sub_id;
2173 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2176 if (!found) {
2177 // if there are text subs to use, use those. (autosubs come last here)
2178 id = 0;
2179 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2182 if (!found && opts->sub_id == -1) {
2183 // finally select subs by language and container hints
2184 if (opts->sub_id == -1)
2185 opts->sub_id =
2186 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2187 opts->sub_lang);
2188 if (opts->sub_id >= 0) {
2189 id = opts->sub_id;
2190 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2193 return found;
2196 #ifdef CONFIG_DVDNAV
2197 #ifndef FF_B_TYPE
2198 #define FF_B_TYPE 3
2199 #endif
2200 /// store decoded video image
2201 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2202 mp_image_t *from_mpi) {
2203 mp_image_t *mpi;
2205 /// Do not store B-frames
2206 if (from_mpi->pict_type == FF_B_TYPE)
2207 return to_mpi;
2209 if (to_mpi &&
2210 to_mpi->w == from_mpi->w &&
2211 to_mpi->h == from_mpi->h &&
2212 to_mpi->imgfmt == from_mpi->imgfmt)
2213 mpi = to_mpi;
2214 else {
2215 if (to_mpi)
2216 free_mp_image(to_mpi);
2217 if (from_mpi->w == 0 || from_mpi->h == 0)
2218 return NULL;
2219 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2222 copy_mpi(mpi,from_mpi);
2223 return mpi;
2226 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2227 struct MPOpts *opts = &ctx->opts;
2228 if (ctx->sh_video) {
2229 /// clear video pts
2230 ctx->d_video->pts = 0.0f;
2231 ctx->sh_video->pts = 0.0f;
2232 ctx->sh_video->i_pts = 0.0f;
2233 ctx->sh_video->last_pts = 0.0f;
2234 ctx->sh_video->num_buffered_pts = 0;
2235 ctx->sh_video->num_frames = 0;
2236 ctx->sh_video->num_frames_decoded = 0;
2237 ctx->sh_video->timer = 0.0f;
2238 ctx->sh_video->stream_delay = 0.0f;
2239 ctx->sh_video->timer = 0;
2240 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2243 if (ctx->sh_audio) {
2244 /// free audio packets and reset
2245 ds_free_packs(ctx->d_audio);
2246 audio_delay -= ctx->sh_audio->stream_delay;
2247 ctx->delay =- audio_delay;
2248 ao_reset(ctx->ao);
2249 resync_audio_stream(ctx->sh_audio);
2252 audio_delay = 0.0f;
2253 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2254 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2255 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2256 if (dvdsub_lang_id != opts->sub_id) {
2257 opts->sub_id = dvdsub_lang_id;
2258 select_subtitle(ctx);
2262 /// clear all EOF related flags
2263 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2266 /// Restore last decoded DVDNAV (still frame)
2267 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2268 int *in_size,
2269 unsigned char **start,
2270 mp_image_t *decoded_frame)
2272 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2273 return decoded_frame;
2275 /// a change occurred in dvdnav stream
2276 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2277 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2278 mp_dvdnav_context_free(mpctx);
2279 mp_dvdnav_reset_stream(mpctx);
2280 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2281 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2284 if (*in_size < 0) {
2285 float len;
2287 /// Display still frame, if any
2288 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2289 decoded_frame = mpctx->nav_smpi;
2291 /// increment video frame : continue playing after still frame
2292 len = get_time_length(mpctx);
2293 if (mpctx->sh_video->pts >= len &&
2294 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2295 mp_dvdnav_skip_still(mpctx->stream);
2296 mp_dvdnav_skip_wait(mpctx->stream);
2298 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2300 if (mpctx->nav_buffer) {
2301 *start = mpctx->nav_start;
2302 *in_size = mpctx->nav_in_size;
2303 if (mpctx->nav_start)
2304 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2308 return decoded_frame;
2311 /// Save last decoded DVDNAV (still frame)
2312 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2313 unsigned char *start,
2314 mp_image_t *decoded_frame)
2316 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2317 return;
2319 free(mpctx->nav_buffer);
2320 mpctx->nav_buffer = NULL;
2321 mpctx->nav_start = NULL;
2322 mpctx->nav_in_size = -1;
2324 if (in_size > 0)
2325 mpctx->nav_buffer = malloc(in_size);
2326 if (mpctx->nav_buffer) {
2327 mpctx->nav_start = start;
2328 memcpy(mpctx->nav_buffer,start,in_size);
2331 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2332 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2334 #endif /* CONFIG_DVDNAV */
2336 /* Modify video timing to match the audio timeline. There are two main
2337 * reasons this is needed. First, video and audio can start from different
2338 * positions at beginning of file or after a seek (MPlayer starts both
2339 * immediately even if they have different pts). Second, the file can have
2340 * audio timestamps that are inconsistent with the duration of the audio
2341 * packets, for example two consecutive timestamp values differing by
2342 * one second but only a packet with enough samples for half a second
2343 * of playback between them.
2345 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2347 current_module = "av_sync";
2349 if (!mpctx->sh_audio || mpctx->syncing_audio)
2350 return;
2352 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2353 double v_pts = mpctx->sh_video->pts;
2354 double av_delay = a_pts - v_pts;
2355 // Try to sync vo_flip() so it will *finish* at given time
2356 av_delay += mpctx->last_vo_flip_duration;
2357 av_delay -= audio_delay; // This much pts difference is desired
2359 double change = av_delay * 0.1;
2360 double max_change = default_max_pts_correction >= 0 ?
2361 default_max_pts_correction : frame_time * 0.1;
2362 if (change < -max_change)
2363 change = -max_change;
2364 else if (change > max_change)
2365 change = max_change;
2366 mpctx->delay += change;
2367 mpctx->total_avsync_change += change;
2370 #define ASYNC_PLAY_DONE -3
2371 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2373 struct ao *ao = mpctx->ao;
2374 struct MPOpts *opts = &mpctx->opts;
2375 sh_audio_t * const sh_audio = mpctx->sh_audio;
2376 int res;
2378 // Timing info may not be set without
2379 res = decode_audio(sh_audio, &ao->buffer, 1);
2380 if (res < 0)
2381 return res;
2383 int bytes;
2384 bool did_retry = false;
2385 while (1) {
2386 double written_pts = written_audio_pts(mpctx);
2387 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2388 - audio_delay;
2389 bytes = ptsdiff * ao->bps / mpctx->opts.playback_speed;
2390 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2392 // ogg demuxers give packets without timing
2393 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2394 if (!did_retry) {
2395 // Try to read more data to see packets that have pts
2396 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2397 if (res < 0)
2398 return res;
2399 did_retry = true;
2400 continue;
2402 bytes = 0;
2405 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2406 bytes = 0;
2408 if (bytes > 0)
2409 break;
2411 mpctx->syncing_audio = false;
2412 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2413 int res = decode_audio(sh_audio, &ao->buffer, a);
2414 bytes += ao->buffer.len;
2415 if (bytes >= 0) {
2416 memmove(ao->buffer.start,
2417 ao->buffer.start + ao->buffer.len - bytes, bytes);
2418 ao->buffer.len = bytes;
2419 if (res < 0)
2420 return res;
2421 return decode_audio(sh_audio, &ao->buffer, playsize);
2423 ao->buffer.len = 0;
2424 if (res < 0)
2425 return res;
2427 int fillbyte = 0;
2428 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2429 fillbyte = 0x80;
2430 if (bytes >= playsize) {
2431 /* This case could fall back to the one below with
2432 * bytes = playsize, but then silence would keep accumulating
2433 * in a_out_buffer if the AO accepts less data than it asks for
2434 * in playsize. */
2435 char *p = malloc(playsize);
2436 memset(p, fillbyte, playsize);
2437 playsize = ao_play(ao, p, playsize, 0);
2438 free(p);
2439 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2440 return ASYNC_PLAY_DONE;
2442 mpctx->syncing_audio = false;
2443 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2444 return decode_audio(sh_audio, &ao->buffer, playsize);
2447 static int fill_audio_out_buffers(struct MPContext *mpctx)
2449 struct MPOpts *opts = &mpctx->opts;
2450 struct ao *ao = mpctx->ao;
2451 unsigned int t;
2452 double tt;
2453 int playsize;
2454 int playflags=0;
2455 bool audio_eof = false;
2456 bool partial_fill = false;
2457 sh_audio_t * const sh_audio = mpctx->sh_audio;
2458 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2459 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2461 current_module="play_audio";
2463 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2464 return 0;
2466 // all the current uses of ao->pts seem to be in aos that handle
2467 // sync completely wrong; there should be no need to use ao->pts
2468 // in get_space()
2469 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2470 playsize = ao_get_space(ao);
2472 // Fill buffer if needed:
2473 current_module="decode_audio";
2474 t = GetTimer();
2476 if (!opts->initial_audio_sync || !modifiable_audio_format)
2477 mpctx->syncing_audio = false;
2479 int res;
2480 if (mpctx->syncing_audio && mpctx->sh_video)
2481 res = audio_start_sync(mpctx, playsize);
2482 else
2483 res = decode_audio(sh_audio, &ao->buffer, playsize);
2484 if (res < 0) { // EOF, error or format change
2485 if (res == -2) {
2486 /* The format change isn't handled too gracefully. A more precise
2487 * implementation would require draining buffered old-format audio
2488 * while displaying video, then doing the output format switch.
2490 uninit_player(mpctx, INITIALIZED_AO);
2491 reinit_audio_chain(mpctx);
2492 return -1;
2493 } else if (res == ASYNC_PLAY_DONE)
2494 return 0;
2495 else if (mpctx->d_audio->eof)
2496 audio_eof = true;
2498 t = GetTimer() - t;
2499 tt = t*0.000001f; audio_time_usage+=tt;
2500 if (mpctx->timeline && modifiable_audio_format) {
2501 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2502 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2503 * ao->bps / opts->playback_speed;
2504 if (playsize > bytes) {
2505 playsize = FFMAX(bytes, 0);
2506 playflags |= AOPLAY_FINAL_CHUNK;
2507 audio_eof = true;
2508 partial_fill = true;
2512 assert(ao->buffer.len % unitsize == 0);
2513 if (playsize > ao->buffer.len) {
2514 partial_fill = true;
2515 playsize = ao->buffer.len;
2516 if (audio_eof)
2517 playflags |= AOPLAY_FINAL_CHUNK;
2519 playsize -= playsize % unitsize;
2520 if (!playsize)
2521 return partial_fill && audio_eof ? -2 : -partial_fill;
2523 // play audio:
2524 current_module="play_audio";
2526 // Is this pts value actually useful for the aos that access it?
2527 // They're obviously badly broken in the way they handle av sync;
2528 // would not having access to this make them more broken?
2529 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2530 int played = ao_play(ao, ao->buffer.start, playsize, playflags);
2531 assert(played % unitsize == 0);
2532 ao->buffer_playable_size = playsize - played;
2534 if (played > 0) {
2535 ao->buffer.len -= played;
2536 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2537 mpctx->delay += opts->playback_speed * played / ao->bps;
2538 } else if (audio_eof && ao_get_delay(ao) < .04) {
2539 // Sanity check to avoid hanging in case current ao doesn't output
2540 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2541 return -2;
2544 return -partial_fill;
2547 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2548 bool sync_to_audio, float *aq_sleep_time)
2550 struct MPOpts *opts = &mpctx->opts;
2551 double audio_limit = 2;
2552 current_module="calc_sleep_time";
2554 if (mpctx->restart_playback)
2555 return 0;
2557 *time_frame -= get_relative_time(mpctx); // reset timer
2559 if (sync_to_audio) {
2560 float delay = ao_get_delay(mpctx->ao);
2561 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2563 if (opts->autosync) {
2565 * Adjust this raw delay value by calculating the expected
2566 * delay for this frame and generating a new value which is
2567 * weighted between the two. The higher autosync is, the
2568 * closer to the delay value gets to that which "-nosound"
2569 * would have used, and the longer it will take for A/V
2570 * sync to settle at the right value (but it eventually will.)
2571 * This settling time is very short for values below 100.
2573 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2574 float difference = delay - predicted;
2575 delay = predicted + difference / (float)opts->autosync;
2578 *time_frame = delay - mpctx->delay / opts->playback_speed;
2580 // delay = amount of audio buffered in soundcard/driver
2581 delay = FFMIN(delay, 0.5);
2582 delay = FFMAX(delay, 0.1);
2583 audio_limit = delay;
2584 } else {
2585 // If we're lagging more than 200 ms behind the right playback rate,
2586 // don't try to "catch up".
2587 // If benchmark is set always output frames as fast as possible
2588 // without sleeping.
2589 if (*time_frame < -0.2 || opts->benchmark)
2590 *time_frame = 0;
2593 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2595 if (t <= 0.05)
2596 return 0;
2598 t -= 0.05;
2599 if (t > audio_limit * 0.6)
2600 t = audio_limit * 0.5;
2601 *aq_sleep_time += t;
2602 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2603 return 1;
2606 int reinit_video_chain(struct MPContext *mpctx)
2608 struct MPOpts *opts = &mpctx->opts;
2609 sh_video_t * const sh_video = mpctx->sh_video;
2610 if (!sh_video)
2611 return 0;
2612 double ar=-1.0;
2613 //================== Init VIDEO (codec & libvo) ==========================
2614 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2615 current_module="preinit_libvo";
2617 //shouldn't we set dvideo->id=-2 when we fail?
2618 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2619 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2620 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing 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, &ar) != STREAM_UNSUPPORTED)
2627 mpctx->sh_video->stream_aspect = ar;
2628 current_module="init_video_filters";
2630 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2631 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2633 #ifdef CONFIG_MENU
2634 if(use_menu) {
2635 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2636 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2637 if(!vf_menu) {
2638 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2639 use_menu = 0;
2642 if(vf_menu)
2643 sh_video->vfilter = vf_menu;
2644 #endif
2646 #ifdef CONFIG_ASS
2647 if(opts->ass_enabled) {
2648 int i;
2649 int insert = 1;
2650 if (opts->vf_settings)
2651 for (i = 0; opts->vf_settings[i].name; ++i)
2652 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2653 insert = 0;
2654 break;
2656 if (insert) {
2657 extern vf_info_t vf_info_ass;
2658 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2659 char* vf_arg[] = {"auto", "1", NULL};
2660 int retcode = 0;
2661 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2662 sh_video->vfilter,
2663 "ass", vf_arg,
2664 &retcode);
2665 if (vf_ass)
2666 sh_video->vfilter = vf_ass;
2667 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2668 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2669 else
2670 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2673 #endif
2675 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2677 #ifdef CONFIG_ASS
2678 if (opts->ass_enabled)
2679 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2680 #endif
2682 current_module="init_video_codec";
2684 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2685 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2686 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2688 if(!sh_video->initialized){
2689 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2690 goto err_out;
2693 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2695 if (sh_video->codec)
2696 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2698 sh_video->last_pts = MP_NOPTS_VALUE;
2699 sh_video->num_buffered_pts = 0;
2700 sh_video->next_frame_time = 0;
2702 if (opts->auto_quality > 0) {
2703 // Auto quality option enabled
2704 output_quality=get_video_quality_max(sh_video);
2705 if (opts->auto_quality > output_quality)
2706 opts->auto_quality = output_quality;
2707 else
2708 output_quality = opts->auto_quality;
2709 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2710 set_video_quality(sh_video,output_quality);
2713 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2715 current_module="init_vo";
2717 return 1;
2719 err_out:
2720 mpctx->sh_video = mpctx->d_video->sh = NULL;
2721 return 0;
2724 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2726 struct sh_video *sh_video = mpctx->sh_video;
2727 double frame_time = 0;
2728 struct vo *video_out = mpctx->video_out;
2729 while (1) {
2730 current_module = "filter_video";
2731 // In nocorrect-pts mode there is no way to properly time these frames
2732 if (vo_get_buffered_frame(video_out, 0) >= 0)
2733 break;
2734 if (vf_output_queued_frame(sh_video->vfilter))
2735 break;
2736 unsigned char *packet = NULL;
2737 frame_time = sh_video->next_frame_time;
2738 if (mpctx->restart_playback)
2739 frame_time = 0;
2740 int 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, packet, in_size, framedrop_type,
2772 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 (!mpctx->hrseek_active
2831 && vo_get_buffered_frame(video_out, false) >= 0)
2832 break;
2833 // XXX Time used in this call is not counted in any performance
2834 // timer now
2835 if (vf_output_queued_frame(sh_video->vfilter))
2836 break;
2837 unsigned char *packet = NULL;
2838 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2839 if (pts != MP_NOPTS_VALUE)
2840 pts += mpctx->video_offset;
2841 bool hit_eof = false;
2842 if (in_size < 0) {
2843 // try to extract last frames in case of decoder lag
2844 in_size = 0;
2845 pts = MP_NOPTS_VALUE;
2846 hit_eof = true;
2848 if (in_size > max_framesize)
2849 max_framesize = in_size;
2850 current_module = "decode video";
2851 if (pts >= mpctx->hrseek_pts - .005)
2852 mpctx->hrseek_framedrop = false;
2853 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2854 check_framedrop(mpctx, sh_video->frametime);
2855 void *decoded_frame = decode_video(sh_video, packet, in_size,
2856 framedrop_type, pts);
2857 if (decoded_frame) {
2858 determine_frame_pts(mpctx);
2859 current_module = "filter video";
2860 filter_video(sh_video, decoded_frame, sh_video->pts);
2861 } else if (hit_eof) {
2862 if (vo_get_buffered_frame(video_out, true) < 0)
2863 return -1;
2865 break;
2868 if (!video_out->frame_loaded)
2869 return 0;
2871 pts = video_out->next_pts;
2872 if (pts == MP_NOPTS_VALUE) {
2873 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2874 // Try to use decoder pts from before filters
2875 pts = sh_video->pts;
2876 if (pts == MP_NOPTS_VALUE)
2877 pts = sh_video->last_pts;
2879 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2880 vo_skip_frame(video_out);
2881 return 0;
2883 mpctx->hrseek_active = false;
2884 sh_video->pts = pts;
2885 if (sh_video->last_pts == MP_NOPTS_VALUE)
2886 sh_video->last_pts = sh_video->pts;
2887 else if (sh_video->last_pts > sh_video->pts) {
2888 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2889 sh_video->pts, sh_video->last_pts);
2890 /* If the difference in pts is small treat it as jitter around the
2891 * right value (possibly caused by incorrect timestamp ordering) and
2892 * just show this frame immediately after the last one.
2893 * Treat bigger differences as timestamp resets and start counting
2894 * timing of later frames from the position of this one. */
2895 if (sh_video->last_pts - sh_video->pts > 0.5)
2896 sh_video->last_pts = sh_video->pts;
2897 else
2898 sh_video->pts = sh_video->last_pts;
2900 double frame_time = sh_video->pts - sh_video->last_pts;
2901 sh_video->last_pts = sh_video->pts;
2902 sh_video->timer += frame_time;
2903 if (mpctx->sh_audio)
2904 mpctx->delay -= frame_time;
2905 return frame_time;
2908 void pause_player(struct MPContext *mpctx)
2910 if (mpctx->paused)
2911 return;
2912 mpctx->paused = 1;
2913 mpctx->step_frames = 0;
2914 mpctx->time_frame -= get_relative_time(mpctx);
2916 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2917 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2919 if (mpctx->ao && mpctx->sh_audio)
2920 ao_pause(mpctx->ao); // pause audio, keep data if possible
2923 void unpause_player(struct MPContext *mpctx)
2925 if (!mpctx->paused)
2926 return;
2927 mpctx->paused = 0;
2929 if (mpctx->ao && mpctx->sh_audio)
2930 ao_resume(mpctx->ao);
2931 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2932 && !mpctx->step_frames)
2933 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2934 (void)get_relative_time(mpctx); // ignore time that passed during pause
2937 void add_step_frame(struct MPContext *mpctx)
2939 mpctx->step_frames++;
2940 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2941 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2942 unpause_player(mpctx);
2945 static void pause_loop(struct MPContext *mpctx)
2947 struct MPOpts *opts = &mpctx->opts;
2948 mp_cmd_t* cmd;
2949 #ifdef CONFIG_STREAM_CACHE
2950 int old_cache_fill = stream_cache_size > 0 ?
2951 cache_fill_status(mpctx->stream) : 0;
2952 #endif
2953 if (!opts->quiet) {
2954 if (opts->term_osd && !mpctx->sh_video) {
2955 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
2956 update_osd_msg(mpctx);
2957 } else
2958 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
2959 mp_gtext(" ===== PAUSE ====="));
2960 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2963 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2964 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2965 if (cmd) {
2966 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2967 run_command(mpctx, cmd);
2968 mp_cmd_free(cmd);
2969 continue;
2971 if (mpctx->sh_video && mpctx->video_out)
2972 vo_check_events(mpctx->video_out);
2973 #ifdef CONFIG_MENU
2974 if (vf_menu)
2975 vf_menu_pause_update(vf_menu);
2976 #endif
2977 usec_sleep(20000);
2978 update_osd_msg(mpctx);
2979 int hack = vo_osd_changed(0);
2980 vo_osd_changed(hack);
2981 if (hack)
2982 break;
2983 #ifdef CONFIG_STREAM_CACHE
2984 if (!opts->quiet && stream_cache_size > 0) {
2985 int new_cache_fill = cache_fill_status(mpctx->stream);
2986 if (new_cache_fill != old_cache_fill) {
2987 if (opts->term_osd && !mpctx->sh_video) {
2988 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
2989 mp_gtext(" ===== PAUSE ====="),
2990 new_cache_fill);
2991 update_osd_msg(mpctx);
2992 } else
2993 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
2994 mp_gtext(" ===== PAUSE ====="),
2995 new_cache_fill);
2996 old_cache_fill = new_cache_fill;
2999 #endif
3004 // Find the right mute status and record position for new file position
3005 static void edl_seek_reset(MPContext *mpctx)
3007 mpctx->edl_muted = 0;
3008 next_edl_record = edl_records;
3010 while (next_edl_record) {
3011 if (next_edl_record->start_sec >= get_current_time(mpctx))
3012 break;
3014 if (next_edl_record->action == EDL_MUTE)
3015 mpctx->edl_muted = !mpctx->edl_muted;
3016 next_edl_record = next_edl_record->next;
3018 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3019 mixer_mute(&mpctx->mixer);
3023 // Execute EDL command for the current position if one exists
3024 static void edl_update(MPContext *mpctx)
3026 if (!next_edl_record)
3027 return;
3029 if (!mpctx->sh_video) {
3030 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
3031 free_edl(edl_records);
3032 next_edl_record = NULL;
3033 edl_records = NULL;
3034 return;
3037 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3038 if (next_edl_record->action == EDL_SKIP) {
3039 mpctx->osd_function = OSD_FFW;
3040 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3041 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3042 "[%f], length [%f]\n", next_edl_record->start_sec,
3043 next_edl_record->stop_sec, next_edl_record->length_sec);
3045 else if (next_edl_record->action == EDL_MUTE) {
3046 mpctx->edl_muted = !mpctx->edl_muted;
3047 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3048 mixer_mute(&mpctx->mixer);
3049 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3050 next_edl_record->start_sec );
3052 next_edl_record = next_edl_record->next;
3056 static void reinit_decoders(struct MPContext *mpctx)
3058 reinit_video_chain(mpctx);
3059 reinit_audio_chain(mpctx);
3060 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3063 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3065 if (mpctx->sh_video) {
3066 current_module = "seek_video_reset";
3067 resync_video_stream(mpctx->sh_video);
3068 mpctx->sh_video->timer = 0;
3069 vo_seek_reset(mpctx->video_out);
3070 mpctx->sh_video->timer = 0;
3071 mpctx->sh_video->num_buffered_pts = 0;
3072 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3073 mpctx->delay = 0;
3074 mpctx->time_frame = 0;
3075 mpctx->restart_playback = true;
3076 // Not all demuxers set d_video->pts during seek, so this value
3077 // (which is used by at least vobsub and edl code below) may
3078 // be completely wrong (probably 0).
3079 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3080 mpctx->video_pts = mpctx->sh_video->pts;
3081 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3082 true);
3083 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3086 if (mpctx->sh_audio) {
3087 current_module = "seek_audio_reset";
3088 resync_audio_stream(mpctx->sh_audio);
3089 if (reset_ao)
3090 ao_reset(mpctx->ao);
3091 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3092 mpctx->sh_audio->a_buffer_len = 0;
3093 if (!mpctx->sh_video)
3094 update_subtitles(mpctx, mpctx->sh_audio->pts,
3095 mpctx->video_offset, true);
3098 if (vo_vobsub && mpctx->sh_video) {
3099 current_module = "seek_vobsub_reset";
3100 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3103 edl_seek_reset(mpctx);
3105 mpctx->hrseek_active = false;
3106 mpctx->hrseek_framedrop = false;
3107 mpctx->total_avsync_change = 0;
3108 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3109 drop_frame_cnt = 0;
3111 current_module = NULL;
3114 static bool timeline_set_part(struct MPContext *mpctx, int i)
3116 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3117 struct timeline_part *n = mpctx->timeline + i;
3118 mpctx->timeline_part = i;
3119 mpctx->video_offset = n->start - n->source_start;
3120 if (n->source == p->source)
3121 return false;
3122 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3123 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3124 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3125 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3126 mpctx->stop_play = orig_stop_play;
3127 mpctx->demuxer = n->source->demuxer;
3128 mpctx->d_video = mpctx->demuxer->video;
3129 mpctx->d_audio = mpctx->demuxer->audio;
3130 mpctx->d_sub = mpctx->demuxer->sub;
3131 mpctx->sh_video = mpctx->d_video->sh;
3132 mpctx->sh_audio = mpctx->d_audio->sh;
3133 return true;
3136 // Given pts, switch playback to the corresponding part.
3137 // Return offset within that part.
3138 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3139 bool *need_reset)
3141 if (pts < 0)
3142 pts = 0;
3143 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3144 struct timeline_part *p = mpctx->timeline + i;
3145 if (pts < (p+1)->start) {
3146 *need_reset = timeline_set_part(mpctx, i);
3147 return pts - p->start + p->source_start;
3150 return -1;
3154 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3155 static int seek(MPContext *mpctx, struct seek_params seek,
3156 bool timeline_fallthrough)
3158 struct MPOpts *opts = &mpctx->opts;
3160 current_module = "seek";
3161 if (mpctx->stop_play == AT_END_OF_FILE)
3162 mpctx->stop_play = KEEP_PLAYING;
3163 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3164 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3165 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3166 || opts->hr_seek > 0 || seek.exact > 0;
3167 if (seek.type == MPSEEK_FACTOR
3168 || seek.type == MPSEEK_ABSOLUTE
3169 && seek.amount < mpctx->last_chapter_pts
3170 || seek.amount < 0)
3171 mpctx->last_chapter_seek = -1;
3172 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3173 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3174 seek.type = MPSEEK_ABSOLUTE;
3176 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3177 && seek.type == MPSEEK_RELATIVE) {
3178 seek.type = MPSEEK_ABSOLUTE;
3179 seek.direction = seek.amount > 0 ? 1 : -1;
3180 seek.amount += get_current_time(mpctx);
3183 /* At least the liba52 decoder wants to read from the input stream
3184 * during initialization, so reinit must be done after the demux_seek()
3185 * call that clears possible stream EOF. */
3186 bool need_reset = false;
3187 double demuxer_amount = seek.amount;
3188 if (mpctx->timeline) {
3189 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3190 &need_reset);
3191 if (demuxer_amount == -1) {
3192 mpctx->stop_play = AT_END_OF_FILE;
3193 // Clear audio from current position
3194 if (mpctx->sh_audio) {
3195 ao_reset(mpctx->ao);
3196 mpctx->sh_audio->a_buffer_len = 0;
3198 return -1;
3201 int demuxer_style = 0;
3202 switch (seek.type) {
3203 case MPSEEK_FACTOR:
3204 demuxer_style |= SEEK_FACTOR; // fallthrough
3205 case MPSEEK_ABSOLUTE:
3206 demuxer_style |= SEEK_ABSOLUTE;
3208 if (hr_seek || seek.direction < 0)
3209 demuxer_style |= SEEK_BACKWARD;
3210 else if (seek.direction > 0)
3211 demuxer_style |= SEEK_FORWARD;
3213 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3214 demuxer_style);
3215 if (need_reset)
3216 reinit_decoders(mpctx);
3217 if (seekresult == 0)
3218 return -1;
3220 seek_reset(mpctx, !timeline_fallthrough);
3222 /* Use the target time as "current position" for further relative
3223 * seeks etc until a new video frame has been decoded */
3224 if (seek.type == MPSEEK_ABSOLUTE)
3225 mpctx->video_pts = seek.amount;
3227 if (hr_seek) {
3228 mpctx->hrseek_active = true;
3229 mpctx->hrseek_framedrop = true;
3230 mpctx->hrseek_pts = seek.amount;
3233 mpctx->start_timestamp = GetTimerMS();
3235 return 0;
3238 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3239 int exact)
3241 struct seek_params *seek = &mpctx->seek;
3242 switch (type) {
3243 case MPSEEK_RELATIVE:
3244 if (seek->type == MPSEEK_FACTOR)
3245 return; // Well... not common enough to bother doing better
3246 seek->amount += amount;
3247 seek->exact = FFMAX(seek->exact, exact);
3248 if (seek->type == MPSEEK_NONE)
3249 seek->exact = exact;
3250 if (seek->type == MPSEEK_ABSOLUTE)
3251 return;
3252 if (seek->amount == 0) {
3253 *seek = (struct seek_params){0};
3254 return;
3256 seek->type = MPSEEK_RELATIVE;
3257 return;
3258 case MPSEEK_ABSOLUTE:
3259 case MPSEEK_FACTOR:
3260 *seek = (struct seek_params) {
3261 .type = type,
3262 .amount = amount,
3263 .exact = exact,
3265 return;
3266 case MPSEEK_NONE:
3267 *seek = (struct seek_params){0};
3268 return;
3270 abort();
3274 double get_time_length(struct MPContext *mpctx)
3276 if (mpctx->timeline)
3277 return mpctx->timeline[mpctx->num_timeline_parts].start;
3279 struct demuxer *demuxer = mpctx->demuxer;
3280 double get_time_ans;
3281 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3282 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3283 (void *) &get_time_ans) > 0)
3284 return get_time_ans;
3286 struct sh_video *sh_video = mpctx->d_video->sh;
3287 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3288 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3289 return (double) (demuxer->movi_end - demuxer->movi_start) /
3290 (sh_video->i_bps + sh_audio->i_bps);
3291 if (sh_video && sh_video->i_bps)
3292 return (double) (demuxer->movi_end - demuxer->movi_start) /
3293 sh_video->i_bps;
3294 if (sh_audio && sh_audio->i_bps)
3295 return (double) (demuxer->movi_end - demuxer->movi_start) /
3296 sh_audio->i_bps;
3297 return 0;
3300 /* If there are timestamps from stream level then use those (for example
3301 * DVDs can have consistent times there while the MPEG-level timestamps
3302 * reset). */
3303 double get_current_time(struct MPContext *mpctx)
3305 struct demuxer *demuxer = mpctx->demuxer;
3306 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3307 return demuxer->stream_pts;
3308 struct sh_video *sh_video = demuxer->video->sh;
3309 if (sh_video)
3310 return mpctx->video_pts;
3311 return playing_audio_pts(mpctx);
3314 int get_percent_pos(struct MPContext *mpctx)
3316 struct demuxer *demuxer = mpctx->demuxer;
3317 int ans = 0;
3318 if (mpctx->timeline)
3319 ans = get_current_time(mpctx) * 100 /
3320 mpctx->timeline[mpctx->num_timeline_parts].start;
3321 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3323 else {
3324 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3325 off_t pos = demuxer->filepos > 0 ?
3326 demuxer->filepos : stream_tell(demuxer->stream);
3327 if (len > 0)
3328 ans = (pos - demuxer->movi_start) / len;
3329 else
3330 ans = 0;
3332 if (ans < 0)
3333 ans = 0;
3334 if (ans > 100)
3335 ans = 100;
3336 return ans;
3339 // -2 is no chapters, -1 is before first chapter
3340 int get_current_chapter(struct MPContext *mpctx)
3342 double current_pts = get_current_time(mpctx);
3343 if (!mpctx->chapters)
3344 return FFMAX(mpctx->last_chapter_seek,
3345 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3347 int i;
3348 for (i = 1; i < mpctx->num_chapters; i++)
3349 if (current_pts < mpctx->chapters[i].start)
3350 break;
3351 return FFMAX(mpctx->last_chapter_seek, i - 1);
3354 // currently returns a string allocated with malloc, not talloc
3355 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3357 if (!mpctx->chapters || !mpctx->sh_video)
3358 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3359 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3362 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3363 char **chapter_name)
3365 mpctx->last_chapter_seek = -1;
3366 if (!mpctx->chapters || !mpctx->sh_video) {
3367 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3368 chapter_name);
3369 if (res >= 0) {
3370 if (*seek_pts == -1)
3371 seek_reset(mpctx, true);
3372 else {
3373 mpctx->last_chapter_seek = res;
3374 mpctx->last_chapter_pts = *seek_pts;
3377 return res;
3380 if (chapter >= mpctx->num_chapters)
3381 return -1;
3382 if (chapter < 0)
3383 chapter = 0;
3384 *seek_pts = mpctx->chapters[chapter].start;
3385 mpctx->last_chapter_seek = chapter;
3386 mpctx->last_chapter_pts = *seek_pts;
3387 if (chapter_name)
3388 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3389 return chapter;
3393 static void run_playloop(struct MPContext *mpctx)
3395 struct MPOpts *opts = &mpctx->opts;
3396 float aq_sleep_time = 0;
3397 bool full_audio_buffers = false;
3399 if (opts->chapterrange[1] > 0) {
3400 int cur_chapter = get_current_chapter(mpctx);
3401 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3402 mpctx->stop_play = PT_NEXT_ENTRY;
3405 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3406 mpctx->sh_audio = mpctx->d_audio->sh;
3407 mpctx->sh_audio->ds = mpctx->d_audio;
3408 reinit_audio_chain(mpctx);
3411 /*========================== PLAY AUDIO ============================*/
3413 if (mpctx->sh_audio && !mpctx->paused
3414 && (!mpctx->restart_playback || !mpctx->sh_video)) {
3415 int status = fill_audio_out_buffers(mpctx);
3416 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3417 if (status == -2)
3418 // at eof, all audio at least written to ao
3419 if (!mpctx->sh_video)
3420 mpctx->stop_play = AT_END_OF_FILE;
3424 if (!mpctx->sh_video) {
3425 mpctx->restart_playback = false;
3426 if (mpctx->step_frames) {
3427 mpctx->step_frames = 0;
3428 pause_player(mpctx);
3430 // handle audio-only case:
3431 double a_pos = 0, a_buf = 0;
3432 // sh_audio can be NULL due to video stream switching
3433 // TODO: handle this better
3434 if (mpctx->sh_audio) {
3435 a_buf = ao_get_delay(mpctx->ao);
3436 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3437 a_buf;
3440 print_status(mpctx, a_pos, false);
3442 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3443 update_osd_msg(mpctx);
3444 if (end_at.type == END_AT_TIME && end_at.pos < a_pos) {
3445 mpctx->stop_play = AT_END_OF_FILE;
3446 } else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3447 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3448 && mpctx->sh_audio) {
3449 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3450 if (!opts->gapless_audio && p->source != (p+1)->source
3451 && a_buf > 0.05) {
3452 mpctx->stop_play = KEEP_PLAYING;
3453 mp_input_get_cmd(mpctx->input, (a_buf-.05) * 1000, true);
3454 } else {
3455 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3456 .amount = (p+1)->start },
3457 true);
3459 } else if (!mpctx->stop_play) {
3460 int sleep_time = 100;
3461 if (mpctx->sh_audio) {
3462 if (mpctx->ao->untimed)
3463 sleep_time = 0;
3464 else if (full_audio_buffers)
3465 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3466 else
3467 sleep_time = 20;
3468 sleep_time = FFMIN(sleep_time, 100);
3470 mp_input_get_cmd(mpctx->input, sleep_time, true);
3472 } else {
3474 /*========================== PLAY VIDEO ============================*/
3476 vo_pts = mpctx->sh_video->timer * 90000.0;
3477 vo_fps = mpctx->sh_video->fps;
3479 bool blit_frame = mpctx->video_out->frame_loaded;
3480 if (!blit_frame || mpctx->hrseek_active) {
3481 double frame_time = update_video(mpctx);
3482 blit_frame = mpctx->video_out->frame_loaded;
3483 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3484 if (mpctx->sh_video->vf_initialized < 0) {
3485 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3486 "\nFATAL: Could not initialize video filters (-vf) "
3487 "or video output (-vo).\n");
3488 mpctx->stop_play = PT_NEXT_ENTRY;
3489 return;
3491 if (frame_time < 0)
3492 mpctx->stop_play = AT_END_OF_FILE;
3493 else if (!mpctx->restart_playback) {
3494 mpctx->time_frame += frame_time / opts->playback_speed;
3495 adjust_sync(mpctx, frame_time);
3498 if (mpctx->timeline) {
3499 struct timeline_part *next =
3500 mpctx->timeline + mpctx->timeline_part + 1;
3501 if (mpctx->sh_video->pts >= next->start
3502 || mpctx->stop_play == AT_END_OF_FILE
3503 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3504 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3505 .amount = next->start },
3506 true);
3507 return;
3511 // ==========================================================================
3513 current_module = "vo_check_events";
3514 vo_check_events(mpctx->video_out);
3516 #ifdef CONFIG_X11
3517 if (stop_xscreensaver) {
3518 current_module = "stop_xscreensaver";
3519 xscreensaver_heartbeat(mpctx->x11_state);
3521 #endif
3522 if (heartbeat_cmd) {
3523 static unsigned last_heartbeat;
3524 unsigned now = GetTimerMS();
3525 if (now - last_heartbeat > 30000) {
3526 last_heartbeat = now;
3527 system(heartbeat_cmd);
3531 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3532 &mpctx->time_frame,
3533 full_audio_buffers,
3534 &aq_sleep_time);
3536 //====================== FLIP PAGE (VIDEO BLT): =========================
3538 current_module = "flip_page";
3539 if (!frame_time_remaining && blit_frame) {
3540 struct sh_video *sh_video = mpctx->sh_video;
3541 mpctx->video_pts = sh_video->pts;
3542 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3543 update_teletext(sh_video, mpctx->demuxer, 0);
3544 update_osd_msg(mpctx);
3545 struct vf_instance *vf = sh_video->vfilter;
3546 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3547 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3548 vo_osd_changed(0);
3550 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3551 aq_sleep_time += mpctx->time_frame;
3552 // flag 256 means: libvo driver does its timing (dvb card)
3553 if (mpctx->time_frame > 0.001
3554 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3555 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3556 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3558 unsigned int t2 = GetTimer();
3559 /* Playing with playback speed it's possible to get pathological
3560 * cases with mpctx->time_frame negative enough to cause an
3561 * overflow in pts_us calculation, thus the FFMAX. */
3562 double time_frame = FFMAX(mpctx->time_frame, -1);
3563 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3564 int duration = -1;
3565 double pts2 = mpctx->video_out->next_pts2;
3566 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3567 && !mpctx->restart_playback) {
3568 // expected A/V sync correction is ignored
3569 double diff = (pts2 - mpctx->video_pts);
3570 diff /= opts->playback_speed;
3571 if (mpctx->time_frame < 0)
3572 diff += mpctx->time_frame;
3573 if (diff < 0)
3574 diff = 0;
3575 if (diff > 10)
3576 diff = 10;
3577 duration = diff * 1e6;
3579 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3581 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3582 vout_time_usage += mpctx->last_vo_flip_duration;
3583 if (mpctx->video_out->driver->flip_page_timed) {
3584 // No need to adjust sync based on flip speed
3585 mpctx->last_vo_flip_duration = 0;
3586 // For print_status - VO call finishing early is OK for sync
3587 mpctx->time_frame -= get_relative_time(mpctx);
3589 if (mpctx->restart_playback) {
3590 mpctx->syncing_audio = true;
3591 if (mpctx->sh_audio && !mpctx->paused)
3592 fill_audio_out_buffers(mpctx);
3593 mpctx->restart_playback = false;
3594 mpctx->time_frame = 0;
3595 get_relative_time(mpctx);
3597 print_status(mpctx, MP_NOPTS_VALUE, true);
3598 } else
3599 print_status(mpctx, MP_NOPTS_VALUE, false);
3601 //============================ Auto QUALITY ============================
3603 /*Output quality adjustments:*/
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
3609 if (output_quality>1 && aq_sleep_time<0)
3610 --output_quality;
3611 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3612 output_quality = 0;
3613 set_video_quality(mpctx->sh_video, output_quality);
3616 if (!frame_time_remaining && blit_frame) {
3617 if (play_n_frames >= 0) {
3618 --play_n_frames;
3619 if (play_n_frames <= 0)
3620 mpctx->stop_play = PT_NEXT_ENTRY;
3622 if (mpctx->step_frames > 0) {
3623 mpctx->step_frames--;
3624 if (mpctx->step_frames == 0)
3625 pause_player(mpctx);
3629 // FIXME: add size based support for -endpos
3630 if (end_at.type == END_AT_TIME &&
3631 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3632 mpctx->stop_play = PT_NEXT_ENTRY;
3634 } // end if(mpctx->sh_video)
3636 #ifdef CONFIG_DVDNAV
3637 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3638 nav_highlight_t hl;
3639 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3640 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3641 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3642 vo_osd_changed(OSDTYPE_DVDNAV);
3643 } else {
3644 osd_set_nav_box(0, 0, 0, 0);
3645 vo_osd_changed(OSDTYPE_DVDNAV);
3646 vo_osd_changed(OSDTYPE_SPU);
3649 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3650 double ar = -1.0;
3651 if (mpctx->sh_video &&
3652 stream_control(mpctx->demuxer->stream,
3653 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3654 != STREAM_UNSUPPORTED)
3655 mpctx->sh_video->stream_aspect = ar;
3658 #endif
3660 //================= Keyboard events, SEEKing ====================
3662 current_module = "key_events";
3664 while (1) {
3665 mp_cmd_t *cmd;
3666 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3667 /* Allow running consecutive seek commands to combine them,
3668 * but execute the seek before running other commands.
3669 * If the user seeks continuously (keeps arrow key down)
3670 * try to finish showing a frame from one location before doing
3671 * another seek (which could lead to unchanging display). */
3672 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3673 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3674 && GetTimerMS() - mpctx->start_timestamp < 300)
3675 break;
3676 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3677 run_command(mpctx, cmd);
3678 mp_cmd_free(cmd);
3679 if (mpctx->stop_play)
3680 break;
3682 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3683 || mpctx->restart_playback)
3684 break;
3685 if (mpctx->sh_video) {
3686 update_osd_msg(mpctx);
3687 int hack = vo_osd_changed(0);
3688 vo_osd_changed(hack);
3689 if (hack) {
3690 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3691 add_step_frame(mpctx);
3692 break;
3693 } else
3694 vo_osd_changed(0);
3697 pause_loop(mpctx);
3700 // handle -sstep
3701 if (step_sec > 0 && !mpctx->paused) {
3702 mpctx->osd_function = OSD_FFW;
3703 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3706 edl_update(mpctx);
3708 /* Looping. */
3709 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3710 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3712 if (opts->loop_times>1)
3713 opts->loop_times--;
3714 else if (opts->loop_times==1)
3715 opts->loop_times = -1;
3716 play_n_frames = play_n_frames_mf;
3717 mpctx->stop_play = 0;
3718 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3721 if (mpctx->seek.type) {
3722 seek(mpctx, mpctx->seek, false);
3723 mpctx->seek = (struct seek_params){0};
3728 static int read_keys(void *ctx, int fd)
3730 getch2(ctx);
3731 return mplayer_get_key(ctx, 0);
3734 static bool attachment_is_font(struct demux_attachment *att)
3736 if (!att->name || !att->type || !att->data || !att->data_size)
3737 return false;
3738 // match against MIME types
3739 if (strcmp(att->type, "application/x-truetype-font") == 0
3740 || strcmp(att->type, "application/x-font") == 0)
3741 return true;
3742 // fallback: match against file extension
3743 if (strlen(att->name) > 4) {
3744 char *ext = att->name + strlen(att->name) - 4;
3745 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3746 || strcasecmp(ext, ".otf") == 0)
3747 return true;
3749 return false;
3752 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3754 if (audio_id == -1)
3755 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3756 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3757 demuxer_switch_audio(demuxer, audio_id);
3758 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3759 demuxer->audio->id = -2;
3760 demuxer->audio->sh = NULL;
3762 return demuxer->audio->id;
3765 static void print_version(const char* name)
3767 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3769 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3770 GetCpuCaps(&gCpuCaps);
3771 #if ARCH_X86
3772 mp_msg(MSGT_CPLAYER, MSGL_V,
3773 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3774 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3775 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3776 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3777 #if CONFIG_RUNTIME_CPUDETECT
3778 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3779 #else
3780 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3781 if (HAVE_MMX)
3782 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3783 if (HAVE_MMX2)
3784 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3785 if (HAVE_AMD3DNOW)
3786 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3787 if (HAVE_AMD3DNOWEXT)
3788 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3789 if (HAVE_SSE)
3790 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3791 if (HAVE_SSE2)
3792 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3793 if (HAVE_SSSE3)
3794 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3795 if (HAVE_CMOV)
3796 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3797 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3798 #endif /* CONFIG_RUNTIME_CPUDETECT */
3799 #endif /* ARCH_X86 */
3802 #ifdef PTW32_STATIC_LIB
3803 static void detach_ptw32(void)
3805 pthread_win32_thread_detach_np();
3806 pthread_win32_process_detach_np();
3808 #endif
3810 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3811 * file for some tools to link against. */
3812 #ifndef DISABLE_MAIN
3813 int main(int argc,char* argv[]){
3814 #ifdef PTW32_STATIC_LIB
3815 pthread_win32_process_attach_np();
3816 pthread_win32_thread_attach_np();
3817 atexit(detach_ptw32);
3818 #endif
3819 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3820 talloc_enable_leak_report();
3822 char * mem_ptr;
3824 // movie info:
3826 /* Flag indicating whether MPlayer should exit without playing anything. */
3827 int opt_exit = 0;
3828 int i;
3830 struct MPContext *mpctx = &(struct MPContext){
3831 .osd_function = OSD_PLAY,
3832 .begin_skip = MP_NOPTS_VALUE,
3833 .play_tree_step = 1,
3834 .global_sub_pos = -1,
3835 .set_of_sub_pos = -1,
3836 .file_format = DEMUXER_TYPE_UNKNOWN,
3837 .last_dvb_step = 1,
3840 InitTimer();
3841 srand(GetTimerMS());
3843 mp_msg_init();
3844 set_av_log_callback();
3846 #ifdef CONFIG_X11
3847 mpctx->x11_state = vo_x11_init_state();
3848 #endif
3849 struct MPOpts *opts = &mpctx->opts;
3850 set_default_mplayer_options(opts);
3851 // Create the config context and register the options
3852 mpctx->mconfig = m_config_new(opts, cfg_include);
3853 m_config_register_options(mpctx->mconfig,mplayer_opts);
3854 m_config_register_options(mpctx->mconfig, common_opts);
3855 mp_input_register_options(mpctx->mconfig);
3857 // Preparse the command line
3858 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3860 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3861 set_path_env();
3862 #endif
3864 #ifdef CONFIG_TV
3865 stream_tv_defaults.immediate = 1;
3866 #endif
3868 parse_cfgfiles(mpctx, mpctx->mconfig);
3870 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3871 if(mpctx->playtree == NULL)
3872 opt_exit = 1;
3873 else {
3874 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3875 if(mpctx->playtree) {
3876 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3877 if(mpctx->playtree_iter) {
3878 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3879 play_tree_iter_free(mpctx->playtree_iter);
3880 mpctx->playtree_iter = NULL;
3882 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3886 mpctx->key_fifo = mp_fifo_create(opts);
3888 print_version("MPlayer2");
3890 #if defined(__MINGW32__) || defined(__CYGWIN__)
3892 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3893 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3894 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3895 if (kernel32) {
3896 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3897 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3899 if (setDEP) setDEP(3);
3900 if (setDllDir) setDllDir("");
3902 // stop Windows from showing all kinds of annoying error dialogs
3903 SetErrorMode(0x8003);
3904 // request 1ms timer resolution
3905 timeBeginPeriod(1);
3906 #endif
3908 #ifdef CONFIG_PRIORITY
3909 set_priority();
3910 #endif
3912 if (codec_path)
3913 set_codec_path(codec_path);
3915 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3916 list_video_out();
3917 opt_exit = 1;
3920 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3921 list_audio_out();
3922 opt_exit = 1;
3925 /* Check codecs.conf. */
3926 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3927 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3928 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3929 if(!parse_codec_cfg(NULL)){
3930 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3932 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3935 free( mem_ptr ); // release the buffer created by get_path()
3938 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3939 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3940 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3941 list_codecs(1);
3942 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3943 opt_exit = 1;
3945 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3946 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3947 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3948 list_codecs(0);
3949 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3950 opt_exit = 1;
3952 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3953 vfm_help();
3954 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3955 opt_exit = 1;
3957 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3958 afm_help();
3959 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3960 opt_exit = 1;
3962 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3963 af_help();
3964 printf("\n");
3965 opt_exit = 1;
3967 #ifdef CONFIG_X11
3968 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3969 fstype_help();
3970 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3971 opt_exit = 1;
3973 #endif
3974 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3975 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3976 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3977 demuxer_help();
3978 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3979 opt_exit = 1;
3981 if (opts->list_properties) {
3982 property_print_help();
3983 opt_exit = 1;
3986 if(opt_exit)
3987 exit_player(mpctx, EXIT_NONE);
3989 if (!mpctx->filename && !opts->player_idle_mode) {
3990 // no file/vcd/dvd -> show HELP:
3991 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3992 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3995 /* Display what configure line was used */
3996 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3998 // Many users forget to include command line in bugreports...
3999 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
4000 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4001 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
4002 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4005 //------ load global data first ------
4007 mpctx->osd = osd_create();
4009 // check font
4010 #ifdef CONFIG_FREETYPE
4011 init_freetype();
4012 #endif
4013 #ifdef CONFIG_FONTCONFIG
4014 if(font_fontconfig <= 0)
4016 #endif
4017 #ifdef CONFIG_BITMAP_FONT
4018 if(font_name){
4019 vo_font=read_font_desc(font_name,font_factor,verbose>1);
4020 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
4021 filename_recode(font_name));
4022 } else {
4023 // try default:
4024 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
4025 free(mem_ptr); // release the buffer created by get_path()
4026 if(!vo_font)
4027 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
4029 if (sub_font_name)
4030 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
4031 else
4032 mpctx->osd->sub_font = vo_font;
4033 #endif
4034 #ifdef CONFIG_FONTCONFIG
4036 #endif
4038 #ifdef CONFIG_ASS
4039 ass_library = mp_ass_init();
4040 #endif
4042 #ifdef HAVE_RTC
4043 if(opts->rtc)
4045 char *rtc_device = opts->rtc_device;
4046 // seteuid(0); /* Can't hurt to try to get root here */
4047 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4048 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4049 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4050 else {
4051 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4053 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4054 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4055 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4056 close (rtc_fd);
4057 rtc_fd = -1;
4058 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4059 /* variable only by the root */
4060 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4061 close (rtc_fd);
4062 rtc_fd = -1;
4063 } else
4064 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4067 if(rtc_fd<0)
4068 #endif /* HAVE_RTC */
4069 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4070 opts->softsleep ? "software" : timer_name);
4072 #ifdef HAVE_TERMCAP
4073 load_termcap(NULL); // load key-codes
4074 #endif
4076 // ========== Init keyboard FIFO (connection to libvo) ============
4078 // Init input system
4079 current_module = "init_input";
4080 mpctx->input = mp_input_init(&opts->input);
4081 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4082 if(slave_mode) {
4083 #if USE_FD0_CMD_SELECT
4084 int flags = fcntl(0, F_GETFL);
4085 if (flags != -1)
4086 fcntl(0, F_SETFL, flags | O_NONBLOCK);
4087 #endif
4088 mp_input_add_cmd_fd(mpctx->input, 0,USE_FD0_CMD_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4090 else if (opts->consolecontrols)
4091 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4092 // Set the libstream interrupt callback
4093 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4095 #ifdef CONFIG_MENU
4096 if(use_menu) {
4097 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4098 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4099 else {
4100 menu_cfg = get_path("menu.conf");
4101 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4102 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4103 else {
4104 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4105 MPLAYER_CONFDIR "/menu.conf"))
4106 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4107 else {
4108 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4109 use_menu = 0;
4114 #endif
4116 current_module = NULL;
4118 /// Catch signals
4119 #ifndef __MINGW32__
4120 signal(SIGCHLD,child_sighandler);
4121 #endif
4123 #ifdef CONFIG_CRASH_DEBUG
4124 prog_path = argv[0];
4125 #endif
4126 //========= Catch terminate signals: ================
4127 // terminate requests:
4128 signal(SIGTERM,exit_sighandler); // kill
4129 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4131 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4133 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4134 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4135 #ifdef CONFIG_SIGHANDLER
4136 // fatal errors:
4137 signal(SIGBUS,exit_sighandler); // bus error
4138 signal(SIGSEGV,exit_sighandler); // segfault
4139 signal(SIGILL,exit_sighandler); // illegal instruction
4140 signal(SIGFPE,exit_sighandler); // floating point exc.
4141 signal(SIGABRT,exit_sighandler); // abort()
4142 #ifdef CONFIG_CRASH_DEBUG
4143 if (crash_debug)
4144 signal(SIGTRAP,exit_sighandler);
4145 #endif
4146 #endif
4148 // ******************* Now, let's see the per-file stuff ********************
4150 play_next_file:
4152 // init global sub numbers
4153 mpctx->global_sub_size = 0;
4154 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4156 if (mpctx->filename) {
4157 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4158 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4159 load_per_file_config (mpctx->mconfig, mpctx->filename);
4162 if (opts->video_driver_list)
4163 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4164 if (opts->audio_driver_list)
4165 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4167 // We must enable getch2 here to be able to interrupt network connection
4168 // or cache filling
4169 if (opts->consolecontrols && !slave_mode) {
4170 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4171 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4172 else
4173 getch2_enable(); // prepare stdin for hotkeys...
4174 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4175 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4178 // =================== GUI idle loop (STOP state) ===========================
4179 while (opts->player_idle_mode && !mpctx->filename) {
4180 play_tree_t * entry = NULL;
4181 mp_cmd_t * cmd;
4182 if (mpctx->video_out && mpctx->video_out->config_ok)
4183 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4184 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4185 if (mpctx->video_out)
4186 vo_check_events(mpctx->video_out);
4187 usec_sleep(20000);
4189 switch (cmd->id) {
4190 case MP_CMD_LOADFILE:
4191 // prepare a tree entry with the new filename
4192 entry = play_tree_new();
4193 play_tree_add_file(entry, cmd->args[0].v.s);
4194 // The entry is added to the main playtree after the switch().
4195 break;
4196 case MP_CMD_LOADLIST:
4197 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4198 break;
4199 case MP_CMD_QUIT:
4200 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4201 break;
4202 case MP_CMD_VO_FULLSCREEN:
4203 case MP_CMD_GET_PROPERTY:
4204 case MP_CMD_SET_PROPERTY:
4205 case MP_CMD_STEP_PROPERTY:
4206 run_command(mpctx, cmd);
4207 break;
4210 mp_cmd_free(cmd);
4212 if (entry) { // user entered a command that gave a valid entry
4213 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4214 play_tree_free_list(mpctx->playtree->child, 1);
4215 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4217 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4219 play_tree_set_child(mpctx->playtree, entry);
4221 /* Make iterator start at the top the of tree. */
4222 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4223 if (!mpctx->playtree_iter) continue;
4225 // find the first real item in the tree
4226 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4227 // no items!
4228 play_tree_iter_free(mpctx->playtree_iter);
4229 mpctx->playtree_iter = NULL;
4230 continue; // wait for next command
4232 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4235 //---------------------------------------------------------------------------
4237 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4238 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4240 if (mpctx->filename) {
4241 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4242 filename_recode(mpctx->filename));
4243 if(use_filename_title && opts->vo_wintitle == NULL)
4244 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4247 if (edl_filename) {
4248 if (edl_records) free_edl(edl_records);
4249 next_edl_record = edl_records = edl_parse_file();
4251 if (edl_output_filename) {
4252 if (edl_fd) fclose(edl_fd);
4253 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4255 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4256 filename_recode(edl_output_filename));
4260 //==================== Open VOB-Sub ============================
4262 current_module="vobsub";
4263 if (opts->vobsub_name){
4264 vo_vobsub=vobsub_open(opts->vobsub_name,spudec_ifo,1,&vo_spudec);
4265 if(vo_vobsub==NULL)
4266 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4267 filename_recode(opts->vobsub_name));
4268 } else if (opts->sub_auto && mpctx->filename){
4269 char **vob = find_vob_subtitles(opts, mpctx->filename);
4270 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4271 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4272 if (vo_vobsub)
4273 break;
4275 talloc_free(vob);
4277 if(vo_vobsub){
4278 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4279 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4280 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4282 // setup global sub numbering
4283 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4286 //============ Open & Sync STREAM --- fork cache2 ====================
4288 mpctx->stream=NULL;
4289 mpctx->demuxer=NULL;
4290 mpctx->d_audio=NULL;
4291 mpctx->d_video=NULL;
4292 mpctx->d_sub = NULL;
4293 mpctx->sh_audio=NULL;
4294 mpctx->sh_video=NULL;
4296 current_module="open_stream";
4297 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4298 if(!mpctx->stream) { // error...
4299 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4300 goto goto_next_file;
4302 mpctx->initialized_flags|=INITIALIZED_STREAM;
4304 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4305 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4306 "playlist support will not be used automatically.\n"
4307 "MPlayer's playlist code is unsafe and should only be used with "
4308 "trusted sources.\nPlayback will probably fail.\n\n");
4309 #if 0
4310 play_tree_t* entry;
4311 // Handle playlist
4312 current_module="handle_playlist";
4313 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4314 filename_recode(mpctx->filename));
4315 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4316 mpctx->eof=playtree_add_playlist(mpctx, entry);
4317 goto goto_next_file;
4318 #endif
4320 mpctx->stream->start_pos+=seek_to_byte;
4322 if(stream_dump_type==5){
4323 unsigned char buf[4096];
4324 int len;
4325 FILE *f;
4326 current_module="dumpstream";
4327 stream_reset(mpctx->stream);
4328 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4329 f=fopen(opts->stream_dump_name,"wb");
4330 if(!f){
4331 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4332 exit_player(mpctx, EXIT_ERROR);
4334 if (opts->chapterrange[0] > 1) {
4335 int chapter = opts->chapterrange[0] - 1;
4336 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4338 struct stream_dump_progress info;
4339 stream_dump_progress_start(&info);
4340 while(!mpctx->stream->eof && !async_quit_request){
4341 len=stream_read(mpctx->stream,buf,4096);
4342 if(len>0) {
4343 if(fwrite(buf,len,1,f) != 1) {
4344 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4345 exit_player(mpctx, EXIT_ERROR);
4348 stream_dump_progress(&info, len, mpctx->stream);
4349 if (opts->chapterrange[1] > 0) {
4350 int chapter = -1;
4351 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4352 &chapter) == STREAM_OK
4353 && chapter + 1 > opts->chapterrange[1])
4354 break;
4357 if(fclose(f)) {
4358 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4359 exit_player(mpctx, EXIT_ERROR);
4361 stream_dump_progress_end(&info, opts->stream_dump_name);
4362 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4363 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4366 #ifdef CONFIG_DVDREAD
4367 if(mpctx->stream->type==STREAMTYPE_DVD){
4368 current_module="dvd lang->id";
4369 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4370 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4371 // setup global sub numbering
4372 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4373 current_module=NULL;
4375 #endif
4377 #ifdef CONFIG_DVDNAV
4378 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4379 current_module="dvdnav lang->id";
4380 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4381 dvdsub_lang_id = -3;
4382 if(opts->sub_lang && opts->sub_id==-1)
4383 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4384 // setup global sub numbering
4385 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4386 current_module=NULL;
4388 #endif
4390 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4391 goto_enable_cache:
4392 if(stream_cache_size>0){
4393 int res;
4394 float stream_cache_min_percent = opts->stream_cache_min_percent;
4395 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4396 current_module="enable_cache";
4397 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4398 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4399 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4400 if(res == 0)
4401 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4404 //============ Open DEMUXERS --- DETECT file type =======================
4405 current_module="demux_open";
4407 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4409 // HACK to get MOV Reference Files working
4411 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4413 unsigned char* playlist_entry;
4414 play_tree_t *list = NULL, *entry = NULL;
4416 current_module="handle_demux_playlist";
4417 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4419 char *temp;
4420 const char *bname;
4422 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4423 filename_recode(playlist_entry));
4425 bname=mp_basename(playlist_entry);
4426 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4427 continue;
4429 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4430 continue;
4432 entry = play_tree_new();
4434 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4436 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4437 if (temp)
4439 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4440 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4441 strcat(temp, playlist_entry);
4442 if (!strcmp(temp, mpctx->filename)) {
4443 free(temp);
4444 continue;
4446 play_tree_add_file(entry,temp);
4447 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4448 free(temp);
4451 else
4452 play_tree_add_file(entry,playlist_entry);
4454 if(!list)
4455 list = entry;
4456 else
4457 play_tree_append_entry(list,entry);
4459 free_demuxer(mpctx->demuxer);
4460 mpctx->demuxer = NULL;
4462 if (list)
4464 entry = play_tree_new();
4465 play_tree_set_child(entry,list);
4466 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4467 goto goto_next_file;
4471 if(!mpctx->demuxer) {
4472 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4473 goto goto_next_file;
4476 if (mpctx->demuxer->matroska_data.ordered_chapters)
4477 build_ordered_chapter_timeline(mpctx);
4479 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4480 build_edl_timeline(mpctx);
4482 if (mpctx->timeline) {
4483 mpctx->timeline_part = 0;
4484 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4486 int part_count = mpctx->num_timeline_parts;
4487 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4488 "sources. Total length %.3f seconds.\n", part_count,
4489 mpctx->num_sources, mpctx->timeline[part_count].start);
4490 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4491 for (int i = 0; i < mpctx->num_sources; i++)
4492 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4493 filename_recode(mpctx->sources[i].demuxer->filename));
4494 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4495 "source_start, source):\n");
4496 for (int i = 0; i < part_count; i++) {
4497 struct timeline_part *p = mpctx->timeline + i;
4498 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4499 p->source_start, p->source - mpctx->sources);
4501 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4502 mpctx->timeline[part_count].start);
4505 if (!mpctx->sources) {
4506 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4507 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4508 .demuxer = mpctx->demuxer};
4509 mpctx->num_sources = 1;
4512 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4514 #ifdef CONFIG_ASS
4515 if (opts->ass_enabled && ass_library) {
4516 for (int j = 0; j < mpctx->num_sources; j++) {
4517 struct demuxer *d = mpctx->sources[j].demuxer;
4518 for (int i = 0; i < d->num_attachments; i++) {
4519 struct demux_attachment *att = d->attachments + i;
4520 if (use_embedded_fonts && attachment_is_font(att))
4521 ass_add_font(ass_library, att->name, att->data, att->data_size);
4525 #endif
4527 current_module="demux_open2";
4529 mpctx->d_audio=mpctx->demuxer->audio;
4530 mpctx->d_video=mpctx->demuxer->video;
4531 mpctx->d_sub=mpctx->demuxer->sub;
4533 if (ts_prog) {
4534 int tmp = ts_prog;
4535 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4537 // select audio stream
4538 for (int i = 0; i < mpctx->num_sources; i++)
4539 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4540 opts->audio_lang);
4542 // DUMP STREAMS:
4543 if((stream_dump_type)&&(stream_dump_type<4)){
4544 FILE *f;
4545 demux_stream_t *ds=NULL;
4546 current_module="dump";
4547 // select stream to dump
4548 switch(stream_dump_type){
4549 case 1: ds=mpctx->d_audio;break;
4550 case 2: ds=mpctx->d_video;break;
4551 case 3: ds=mpctx->d_sub;break;
4553 if(!ds){
4554 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4555 exit_player(mpctx, EXIT_ERROR);
4557 // disable other streams:
4558 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4559 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4560 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4561 // let's dump it!
4562 f=fopen(opts->stream_dump_name,"wb");
4563 if(!f){
4564 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4565 exit_player(mpctx, EXIT_ERROR);
4567 struct stream_dump_progress info;
4568 stream_dump_progress_start(&info);
4569 while(!ds->eof){
4570 unsigned char* start;
4571 int in_size=ds_get_packet(ds,&start);
4572 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4573 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4574 if(in_size>0) {
4575 fwrite(start,in_size,1,f);
4576 stream_dump_progress(&info, in_size, mpctx->stream);
4578 if (opts->chapterrange[1] > 0) {
4579 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4580 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4581 break;
4584 fclose(f);
4585 stream_dump_progress_end(&info, opts->stream_dump_name);
4586 mp_tmsg(MSGT_CPLAYER ,MSGL_INFO, "Stream dump complete.\n");
4587 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4590 mpctx->sh_audio=mpctx->d_audio->sh;
4591 mpctx->sh_video=mpctx->d_video->sh;
4593 if(mpctx->sh_video){
4595 current_module="video_read_properties";
4596 if(!video_read_properties(mpctx->sh_video)) {
4597 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4598 mpctx->sh_video=mpctx->d_video->sh=NULL;
4599 } else {
4600 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4601 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4602 mpctx->sh_video->fps,mpctx->sh_video->frametime
4605 /* need to set fps here for output encoders to pick it up in their init */
4606 if(force_fps){
4607 mpctx->sh_video->fps=force_fps;
4608 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4610 vo_fps = mpctx->sh_video->fps;
4612 if(!mpctx->sh_video->fps && !force_fps){
4613 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4614 mpctx->opts.correct_pts = 1;
4620 if(!mpctx->sh_video && !mpctx->sh_audio){
4621 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4622 #ifdef CONFIG_DVBIN
4623 if(mpctx->stream->type == STREAMTYPE_DVB)
4625 int dir;
4626 int v = mpctx->last_dvb_step;
4627 if(v > 0)
4628 dir = DVB_CHANNEL_HIGHER;
4629 else
4630 dir = DVB_CHANNEL_LOWER;
4632 if(dvb_step_channel(mpctx->stream, dir)) {
4633 mpctx->stop_play = PT_NEXT_ENTRY;
4634 mpctx->dvbin_reopen = 1;
4637 #endif
4638 goto goto_next_file; // exit_player(_("Fatal error"));
4641 /* display clip info */
4642 demux_info_print(mpctx->demuxer);
4644 //================== Read SUBTITLES (DVD & TEXT) ==========================
4645 if(vo_spudec==NULL &&
4646 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4647 init_vo_spudec(mpctx);
4650 // after reading video params we should load subtitles because
4651 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4652 // check .sub
4653 current_module="read_subtitles_file";
4654 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4655 if(opts->sub_name){
4656 for (i = 0; opts->sub_name[i] != NULL; ++i)
4657 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4659 if(opts->sub_auto) { // auto load sub file ...
4660 char **tmp = find_text_subtitles(opts, mpctx->filename);
4661 int nsub = MP_TALLOC_ELEMS(tmp);
4662 for (int i = 0; i < nsub; i++)
4663 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4664 talloc_free(tmp);
4666 if (mpctx->set_of_sub_size > 0)
4667 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4669 if (select_subtitle(mpctx)) {
4670 if(mpctx->subdata)
4671 switch (stream_dump_type) {
4672 case 3: list_sub_file(mpctx->subdata); break;
4673 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4674 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4675 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4676 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4677 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4681 print_file_properties(mpctx, mpctx->filename);
4683 reinit_video_chain(mpctx);
4684 if (mpctx->sh_video) {
4685 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4686 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4687 #ifdef CONFIG_FREETYPE
4688 force_load_font = 1;
4689 #endif
4690 } else if (!mpctx->sh_audio)
4691 goto goto_next_file;
4693 //================== MAIN: ==========================
4694 current_module="main";
4696 if (opts->playing_msg) {
4697 char* msg = property_expand_string(mpctx, opts->playing_msg);
4698 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4699 free(msg);
4703 // Disable the term OSD in verbose mode
4704 if (verbose)
4705 opts->term_osd = 0;
4709 // Make sure old OSD does not stay around,
4710 // e.g. with -fixed-vo and same-resolution files
4711 clear_osd_msgs();
4712 update_osd_msg(mpctx);
4714 //================ SETUP AUDIO ==========================
4716 if(mpctx->sh_audio){
4717 reinit_audio_chain(mpctx);
4718 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4719 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4722 current_module="av_init";
4724 if(mpctx->sh_video){
4725 mpctx->sh_video->timer=0;
4726 if (! ignore_start)
4727 audio_delay += mpctx->sh_video->stream_delay;
4729 if(mpctx->sh_audio){
4730 if (start_volume >= 0)
4731 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4732 if (! ignore_start)
4733 audio_delay -= mpctx->sh_audio->stream_delay;
4734 mpctx->delay=-audio_delay;
4737 if(!mpctx->sh_audio){
4738 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4739 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4740 ds_free_packs(mpctx->d_audio); // free buffered chunks
4741 //mpctx->d_audio->id=-2; // do not read audio chunks
4742 //uninit_player(mpctx, INITIALIZED_AO); // close device
4744 if(!mpctx->sh_video){
4745 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4746 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4747 ds_free_packs(mpctx->d_video);
4748 mpctx->d_video->id=-2;
4749 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4752 if (!mpctx->sh_video && !mpctx->sh_audio)
4753 goto goto_next_file;
4755 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4756 if(force_fps && mpctx->sh_video){
4757 vo_fps = mpctx->sh_video->fps=force_fps;
4758 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4759 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4762 mp_input_set_section(mpctx->input, NULL);
4763 //TODO: add desired (stream-based) sections here
4764 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4765 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4767 //==================== START PLAYING =======================
4769 if(opts->loop_times>1) opts->loop_times--; else
4770 if(opts->loop_times==1) opts->loop_times = -1;
4772 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4774 total_time_usage_start=GetTimer();
4775 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4776 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4777 play_n_frames=play_n_frames_mf;
4779 if(play_n_frames==0){
4780 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4783 mpctx->time_frame = 0;
4784 mpctx->drop_message_shown = 0;
4785 mpctx->restart_playback = true;
4786 mpctx->video_pts = 0;
4787 mpctx->hrseek_active = false;
4788 mpctx->hrseek_framedrop = false;
4789 mpctx->step_frames = 0;
4790 mpctx->total_avsync_change = 0;
4791 mpctx->last_chapter_seek = -1;
4793 // If there's a timeline force an absolute seek to initialize state
4794 if (seek_to_sec || mpctx->timeline) {
4795 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4796 seek(mpctx, mpctx->seek, false);
4797 end_at.pos += seek_to_sec;
4799 if (opts->chapterrange[0] > 0) {
4800 double pts;
4801 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4802 && pts > -1.0) {
4803 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4804 seek(mpctx, mpctx->seek, false);
4808 if (end_at.type == END_AT_SIZE) {
4809 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4810 end_at.type = END_AT_NONE;
4813 #ifdef CONFIG_DVDNAV
4814 mp_dvdnav_context_free(mpctx);
4815 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4816 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4817 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4819 #endif
4821 mpctx->seek = (struct seek_params){0};
4822 get_relative_time(mpctx); // reset current delta
4823 // Make sure VO knows current pause state
4824 if (mpctx->sh_video)
4825 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4826 NULL);
4828 while (!mpctx->stop_play)
4829 run_playloop(mpctx);
4831 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4833 #ifdef CONFIG_DVBIN
4834 if(mpctx->dvbin_reopen)
4836 mpctx->stop_play = 0;
4837 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4838 cache_uninit(mpctx->stream);
4839 mpctx->dvbin_reopen = 0;
4840 goto goto_enable_cache;
4842 #endif
4845 goto_next_file: // don't jump here after ao/vo/getch initialization!
4847 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4849 if (opts->benchmark) {
4850 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4851 double total_time_usage;
4852 total_time_usage_start=GetTimer()-total_time_usage_start;
4853 total_time_usage = (float)total_time_usage_start*0.000001;
4854 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4855 video_time_usage,vout_time_usage,audio_time_usage,
4856 total_time_usage-tot,total_time_usage);
4857 if(total_time_usage>0.0)
4858 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4859 100.0*video_time_usage/total_time_usage,
4860 100.0*vout_time_usage/total_time_usage,
4861 100.0*audio_time_usage/total_time_usage,
4862 100.0*(total_time_usage-tot)/total_time_usage,
4863 100.0);
4864 if(total_frame_cnt && frame_dropping)
4865 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4866 total_frame_cnt-drop_frame_cnt,
4867 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4868 drop_frame_cnt,
4869 100*drop_frame_cnt/total_frame_cnt,
4870 total_frame_cnt,
4871 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4874 // time to uninit all, except global stuff:
4875 int uninitialize_parts = INITIALIZED_ALL;
4876 if (opts->fixed_vo)
4877 uninitialize_parts -= INITIALIZED_VO;
4878 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4879 uninitialize_parts -= INITIALIZED_AO;
4880 uninit_player(mpctx, uninitialize_parts);
4882 if(mpctx->set_of_sub_size > 0) {
4883 current_module="sub_free";
4884 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4885 sub_free(mpctx->set_of_subtitles[i]);
4886 #ifdef CONFIG_ASS
4887 if(mpctx->set_of_ass_tracks[i])
4888 ass_free_track( mpctx->set_of_ass_tracks[i] );
4889 #endif
4891 mpctx->set_of_sub_size = 0;
4893 mpctx->vo_sub_last = vo_sub=NULL;
4894 mpctx->subdata=NULL;
4895 #ifdef CONFIG_ASS
4896 mpctx->osd->ass_track = NULL;
4897 if(ass_library)
4898 ass_clear_fonts(ass_library);
4899 #endif
4901 if (!mpctx->stop_play) // In case some goto jumped here...
4902 mpctx->stop_play = PT_NEXT_ENTRY;
4904 int playtree_direction = 1;
4906 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4907 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4908 play_tree_iter_free(mpctx->playtree_iter);
4909 mpctx->playtree_iter = NULL;
4911 mpctx->play_tree_step = 1;
4912 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4913 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4914 if(mpctx->playtree_iter) {
4915 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4916 play_tree_iter_free(mpctx->playtree_iter);
4917 mpctx->playtree_iter = NULL;
4920 } else if (mpctx->stop_play == PT_STOP) {
4921 play_tree_iter_free(mpctx->playtree_iter);
4922 mpctx->playtree_iter = NULL;
4923 } else { // NEXT PREV SRC
4924 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4927 while(mpctx->playtree_iter != NULL) {
4928 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4929 if(mpctx->filename == NULL) {
4930 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4931 play_tree_iter_free(mpctx->playtree_iter);
4932 mpctx->playtree_iter = NULL;
4934 } else
4935 break;
4938 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4939 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4940 mpctx->stop_play = 0;
4941 goto play_next_file;
4945 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4947 return 1;
4949 #endif /* DISABLE_MAIN */