demux_ts: Fix subtitle sync issues
[mplayer/glamo.git] / mplayer.c
blobb44e2725994c19ad39567ed638891aa3946eb8f8
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 "config.h"
26 #include "talloc.h"
28 #if defined(__MINGW32__) || defined(__CYGWIN__)
29 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
30 #include <windows.h>
31 #endif
32 #include <string.h>
33 #include <unistd.h>
35 // #include <sys/mman.h>
36 #include <sys/types.h>
37 #ifndef __MINGW32__
38 #include <sys/ioctl.h>
39 #include <sys/wait.h>
40 #else
41 #define SIGHUP 1 /* hangup */
42 #define SIGQUIT 3 /* quit */
43 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
44 #define SIGBUS 10 /* bus error */
45 #define SIGPIPE 13 /* broken pipe */
46 #endif
48 #include <sys/time.h>
49 #include <sys/stat.h>
51 #include <signal.h>
52 #include <time.h>
53 #include <fcntl.h>
54 #include <limits.h>
56 #include <errno.h>
58 #include "mp_msg.h"
59 #include "av_log.h"
62 #include "m_option.h"
63 #include "m_config.h"
64 #include "mplayer.h"
65 #include "access_mpcontext.h"
66 #include "m_property.h"
68 #include "cfg-mplayer-def.h"
70 #include "libavutil/avstring.h"
72 #include "subreader.h"
74 #include "mp_osd.h"
75 #include "libvo/video_out.h"
77 #include "libvo/font_load.h"
78 #include "libvo/sub.h"
80 #ifdef CONFIG_X11
81 #include "libvo/x11_common.h"
82 #endif
84 #include "libao2/audio_out.h"
86 #include "codec-cfg.h"
88 #include "edl.h"
90 #include "spudec.h"
91 #include "vobsub.h"
93 #include "osdep/getch2.h"
94 #include "osdep/timer.h"
95 #include "osdep/findfiles.h"
97 #include "input/input.h"
99 const int under_mencoder = 0;
100 int slave_mode=0;
101 int player_idle_mode=0;
102 int quiet=0;
103 int enable_mouse_movements=0;
104 float start_volume = -1;
106 #include "osdep/priority.h"
108 char *heartbeat_cmd;
110 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
112 #ifdef HAVE_RTC
113 #ifdef __linux__
114 #include <linux/rtc.h>
115 #else
116 #include <rtc.h>
117 #define RTC_IRQP_SET RTCIO_IRQP_SET
118 #define RTC_PIE_ON RTCIO_PIE_ON
119 #endif /* __linux__ */
120 #endif /* HAVE_RTC */
122 #include "stream/tv.h"
123 #include "stream/stream_radio.h"
124 #ifdef CONFIG_DVBIN
125 #include "stream/dvbin.h"
126 #endif
127 #include "stream/cache2.h"
129 //**************************************************************************//
130 // Playtree
131 //**************************************************************************//
132 #include "playtree.h"
133 #include "playtreeparser.h"
135 //**************************************************************************//
136 // Config
137 //**************************************************************************//
138 #include "parser-cfg.h"
139 #include "parser-mpcmd.h"
141 //**************************************************************************//
142 // Config file
143 //**************************************************************************//
145 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
147 #include "path.h"
149 //**************************************************************************//
150 //**************************************************************************//
151 // Input media streaming & demultiplexer:
152 //**************************************************************************//
154 static int max_framesize=0;
156 #include "stream/stream.h"
157 #include "libmpdemux/demuxer.h"
158 #include "libmpdemux/stheader.h"
160 #ifdef CONFIG_DVDREAD
161 #include "stream/stream_dvd.h"
162 #endif
163 #include "stream/stream_dvdnav.h"
165 #include "libmpcodecs/dec_audio.h"
166 #include "libmpcodecs/dec_video.h"
167 #include "libmpcodecs/mp_image.h"
168 #include "libmpcodecs/vf.h"
169 #include "libmpcodecs/vd.h"
171 #include "mixer.h"
173 #include "mp_core.h"
174 #include "options.h"
175 #include "defaultopts.h"
177 static const char help_text[]=_(
178 "Usage: mplayer [options] [url|path/]filename\n"
179 "\n"
180 "Basic options: (complete list in the man page)\n"
181 " -vo <drv> select video output driver ('-vo help' for a list)\n"
182 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
183 #ifdef CONFIG_VCD
184 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
185 #endif
186 #ifdef CONFIG_DVDREAD
187 " dvd://<titleno> play DVD title from device instead of plain file\n"
188 #endif
189 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
190 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
191 " -nosound do not play sound\n"
192 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
193 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
194 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
195 " -playlist <file> specify playlist file\n"
196 " -vid x -aid y select video (x) and audio (y) stream to play\n"
197 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
198 " -pp <quality> enable postprocessing filter (details in the man page)\n"
199 " -framedrop enable frame dropping (for slow machines)\n"
200 "\n"
201 "Basic keys: (complete list in the man page, also check input.conf)\n"
202 " <- or -> seek backward/forward 10 seconds\n"
203 " down or up seek backward/forward 1 minute\n"
204 " pgdown or pgup seek backward/forward 10 minutes\n"
205 " < or > step backward/forward in playlist\n"
206 " p or SPACE pause movie (press any key to continue)\n"
207 " q or ESC stop playing and quit program\n"
208 " + or - adjust audio delay by +/- 0.1 second\n"
209 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
210 " * or / increase or decrease PCM volume\n"
211 " x or z adjust subtitle delay by +/- 0.1 second\n"
212 " r or t adjust subtitle position up/down, also see -vf expand\n"
213 "\n"
214 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
215 "\n");
218 #define Exit_SIGILL_RTCpuSel _(\
219 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
220 " It may be a bug in our new runtime CPU-detection code...\n"\
221 " Please read DOCS/HTML/en/bugreports.html.\n")
223 #define Exit_SIGILL _(\
224 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
225 " It usually happens when you run it on a CPU different than the one it was\n"\
226 " compiled/optimized for.\n"\
227 " Verify this!\n")
229 #define Exit_SIGSEGV_SIGFPE _(\
230 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
231 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
232 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
234 #define Exit_SIGCRASH _(\
235 "- MPlayer crashed. This shouldn't happen.\n"\
236 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
237 " gcc version. If you think it's MPlayer's fault, please read\n"\
238 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
239 " won't help unless you provide this information when reporting a possible bug.\n")
241 #define SystemTooSlow _("\n\n"\
242 " ************************************************\n"\
243 " **** Your system is too SLOW to play this! ****\n"\
244 " ************************************************\n\n"\
245 "Possible reasons, problems, workarounds:\n"\
246 "- Most common: broken/buggy _audio_ driver\n"\
247 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
248 " - Experiment with different values for -autosync, 30 is a good start.\n"\
249 "- Slow video output\n"\
250 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
251 "- Slow CPU\n"\
252 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
253 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
254 "- Broken file\n"\
255 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
256 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
257 " - Try -cache 8192.\n"\
258 "- Are you using -cache to play a non-interleaved AVI file?\n"\
259 " - Try -nocache.\n"\
260 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
261 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
264 //**************************************************************************//
265 //**************************************************************************//
267 // Common FIFO functions, and keyboard/event FIFO code
268 #include "mp_fifo.h"
269 int noconsolecontrols=0;
270 //**************************************************************************//
272 // benchmark:
273 double video_time_usage=0;
274 double vout_time_usage=0;
275 static double audio_time_usage=0;
276 static int total_time_usage_start=0;
277 static int total_frame_cnt=0;
278 static int drop_frame_cnt=0; // total number of dropped frames
279 int benchmark=0;
281 // options:
282 int auto_quality=0;
283 static int output_quality=0;
285 static int list_properties = 0;
287 int term_osd = 1;
288 static char* term_osd_esc = "\x1b[A\r\x1b[K";
289 static char* playing_msg = NULL;
290 // seek:
291 static double seek_to_sec;
292 static off_t seek_to_byte=0;
293 static off_t step_sec=0;
295 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
297 // A/V sync:
298 int autosync=0; // 30 might be a good default value.
300 // codecs:
301 char **audio_codec_list=NULL; // override audio codec
302 char **video_codec_list=NULL; // override video codec
303 char **audio_fm_list=NULL; // override audio codec family
304 char **video_fm_list=NULL; // override video codec family
306 // demuxer:
307 extern char *demuxer_name; // override demuxer
308 extern char *audio_demuxer_name; // override audio demuxer
309 extern char *sub_demuxer_name; // override sub demuxer
311 // this dvdsub_id was selected via slang
312 // use this to allow dvdnav to follow -slang across stream resets,
313 // in particular the subtitle ID for a language changes
314 int dvdsub_lang_id;
315 int vobsub_id=-1;
316 static char* spudec_ifo=NULL;
317 int forced_subs_only=0;
318 int file_filter=1;
320 // cache2:
321 int stream_cache_size=-1;
322 #ifdef CONFIG_STREAM_CACHE
323 float stream_cache_min_percent=20.0;
324 float stream_cache_seek_min_percent=50.0;
325 #endif
327 // dump:
328 int stream_dump_type=0;
330 // A-V sync:
331 static float default_max_pts_correction=-1;//0.01f;
332 float audio_delay=0;
333 static int ignore_start=0;
335 static int softsleep=0;
337 double force_fps=0;
338 static int force_srate=0;
339 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
340 static int play_n_frames=-1;
341 static int play_n_frames_mf=-1;
343 // sub:
344 char *font_name=NULL;
345 char *sub_font_name=NULL;
346 extern int font_fontconfig;
347 float font_factor=0.75;
348 char **sub_name=NULL;
349 float sub_delay=0;
350 float sub_fps=0;
351 int sub_auto = 1;
352 char *vobsub_name=NULL;
353 int subcc_enabled=0;
354 int suboverlap_enabled = 1;
356 #include "ass_mp.h"
358 char* current_module=NULL; // for debugging
361 // ---
363 #ifdef CONFIG_MENU
364 #include "m_struct.h"
365 #include "libmenu/menu.h"
366 static const vf_info_t* const libmenu_vfs[] = {
367 &vf_info_menu,
368 NULL
370 static vf_instance_t* vf_menu = NULL;
371 int use_menu = 0;
372 static char* menu_cfg = NULL;
373 static char* menu_root = "main";
374 #endif
377 #ifdef HAVE_RTC
378 static int nortc = 1;
379 static char* rtc_device;
380 #endif
382 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
383 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
384 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
385 int use_filedir_conf;
386 int use_filename_title;
388 #include "mpcommon.h"
389 #include "command.h"
391 #include "metadata.h"
393 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
395 const void *mpctx_get_video_out(MPContext *mpctx)
397 return mpctx->video_out;
400 const void *mpctx_get_audio_out(MPContext *mpctx)
402 return mpctx->audio_out;
405 void *mpctx_get_demuxer(MPContext *mpctx)
407 return mpctx->demuxer;
410 void *mpctx_get_playtree_iter(MPContext *mpctx)
412 return mpctx->playtree_iter;
415 void *mpctx_get_mixer(MPContext *mpctx)
417 return &mpctx->mixer;
420 int mpctx_get_global_sub_size(MPContext *mpctx)
422 return mpctx->global_sub_size;
425 int mpctx_get_osd_function(MPContext *mpctx)
427 return mpctx->osd_function;
430 static float get_relative_time(struct MPContext *mpctx)
432 unsigned int new_time = GetTimer();
433 unsigned int delta = new_time - mpctx->last_time;
434 mpctx->last_time = new_time;
435 return delta * 0.000001;
438 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
439 switch (type)
441 /* check for valid video stream */
442 case META_VIDEO_CODEC:
443 case META_VIDEO_BITRATE:
444 case META_VIDEO_RESOLUTION:
446 if (!mpctx->sh_video)
447 return 0;
448 break;
451 /* check for valid audio stream */
452 case META_AUDIO_CODEC:
453 case META_AUDIO_BITRATE:
454 case META_AUDIO_SAMPLES:
456 if (!mpctx->sh_audio)
457 return 0;
458 break;
461 /* check for valid demuxer */
462 case META_INFO_TITLE:
463 case META_INFO_ARTIST:
464 case META_INFO_ALBUM:
465 case META_INFO_YEAR:
466 case META_INFO_COMMENT:
467 case META_INFO_TRACK:
468 case META_INFO_GENRE:
470 if (!mpctx->demuxer)
471 return 0;
472 break;
475 default:
476 break;
479 return 1;
482 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
483 char **info = mpctx->demuxer->info;
484 int n;
486 if (!info || !tag)
487 return NULL;
489 for (n = 0; info[2*n] != NULL ; n++)
490 if (!strcasecmp (info[2*n], tag))
491 break;
493 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
496 char *get_metadata(struct MPContext *mpctx, metadata_t type)
498 char *meta = NULL;
499 sh_audio_t * const sh_audio = mpctx->sh_audio;
500 sh_video_t * const sh_video = mpctx->sh_video;
502 if (!is_valid_metadata_type(mpctx, type))
503 return NULL;
505 switch (type)
507 case META_NAME:
509 return strdup (mp_basename2 (mpctx->filename));
512 case META_VIDEO_CODEC:
514 if (sh_video->format == 0x10000001)
515 meta = strdup ("mpeg1");
516 else if (sh_video->format == 0x10000002)
517 meta = strdup ("mpeg2");
518 else if (sh_video->format == 0x10000004)
519 meta = strdup ("mpeg4");
520 else if (sh_video->format == 0x10000005)
521 meta = strdup ("h264");
522 else if (sh_video->format >= 0x20202020)
524 meta = malloc (8);
525 sprintf (meta, "%.4s", (char *) &sh_video->format);
527 else
529 meta = malloc (8);
530 sprintf (meta, "0x%08X", sh_video->format);
532 return meta;
535 case META_VIDEO_BITRATE:
537 meta = malloc (16);
538 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
539 return meta;
542 case META_VIDEO_RESOLUTION:
544 meta = malloc (16);
545 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
546 return meta;
549 case META_AUDIO_CODEC:
551 if (sh_audio->codec && sh_audio->codec->name)
552 meta = strdup (sh_audio->codec->name);
553 return meta;
556 case META_AUDIO_BITRATE:
558 meta = malloc (16);
559 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
560 return meta;
563 case META_AUDIO_SAMPLES:
565 meta = malloc (16);
566 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
567 return meta;
570 /* check for valid demuxer */
571 case META_INFO_TITLE:
572 return get_demuxer_info(mpctx, "Title");
574 case META_INFO_ARTIST:
575 return get_demuxer_info(mpctx, "Artist");
577 case META_INFO_ALBUM:
578 return get_demuxer_info(mpctx, "Album");
580 case META_INFO_YEAR:
581 return get_demuxer_info(mpctx, "Year");
583 case META_INFO_COMMENT:
584 return get_demuxer_info(mpctx, "Comment");
586 case META_INFO_TRACK:
587 return get_demuxer_info(mpctx, "Track");
589 case META_INFO_GENRE:
590 return get_demuxer_info(mpctx, "Genre");
592 default:
593 break;
596 return meta;
599 static void print_file_properties(const MPContext *mpctx, const char *filename)
601 double start_pts = MP_NOPTS_VALUE;
602 double video_start_pts = MP_NOPTS_VALUE;
603 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
604 filename_recode(filename));
605 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
606 if (mpctx->sh_video) {
607 /* Assume FOURCC if all bytes >= 0x20 (' ') */
608 if (mpctx->sh_video->format >= 0x20202020)
609 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
610 else
611 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
612 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
613 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
614 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
615 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
616 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
617 video_start_pts = ds_get_next_pts(mpctx->d_video);
619 if (mpctx->sh_audio) {
620 /* Assume FOURCC if all bytes >= 0x20 (' ') */
621 if (mpctx->sh_audio->format >= 0x20202020)
622 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
623 else
624 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
625 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
626 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
627 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
628 start_pts = ds_get_next_pts(mpctx->d_audio);
630 if (video_start_pts != MP_NOPTS_VALUE) {
631 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
632 (mpctx->sh_video && video_start_pts < start_pts))
633 start_pts = video_start_pts;
635 if (start_pts != MP_NOPTS_VALUE)
636 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
637 else
638 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
639 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", mpctx->timeline ?
640 mpctx->timeline[mpctx->num_timeline_parts].start :
641 demuxer_get_time_length(mpctx->demuxer));
642 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
643 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
644 if (mpctx->demuxer) {
645 if (mpctx->demuxer->num_chapters == 0)
646 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
647 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
651 /// step size of mixer changes
652 int volstep = 3;
654 #ifdef CONFIG_DVDNAV
655 static void mp_dvdnav_context_free(MPContext *ctx){
656 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
657 ctx->nav_smpi = NULL;
658 if (ctx->nav_buffer) free(ctx->nav_buffer);
659 ctx->nav_buffer = NULL;
660 ctx->nav_start = NULL;
661 ctx->nav_in_size = 0;
663 #endif
665 void uninit_player(struct MPContext *mpctx, unsigned int mask){
666 mask &= mpctx->initialized_flags;
668 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
670 if(mask&INITIALIZED_ACODEC){
671 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
672 current_module="uninit_acodec";
673 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
674 mpctx->sh_audio=NULL;
675 mpctx->mixer.afilter = NULL;
678 if(mask&INITIALIZED_VCODEC){
679 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
680 current_module="uninit_vcodec";
681 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
682 mpctx->sh_video=NULL;
683 #ifdef CONFIG_MENU
684 vf_menu=NULL;
685 #endif
688 if(mask&INITIALIZED_DEMUXER){
689 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
690 current_module="free_demuxer";
691 if (mpctx->num_sources) {
692 mpctx->demuxer = mpctx->sources[0].demuxer;
693 for (int i = 1; i < mpctx->num_sources; i++) {
694 free_stream(mpctx->sources[i].stream);
695 free_demuxer(mpctx->sources[i].demuxer);
698 talloc_free(mpctx->sources);
699 mpctx->sources = NULL;
700 mpctx->num_sources = 0;
701 talloc_free(mpctx->timeline);
702 mpctx->timeline = NULL;
703 mpctx->num_timeline_parts = 0;
704 talloc_free(mpctx->chapters);
705 mpctx->chapters = NULL;
706 mpctx->num_chapters = 0;
707 mpctx->video_offset = 0;
708 if(mpctx->demuxer){
709 mpctx->stream=mpctx->demuxer->stream;
710 free_demuxer(mpctx->demuxer);
712 mpctx->demuxer=NULL;
715 // kill the cache process:
716 if(mask&INITIALIZED_STREAM){
717 mpctx->initialized_flags&=~INITIALIZED_STREAM;
718 current_module="uninit_stream";
719 if(mpctx->stream) free_stream(mpctx->stream);
720 mpctx->stream=NULL;
723 if(mask&INITIALIZED_VO){
724 mpctx->initialized_flags&=~INITIALIZED_VO;
725 current_module="uninit_vo";
726 vo_destroy(mpctx->video_out);
727 mpctx->video_out=NULL;
728 #ifdef CONFIG_DVDNAV
729 mp_dvdnav_context_free(mpctx);
730 #endif
733 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
734 if(mask&INITIALIZED_GETCH2){
735 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
736 current_module="uninit_getch2";
737 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
738 // restore terminal:
739 getch2_disable();
742 if(mask&INITIALIZED_VOBSUB){
743 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
744 current_module="uninit_vobsub";
745 if(vo_vobsub) vobsub_close(vo_vobsub);
746 vo_vobsub=NULL;
749 if (mask&INITIALIZED_SPUDEC){
750 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
751 current_module="uninit_spudec";
752 spudec_free(vo_spudec);
753 vo_spudec=NULL;
756 if(mask&INITIALIZED_AO){
757 mpctx->initialized_flags&=~INITIALIZED_AO;
758 current_module="uninit_ao";
759 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
760 if (mpctx->audio_out)
761 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
762 mpctx->audio_out=NULL;
765 current_module=NULL;
768 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
770 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
771 uninit_player(mpctx, INITIALIZED_ALL);
772 #if defined(__MINGW32__) || defined(__CYGWIN__)
773 timeEndPeriod(1);
774 #endif
775 #ifdef CONFIG_X11
776 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
777 #endif
779 current_module="uninit_input";
780 mp_input_uninit(mpctx->input);
781 #ifdef CONFIG_MENU
782 if (use_menu)
783 menu_uninit();
784 #endif
786 #ifdef CONFIG_FREETYPE
787 current_module="uninit_font";
788 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
789 free_font_desc(mpctx->osd->sub_font);
790 free_font_desc(vo_font);
791 vo_font = NULL;
792 done_freetype();
793 #endif
794 osd_free(mpctx->osd);
796 #ifdef CONFIG_ASS
797 ass_library_done(ass_library);
798 ass_library = NULL;
799 #endif
801 current_module="exit_player";
803 // free mplayer config
804 if(mpctx->mconfig)
805 m_config_free(mpctx->mconfig);
806 mpctx->mconfig = NULL;
808 if(mpctx->playtree_iter)
809 play_tree_iter_free(mpctx->playtree_iter);
810 mpctx->playtree_iter = NULL;
811 if(mpctx->playtree)
812 play_tree_free(mpctx->playtree, 1);
813 mpctx->playtree = NULL;
815 talloc_free(mpctx->key_fifo);
817 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
818 edl_records = NULL;
819 switch(how) {
820 case EXIT_QUIT:
821 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
822 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
823 break;
824 case EXIT_EOF:
825 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
826 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
827 break;
828 case EXIT_ERROR:
829 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
830 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
831 break;
832 default:
833 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
835 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
837 exit(rc);
840 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
842 exit_player_with_rc(mpctx, how, 1);
845 #ifndef __MINGW32__
846 static void child_sighandler(int x){
847 pid_t pid;
848 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
850 #endif
852 #ifdef CONFIG_CRASH_DEBUG
853 static char *prog_path;
854 static int crash_debug = 0;
855 #endif
857 static void exit_sighandler(int x){
858 static int sig_count=0;
859 #ifdef CONFIG_CRASH_DEBUG
860 if (!crash_debug || x != SIGTRAP)
861 #endif
862 ++sig_count;
863 if(sig_count==5)
865 /* We're crashing bad and can't uninit cleanly :(
866 * by popular request, we make one last (dirty)
867 * effort to restore the user's
868 * terminal. */
869 getch2_disable();
870 exit(1);
872 if(sig_count==6) exit(1);
873 if(sig_count>6){
874 // can't stop :(
875 #ifndef __MINGW32__
876 kill(getpid(),SIGKILL);
877 #endif
879 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
880 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
881 "\nMPlayer interrupted by signal %d in module: %s\n", x,
882 current_module ? current_module : "unknown");
883 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
884 if(sig_count<=1)
885 switch(x){
886 case SIGINT:
887 case SIGPIPE:
888 case SIGQUIT:
889 case SIGTERM:
890 case SIGKILL:
891 async_quit_request = 1;
892 return; // killed from keyboard (^C) or killed [-9]
893 case SIGILL:
894 #if CONFIG_RUNTIME_CPUDETECT
895 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
896 #else
897 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
898 #endif
899 case SIGFPE:
900 case SIGSEGV:
901 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
902 default:
903 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
904 #ifdef CONFIG_CRASH_DEBUG
905 if (crash_debug) {
906 int gdb_pid;
907 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
908 gdb_pid = fork();
909 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
910 if (gdb_pid == 0) { // We are the child
911 char spid[20];
912 snprintf(spid, sizeof(spid), "%i", getppid());
913 getch2_disable(); // allow terminal to work properly with gdb
914 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
915 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
916 } else if (gdb_pid < 0)
917 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
918 else {
919 waitpid(gdb_pid, NULL, 0);
921 if (x == SIGTRAP) return;
923 #endif
925 getch2_disable();
926 exit(1);
929 #include "cfg-mplayer.h"
931 static int cfg_include(m_option_t *conf, char *filename)
933 return m_config_parse_config_file(conf->priv, filename);
936 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
938 char *conffile;
939 int conffile_fd;
940 if (!disable_system_conf &&
941 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
942 exit_player(mpctx, EXIT_NONE);
943 if ((conffile = get_path("")) == NULL) {
944 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
945 } else {
946 #ifdef __MINGW32__
947 mkdir(conffile);
948 #else
949 mkdir(conffile, 0777);
950 #endif
951 free(conffile);
952 if ((conffile = get_path("config")) == NULL) {
953 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
954 } else {
955 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
956 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
957 write(conffile_fd, default_config, strlen(default_config));
958 close(conffile_fd);
960 if (!disable_user_conf &&
961 m_config_parse_config_file(conf, conffile) < 0)
962 exit_player(mpctx, EXIT_NONE);
963 free(conffile);
968 #define PROFILE_CFG_PROTOCOL "protocol."
970 static void load_per_protocol_config (m_config_t* conf, const char *const file)
972 char *str;
973 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
974 m_profile_t *p;
976 /* does filename actually uses a protocol ? */
977 str = strstr (file, "://");
978 if (!str)
979 return;
981 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
982 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
983 p = m_config_get_profile (conf, protocol);
984 if (p)
986 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
987 m_config_set_profile(conf,p);
991 #define PROFILE_CFG_EXTENSION "extension."
993 static void load_per_extension_config (m_config_t* conf, const char *const file)
995 char *str;
996 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
997 m_profile_t *p;
999 /* does filename actually have an extension ? */
1000 str = strrchr (file, '.');
1001 if (!str)
1002 return;
1004 sprintf (extension, PROFILE_CFG_EXTENSION);
1005 strncat (extension, ++str, 7);
1006 p = m_config_get_profile (conf, extension);
1007 if (p)
1009 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
1010 m_config_set_profile(conf,p);
1014 #define PROFILE_CFG_VO "vo."
1015 #define PROFILE_CFG_AO "ao."
1017 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
1019 char profile[strlen (cfg) + strlen (out) + 1];
1020 m_profile_t *p;
1022 sprintf (profile, "%s%s", cfg, out);
1023 p = m_config_get_profile (conf, profile);
1024 if (p)
1026 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
1027 m_config_set_profile(conf,p);
1032 * Tries to load a config file
1033 * @return 0 if file was not found, 1 otherwise
1035 static int try_load_config(m_config_t *conf, const char *file)
1037 struct stat st;
1038 if (stat(file, &st))
1039 return 0;
1040 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1041 m_config_parse_config_file (conf, file);
1042 return 1;
1045 static void load_per_file_config (m_config_t* conf, const char *const file)
1047 char *confpath;
1048 char cfg[PATH_MAX];
1049 char *name;
1051 if (strlen(file) > PATH_MAX - 14) {
1052 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1053 return;
1055 sprintf (cfg, "%s.conf", file);
1057 name = strrchr(cfg, '/');
1058 if (HAVE_DOS_PATHS) {
1059 char *tmp = strrchr(cfg, '\\');
1060 if (!name || tmp > name)
1061 name = tmp;
1062 tmp = strrchr(cfg, ':');
1063 if (!name || tmp > name)
1064 name = tmp;
1066 if (!name)
1067 name = cfg;
1068 else
1069 name++;
1071 if (use_filedir_conf) {
1072 char dircfg[PATH_MAX];
1073 strcpy(dircfg, cfg);
1074 strcpy(dircfg + (name - cfg), "mplayer.conf");
1075 try_load_config(conf, dircfg);
1077 if (try_load_config(conf, cfg))
1078 return;
1081 if ((confpath = get_path (name)) != NULL)
1083 try_load_config(conf, confpath);
1085 free (confpath);
1089 /* When libmpdemux performs a blocking operation (network connection or
1090 * cache filling) if the operation fails we use this function to check
1091 * if it was interrupted by the user.
1092 * The function returns a new value for eof. */
1093 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1095 mp_cmd_t* cmd;
1096 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1097 switch(cmd->id) {
1098 case MP_CMD_QUIT:
1099 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1100 case MP_CMD_PLAY_TREE_STEP: {
1101 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1102 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1103 } break;
1104 case MP_CMD_PLAY_TREE_UP_STEP: {
1105 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1106 } break;
1107 case MP_CMD_PLAY_ALT_SRC_STEP: {
1108 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1109 } break;
1111 mp_cmd_free(cmd);
1113 return stop_play;
1116 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1118 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1120 play_tree_add_bpf(entry,mpctx->filename);
1123 if(!entry) {
1124 entry = mpctx->playtree_iter->tree;
1125 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1126 return PT_NEXT_ENTRY;
1128 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1129 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1130 return PT_NEXT_ENTRY;
1133 play_tree_remove(entry,1,1);
1134 return PT_NEXT_SRC;
1136 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1137 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1138 entry = mpctx->playtree_iter->tree;
1139 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1140 return PT_NEXT_ENTRY;
1142 play_tree_remove(entry,1,1);
1144 return PT_NEXT_SRC;
1147 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1149 struct MPOpts *opts = &mpctx->opts;
1150 sub_data *subd = NULL;
1151 struct ass_track *asst = NULL;
1153 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1154 return;
1157 #ifdef CONFIG_ASS
1158 if (opts->ass_enabled) {
1159 #ifdef CONFIG_ICONV
1160 asst = ass_read_stream(ass_library, filename, sub_cp);
1161 #else
1162 asst = ass_read_stream(ass_library, filename, 0);
1163 #endif
1164 if (!asst) {
1165 subd = sub_read_file(filename, fps);
1166 if (subd) {
1167 asst = ass_read_subdata(ass_library, subd, fps);
1168 if (asst) {
1169 sub_free(subd);
1170 subd = NULL;
1174 } else
1175 #endif
1176 subd = sub_read_file(filename, fps);
1179 if (!asst && !subd) {
1180 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1181 "Cannot load subtitles: %s\n", filename_recode(filename));
1182 return;
1185 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1186 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1187 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1188 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1189 filename_recode(filename));
1190 ++mpctx->set_of_sub_size;
1191 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1192 filename_recode(filename));
1195 void init_vo_spudec(struct MPContext *mpctx)
1197 if (vo_spudec)
1198 spudec_free(vo_spudec);
1199 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1200 vo_spudec = NULL;
1202 // we currently can't work without video stream
1203 if (!mpctx->sh_video)
1204 return;
1206 if (spudec_ifo) {
1207 unsigned int palette[16], width, height;
1208 current_module="spudec_init_vobsub";
1209 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1210 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1213 #ifdef CONFIG_DVDREAD
1214 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1215 current_module="spudec_init_dvdread";
1216 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1217 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1218 NULL, 0);
1220 #endif
1222 #ifdef CONFIG_DVDNAV
1223 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1224 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1225 current_module="spudec_init_dvdnav";
1226 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1228 #endif
1230 if (vo_spudec==NULL) {
1231 sh_sub_t *sh = mpctx->d_sub->sh;
1232 current_module="spudec_init_normal";
1233 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1234 spudec_set_font_factor(vo_spudec,font_factor);
1237 if (vo_spudec!=NULL) {
1238 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1239 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1244 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1245 * make it all work is to use the builtin SDL-bootstrap code, which
1246 * will be done automatically by replacing our main() if we include SDL.h.
1248 #if defined(__APPLE__) && defined(CONFIG_SDL)
1249 #ifdef CONFIG_SDL_SDL_H
1250 #include <SDL/SDL.h>
1251 #else
1252 #include <SDL.h>
1253 #endif
1254 #endif
1257 * \brief append a formatted string
1258 * \param buf buffer to print into
1259 * \param pos position of terminating 0 in buf
1260 * \param len maximum number of characters in buf, not including terminating 0
1261 * \param format printf format string
1263 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1265 va_list va;
1266 va_start(va, format);
1267 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1268 va_end(va);
1269 if (*pos >= len ) {
1270 buf[len] = 0;
1271 *pos = len;
1276 * \brief append time in the hh:mm:ss.f format
1277 * \param buf buffer to print into
1278 * \param pos position of terminating 0 in buf
1279 * \param len maximum number of characters in buf, not including terminating 0
1280 * \param time time value to convert/append
1282 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1283 int64_t tenths = 10 * time;
1284 int f1 = tenths % 10;
1285 int ss = (tenths / 10) % 60;
1286 int mm = (tenths / 600) % 60;
1287 int hh = tenths / 36000;
1288 if (time <= 0) {
1289 saddf(buf, pos, len, "unknown");
1290 return;
1292 if (hh > 0)
1293 saddf(buf, pos, len, "%2d:", hh);
1294 if (hh > 0 || mm > 0)
1295 saddf(buf, pos, len, "%02d:", mm);
1296 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1299 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1301 struct MPOpts *opts = &mpctx->opts;
1302 sh_video_t * const sh_video = mpctx->sh_video;
1304 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1305 a_pos = playing_audio_pts(mpctx);
1306 if (mpctx->sh_audio && sh_video && at_frame) {
1307 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1308 if (mpctx->time_frame > 0)
1309 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1310 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1311 && !mpctx->drop_message_shown) {
1312 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1313 mpctx->drop_message_shown = true;
1316 if (quiet)
1317 return;
1320 int width;
1321 char *line;
1322 unsigned pos = 0;
1323 get_screen_size();
1324 if (screen_width > 0)
1325 width = screen_width;
1326 else
1327 width = 80;
1328 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1329 /* Windows command line is broken (MinGW's rxvt works, but we
1330 * should not depend on that). */
1331 width--;
1332 #endif
1333 line = malloc(width + 1); // one additional char for the terminating null
1335 // Audio time
1336 if (mpctx->sh_audio) {
1337 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1338 if (!sh_video) {
1339 float len = demuxer_get_time_length(mpctx->demuxer);
1340 saddf(line, &pos, width, "(");
1341 sadd_hhmmssf(line, &pos, width, a_pos);
1342 saddf(line, &pos, width, ") of %.1f (", len);
1343 sadd_hhmmssf(line, &pos, width, len);
1344 saddf(line, &pos, width, ") ");
1348 // Video time
1349 if (sh_video)
1350 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1352 // A-V sync
1353 if (mpctx->sh_audio && sh_video)
1354 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1355 mpctx->last_av_difference, mpctx->total_avsync_change);
1357 // Video stats
1358 if (sh_video)
1359 saddf(line, &pos, width, "%3d/%3d ",
1360 (int)sh_video->num_frames,
1361 (int)sh_video->num_frames_decoded);
1363 // CPU usage
1364 if (sh_video) {
1365 if (sh_video->timer > 0.5)
1366 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1367 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1368 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1369 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1370 else
1371 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1372 } else if (mpctx->sh_audio) {
1373 if (mpctx->delay > 0.5)
1374 saddf(line, &pos, width, "%4.1f%% ",
1375 100.0*audio_time_usage/(double)mpctx->delay);
1376 else
1377 saddf(line, &pos, width, "??,?%% ");
1380 // VO stats
1381 if (sh_video)
1382 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1384 #ifdef CONFIG_STREAM_CACHE
1385 // cache stats
1386 if (stream_cache_size > 0)
1387 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1388 #endif
1390 // other
1391 if (opts->playback_speed != 1)
1392 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1394 // end
1395 if (erase_to_end_of_line) {
1396 line[pos] = 0;
1397 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1398 } else {
1399 memset(&line[pos], ' ', width - pos);
1400 line[width] = 0;
1401 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1403 free(line);
1407 * \brief build a chain of audio filters that converts the input format
1408 * to the ao's format, taking into account the current playback_speed.
1409 * \param sh_audio describes the requested input format of the chain.
1410 * \param ao_data describes the requested output format of the chain.
1412 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1414 struct MPOpts *opts = &mpctx->opts;
1415 int new_srate;
1416 int result;
1417 if (!sh_audio)
1419 mpctx->mixer.afilter = NULL;
1420 return 0;
1422 if(af_control_any_rev(sh_audio->afilter,
1423 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1424 &opts->playback_speed)) {
1425 new_srate = sh_audio->samplerate;
1426 } else {
1427 new_srate = sh_audio->samplerate * opts->playback_speed;
1428 if (new_srate != ao_data->samplerate) {
1429 // limits are taken from libaf/af_resample.c
1430 if (new_srate < 8000)
1431 new_srate = 8000;
1432 if (new_srate > 192000)
1433 new_srate = 192000;
1434 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1437 result = init_audio_filters(sh_audio, new_srate,
1438 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1439 mpctx->mixer.afilter = sh_audio->afilter;
1440 return result;
1444 typedef struct mp_osd_msg mp_osd_msg_t;
1445 struct mp_osd_msg {
1446 /// Previous message on the stack.
1447 mp_osd_msg_t* prev;
1448 /// Message text.
1449 char msg[128];
1450 int id,level,started;
1451 /// Display duration in ms.
1452 unsigned time;
1455 /// OSD message stack.
1456 static mp_osd_msg_t* osd_msg_stack = NULL;
1459 * \brief Add a message on the OSD message stack
1461 * If a message with the same id is already present in the stack
1462 * it is pulled on top of the stack, otherwise a new message is created.
1465 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1466 va_list ap)
1468 mp_osd_msg_t *msg,*last=NULL;
1469 int r;
1471 // look if the id is already in the stack
1472 for(msg = osd_msg_stack ; msg && msg->id != id ;
1473 last = msg, msg = msg->prev);
1474 // not found: alloc it
1475 if(!msg) {
1476 msg = calloc(1,sizeof(mp_osd_msg_t));
1477 msg->prev = osd_msg_stack;
1478 osd_msg_stack = msg;
1479 } else if(last) { // found, but it's not on top of the stack
1480 last->prev = msg->prev;
1481 msg->prev = osd_msg_stack;
1482 osd_msg_stack = msg;
1484 // write the msg
1485 r = vsnprintf(msg->msg, 128, fmt, ap);
1486 if(r >= 128) msg->msg[127] = 0;
1487 // set id and time
1488 msg->id = id;
1489 msg->level = level;
1490 msg->time = time;
1494 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1496 va_list ap;
1497 va_start(ap, fmt);
1498 set_osd_msg_va(id, level, time, fmt, ap);
1499 va_end(ap);
1502 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1504 va_list ap;
1505 va_start(ap, fmt);
1506 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1507 va_end(ap);
1512 * \brief Remove a message from the OSD stack
1514 * This function can be used to get rid of a message right away.
1518 void rm_osd_msg(int id) {
1519 mp_osd_msg_t *msg,*last=NULL;
1521 // Search for the msg
1522 for(msg = osd_msg_stack ; msg && msg->id != id ;
1523 last = msg, msg = msg->prev);
1524 if(!msg) return;
1526 // Detach it from the stack and free it
1527 if(last)
1528 last->prev = msg->prev;
1529 else
1530 osd_msg_stack = msg->prev;
1531 free(msg);
1535 * \brief Remove all messages from the OSD stack
1539 static void clear_osd_msgs(void) {
1540 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1541 while(msg) {
1542 prev = msg->prev;
1543 free(msg);
1544 msg = prev;
1546 osd_msg_stack = NULL;
1550 * \brief Get the current message from the OSD stack.
1552 * This function decrements the message timer and destroys the old ones.
1553 * The message that should be displayed is returned (if any).
1557 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1559 struct MPOpts *opts = &mpctx->opts;
1560 mp_osd_msg_t *msg,*prev,*last = NULL;
1561 static unsigned last_update = 0;
1562 unsigned now = GetTimerMS();
1563 unsigned diff;
1564 char hidden_dec_done = 0;
1566 if (mpctx->osd_visible) {
1567 // 36000000 means max timed visibility is 1 hour into the future, if
1568 // the difference is greater assume it's wrapped around from below 0
1569 if (mpctx->osd_visible - now > 36000000) {
1570 mpctx->osd_visible = 0;
1571 vo_osd_progbar_type = -1; // disable
1572 vo_osd_changed(OSDTYPE_PROGBAR);
1573 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1576 if (mpctx->osd_show_percentage_until - now > 36000000)
1577 mpctx->osd_show_percentage_until = 0;
1579 if(!last_update) last_update = now;
1580 diff = now >= last_update ? now - last_update : 0;
1582 last_update = now;
1584 // Look for the first message in the stack with high enough level.
1585 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1586 prev = msg->prev;
1587 if (msg->level > opts->osd_level && hidden_dec_done)
1588 continue;
1589 // The message has a high enough level or it is the first hidden one
1590 // in both cases we decrement the timer or kill it.
1591 if(!msg->started || msg->time > diff) {
1592 if(msg->started) msg->time -= diff;
1593 else msg->started = 1;
1594 // display it
1595 if (msg->level <= opts->osd_level)
1596 return msg;
1597 hidden_dec_done = 1;
1598 continue;
1600 // kill the message
1601 free(msg);
1602 if(last) {
1603 last->prev = prev;
1604 msg = last;
1605 } else {
1606 osd_msg_stack = prev;
1607 msg = NULL;
1610 // Nothing found
1611 return NULL;
1615 * \brief Display the OSD bar.
1617 * Display the OSD bar or fall back on a simple message.
1621 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1622 struct MPOpts *opts = &mpctx->opts;
1623 if (opts->osd_level < 1)
1624 return;
1626 if(mpctx->sh_video) {
1627 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1628 vo_osd_progbar_type = type;
1629 vo_osd_progbar_value = 256*(val-min)/(max-min);
1630 vo_osd_changed(OSDTYPE_PROGBAR);
1631 return;
1634 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1635 name, ROUND(100*(val-min)/(max-min)));
1639 * \brief Display text subtitles on the OSD
1641 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1643 int i;
1644 vo_sub = subs;
1645 vo_osd_changed(OSDTYPE_SUBTITLE);
1646 if (!mpctx->sh_video) {
1647 // reverse order, since newest set_osd_msg is displayed first
1648 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1649 if (!subs || i >= subs->lines || !subs->text[i])
1650 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1651 else {
1652 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1653 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1654 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1661 * \brief Update the OSD message line.
1663 * This function displays the current message on the vo OSD or on the term.
1664 * If the stack is empty and the OSD level is high enough the timer
1665 * is displayed (only on the vo OSD).
1669 static void update_osd_msg(struct MPContext *mpctx)
1671 struct MPOpts *opts = &mpctx->opts;
1672 mp_osd_msg_t *msg;
1673 struct osd_state *osd = mpctx->osd;
1674 char osd_text_timer[128];
1676 if (mpctx->add_osd_seek_info) {
1677 double percentage;
1678 if (mpctx->timeline && mpctx->sh_video)
1679 percentage = mpctx->sh_video->pts * 100 /
1680 mpctx->timeline[mpctx->num_timeline_parts].start;
1681 else
1682 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1683 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1684 if (mpctx->sh_video)
1685 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1686 mpctx->add_osd_seek_info = false;
1689 // Look if we have a msg
1690 if((msg = get_osd_msg(mpctx))) {
1691 if (strcmp(osd->osd_text, msg->msg)) {
1692 strncpy(osd->osd_text, msg->msg, 127);
1693 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1694 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1696 return;
1699 if(mpctx->sh_video) {
1700 // fallback on the timer
1701 if (opts->osd_level >= 2) {
1702 int len;
1703 if (mpctx->timeline)
1704 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1705 else
1706 len = demuxer_get_time_length(mpctx->demuxer);
1707 int percentage = -1;
1708 char percentage_text[10];
1709 int pts = demuxer_get_current_time(mpctx->demuxer);
1711 if (mpctx->osd_show_percentage_until) {
1712 if (mpctx->timeline)
1713 percentage = mpctx->sh_video->pts * 100 /
1714 mpctx->timeline[mpctx->num_timeline_parts].start;
1715 else
1716 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1719 if (percentage >= 0)
1720 snprintf(percentage_text, 9, " (%d%%)", percentage);
1721 else
1722 percentage_text[0] = 0;
1724 if (opts->osd_level == 3)
1725 snprintf(osd_text_timer, 63,
1726 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1727 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1728 len/3600,(len/60)%60,len%60,percentage_text);
1729 else
1730 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1731 mpctx->osd_function,pts/3600,(pts/60)%60,
1732 pts%60,percentage_text);
1733 } else
1734 osd_text_timer[0]=0;
1736 if (strcmp(osd->osd_text, osd_text_timer)) {
1737 strncpy(osd->osd_text, osd_text_timer, 63);
1738 vo_osd_changed(OSDTYPE_OSD);
1740 return;
1743 // Clear the term osd line
1744 if (term_osd && osd->osd_text[0]) {
1745 osd->osd_text[0] = 0;
1746 printf("%s\n",term_osd_esc);
1750 ///@}
1751 // OSDMsgStack
1754 void reinit_audio_chain(struct MPContext *mpctx)
1756 struct MPOpts *opts = &mpctx->opts;
1757 if (!mpctx->sh_audio)
1758 return;
1759 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1760 current_module="init_audio_codec";
1761 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1762 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1763 goto init_error;
1765 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1766 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1770 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1771 current_module="af_preinit";
1772 ao_data.samplerate=force_srate;
1773 ao_data.channels=0;
1774 ao_data.format = opts->audio_output_format;
1775 // first init to detect best values
1776 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1777 // input:
1778 mpctx->sh_audio->samplerate,
1779 // output:
1780 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1781 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1782 "pre-init!\n");
1783 exit_player(mpctx, EXIT_ERROR);
1785 current_module="ao2_init";
1786 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1787 0, // plugin flag
1788 ao_data.samplerate,
1789 ao_data.channels,
1790 ao_data.format, 0);
1791 if(!mpctx->audio_out){
1792 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1793 goto init_error;
1795 mpctx->initialized_flags|=INITIALIZED_AO;
1796 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1797 mpctx->audio_out->info->short_name,
1798 ao_data.samplerate, ao_data.channels,
1799 af_fmt2str_short(ao_data.format),
1800 af_fmt2bits(ao_data.format)/8 );
1801 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1802 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1803 if(strlen(mpctx->audio_out->info->comment) > 0)
1804 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1807 // init audio filters:
1808 current_module="af_init";
1809 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1810 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1811 goto init_error;
1813 mpctx->mixer.audio_out = mpctx->audio_out;
1814 mpctx->mixer.volstep = volstep;
1815 return;
1817 init_error:
1818 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1819 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1820 mpctx->d_audio->id = -2;
1824 ///@}
1825 // Command2Property
1828 // Return pts value corresponding to the end point of audio written to the
1829 // ao so far.
1830 static double written_audio_pts(struct MPContext *mpctx)
1832 sh_audio_t *sh_audio = mpctx->sh_audio;
1833 demux_stream_t *d_audio = mpctx->d_audio;
1834 double buffered_output;
1835 // first calculate the end pts of audio that has been output by decoder
1836 double a_pts = sh_audio->pts;
1837 if (a_pts != MP_NOPTS_VALUE)
1838 // Good, decoder supports new way of calculating audio pts.
1839 // sh_audio->pts is the timestamp of the latest input packet with
1840 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1841 // the amount of bytes the decoder has written after that timestamp.
1842 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1843 else {
1844 // Decoder doesn't support new way of calculating pts (or we're
1845 // being called before it has decoded anything with known timestamp).
1846 // Use the old method of audio pts calculation: take the timestamp
1847 // of last packet with known pts the decoder has read data from,
1848 // and add amount of bytes read after the beginning of that packet
1849 // divided by input bps. This will be inaccurate if the input/output
1850 // ratio is not constant for every audio packet or if it is constant
1851 // but not accurately known in sh_audio->i_bps.
1853 a_pts = d_audio->pts;
1854 // ds_tell_pts returns bytes read after last timestamp from
1855 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1856 // it has read but not decoded
1857 if (sh_audio->i_bps)
1858 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1859 (double)sh_audio->i_bps;
1861 // Now a_pts hopefully holds the pts for end of audio from decoder.
1862 // Substract data in buffers between decoder and audio out.
1864 // Decoded but not filtered
1865 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1867 // Data buffered in audio filters, measured in bytes of "missing" output
1868 buffered_output = af_calc_delay(sh_audio->afilter);
1870 // Data that was ready for ao but was buffered because ao didn't fully
1871 // accept everything to internal buffers yet
1872 buffered_output += sh_audio->a_out_buffer_len;
1874 // Filters divide audio length by playback_speed, so multiply by it
1875 // to get the length in original units without speedup or slowdown
1876 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1878 return a_pts + mpctx->video_offset;
1881 // Return pts value corresponding to currently playing audio.
1882 double playing_audio_pts(struct MPContext *mpctx)
1884 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1885 mpctx->audio_out->get_delay();
1888 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1889 struct MPOpts *opts = &mpctx->opts;
1890 // check for frame-drop:
1891 current_module = "check_framedrop";
1892 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1893 static int dropped_frames;
1894 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1895 float d = delay-mpctx->delay;
1896 ++total_frame_cnt;
1897 // we should avoid dropping too many frames in sequence unless we
1898 // are too late. and we allow 100ms A-V delay here:
1899 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1900 && !mpctx->update_video_immediately) {
1901 ++drop_frame_cnt;
1902 ++dropped_frames;
1903 return frame_dropping;
1904 } else
1905 dropped_frames = 0;
1907 return 0;
1911 #ifdef HAVE_RTC
1912 int rtc_fd = -1;
1913 #endif
1915 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1917 #ifdef HAVE_RTC
1918 if (rtc_fd >= 0){
1919 // -------- RTC -----------
1920 current_module="sleep_rtc";
1921 while (time_frame > 0.000) {
1922 unsigned long rtc_ts;
1923 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1924 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1925 time_frame -= get_relative_time(mpctx);
1927 } else
1928 #endif
1930 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1931 // unnecessarily high CPU usage
1932 float margin = softsleep ? 0.011 : 0;
1933 current_module = "sleep_timer";
1934 while (time_frame > margin) {
1935 usec_sleep(1000000 * (time_frame - margin));
1936 time_frame -= get_relative_time(mpctx);
1938 if (softsleep){
1939 current_module = "sleep_soft";
1940 if (time_frame < 0)
1941 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1942 while (time_frame > 0)
1943 time_frame -= get_relative_time(mpctx); // burn the CPU
1946 return time_frame;
1949 static int select_subtitle(MPContext *mpctx)
1951 struct MPOpts *opts = &mpctx->opts;
1952 // find the best sub to use
1953 int id;
1954 int found = 0;
1955 mpctx->global_sub_pos = -1; // no subs by default
1956 if (vobsub_id >= 0) {
1957 // if user asks for a vobsub id, use that first.
1958 id = vobsub_id;
1959 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1962 if (!found && opts->sub_id >= 0) {
1963 // if user asks for a dvd sub id, use that next.
1964 id = opts->sub_id;
1965 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1968 if (!found) {
1969 // if there are text subs to use, use those. (autosubs come last here)
1970 id = 0;
1971 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1974 if (!found && opts->sub_id == -1) {
1975 // finally select subs by language and container hints
1976 if (opts->sub_id == -1 && opts->sub_lang)
1977 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, opts->sub_lang);
1978 if (opts->sub_id == -1)
1979 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
1980 if (opts->sub_id >= 0) {
1981 id = opts->sub_id;
1982 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1985 return found;
1988 #ifdef CONFIG_DVDNAV
1989 #ifndef FF_B_TYPE
1990 #define FF_B_TYPE 3
1991 #endif
1992 /// store decoded video image
1993 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1994 mp_image_t *from_mpi) {
1995 mp_image_t *mpi;
1997 /// Do not store B-frames
1998 if (from_mpi->pict_type == FF_B_TYPE)
1999 return to_mpi;
2001 if (to_mpi &&
2002 to_mpi->w == from_mpi->w &&
2003 to_mpi->h == from_mpi->h &&
2004 to_mpi->imgfmt == from_mpi->imgfmt)
2005 mpi = to_mpi;
2006 else {
2007 if (to_mpi)
2008 free_mp_image(to_mpi);
2009 if (from_mpi->w == 0 || from_mpi->h == 0)
2010 return NULL;
2011 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2014 copy_mpi(mpi,from_mpi);
2015 return mpi;
2018 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2019 struct MPOpts *opts = &ctx->opts;
2020 if (ctx->sh_video) {
2021 /// clear video pts
2022 ctx->d_video->pts = 0.0f;
2023 ctx->sh_video->pts = 0.0f;
2024 ctx->sh_video->i_pts = 0.0f;
2025 ctx->sh_video->last_pts = 0.0f;
2026 ctx->sh_video->num_buffered_pts = 0;
2027 ctx->sh_video->num_frames = 0;
2028 ctx->sh_video->num_frames_decoded = 0;
2029 ctx->sh_video->timer = 0.0f;
2030 ctx->sh_video->stream_delay = 0.0f;
2031 ctx->sh_video->timer = 0;
2032 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2035 if (ctx->sh_audio) {
2036 /// free audio packets and reset
2037 ds_free_packs(ctx->d_audio);
2038 audio_delay -= ctx->sh_audio->stream_delay;
2039 ctx->delay =- audio_delay;
2040 ctx->audio_out->reset();
2041 resync_audio_stream(ctx->sh_audio);
2044 audio_delay = 0.0f;
2045 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2046 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2047 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2048 if (dvdsub_lang_id != opts->sub_id) {
2049 opts->sub_id = dvdsub_lang_id;
2050 select_subtitle(ctx);
2054 /// clear all EOF related flags
2055 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2058 /// Restore last decoded DVDNAV (still frame)
2059 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2060 int *in_size,
2061 unsigned char **start,
2062 mp_image_t *decoded_frame)
2064 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2065 return decoded_frame;
2067 /// a change occured in dvdnav stream
2068 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2069 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2070 mp_dvdnav_context_free(mpctx);
2071 mp_dvdnav_reset_stream(mpctx);
2072 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2073 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2076 if (*in_size < 0) {
2077 float len;
2079 /// Display still frame, if any
2080 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2081 decoded_frame = mpctx->nav_smpi;
2083 /// increment video frame : continue playing after still frame
2084 len = demuxer_get_time_length(mpctx->demuxer);
2085 if (mpctx->sh_video->pts >= len &&
2086 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2087 mp_dvdnav_skip_still(mpctx->stream);
2088 mp_dvdnav_skip_wait(mpctx->stream);
2090 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2092 if (mpctx->nav_buffer) {
2093 *start = mpctx->nav_start;
2094 *in_size = mpctx->nav_in_size;
2095 if (mpctx->nav_start)
2096 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2100 return decoded_frame;
2103 /// Save last decoded DVDNAV (still frame)
2104 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2105 unsigned char *start,
2106 mp_image_t *decoded_frame)
2108 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2109 return;
2111 if (mpctx->nav_buffer)
2112 free(mpctx->nav_buffer);
2114 mpctx->nav_buffer = malloc(in_size);
2115 mpctx->nav_start = start;
2116 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2117 if (mpctx->nav_buffer)
2118 memcpy(mpctx->nav_buffer,start,in_size);
2120 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2121 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2123 #endif /* CONFIG_DVDNAV */
2125 /* Modify video timing to match the audio timeline. There are two main
2126 * reasons this is needed. First, video and audio can start from different
2127 * positions at beginning of file or after a seek (MPlayer starts both
2128 * immediately even if they have different pts). Second, the file can have
2129 * audio timestamps that are inconsistent with the duration of the audio
2130 * packets, for example two consecutive timestamp values differing by
2131 * one second but only a packet with enough samples for half a second
2132 * of playback between them.
2134 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2136 current_module = "av_sync";
2138 if (!mpctx->sh_audio)
2139 return;
2141 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2142 double v_pts = mpctx->sh_video->pts;
2143 double av_delay = a_pts - v_pts;
2144 // Try to sync vo_flip() so it will *finish* at given time
2145 av_delay += mpctx->last_vo_flip_duration;
2146 av_delay -= audio_delay; // This much pts difference is desired
2148 double change = av_delay * 0.1;
2149 double max_change = default_max_pts_correction >= 0 ?
2150 default_max_pts_correction : frame_time * 0.1;
2151 if (change < -max_change)
2152 change = -max_change;
2153 else if (change > max_change)
2154 change = max_change;
2155 mpctx->delay += change;
2156 mpctx->total_avsync_change += change;
2159 static int fill_audio_out_buffers(struct MPContext *mpctx)
2161 struct MPOpts *opts = &mpctx->opts;
2162 unsigned int t;
2163 double tt;
2164 int playsize;
2165 int playflags=0;
2166 int audio_eof=0;
2167 bool format_change = false;
2168 sh_audio_t * const sh_audio = mpctx->sh_audio;
2170 current_module="play_audio";
2172 while (1) {
2173 int sleep_time;
2174 // all the current uses of ao_data.pts seem to be in aos that handle
2175 // sync completely wrong; there should be no need to use ao_data.pts
2176 // in get_space()
2177 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2178 playsize = mpctx->audio_out->get_space();
2179 if (mpctx->sh_video || playsize >= ao_data.outburst)
2180 break;
2182 // handle audio-only case:
2183 // this is where mplayer sleeps during audio-only playback
2184 // to avoid 100% CPU use
2185 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2186 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2187 usec_sleep(sleep_time * 1000);
2190 // Fill buffer if needed:
2191 current_module="decode_audio";
2192 t = GetTimer();
2193 int res = decode_audio(sh_audio, playsize);
2194 if (res < 0) { // EOF, error or format change
2195 if (res == -2)
2196 format_change = true;
2197 else if (mpctx->d_audio->eof) {
2198 audio_eof = 1;
2199 if (sh_audio->a_out_buffer_len == 0)
2200 return 0;
2203 t = GetTimer() - t;
2204 tt = t*0.000001f; audio_time_usage+=tt;
2205 if (playsize > sh_audio->a_out_buffer_len) {
2206 playsize = sh_audio->a_out_buffer_len;
2207 if (audio_eof)
2208 playflags |= AOPLAY_FINAL_CHUNK;
2210 if (!playsize)
2211 return 1;
2213 // play audio:
2214 current_module="play_audio";
2216 // Is this pts value actually useful for the aos that access it?
2217 // They're obviously badly broken in the way they handle av sync;
2218 // would not having access to this make them more broken?
2219 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2220 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2222 if (playsize > 0) {
2223 sh_audio->a_out_buffer_len -= playsize;
2224 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2225 sh_audio->a_out_buffer_len);
2226 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2228 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2229 // Sanity check to avoid hanging in case current ao doesn't output
2230 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2231 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2232 sh_audio->a_out_buffer_len = 0;
2235 /* The format change isn't handled too gracefully. A more precise
2236 * implementation would require draining buffered old-format audio
2237 * while displaying video, then doing the output format switch.
2239 if (format_change) {
2240 uninit_player(mpctx, INITIALIZED_AO);
2241 reinit_audio_chain(mpctx);
2244 return 1;
2247 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2248 float *aq_sleep_time)
2250 struct MPOpts *opts = &mpctx->opts;
2251 int frame_time_remaining = 0;
2252 current_module="calc_sleep_time";
2254 *time_frame -= get_relative_time(mpctx); // reset timer
2256 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2257 float delay = mpctx->audio_out->get_delay();
2258 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2260 if (autosync) {
2262 * Adjust this raw delay value by calculating the expected
2263 * delay for this frame and generating a new value which is
2264 * weighted between the two. The higher autosync is, the
2265 * closer to the delay value gets to that which "-nosound"
2266 * would have used, and the longer it will take for A/V
2267 * sync to settle at the right value (but it eventually will.)
2268 * This settling time is very short for values below 100.
2270 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2271 float difference = delay - predicted;
2272 delay = predicted + difference / (float)autosync;
2275 *time_frame = delay - mpctx->delay / opts->playback_speed;
2276 *time_frame -= mpctx->video_out->flip_queue_offset;
2278 // delay = amount of audio buffered in soundcard/driver
2279 if (delay > 0.25) delay=0.25; else
2280 if (delay < 0.10) delay=0.10;
2282 if (*time_frame > delay*0.6) {
2283 // sleep time too big - may cause audio drops (buffer underrun)
2284 frame_time_remaining = 1;
2285 *time_frame = delay*0.5;
2287 } else {
2288 // If we're lagging more than 200 ms behind the right playback rate,
2289 // don't try to "catch up".
2290 // If benchmark is set always output frames as fast as possible
2291 // without sleeping.
2292 if (*time_frame < -0.2 || benchmark)
2293 *time_frame = 0;
2294 *time_frame -= mpctx->video_out->flip_queue_offset;
2297 *aq_sleep_time += *time_frame;
2300 //============================== SLEEP: ===================================
2302 // flag 256 means: libvo driver does its timing (dvb card)
2303 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2304 *time_frame = timing_sleep(mpctx, *time_frame);
2305 *time_frame += mpctx->video_out->flip_queue_offset;
2306 return frame_time_remaining;
2309 int reinit_video_chain(struct MPContext *mpctx)
2311 struct MPOpts *opts = &mpctx->opts;
2312 sh_video_t * const sh_video = mpctx->sh_video;
2313 double ar=-1.0;
2314 //================== Init VIDEO (codec & libvo) ==========================
2315 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2316 current_module="preinit_libvo";
2318 //shouldn't we set dvideo->id=-2 when we fail?
2319 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2320 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2321 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2322 goto err_out;
2324 mpctx->initialized_flags|=INITIALIZED_VO;
2327 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2328 mpctx->sh_video->stream_aspect = ar;
2329 current_module="init_video_filters";
2331 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2332 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2334 #ifdef CONFIG_MENU
2335 if(use_menu) {
2336 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2337 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2338 if(!vf_menu) {
2339 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2340 use_menu = 0;
2343 if(vf_menu)
2344 sh_video->vfilter = vf_menu;
2345 #endif
2347 #ifdef CONFIG_ASS
2348 if(opts->ass_enabled) {
2349 int i;
2350 int insert = 1;
2351 if (opts->vf_settings)
2352 for (i = 0; opts->vf_settings[i].name; ++i)
2353 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2354 insert = 0;
2355 break;
2357 if (insert) {
2358 extern vf_info_t vf_info_ass;
2359 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2360 char* vf_arg[] = {"auto", "1", NULL};
2361 int retcode = 0;
2362 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2363 sh_video->vfilter,
2364 "ass", vf_arg,
2365 &retcode);
2366 if (vf_ass)
2367 sh_video->vfilter = vf_ass;
2368 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2369 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2370 else
2371 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2374 #endif
2376 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2378 #ifdef CONFIG_ASS
2379 if (opts->ass_enabled)
2380 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2381 #endif
2383 current_module="init_video_codec";
2385 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2386 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2387 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2389 if(!sh_video->initialized){
2390 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2391 goto err_out;
2394 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2396 if (sh_video->codec)
2397 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2399 sh_video->last_pts = MP_NOPTS_VALUE;
2400 sh_video->num_buffered_pts = 0;
2401 sh_video->next_frame_time = 0;
2403 if(auto_quality>0){
2404 // Auto quality option enabled
2405 output_quality=get_video_quality_max(sh_video);
2406 if(auto_quality>output_quality) auto_quality=output_quality;
2407 else output_quality=auto_quality;
2408 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2409 set_video_quality(sh_video,output_quality);
2412 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2414 current_module="init_vo";
2416 return 1;
2418 err_out:
2419 mpctx->sh_video = mpctx->d_video->sh = NULL;
2420 return 0;
2423 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2425 struct sh_video *sh_video = mpctx->sh_video;
2426 double frame_time = 0;
2427 struct vo *video_out = mpctx->video_out;
2428 while (!video_out->frame_loaded) {
2429 current_module = "filter_video";
2430 // In nocorrect-pts mode there is no way to properly time these frames
2431 if (vo_get_buffered_frame(video_out, 0) >= 0)
2432 break;
2433 if (vf_output_queued_frame(sh_video->vfilter))
2434 continue;
2435 unsigned char *packet = NULL;
2436 frame_time = sh_video->next_frame_time;
2437 if (mpctx->update_video_immediately)
2438 frame_time = 0;
2439 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2440 &packet, force_fps);
2441 if (in_size < 0) {
2442 #ifdef CONFIG_DVDNAV
2443 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2444 if (mp_dvdnav_is_eof(mpctx->stream))
2445 return -1;
2446 if (mpctx->d_video)
2447 mpctx->d_video->eof = 0;
2448 if (mpctx->d_audio)
2449 mpctx->d_audio->eof = 0;
2450 mpctx->stream->eof = 0;
2451 } else
2452 #endif
2453 return -1;
2455 if (in_size > max_framesize)
2456 max_framesize = in_size;
2457 sh_video->timer += frame_time;
2458 if (mpctx->sh_audio)
2459 mpctx->delay -= frame_time;
2460 // video_read_frame can change fps (e.g. for ASF video)
2461 vo_fps = sh_video->fps;
2462 int framedrop_type = check_framedrop(mpctx, frame_time);
2463 current_module = "decode video";
2465 void *decoded_frame;
2466 #ifdef CONFIG_DVDNAV
2467 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2468 if (in_size >= 0 && !decoded_frame)
2469 #endif
2470 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2471 sh_video->pts);
2472 #ifdef CONFIG_DVDNAV
2473 // Save last still frame for future display
2474 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2475 #endif
2476 if (decoded_frame) {
2477 current_module = "filter video";
2478 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2479 if (!video_out->config_ok)
2480 break;
2483 return frame_time;
2486 static void determine_frame_pts(struct MPContext *mpctx)
2488 struct sh_video *sh_video = mpctx->sh_video;
2489 struct MPOpts *opts = &mpctx->opts;
2491 if (opts->user_pts_assoc_mode) {
2492 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2493 } else if (sh_video->pts_assoc_mode == 0) {
2494 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2495 sh_video->pts_assoc_mode = 1;
2496 else
2497 sh_video->pts_assoc_mode = 2;
2498 } else {
2499 int probcount1 = sh_video->num_reordered_pts_problems;
2500 int probcount2 = sh_video->num_sorted_pts_problems;
2501 if (sh_video->pts_assoc_mode == 2) {
2502 int tmp = probcount1;
2503 probcount1 = probcount2;
2504 probcount2 = tmp;
2506 if (probcount1 >= probcount2 * 1.5 + 2) {
2507 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2508 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2509 "%d.\n", sh_video->pts_assoc_mode);
2512 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2513 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2516 static double update_video(struct MPContext *mpctx)
2518 struct sh_video *sh_video = mpctx->sh_video;
2519 struct vo *video_out = mpctx->video_out;
2520 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2521 mpctx->osd); // hack for vf_expand
2522 if (!mpctx->opts.correct_pts)
2523 return update_video_nocorrect_pts(mpctx);
2525 double pts;
2527 bool hit_eof = false;
2528 while (!video_out->frame_loaded) {
2529 current_module = "filter_video";
2530 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2531 break;
2532 // XXX Time used in this call is not counted in any performance
2533 // timer now, OSD time is not updated correctly for filter-added frames
2534 if (vf_output_queued_frame(sh_video->vfilter))
2535 continue;
2536 if (hit_eof)
2537 return -1;
2538 unsigned char *packet = NULL;
2539 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2540 if (pts != MP_NOPTS_VALUE)
2541 pts += mpctx->video_offset;
2542 if (in_size < 0) {
2543 // try to extract last frames in case of decoder lag
2544 in_size = 0;
2545 pts = MP_NOPTS_VALUE;
2546 hit_eof = true;
2548 if (in_size > max_framesize)
2549 max_framesize = in_size;
2550 current_module = "decode video";
2551 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2552 void *decoded_frame = decode_video(sh_video, packet, in_size,
2553 framedrop_type, pts);
2554 if (decoded_frame) {
2555 determine_frame_pts(mpctx);
2556 current_module = "filter video";
2557 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2558 if (!video_out->config_ok)
2559 break; // We'd likely hang in this loop otherwise
2563 pts = video_out->next_pts;
2564 if (pts == MP_NOPTS_VALUE) {
2565 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2566 // Try to use decoder pts from before filters
2567 pts = sh_video->pts;
2568 if (pts == MP_NOPTS_VALUE)
2569 pts = sh_video->last_pts;
2571 sh_video->pts = pts;
2572 if (sh_video->last_pts == MP_NOPTS_VALUE)
2573 sh_video->last_pts = sh_video->pts;
2574 else if (sh_video->last_pts > sh_video->pts) {
2575 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2576 sh_video->pts, sh_video->last_pts);
2577 /* If the difference in pts is small treat it as jitter around the
2578 * right value (possibly caused by incorrect timestamp ordering) and
2579 * just show this frame immediately after the last one.
2580 * Treat bigger differences as timestamp resets and start counting
2581 * timing of later frames from the position of this one. */
2582 if (sh_video->last_pts - sh_video->pts > 0.5)
2583 sh_video->last_pts = sh_video->pts;
2584 else
2585 sh_video->pts = sh_video->last_pts;
2587 double frame_time = sh_video->pts - sh_video->last_pts;
2588 sh_video->last_pts = sh_video->pts;
2589 sh_video->timer += frame_time;
2590 if (mpctx->sh_audio)
2591 mpctx->delay -= frame_time;
2592 return frame_time;
2595 void pause_player(struct MPContext *mpctx)
2597 if (mpctx->paused)
2598 return;
2599 mpctx->paused = 1;
2600 mpctx->step_frames = 0;
2601 mpctx->time_frame -= get_relative_time(mpctx);
2603 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2604 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2606 if (mpctx->audio_out && mpctx->sh_audio)
2607 mpctx->audio_out->pause(); // pause audio, keep data if possible
2610 void unpause_player(struct MPContext *mpctx)
2612 if (!mpctx->paused)
2613 return;
2614 mpctx->paused = 0;
2616 if (mpctx->audio_out && mpctx->sh_audio)
2617 mpctx->audio_out->resume(); // resume audio
2618 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2619 && !mpctx->step_frames)
2620 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2621 (void)get_relative_time(mpctx); // ignore time that passed during pause
2624 void add_step_frame(struct MPContext *mpctx)
2626 mpctx->step_frames++;
2627 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2628 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2629 unpause_player(mpctx);
2632 static void pause_loop(struct MPContext *mpctx)
2634 mp_cmd_t* cmd;
2635 if (!quiet) {
2636 // Small hack to display the pause message on the OSD line.
2637 // The pause string is: "\n == PAUSE == \r" so we need to
2638 // take the first and the last char out
2639 if (term_osd && !mpctx->sh_video) {
2640 char msg[128] = _("\n ===== PAUSE =====\r");
2641 int mlen = strlen(msg);
2642 msg[mlen-1] = '\0';
2643 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2644 update_osd_msg(mpctx);
2645 } else
2646 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2647 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2650 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2651 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2652 if (cmd) {
2653 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2654 run_command(mpctx, cmd);
2655 mp_cmd_free(cmd);
2656 continue;
2658 if (mpctx->sh_video && mpctx->video_out)
2659 vo_check_events(mpctx->video_out);
2660 #ifdef CONFIG_MENU
2661 if (vf_menu)
2662 vf_menu_pause_update(vf_menu);
2663 #endif
2664 usec_sleep(20000);
2665 update_osd_msg(mpctx);
2666 int hack = vo_osd_changed(0);
2667 vo_osd_changed(hack);
2668 if (hack)
2669 break;
2674 // Find the right mute status and record position for new file position
2675 static void edl_seek_reset(MPContext *mpctx)
2677 mpctx->edl_muted = 0;
2678 next_edl_record = edl_records;
2680 while (next_edl_record) {
2681 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2682 break;
2684 if (next_edl_record->action == EDL_MUTE)
2685 mpctx->edl_muted = !mpctx->edl_muted;
2686 next_edl_record = next_edl_record->next;
2688 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2689 mixer_mute(&mpctx->mixer);
2693 // Execute EDL command for the current position if one exists
2694 static void edl_update(MPContext *mpctx)
2696 if (!next_edl_record)
2697 return;
2699 if (!mpctx->sh_video) {
2700 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2701 free_edl(edl_records);
2702 next_edl_record = NULL;
2703 edl_records = NULL;
2704 return;
2707 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2708 if (next_edl_record->action == EDL_SKIP) {
2709 mpctx->osd_function = OSD_FFW;
2710 mpctx->abs_seek_pos = 0;
2711 mpctx->rel_seek_secs = next_edl_record->length_sec;
2712 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2713 "[%f], length [%f]\n", next_edl_record->start_sec,
2714 next_edl_record->stop_sec, next_edl_record->length_sec);
2716 else if (next_edl_record->action == EDL_MUTE) {
2717 mpctx->edl_muted = !mpctx->edl_muted;
2718 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2719 mixer_mute(&mpctx->mixer);
2720 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2721 next_edl_record->start_sec );
2723 next_edl_record = next_edl_record->next;
2727 static void reinit_decoders(struct MPContext *mpctx)
2729 reinit_video_chain(mpctx);
2730 reinit_audio_chain(mpctx);
2731 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2734 static void seek_reset(struct MPContext *mpctx)
2736 if (mpctx->sh_video) {
2737 current_module = "seek_video_reset";
2738 resync_video_stream(mpctx->sh_video);
2739 mpctx->sh_video->timer = 0;
2740 vo_seek_reset(mpctx->video_out);
2741 mpctx->sh_video->timer = 0;
2742 mpctx->sh_video->num_buffered_pts = 0;
2743 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2744 mpctx->delay = 0;
2745 mpctx->time_frame = 0;
2746 mpctx->update_video_immediately = true;
2747 // Not all demuxers set d_video->pts during seek, so this value
2748 // (which is used by at least vobsub and edl code below) may
2749 // be completely wrong (probably 0).
2750 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2751 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2752 mpctx->sh_video->pts, mpctx->video_offset,
2753 mpctx->d_sub, 1);
2754 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2757 if (mpctx->sh_audio) {
2758 current_module = "seek_audio_reset";
2759 resync_audio_stream(mpctx->sh_audio);
2760 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2761 mpctx->sh_audio->a_buffer_len = 0;
2762 mpctx->sh_audio->a_out_buffer_len = 0;
2763 if (!mpctx->sh_video)
2764 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2765 mpctx->video_offset, mpctx->d_sub, 1);
2768 if (vo_vobsub && mpctx->sh_video) {
2769 current_module = "seek_vobsub_reset";
2770 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2773 edl_seek_reset(mpctx);
2775 mpctx->total_avsync_change = 0;
2776 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2777 drop_frame_cnt = 0;
2779 current_module = NULL;
2782 static bool timeline_set_part(struct MPContext *mpctx, int i)
2784 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2785 struct timeline_part *n = mpctx->timeline + i;
2786 mpctx->timeline_part = i;
2787 mpctx->video_offset = n->start - n->source_start;
2788 if (n->source == p->source)
2789 return false;
2790 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2791 mpctx->demuxer = n->source->demuxer;
2792 mpctx->d_video = mpctx->demuxer->video;
2793 mpctx->d_audio = mpctx->demuxer->audio;
2794 mpctx->d_sub = mpctx->demuxer->sub;
2795 mpctx->sh_video = mpctx->d_video->sh;
2796 mpctx->sh_audio = mpctx->d_audio->sh;
2797 return true;
2800 // Given pts, switch playback to the corresponding part.
2801 // Return offset within that part.
2802 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2803 bool *need_reset)
2805 if (pts < 0)
2806 pts = 0;
2807 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2808 struct timeline_part *p = mpctx->timeline + i;
2809 if (pts < (p+1)->start) {
2810 *need_reset = timeline_set_part(mpctx, i);
2811 return pts - p->start + p->source_start;
2814 return -1;
2818 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2819 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2820 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2821 static int seek(MPContext *mpctx, double amount, int style)
2823 current_module = "seek";
2824 if (mpctx->stop_play == AT_END_OF_FILE)
2825 mpctx->stop_play = KEEP_PLAYING;
2826 if (style & SEEK_FACTOR
2827 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2828 || amount < 0)
2829 mpctx->last_chapter_seek = -1;
2830 if (mpctx->timeline && style & SEEK_FACTOR) {
2831 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2832 style &= ~SEEK_FACTOR;
2834 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2835 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2836 style |= SEEK_ABSOLUTE;
2837 if (amount > 0)
2838 style |= SEEK_FORWARD;
2839 else
2840 style |= SEEK_BACKWARD;
2841 amount += mpctx->sh_video->pts;
2844 /* At least the liba52 decoder wants to read from the input stream
2845 * during initialization, so reinit must be done after the demux_seek()
2846 * call that clears possible stream EOF. */
2847 bool need_reset = false;
2848 if (mpctx->timeline) {
2849 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2850 if (amount == -1) {
2851 mpctx->stop_play = AT_END_OF_FILE;
2852 // Clear audio from current position
2853 if (mpctx->sh_audio) {
2854 mpctx->audio_out->reset();
2855 mpctx->sh_audio->a_buffer_len = 0;
2856 mpctx->sh_audio->a_out_buffer_len = 0;
2858 return -1;
2861 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2862 if (need_reset)
2863 reinit_decoders(mpctx);
2864 if (seekresult == 0)
2865 return -1;
2867 seek_reset(mpctx);
2868 return 0;
2871 // -2 is no chapters, -1 is before first chapter
2872 int get_current_chapter(struct MPContext *mpctx)
2874 if (!mpctx->chapters || !mpctx->sh_video)
2875 return FFMAX(mpctx->last_chapter_seek,
2876 demuxer_get_current_chapter(mpctx->demuxer));
2878 int i;
2879 double current_pts = mpctx->sh_video->pts;
2880 for (i = 1; i < mpctx->num_chapters; i++)
2881 if (current_pts < mpctx->chapters[i].start)
2882 break;
2883 return FFMAX(mpctx->last_chapter_seek, i - 1);
2886 // currently returns a string allocated with malloc, not talloc
2887 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2889 if (!mpctx->chapters || !mpctx->sh_video)
2890 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2891 return strdup(mpctx->chapters[chapter].name);
2894 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2895 char **chapter_name)
2897 mpctx->last_chapter_seek = -1;
2898 if (!mpctx->chapters || !mpctx->sh_video) {
2899 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2900 chapter_name);
2901 if (res >= 0) {
2902 if (*seek_pts == -1)
2903 seek_reset(mpctx);
2904 else {
2905 mpctx->last_chapter_seek = res;
2906 mpctx->last_chapter_pts = *seek_pts;
2909 return res;
2912 if (chapter >= mpctx->num_chapters)
2913 return -1;
2914 if (chapter < 0)
2915 chapter = 0;
2916 *seek_pts = mpctx->chapters[chapter].start;
2917 mpctx->last_chapter_seek = chapter;
2918 mpctx->last_chapter_pts = *seek_pts;
2919 if (chapter_name)
2920 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2921 return chapter;
2924 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2925 struct content_source *sources,
2926 int num_sources,
2927 unsigned char uid_map[][16])
2929 int num_filenames = 0;
2930 char **filenames = NULL;
2931 if (num_sources > 1) {
2932 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2933 "other sources.\n");
2934 if (mpctx->stream->type != STREAMTYPE_FILE) {
2935 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2936 "normal disk file. Will not search for related files.\n");
2937 } else {
2938 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2939 "same directory to find referenced sources.\n");
2940 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2941 &num_filenames);
2945 int num_left = num_sources - 1;
2946 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2947 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2948 filename_recode(filenames[i]));
2949 int format;
2950 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2951 if (!s)
2952 continue;
2953 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2954 mpctx->opts.audio_id,
2955 mpctx->opts.video_id,
2956 mpctx->opts.sub_id, filenames[i]);
2957 if (!d) {
2958 free_stream(s);
2959 continue;
2961 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2962 for (int i = 1; i < num_sources; i++) {
2963 if (sources[i].demuxer)
2964 continue;
2965 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2966 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2967 i, filename_recode(d->filename));
2968 sources[i].stream = s;
2969 sources[i].demuxer = d;
2970 num_left--;
2971 goto match;
2975 free_demuxer(d);
2976 free_stream(s);
2977 continue;
2978 match:
2981 talloc_free(filenames);
2982 if (num_left) {
2983 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2984 "There will be parts MISSING from the video!\n");
2985 for (int i = 1, j = 1; i < num_sources; i++)
2986 if (sources[i].demuxer) {
2987 sources[j] = sources[i];
2988 memcpy(uid_map[j], uid_map[i], 16);
2989 j++;
2992 return num_sources - num_left;
2995 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2997 if (!mpctx->opts.ordered_chapters) {
2998 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
2999 "you have disabled support for them. Ignoring.\n");
3000 return;
3003 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3004 "edit timeline.\n");
3006 struct demuxer *demuxer = mpctx->demuxer;
3007 struct matroska_data *m = &demuxer->matroska_data;
3009 // +1 because sources/uid_map[0] is original file even if all chapters
3010 // actually use other sources and need separate entries
3011 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3012 m->num_ordered_chapters+1);
3013 sources[0].stream = mpctx->stream;
3014 sources[0].demuxer = mpctx->demuxer;
3015 unsigned char uid_map[m->num_ordered_chapters+1][16];
3016 int num_sources = 1;
3017 memcpy(uid_map[0], m->segment_uid, 16);
3019 for (int i = 0; i < m->num_ordered_chapters; i++) {
3020 struct matroska_chapter *c = m->ordered_chapters + i;
3021 if (!c->has_segment_uid)
3022 memcpy(c->segment_uid, m->segment_uid, 16);
3024 for (int j = 0; j < num_sources; j++)
3025 if (!memcmp(c->segment_uid, uid_map[j], 16))
3026 goto found1;
3027 memcpy(uid_map[num_sources], c->segment_uid, 16);
3028 sources[num_sources] = (struct content_source){};
3029 num_sources++;
3030 found1:
3034 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3035 uid_map);
3038 // +1 for terminating chapter with start time marking end of last real one
3039 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3040 m->num_ordered_chapters + 1);
3041 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3042 m->num_ordered_chapters);
3043 uint64_t starttime = 0;
3044 uint64_t missing_time = 0;
3045 int part_count = 0;
3046 int num_chapters = 0;
3047 uint64_t prev_part_offset = 0;
3048 for (int i = 0; i < m->num_ordered_chapters; i++) {
3049 struct matroska_chapter *c = m->ordered_chapters + i;
3051 int j;
3052 for (j = 0; j < num_sources; j++) {
3053 if (!memcmp(c->segment_uid, uid_map[j], 16))
3054 goto found2;
3056 missing_time += c->end - c->start;
3057 continue;
3058 found2:;
3059 chapters[num_chapters].start = starttime / 1000.;
3060 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3061 /* Only add a separate part if the time or file actually changes.
3062 * Matroska files have chapter divisions that are redundant from
3063 * timeline point of view because the same chapter structure is used
3064 * both to specify the timeline and for normal chapter information.
3065 * Removing a missing inserted external chapter can also cause this. */
3066 if (part_count == 0 || c->start != starttime + prev_part_offset
3067 || sources + j != timeline[part_count - 1].source) {
3068 timeline[part_count].source = sources + j;
3069 timeline[part_count].start = chapters[num_chapters].start;
3070 timeline[part_count].source_start = c->start / 1000.;
3071 prev_part_offset = c->start - starttime;
3072 part_count++;
3074 starttime += c->end - c->start;
3075 num_chapters++;
3077 timeline[part_count].start = starttime / 1000.;
3079 if (!part_count) {
3080 // None of the parts come from the file itself???
3081 talloc_free(sources);
3082 talloc_free(timeline);
3083 talloc_free(chapters);
3084 return;
3087 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3088 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3089 timeline[part_count].start);
3090 if (missing_time)
3091 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3092 "from the timeline!\n", missing_time / 1000.);
3093 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3094 for (int i = 0; i < num_sources; i++)
3095 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3096 filename_recode(sources[i].demuxer->filename));
3097 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3098 "source_start, source):\n");
3099 for (int i = 0; i < part_count; i++) {
3100 struct timeline_part *p = timeline + i;
3101 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3102 p->source_start, p->source - sources);
3104 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3105 mpctx->sources = sources;
3106 mpctx->num_sources = num_sources;
3107 mpctx->timeline = timeline;
3108 mpctx->num_timeline_parts = part_count;
3109 mpctx->num_chapters = num_chapters;
3110 mpctx->chapters = chapters;
3112 mpctx->timeline_part = 0;
3113 mpctx->demuxer = timeline[0].source->demuxer;
3117 static int read_keys(void *ctx, int fd)
3119 getch2(ctx);
3120 return mplayer_get_key(ctx, 0);
3124 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3125 * file for some tools to link against. */
3126 #ifndef DISABLE_MAIN
3127 int main(int argc,char* argv[]){
3130 char * mem_ptr;
3132 // movie info:
3134 /* Flag indicating whether MPlayer should exit without playing anything. */
3135 int opt_exit = 0;
3136 int i;
3138 struct MPContext *mpctx = &(struct MPContext){
3139 .osd_function = OSD_PLAY,
3140 .begin_skip = MP_NOPTS_VALUE,
3141 .play_tree_step = 1,
3142 .global_sub_pos = -1,
3143 .set_of_sub_pos = -1,
3144 .file_format = DEMUXER_TYPE_UNKNOWN,
3145 .last_dvb_step = 1,
3148 InitTimer();
3149 srand(GetTimerMS());
3151 mp_msg_init();
3152 set_av_log_callback();
3154 #ifdef CONFIG_X11
3155 mpctx->x11_state = vo_x11_init_state();
3156 #endif
3157 struct MPOpts *opts = &mpctx->opts;
3158 set_default_mplayer_options(opts);
3159 // Create the config context and register the options
3160 mpctx->mconfig = m_config_new(opts, cfg_include);
3161 m_config_register_options(mpctx->mconfig,mplayer_opts);
3162 m_config_register_options(mpctx->mconfig, common_opts);
3163 mp_input_register_options(mpctx->mconfig);
3165 // Preparse the command line
3166 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3168 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3169 set_path_env();
3170 #endif
3172 #ifdef CONFIG_TV
3173 stream_tv_defaults.immediate = 1;
3174 #endif
3176 parse_cfgfiles(mpctx, mpctx->mconfig);
3178 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3179 if(mpctx->playtree == NULL)
3180 opt_exit = 1;
3181 else {
3182 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3183 if(mpctx->playtree) {
3184 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3185 if(mpctx->playtree_iter) {
3186 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3187 play_tree_iter_free(mpctx->playtree_iter);
3188 mpctx->playtree_iter = NULL;
3190 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3194 mpctx->key_fifo = mp_fifo_create(opts);
3196 print_version("MPlayer");
3198 #if defined(__MINGW32__) || defined(__CYGWIN__)
3200 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3201 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3202 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3203 if (kernel32) {
3204 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3205 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3207 if (setDEP) setDEP(3);
3208 if (setDllDir) setDllDir("");
3210 // stop Windows from showing all kinds of annoying error dialogs
3211 SetErrorMode(0x8003);
3212 // request 1ms timer resolution
3213 timeBeginPeriod(1);
3214 #endif
3216 #ifdef CONFIG_PRIORITY
3217 set_priority();
3218 #endif
3220 if (codec_path)
3221 set_codec_path(codec_path);
3223 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3224 list_video_out();
3225 opt_exit = 1;
3228 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3229 list_audio_out();
3230 opt_exit = 1;
3233 /* Check codecs.conf. */
3234 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3235 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3236 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3237 if(!parse_codec_cfg(NULL)){
3238 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3240 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3243 free( mem_ptr ); // release the buffer created by get_path()
3246 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3247 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3248 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3249 list_codecs(1);
3250 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3251 opt_exit = 1;
3253 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3254 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3255 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3256 list_codecs(0);
3257 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3258 opt_exit = 1;
3260 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3261 vfm_help();
3262 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3263 opt_exit = 1;
3265 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3266 afm_help();
3267 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3268 opt_exit = 1;
3270 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3271 af_help();
3272 printf("\n");
3273 opt_exit = 1;
3275 #ifdef CONFIG_X11
3276 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3277 fstype_help();
3278 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3279 opt_exit = 1;
3281 #endif
3282 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3283 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3284 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3285 demuxer_help();
3286 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3287 opt_exit = 1;
3289 if(list_properties) {
3290 property_print_help();
3291 opt_exit = 1;
3294 if(opt_exit)
3295 exit_player(mpctx, EXIT_NONE);
3297 if(!mpctx->filename && !player_idle_mode){
3298 // no file/vcd/dvd -> show HELP:
3299 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3300 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3303 /* Display what configure line was used */
3304 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3306 // Many users forget to include command line in bugreports...
3307 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3308 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3309 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3310 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3313 //------ load global data first ------
3315 mpctx->osd = osd_create();
3317 // check font
3318 #ifdef CONFIG_FREETYPE
3319 init_freetype();
3320 #endif
3321 #ifdef CONFIG_FONTCONFIG
3322 if(font_fontconfig <= 0)
3324 #endif
3325 #ifdef CONFIG_BITMAP_FONT
3326 if(font_name){
3327 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3328 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3329 filename_recode(font_name));
3330 } else {
3331 // try default:
3332 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3333 free(mem_ptr); // release the buffer created by get_path()
3334 if(!vo_font)
3335 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3337 if (sub_font_name)
3338 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3339 else
3340 mpctx->osd->sub_font = vo_font;
3341 #endif
3342 #ifdef CONFIG_FONTCONFIG
3344 #endif
3346 #ifdef CONFIG_ASS
3347 ass_library = ass_init();
3348 #endif
3350 #ifdef HAVE_RTC
3351 if(!nortc)
3353 // seteuid(0); /* Can't hurt to try to get root here */
3354 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3355 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3356 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3357 else {
3358 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3360 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3361 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3362 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3363 close (rtc_fd);
3364 rtc_fd = -1;
3365 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3366 /* variable only by the root */
3367 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3368 close (rtc_fd);
3369 rtc_fd = -1;
3370 } else
3371 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3374 if(rtc_fd<0)
3375 #endif /* HAVE_RTC */
3376 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3377 softsleep?"software":timer_name);
3379 #ifdef HAVE_TERMCAP
3380 load_termcap(NULL); // load key-codes
3381 #endif
3383 // ========== Init keyboard FIFO (connection to libvo) ============
3385 // Init input system
3386 current_module = "init_input";
3387 mpctx->input = mp_input_init(&opts->input);
3388 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3389 if(slave_mode)
3390 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3391 else if(!noconsolecontrols)
3392 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3393 // Set the libstream interrupt callback
3394 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3396 #ifdef CONFIG_MENU
3397 if(use_menu) {
3398 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3399 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3400 else {
3401 menu_cfg = get_path("menu.conf");
3402 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3403 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3404 else {
3405 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3406 MPLAYER_CONFDIR "/menu.conf"))
3407 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3408 else {
3409 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3410 use_menu = 0;
3415 #endif
3417 current_module = NULL;
3419 /// Catch signals
3420 #ifndef __MINGW32__
3421 signal(SIGCHLD,child_sighandler);
3422 #endif
3424 #ifdef CONFIG_CRASH_DEBUG
3425 prog_path = argv[0];
3426 #endif
3427 //========= Catch terminate signals: ================
3428 // terminate requests:
3429 signal(SIGTERM,exit_sighandler); // kill
3430 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3432 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3434 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3435 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3436 #ifdef CONFIG_SIGHANDLER
3437 // fatal errors:
3438 signal(SIGBUS,exit_sighandler); // bus error
3439 signal(SIGSEGV,exit_sighandler); // segfault
3440 signal(SIGILL,exit_sighandler); // illegal instruction
3441 signal(SIGFPE,exit_sighandler); // floating point exc.
3442 signal(SIGABRT,exit_sighandler); // abort()
3443 #ifdef CONFIG_CRASH_DEBUG
3444 if (crash_debug)
3445 signal(SIGTRAP,exit_sighandler);
3446 #endif
3447 #endif
3449 // ******************* Now, let's see the per-file stuff ********************
3451 play_next_file:
3453 // init global sub numbers
3454 mpctx->global_sub_size = 0;
3455 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3457 if (mpctx->filename) {
3458 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3459 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3460 load_per_file_config (mpctx->mconfig, mpctx->filename);
3463 if (opts->video_driver_list)
3464 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3465 if (opts->audio_driver_list)
3466 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3468 // We must enable getch2 here to be able to interrupt network connection
3469 // or cache filling
3470 if(!noconsolecontrols && !slave_mode){
3471 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3472 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3473 else
3474 getch2_enable(); // prepare stdin for hotkeys...
3475 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3476 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3479 // =================== GUI idle loop (STOP state) ===========================
3480 while (player_idle_mode && !mpctx->filename) {
3481 play_tree_t * entry = NULL;
3482 mp_cmd_t * cmd;
3483 if (mpctx->video_out && mpctx->video_out->config_ok)
3484 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3485 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3486 if (mpctx->video_out)
3487 vo_check_events(mpctx->video_out);
3488 usec_sleep(20000);
3490 switch (cmd->id) {
3491 case MP_CMD_LOADFILE:
3492 // prepare a tree entry with the new filename
3493 entry = play_tree_new();
3494 play_tree_add_file(entry, cmd->args[0].v.s);
3495 // The entry is added to the main playtree after the switch().
3496 break;
3497 case MP_CMD_LOADLIST:
3498 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3499 break;
3500 case MP_CMD_QUIT:
3501 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3502 break;
3503 case MP_CMD_VO_FULLSCREEN:
3504 case MP_CMD_GET_PROPERTY:
3505 case MP_CMD_SET_PROPERTY:
3506 case MP_CMD_STEP_PROPERTY:
3507 run_command(mpctx, cmd);
3508 break;
3511 mp_cmd_free(cmd);
3513 if (entry) { // user entered a command that gave a valid entry
3514 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3515 play_tree_free_list(mpctx->playtree->child, 1);
3516 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3518 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3520 play_tree_set_child(mpctx->playtree, entry);
3522 /* Make iterator start at the top the of tree. */
3523 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3524 if (!mpctx->playtree_iter) continue;
3526 // find the first real item in the tree
3527 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3528 // no items!
3529 play_tree_iter_free(mpctx->playtree_iter);
3530 mpctx->playtree_iter = NULL;
3531 continue; // wait for next command
3533 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3536 //---------------------------------------------------------------------------
3538 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3539 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3541 if (mpctx->filename) {
3542 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3543 filename_recode(mpctx->filename));
3544 if(use_filename_title && opts->vo_wintitle == NULL)
3545 opts->vo_wintitle = strdup(mp_basename2(mpctx->filename));
3548 if (edl_filename) {
3549 if (edl_records) free_edl(edl_records);
3550 next_edl_record = edl_records = edl_parse_file();
3552 if (edl_output_filename) {
3553 if (edl_fd) fclose(edl_fd);
3554 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3556 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3557 filename_recode(edl_output_filename));
3561 //==================== Open VOB-Sub ============================
3563 current_module="vobsub";
3564 if (vobsub_name){
3565 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3566 if(vo_vobsub==NULL)
3567 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3568 filename_recode(vobsub_name));
3569 } else if (sub_auto && mpctx->filename){
3570 /* try to autodetect vobsub from movie filename ::atmos */
3571 char *buf = strdup(mpctx->filename), *psub;
3572 char *pdot = strrchr(buf, '.');
3573 char *pslash = strrchr(buf, '/');
3574 #if defined(__MINGW32__) || defined(__CYGWIN__)
3575 if (!pslash) pslash = strrchr(buf, '\\');
3576 #endif
3577 if (pdot && (!pslash || pdot > pslash))
3578 *pdot = '\0';
3579 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3580 /* try from ~/.mplayer/sub */
3581 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3582 char *bname;
3583 int l;
3584 bname = strrchr(buf,'/');
3585 #if defined(__MINGW32__) || defined(__CYGWIN__)
3586 if(!bname) bname = strrchr(buf,'\\');
3587 #endif
3588 if(bname) bname++;
3589 else bname = buf;
3590 l = strlen(psub) + strlen(bname) + 1;
3591 psub = realloc(psub,l);
3592 strcat(psub,bname);
3593 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3594 free(psub);
3596 free(buf);
3598 if(vo_vobsub){
3599 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3600 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3601 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3603 // setup global sub numbering
3604 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3607 //============ Open & Sync STREAM --- fork cache2 ====================
3609 mpctx->stream=NULL;
3610 mpctx->demuxer=NULL;
3611 if (mpctx->d_audio) {
3612 //free_demuxer_stream(mpctx->d_audio);
3613 mpctx->d_audio=NULL;
3615 if (mpctx->d_video) {
3616 //free_demuxer_stream(d_video);
3617 mpctx->d_video=NULL;
3619 mpctx->sh_audio=NULL;
3620 mpctx->sh_video=NULL;
3622 current_module="open_stream";
3623 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3624 if(!mpctx->stream) { // error...
3625 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3626 goto goto_next_file;
3628 mpctx->initialized_flags|=INITIALIZED_STREAM;
3630 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3631 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3632 "playlist support will not be used automatically.\n"
3633 "MPlayer's playlist code is unsafe and should only be used with "
3634 "trusted sources.\nPlayback will probably fail.\n\n");
3635 #if 0
3636 play_tree_t* entry;
3637 // Handle playlist
3638 current_module="handle_playlist";
3639 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3640 filename_recode(mpctx->filename));
3641 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3642 mpctx->eof=playtree_add_playlist(mpctx, entry);
3643 goto goto_next_file;
3644 #endif
3646 mpctx->stream->start_pos+=seek_to_byte;
3648 if(stream_dump_type==5){
3649 unsigned char buf[4096];
3650 int len;
3651 FILE *f;
3652 current_module="dumpstream";
3653 stream_reset(mpctx->stream);
3654 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3655 f=fopen(opts->stream_dump_name,"wb");
3656 if(!f){
3657 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3658 exit_player(mpctx, EXIT_ERROR);
3660 if (opts->chapterrange[0] > 1) {
3661 int chapter = opts->chapterrange[0] - 1;
3662 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3664 while(!mpctx->stream->eof && !async_quit_request){
3665 len=stream_read(mpctx->stream,buf,4096);
3666 if(len>0) {
3667 if(fwrite(buf,len,1,f) != 1) {
3668 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3669 exit_player(mpctx, EXIT_ERROR);
3672 if (opts->chapterrange[1] > 0) {
3673 int chapter = -1;
3674 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3675 &chapter) == STREAM_OK
3676 && chapter + 1 > opts->chapterrange[1])
3677 break;
3680 if(fclose(f)) {
3681 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3682 exit_player(mpctx, EXIT_ERROR);
3684 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3685 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3688 #ifdef CONFIG_DVDREAD
3689 if(mpctx->stream->type==STREAMTYPE_DVD){
3690 current_module="dvd lang->id";
3691 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3692 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3693 // setup global sub numbering
3694 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3695 current_module=NULL;
3697 #endif
3699 #ifdef CONFIG_DVDNAV
3700 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3701 current_module="dvdnav lang->id";
3702 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3703 dvdsub_lang_id = -3;
3704 if(opts->sub_lang && opts->sub_id==-1)
3705 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3706 // setup global sub numbering
3707 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3708 current_module=NULL;
3710 #endif
3712 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3713 goto_enable_cache:
3714 if(stream_cache_size>0){
3715 int res;
3716 current_module="enable_cache";
3717 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3718 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3719 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3720 if(res == 0)
3721 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3724 //============ Open DEMUXERS --- DETECT file type =======================
3725 current_module="demux_open";
3727 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3729 // HACK to get MOV Reference Files working
3731 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3733 unsigned char* playlist_entry;
3734 play_tree_t *list = NULL, *entry = NULL;
3736 current_module="handle_demux_playlist";
3737 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3739 char *temp, *bname;
3741 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3742 filename_recode(playlist_entry));
3744 bname=mp_basename(playlist_entry);
3745 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3746 continue;
3748 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3749 continue;
3751 entry = play_tree_new();
3753 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3755 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3756 if (temp)
3758 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3759 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3760 strcat(temp, playlist_entry);
3761 if (!strcmp(temp, mpctx->filename)) {
3762 free(temp);
3763 continue;
3765 play_tree_add_file(entry,temp);
3766 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3767 free(temp);
3770 else
3771 play_tree_add_file(entry,playlist_entry);
3773 if(!list)
3774 list = entry;
3775 else
3776 play_tree_append_entry(list,entry);
3778 free_demuxer(mpctx->demuxer);
3779 mpctx->demuxer = NULL;
3781 if (list)
3783 entry = play_tree_new();
3784 play_tree_set_child(entry,list);
3785 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3786 goto goto_next_file;
3790 if(!mpctx->demuxer)
3791 goto goto_next_file;
3793 if (mpctx->demuxer->matroska_data.ordered_chapters)
3794 build_ordered_chapter_timeline(mpctx);
3796 if (!mpctx->sources) {
3797 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3798 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3799 .demuxer = mpctx->demuxer};
3800 mpctx->num_sources = 1;
3803 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3805 #ifdef CONFIG_ASS
3806 if (opts->ass_enabled && ass_library) {
3807 for (int j = 0; j < mpctx->num_sources; j++) {
3808 struct demuxer *d = mpctx->sources[j].demuxer;
3809 for (int i = 0; i < d->num_attachments; i++) {
3810 struct demux_attachment *att = d->attachments + i;
3811 if (use_embedded_fonts && attachment_is_font(att))
3812 ass_add_font(ass_library, att->name, att->data, att->data_size);
3816 #endif
3818 current_module="demux_open2";
3820 mpctx->d_audio=mpctx->demuxer->audio;
3821 mpctx->d_video=mpctx->demuxer->video;
3822 mpctx->d_sub=mpctx->demuxer->sub;
3824 if (ts_prog) {
3825 int tmp = ts_prog;
3826 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3828 // select audio stream
3829 if (mpctx->num_sources)
3830 for (int i = 0; i < mpctx->num_sources; i++)
3831 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3832 opts->audio_lang);
3833 else
3834 select_audio(mpctx->demuxer, opts->audio_id, opts->audio_lang);
3836 // DUMP STREAMS:
3837 if((stream_dump_type)&&(stream_dump_type<4)){
3838 FILE *f;
3839 demux_stream_t *ds=NULL;
3840 current_module="dump";
3841 // select stream to dump
3842 switch(stream_dump_type){
3843 case 1: ds=mpctx->d_audio;break;
3844 case 2: ds=mpctx->d_video;break;
3845 case 3: ds=mpctx->d_sub;break;
3847 if(!ds){
3848 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3849 exit_player(mpctx, EXIT_ERROR);
3851 // disable other streams:
3852 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3853 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3854 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3855 // let's dump it!
3856 f=fopen(opts->stream_dump_name,"wb");
3857 if(!f){
3858 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3859 exit_player(mpctx, EXIT_ERROR);
3861 while(!ds->eof){
3862 unsigned char* start;
3863 int in_size=ds_get_packet(ds,&start);
3864 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3865 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3866 if(in_size>0) fwrite(start,in_size,1,f);
3867 if (opts->chapterrange[1] > 0) {
3868 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3869 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3870 break;
3873 fclose(f);
3874 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3875 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3878 mpctx->sh_audio=mpctx->d_audio->sh;
3879 mpctx->sh_video=mpctx->d_video->sh;
3881 if(mpctx->sh_video){
3883 current_module="video_read_properties";
3884 if(!video_read_properties(mpctx->sh_video)) {
3885 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3886 mpctx->sh_video=mpctx->d_video->sh=NULL;
3887 } else {
3888 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3889 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3890 mpctx->sh_video->fps,mpctx->sh_video->frametime
3893 /* need to set fps here for output encoders to pick it up in their init */
3894 if(force_fps){
3895 mpctx->sh_video->fps=force_fps;
3896 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3898 vo_fps = mpctx->sh_video->fps;
3900 if(!mpctx->sh_video->fps && !force_fps){
3901 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3902 mpctx->opts.correct_pts = 1;
3908 if(!mpctx->sh_video && !mpctx->sh_audio){
3909 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3910 #ifdef CONFIG_DVBIN
3911 if(mpctx->stream->type == STREAMTYPE_DVB)
3913 int dir;
3914 int v = mpctx->last_dvb_step;
3915 if(v > 0)
3916 dir = DVB_CHANNEL_HIGHER;
3917 else
3918 dir = DVB_CHANNEL_LOWER;
3920 if(dvb_step_channel(mpctx->stream, dir)) {
3921 mpctx->stop_play = PT_NEXT_ENTRY;
3922 mpctx->dvbin_reopen = 1;
3925 #endif
3926 goto goto_next_file; // exit_player(_("Fatal error"));
3929 /* display clip info */
3930 demux_info_print(mpctx->demuxer);
3932 //================== Read SUBTITLES (DVD & TEXT) ==========================
3933 if(vo_spudec==NULL &&
3934 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3935 init_vo_spudec(mpctx);
3938 // after reading video params we should load subtitles because
3939 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3940 // check .sub
3941 current_module="read_subtitles_file";
3942 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3943 if(sub_name){
3944 for (i = 0; sub_name[i] != NULL; ++i)
3945 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3947 if(sub_auto) { // auto load sub file ...
3948 char *psub = get_path( "sub/" );
3949 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3950 int i = 0;
3951 free(psub); // release the buffer created by get_path() above
3952 while (tmp[i]) {
3953 add_subtitles(mpctx, tmp[i], sub_fps, 1);
3954 free(tmp[i++]);
3956 free(tmp);
3958 if (mpctx->set_of_sub_size > 0)
3959 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
3961 if (select_subtitle(mpctx)) {
3962 if(subdata)
3963 switch (stream_dump_type) {
3964 case 3: list_sub_file(subdata); break;
3965 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3966 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3967 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3968 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3969 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3973 print_file_properties(mpctx, mpctx->filename);
3975 if(!mpctx->sh_video) goto main; // audio-only
3977 if(!reinit_video_chain(mpctx)) {
3978 if(!mpctx->sh_video){
3979 if(!mpctx->sh_audio) goto goto_next_file;
3980 goto main; // exit_player(_("Fatal error"));
3984 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
3985 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3987 #ifdef CONFIG_FREETYPE
3988 force_load_font = 1;
3989 #endif
3991 //================== MAIN: ==========================
3992 main:
3993 current_module="main";
3995 if(playing_msg) {
3996 char* msg = property_expand_string(mpctx, playing_msg);
3997 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
3998 free(msg);
4002 // Disable the term OSD in verbose mode
4003 if(verbose) term_osd = 0;
4006 int frame_time_remaining=0; // flag
4007 int blit_frame=0;
4009 // Make sure old OSD does not stay around,
4010 // e.g. with -fixed-vo and same-resolution files
4011 clear_osd_msgs();
4012 update_osd_msg(mpctx);
4014 //================ SETUP AUDIO ==========================
4016 if(mpctx->sh_audio){
4017 reinit_audio_chain(mpctx);
4018 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4019 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4022 current_module="av_init";
4024 if(mpctx->sh_video){
4025 mpctx->sh_video->timer=0;
4026 if (! ignore_start)
4027 audio_delay += mpctx->sh_video->stream_delay;
4029 if(mpctx->sh_audio){
4030 if (start_volume >= 0)
4031 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4032 if (! ignore_start)
4033 audio_delay -= mpctx->sh_audio->stream_delay;
4034 mpctx->delay=-audio_delay;
4037 if(!mpctx->sh_audio){
4038 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4039 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4040 ds_free_packs(mpctx->d_audio); // free buffered chunks
4041 //mpctx->d_audio->id=-2; // do not read audio chunks
4042 //uninit_player(mpctx, INITIALIZED_AO); // close device
4044 if(!mpctx->sh_video){
4045 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4046 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4047 ds_free_packs(mpctx->d_video);
4048 mpctx->d_video->id=-2;
4049 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4052 if (!mpctx->sh_video && !mpctx->sh_audio)
4053 goto goto_next_file;
4055 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4056 if(force_fps && mpctx->sh_video){
4057 vo_fps = mpctx->sh_video->fps=force_fps;
4058 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4059 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4062 mp_input_set_section(mpctx->input, NULL);
4063 //TODO: add desired (stream-based) sections here
4064 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4065 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4067 //==================== START PLAYING =======================
4069 if(opts->loop_times>1) opts->loop_times--; else
4070 if(opts->loop_times==1) opts->loop_times = -1;
4072 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4074 total_time_usage_start=GetTimer();
4075 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4076 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4077 play_n_frames=play_n_frames_mf;
4079 if(play_n_frames==0){
4080 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4083 // If there's a timeline force an absolute seek to initialize state
4084 if (seek_to_sec || mpctx->timeline) {
4085 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4086 end_at.pos += seek_to_sec;
4088 if (opts->chapterrange[0] > 0) {
4089 double pts;
4090 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4091 && pts > -1.0)
4092 seek(mpctx, pts, SEEK_ABSOLUTE);
4095 if (end_at.type == END_AT_SIZE) {
4096 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4097 end_at.type = END_AT_NONE;
4100 #ifdef CONFIG_DVDNAV
4101 mp_dvdnav_context_free(mpctx);
4102 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4103 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4104 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4106 #endif
4108 get_relative_time(mpctx); // reset current delta
4109 mpctx->time_frame = 0;
4110 mpctx->drop_message_shown = 0;
4111 mpctx->update_video_immediately = true;
4112 mpctx->total_avsync_change = 0;
4113 mpctx->last_chapter_seek = -1;
4114 // Make sure VO knows current pause state
4115 if (mpctx->sh_video)
4116 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4117 NULL);
4119 while(!mpctx->stop_play){
4120 float aq_sleep_time=0;
4122 if (opts->chapterrange[1] > 0) {
4123 int cur_chapter = get_current_chapter(mpctx);
4124 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4125 goto goto_next_file;
4128 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4129 mpctx->sh_audio = mpctx->d_audio->sh;
4130 mpctx->sh_audio->ds = mpctx->d_audio;
4131 reinit_audio_chain(mpctx);
4134 /*========================== PLAY AUDIO ============================*/
4136 if (mpctx->sh_audio && !mpctx->paused)
4137 if (!fill_audio_out_buffers(mpctx))
4138 // at eof, all audio at least written to ao
4139 if (!mpctx->sh_video)
4140 mpctx->stop_play = AT_END_OF_FILE;
4143 if(!mpctx->sh_video) {
4144 // handle audio-only case:
4145 double a_pos=0;
4146 // sh_audio can be NULL due to video stream switching
4147 // TODO: handle this better
4148 if (mpctx->sh_audio)
4149 a_pos = playing_audio_pts(mpctx);
4151 print_status(mpctx, a_pos, false);
4153 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4154 mpctx->stop_play = PT_NEXT_ENTRY;
4155 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4156 mpctx->d_sub, 0);
4157 update_osd_msg(mpctx);
4159 } else {
4161 /*========================== PLAY VIDEO ============================*/
4163 vo_pts=mpctx->sh_video->timer*90000.0;
4164 vo_fps=mpctx->sh_video->fps;
4166 blit_frame = mpctx->video_out->frame_loaded;
4167 if (!blit_frame) {
4168 double frame_time = update_video(mpctx);
4169 blit_frame = mpctx->video_out->frame_loaded;
4170 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4171 if (mpctx->sh_video->vf_initialized < 0) {
4172 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4173 mpctx->stop_play = PT_NEXT_ENTRY;
4174 goto goto_next_file;
4176 if (blit_frame) {
4177 struct sh_video *sh_video = mpctx->sh_video;
4178 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4179 mpctx->video_offset, mpctx->d_sub, 0);
4180 update_teletext(sh_video, mpctx->demuxer, 0);
4181 update_osd_msg(mpctx);
4182 struct vf_instance *vf = mpctx->sh_video->vfilter;
4183 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4184 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4185 vo_osd_changed(0);
4187 if (frame_time < 0)
4188 mpctx->stop_play = AT_END_OF_FILE;
4189 else {
4190 if (mpctx->update_video_immediately) {
4191 // Show this frame immediately, rest normally
4192 mpctx->update_video_immediately = false;
4193 } else {
4194 mpctx->time_frame += frame_time / opts->playback_speed;
4195 adjust_sync(mpctx, frame_time);
4199 if (mpctx->timeline) {
4200 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4201 if (mpctx->sh_video->pts >= next->start
4202 || mpctx->stop_play == AT_END_OF_FILE
4203 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4204 seek(mpctx, next->start, SEEK_ABSOLUTE);
4205 continue;
4209 // ==========================================================================
4211 // current_module="draw_osd";
4212 // if(vo_config_count) mpctx->video_out->draw_osd();
4214 current_module="vo_check_events";
4215 vo_check_events(mpctx->video_out);
4217 #ifdef CONFIG_X11
4218 if (stop_xscreensaver) {
4219 current_module = "stop_xscreensaver";
4220 xscreensaver_heartbeat(mpctx->x11_state);
4222 #endif
4223 if (heartbeat_cmd) {
4224 static unsigned last_heartbeat;
4225 unsigned now = GetTimerMS();
4226 if (now - last_heartbeat > 30000) {
4227 last_heartbeat = now;
4228 system(heartbeat_cmd);
4232 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4234 //====================== FLIP PAGE (VIDEO BLT): =========================
4236 current_module="flip_page";
4237 if (!frame_time_remaining && blit_frame) {
4238 unsigned int t2=GetTimer();
4239 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4240 int duration = -1;
4241 double pts2 = mpctx->video_out->next_pts2;
4242 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4243 // expected A/V sync correction is ignored
4244 double diff = (pts2 - mpctx->sh_video->pts);
4245 diff /= opts->playback_speed;
4246 if (mpctx->time_frame < 0)
4247 diff += mpctx->time_frame;
4248 if (diff < 0)
4249 diff = 0;
4250 if (diff > 10)
4251 diff = 10;
4252 duration = diff * 1e6;
4254 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4256 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4257 vout_time_usage += mpctx->last_vo_flip_duration;
4258 if (mpctx->video_out->driver->flip_page_timed) {
4259 // No need to adjust sync based on flip speed
4260 mpctx->last_vo_flip_duration = 0;
4261 // For print_status - VO call finishing early is OK for sync
4262 mpctx->time_frame -= get_relative_time(mpctx);
4264 print_status(mpctx, MP_NOPTS_VALUE, true);
4266 else
4267 print_status(mpctx, MP_NOPTS_VALUE, false);
4269 //============================ Auto QUALITY ============================
4271 /*Output quality adjustments:*/
4272 if(auto_quality>0){
4273 current_module="autoq";
4274 // float total=0.000001f * (GetTimer()-aq_total_time);
4275 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4276 if(output_quality<auto_quality && aq_sleep_time>0)
4277 ++output_quality;
4278 else
4279 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4280 if(output_quality>1 && aq_sleep_time<0)
4281 --output_quality;
4282 else
4283 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4284 output_quality=0;
4285 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4286 set_video_quality(mpctx->sh_video,output_quality);
4289 if (!frame_time_remaining && blit_frame) {
4290 if (play_n_frames >= 0) {
4291 --play_n_frames;
4292 if (play_n_frames <= 0)
4293 mpctx->stop_play = PT_NEXT_ENTRY;
4295 if (mpctx->step_frames > 0) {
4296 mpctx->step_frames--;
4297 if (mpctx->step_frames == 0)
4298 pause_player(mpctx);
4303 // FIXME: add size based support for -endpos
4304 if (end_at.type == END_AT_TIME &&
4305 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4306 mpctx->stop_play = PT_NEXT_ENTRY;
4308 } // end if(mpctx->sh_video)
4310 #ifdef CONFIG_DVDNAV
4311 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4312 nav_highlight_t hl;
4313 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4314 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4315 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4316 vo_osd_changed (OSDTYPE_DVDNAV);
4317 } else {
4318 osd_set_nav_box(0, 0, 0, 0);
4319 vo_osd_changed(OSDTYPE_DVDNAV);
4320 vo_osd_changed(OSDTYPE_SPU);
4323 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4324 double ar = -1.0;
4325 if (mpctx->sh_video &&
4326 stream_control (mpctx->demuxer->stream,
4327 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4328 != STREAM_UNSUPPORTED)
4329 mpctx->sh_video->stream_aspect = ar;
4332 #endif
4334 //================= Keyboard events, SEEKing ====================
4336 current_module="key_events";
4339 while (1) {
4340 mp_cmd_t* cmd;
4341 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4342 run_command(mpctx, cmd);
4343 mp_cmd_free(cmd);
4344 if (mpctx->stop_play)
4345 break;
4346 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4347 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4348 /* Allow seek commands to be combined, but execute the real seek
4349 * before processing other commands */
4350 if (!cmd || cmd->id != MP_CMD_SEEK)
4351 break;
4354 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4355 || mpctx->abs_seek_pos)
4356 break;
4357 if (mpctx->sh_video) {
4358 update_osd_msg(mpctx);
4359 int hack = vo_osd_changed(0);
4360 vo_osd_changed(hack);
4361 if (hack) {
4362 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4363 add_step_frame(mpctx);
4364 break;
4366 else
4367 vo_osd_changed(0);
4370 pause_loop(mpctx);
4374 // handle -sstep
4375 if (step_sec > 0 && !mpctx->paused) {
4376 mpctx->osd_function=OSD_FFW;
4377 mpctx->rel_seek_secs+=step_sec;
4380 edl_update(mpctx);
4382 /* Looping. */
4383 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4384 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4386 if(opts->loop_times>1) opts->loop_times--; else
4387 if(opts->loop_times==1) opts->loop_times=-1;
4388 play_n_frames=play_n_frames_mf;
4389 mpctx->stop_play=0;
4390 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4393 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4394 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4396 mpctx->rel_seek_secs=0;
4397 mpctx->abs_seek_pos=0;
4400 } // while(!mpctx->stop_play)
4402 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4404 #ifdef CONFIG_DVBIN
4405 if(mpctx->dvbin_reopen)
4407 mpctx->stop_play = 0;
4408 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4409 cache_uninit(mpctx->stream);
4410 mpctx->dvbin_reopen = 0;
4411 goto goto_enable_cache;
4413 #endif
4416 goto_next_file: // don't jump here after ao/vo/getch initialization!
4418 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4420 if(benchmark){
4421 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4422 double total_time_usage;
4423 total_time_usage_start=GetTimer()-total_time_usage_start;
4424 total_time_usage = (float)total_time_usage_start*0.000001;
4425 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4426 video_time_usage,vout_time_usage,audio_time_usage,
4427 total_time_usage-tot,total_time_usage);
4428 if(total_time_usage>0.0)
4429 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4430 100.0*video_time_usage/total_time_usage,
4431 100.0*vout_time_usage/total_time_usage,
4432 100.0*audio_time_usage/total_time_usage,
4433 100.0*(total_time_usage-tot)/total_time_usage,
4434 100.0);
4435 if(total_frame_cnt && frame_dropping)
4436 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4437 total_frame_cnt-drop_frame_cnt,
4438 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4439 drop_frame_cnt,
4440 100*drop_frame_cnt/total_frame_cnt,
4441 total_frame_cnt,
4442 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4445 // time to uninit all, except global stuff:
4446 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4448 if(mpctx->set_of_sub_size > 0) {
4449 current_module="sub_free";
4450 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4451 sub_free(mpctx->set_of_subtitles[i]);
4452 #ifdef CONFIG_ASS
4453 if(mpctx->set_of_ass_tracks[i])
4454 ass_free_track( mpctx->set_of_ass_tracks[i] );
4455 #endif
4457 mpctx->set_of_sub_size = 0;
4459 vo_sub_last = vo_sub=NULL;
4460 subdata=NULL;
4461 #ifdef CONFIG_ASS
4462 ass_track = NULL;
4463 if(ass_library)
4464 ass_clear_fonts(ass_library);
4465 #endif
4467 if (!mpctx->stop_play) // In case some goto jumped here...
4468 mpctx->stop_play = PT_NEXT_ENTRY;
4470 int playtree_direction = 1;
4472 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4473 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4474 play_tree_iter_free(mpctx->playtree_iter);
4475 mpctx->playtree_iter = NULL;
4477 mpctx->play_tree_step = 1;
4478 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4479 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4480 if(mpctx->playtree_iter) {
4481 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4482 play_tree_iter_free(mpctx->playtree_iter);
4483 mpctx->playtree_iter = NULL;
4486 } else if (mpctx->stop_play == PT_STOP) {
4487 play_tree_iter_free(mpctx->playtree_iter);
4488 mpctx->playtree_iter = NULL;
4489 } else { // NEXT PREV SRC
4490 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4493 while(mpctx->playtree_iter != NULL) {
4494 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4495 if(mpctx->filename == NULL) {
4496 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4497 play_tree_iter_free(mpctx->playtree_iter);
4498 mpctx->playtree_iter = NULL;
4500 } else
4501 break;
4504 if(mpctx->playtree_iter != NULL || player_idle_mode){
4505 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4506 mpctx->stop_play = 0;
4507 goto play_next_file;
4511 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4513 return 1;
4515 #endif /* DISABLE_MAIN */