core: move video pos/length query functions from demux to core
[mplayer/glamo.git] / mplayer.c
blobd6007a58c4ea4b74b889ae74017bbaa6b05edd46
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(struct 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", get_time_length(mpctx));
640 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
641 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
642 if (mpctx->demuxer) {
643 if (mpctx->demuxer->num_chapters == 0)
644 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
645 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
649 /// step size of mixer changes
650 int volstep = 3;
652 #ifdef CONFIG_DVDNAV
653 static void mp_dvdnav_context_free(MPContext *ctx){
654 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
655 ctx->nav_smpi = NULL;
656 free(ctx->nav_buffer);
657 ctx->nav_buffer = NULL;
658 ctx->nav_start = NULL;
659 ctx->nav_in_size = 0;
661 #endif
663 void uninit_player(struct MPContext *mpctx, unsigned int mask){
664 mask &= mpctx->initialized_flags;
666 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
668 if(mask&INITIALIZED_ACODEC){
669 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
670 current_module="uninit_acodec";
671 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
672 mpctx->sh_audio=NULL;
673 mpctx->mixer.afilter = NULL;
676 if(mask&INITIALIZED_VCODEC){
677 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
678 current_module="uninit_vcodec";
679 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
680 mpctx->sh_video=NULL;
681 #ifdef CONFIG_MENU
682 vf_menu=NULL;
683 #endif
686 if(mask&INITIALIZED_DEMUXER){
687 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
688 current_module="free_demuxer";
689 if (mpctx->num_sources) {
690 mpctx->demuxer = mpctx->sources[0].demuxer;
691 for (int i = 1; i < mpctx->num_sources; i++) {
692 free_stream(mpctx->sources[i].stream);
693 free_demuxer(mpctx->sources[i].demuxer);
696 talloc_free(mpctx->sources);
697 mpctx->sources = NULL;
698 mpctx->num_sources = 0;
699 talloc_free(mpctx->timeline);
700 mpctx->timeline = NULL;
701 mpctx->num_timeline_parts = 0;
702 talloc_free(mpctx->chapters);
703 mpctx->chapters = NULL;
704 mpctx->num_chapters = 0;
705 mpctx->video_offset = 0;
706 if(mpctx->demuxer){
707 mpctx->stream=mpctx->demuxer->stream;
708 free_demuxer(mpctx->demuxer);
710 mpctx->demuxer=NULL;
713 // kill the cache process:
714 if(mask&INITIALIZED_STREAM){
715 mpctx->initialized_flags&=~INITIALIZED_STREAM;
716 current_module="uninit_stream";
717 if(mpctx->stream) free_stream(mpctx->stream);
718 mpctx->stream=NULL;
721 if(mask&INITIALIZED_VO){
722 mpctx->initialized_flags&=~INITIALIZED_VO;
723 current_module="uninit_vo";
724 vo_destroy(mpctx->video_out);
725 mpctx->video_out=NULL;
726 #ifdef CONFIG_DVDNAV
727 mp_dvdnav_context_free(mpctx);
728 #endif
731 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
732 if(mask&INITIALIZED_GETCH2){
733 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
734 current_module="uninit_getch2";
735 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
736 // restore terminal:
737 getch2_disable();
740 if(mask&INITIALIZED_VOBSUB){
741 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
742 current_module="uninit_vobsub";
743 if(vo_vobsub) vobsub_close(vo_vobsub);
744 vo_vobsub=NULL;
747 if (mask&INITIALIZED_SPUDEC){
748 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
749 current_module="uninit_spudec";
750 spudec_free(vo_spudec);
751 vo_spudec=NULL;
754 if(mask&INITIALIZED_AO){
755 mpctx->initialized_flags&=~INITIALIZED_AO;
756 current_module="uninit_ao";
757 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
758 if (mpctx->audio_out)
759 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
760 mpctx->audio_out=NULL;
763 current_module=NULL;
766 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
768 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
769 uninit_player(mpctx, INITIALIZED_ALL);
770 #if defined(__MINGW32__) || defined(__CYGWIN__)
771 timeEndPeriod(1);
772 #endif
773 #ifdef CONFIG_X11
774 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
775 #endif
777 current_module="uninit_input";
778 mp_input_uninit(mpctx->input);
779 #ifdef CONFIG_MENU
780 if (use_menu)
781 menu_uninit();
782 #endif
784 #ifdef CONFIG_FREETYPE
785 current_module="uninit_font";
786 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
787 free_font_desc(mpctx->osd->sub_font);
788 free_font_desc(vo_font);
789 vo_font = NULL;
790 done_freetype();
791 #endif
792 osd_free(mpctx->osd);
794 #ifdef CONFIG_ASS
795 ass_library_done(ass_library);
796 ass_library = NULL;
797 #endif
799 current_module="exit_player";
801 // free mplayer config
802 if(mpctx->mconfig)
803 m_config_free(mpctx->mconfig);
804 mpctx->mconfig = NULL;
806 if(mpctx->playtree_iter)
807 play_tree_iter_free(mpctx->playtree_iter);
808 mpctx->playtree_iter = NULL;
809 if(mpctx->playtree)
810 play_tree_free(mpctx->playtree, 1);
811 mpctx->playtree = NULL;
813 talloc_free(mpctx->key_fifo);
815 free(edl_records); // free mem allocated for EDL
816 edl_records = NULL;
817 switch(how) {
818 case EXIT_QUIT:
819 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
820 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
821 break;
822 case EXIT_EOF:
823 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
824 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
825 break;
826 case EXIT_ERROR:
827 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
828 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
829 break;
830 default:
831 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
833 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
835 exit(rc);
838 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
840 exit_player_with_rc(mpctx, how, 1);
843 #ifndef __MINGW32__
844 static void child_sighandler(int x){
845 pid_t pid;
846 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
848 #endif
850 #ifdef CONFIG_CRASH_DEBUG
851 static char *prog_path;
852 static int crash_debug = 0;
853 #endif
855 static void exit_sighandler(int x){
856 static int sig_count=0;
857 #ifdef CONFIG_CRASH_DEBUG
858 if (!crash_debug || x != SIGTRAP)
859 #endif
860 ++sig_count;
861 if(sig_count==5)
863 /* We're crashing bad and can't uninit cleanly :(
864 * by popular request, we make one last (dirty)
865 * effort to restore the user's
866 * terminal. */
867 getch2_disable();
868 exit(1);
870 if(sig_count==6) exit(1);
871 if(sig_count>6){
872 // can't stop :(
873 #ifndef __MINGW32__
874 kill(getpid(),SIGKILL);
875 #endif
877 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
878 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
879 "\nMPlayer interrupted by signal %d in module: %s\n", x,
880 current_module ? current_module : "unknown");
881 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
882 if(sig_count<=1)
883 switch(x){
884 case SIGINT:
885 case SIGPIPE:
886 case SIGQUIT:
887 case SIGTERM:
888 case SIGKILL:
889 async_quit_request = 1;
890 return; // killed from keyboard (^C) or killed [-9]
891 case SIGILL:
892 #if CONFIG_RUNTIME_CPUDETECT
893 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
894 #else
895 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
896 #endif
897 case SIGFPE:
898 case SIGSEGV:
899 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
900 default:
901 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
902 #ifdef CONFIG_CRASH_DEBUG
903 if (crash_debug) {
904 int gdb_pid;
905 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
906 gdb_pid = fork();
907 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
908 if (gdb_pid == 0) { // We are the child
909 char spid[20];
910 snprintf(spid, sizeof(spid), "%i", getppid());
911 getch2_disable(); // allow terminal to work properly with gdb
912 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
913 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
914 } else if (gdb_pid < 0)
915 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
916 else {
917 waitpid(gdb_pid, NULL, 0);
919 if (x == SIGTRAP) return;
921 #endif
923 getch2_disable();
924 exit(1);
927 #include "cfg-mplayer.h"
929 static int cfg_include(m_option_t *conf, char *filename)
931 return m_config_parse_config_file(conf->priv, filename);
934 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
936 char *conffile;
937 int conffile_fd;
938 if (!disable_system_conf &&
939 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
940 exit_player(mpctx, EXIT_NONE);
941 if ((conffile = get_path("")) == NULL) {
942 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
943 } else {
944 #ifdef __MINGW32__
945 mkdir(conffile);
946 #else
947 mkdir(conffile, 0777);
948 #endif
949 free(conffile);
950 if ((conffile = get_path("config")) == NULL) {
951 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
952 } else {
953 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
954 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
955 write(conffile_fd, default_config, strlen(default_config));
956 close(conffile_fd);
958 if (!disable_user_conf &&
959 m_config_parse_config_file(conf, conffile) < 0)
960 exit_player(mpctx, EXIT_NONE);
961 free(conffile);
966 #define PROFILE_CFG_PROTOCOL "protocol."
968 static void load_per_protocol_config (m_config_t* conf, const char *const file)
970 char *str;
971 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
972 m_profile_t *p;
974 /* does filename actually uses a protocol ? */
975 str = strstr (file, "://");
976 if (!str)
977 return;
979 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
980 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
981 p = m_config_get_profile (conf, protocol);
982 if (p)
984 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
985 m_config_set_profile(conf,p);
989 #define PROFILE_CFG_EXTENSION "extension."
991 static void load_per_extension_config (m_config_t* conf, const char *const file)
993 char *str;
994 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
995 m_profile_t *p;
997 /* does filename actually have an extension ? */
998 str = strrchr (file, '.');
999 if (!str)
1000 return;
1002 sprintf (extension, PROFILE_CFG_EXTENSION);
1003 strncat (extension, ++str, 7);
1004 p = m_config_get_profile (conf, extension);
1005 if (p)
1007 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
1008 m_config_set_profile(conf,p);
1012 #define PROFILE_CFG_VO "vo."
1013 #define PROFILE_CFG_AO "ao."
1015 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
1017 char profile[strlen (cfg) + strlen (out) + 1];
1018 m_profile_t *p;
1020 sprintf (profile, "%s%s", cfg, out);
1021 p = m_config_get_profile (conf, profile);
1022 if (p)
1024 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
1025 m_config_set_profile(conf,p);
1030 * Tries to load a config file
1031 * @return 0 if file was not found, 1 otherwise
1033 static int try_load_config(m_config_t *conf, const char *file)
1035 struct stat st;
1036 if (stat(file, &st))
1037 return 0;
1038 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1039 m_config_parse_config_file (conf, file);
1040 return 1;
1043 static void load_per_file_config (m_config_t* conf, const char *const file)
1045 char *confpath;
1046 char cfg[PATH_MAX];
1047 char *name;
1049 if (strlen(file) > PATH_MAX - 14) {
1050 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1051 return;
1053 sprintf (cfg, "%s.conf", file);
1055 name = strrchr(cfg, '/');
1056 if (HAVE_DOS_PATHS) {
1057 char *tmp = strrchr(cfg, '\\');
1058 if (!name || tmp > name)
1059 name = tmp;
1060 tmp = strrchr(cfg, ':');
1061 if (!name || tmp > name)
1062 name = tmp;
1064 if (!name)
1065 name = cfg;
1066 else
1067 name++;
1069 if (use_filedir_conf) {
1070 char dircfg[PATH_MAX];
1071 strcpy(dircfg, cfg);
1072 strcpy(dircfg + (name - cfg), "mplayer.conf");
1073 try_load_config(conf, dircfg);
1075 if (try_load_config(conf, cfg))
1076 return;
1079 if ((confpath = get_path (name)) != NULL)
1081 try_load_config(conf, confpath);
1083 free (confpath);
1087 /* When libmpdemux performs a blocking operation (network connection or
1088 * cache filling) if the operation fails we use this function to check
1089 * if it was interrupted by the user.
1090 * The function returns a new value for eof. */
1091 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1093 mp_cmd_t* cmd;
1094 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1095 switch(cmd->id) {
1096 case MP_CMD_QUIT:
1097 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1098 case MP_CMD_PLAY_TREE_STEP: {
1099 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1100 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1101 } break;
1102 case MP_CMD_PLAY_TREE_UP_STEP: {
1103 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1104 } break;
1105 case MP_CMD_PLAY_ALT_SRC_STEP: {
1106 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1107 } break;
1109 mp_cmd_free(cmd);
1111 return stop_play;
1114 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1116 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1118 play_tree_add_bpf(entry,mpctx->filename);
1121 if(!entry) {
1122 entry = mpctx->playtree_iter->tree;
1123 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1124 return PT_NEXT_ENTRY;
1126 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1127 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1128 return PT_NEXT_ENTRY;
1131 play_tree_remove(entry,1,1);
1132 return PT_NEXT_SRC;
1134 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1135 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1136 entry = mpctx->playtree_iter->tree;
1137 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1138 return PT_NEXT_ENTRY;
1140 play_tree_remove(entry,1,1);
1142 return PT_NEXT_SRC;
1145 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1147 struct MPOpts *opts = &mpctx->opts;
1148 sub_data *subd = NULL;
1149 struct ass_track *asst = NULL;
1151 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1152 return;
1155 #ifdef CONFIG_ASS
1156 if (opts->ass_enabled) {
1157 #ifdef CONFIG_ICONV
1158 asst = ass_read_stream(ass_library, filename, sub_cp);
1159 #else
1160 asst = ass_read_stream(ass_library, filename, 0);
1161 #endif
1162 if (!asst) {
1163 subd = sub_read_file(filename, fps);
1164 if (subd) {
1165 asst = ass_read_subdata(ass_library, subd, fps);
1166 if (asst) {
1167 sub_free(subd);
1168 subd = NULL;
1172 } else
1173 #endif
1174 subd = sub_read_file(filename, fps);
1177 if (!asst && !subd) {
1178 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1179 "Cannot load subtitles: %s\n", filename_recode(filename));
1180 return;
1183 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1184 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1185 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1186 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1187 filename_recode(filename));
1188 ++mpctx->set_of_sub_size;
1189 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1190 filename_recode(filename));
1193 void init_vo_spudec(struct MPContext *mpctx)
1195 if (vo_spudec)
1196 spudec_free(vo_spudec);
1197 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1198 vo_spudec = NULL;
1200 // we currently can't work without video stream
1201 if (!mpctx->sh_video)
1202 return;
1204 if (spudec_ifo) {
1205 unsigned int palette[16], width, height;
1206 current_module="spudec_init_vobsub";
1207 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1208 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1211 #ifdef CONFIG_DVDREAD
1212 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1213 current_module="spudec_init_dvdread";
1214 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1215 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1216 NULL, 0);
1218 #endif
1220 #ifdef CONFIG_DVDNAV
1221 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1222 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1223 current_module="spudec_init_dvdnav";
1224 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1226 #endif
1228 if (vo_spudec==NULL) {
1229 sh_sub_t *sh = mpctx->d_sub->sh;
1230 current_module="spudec_init_normal";
1231 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1232 spudec_set_font_factor(vo_spudec,font_factor);
1235 if (vo_spudec!=NULL) {
1236 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1237 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1242 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1243 * make it all work is to use the builtin SDL-bootstrap code, which
1244 * will be done automatically by replacing our main() if we include SDL.h.
1246 #if defined(__APPLE__) && defined(CONFIG_SDL)
1247 #ifdef CONFIG_SDL_SDL_H
1248 #include <SDL/SDL.h>
1249 #else
1250 #include <SDL.h>
1251 #endif
1252 #endif
1255 * \brief append a formatted string
1256 * \param buf buffer to print into
1257 * \param pos position of terminating 0 in buf
1258 * \param len maximum number of characters in buf, not including terminating 0
1259 * \param format printf format string
1261 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1263 va_list va;
1264 va_start(va, format);
1265 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1266 va_end(va);
1267 if (*pos >= len ) {
1268 buf[len] = 0;
1269 *pos = len;
1274 * \brief append time in the hh:mm:ss.f format
1275 * \param buf buffer to print into
1276 * \param pos position of terminating 0 in buf
1277 * \param len maximum number of characters in buf, not including terminating 0
1278 * \param time time value to convert/append
1280 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1281 int64_t tenths = 10 * time;
1282 int f1 = tenths % 10;
1283 int ss = (tenths / 10) % 60;
1284 int mm = (tenths / 600) % 60;
1285 int hh = tenths / 36000;
1286 if (time <= 0) {
1287 saddf(buf, pos, len, "unknown");
1288 return;
1290 if (hh > 0)
1291 saddf(buf, pos, len, "%2d:", hh);
1292 if (hh > 0 || mm > 0)
1293 saddf(buf, pos, len, "%02d:", mm);
1294 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1297 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1299 struct MPOpts *opts = &mpctx->opts;
1300 sh_video_t * const sh_video = mpctx->sh_video;
1302 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1303 a_pos = playing_audio_pts(mpctx);
1304 if (mpctx->sh_audio && sh_video && at_frame) {
1305 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1306 if (mpctx->time_frame > 0)
1307 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1308 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1309 && !mpctx->drop_message_shown) {
1310 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1311 mpctx->drop_message_shown = true;
1314 if (quiet)
1315 return;
1318 int width;
1319 char *line;
1320 unsigned pos = 0;
1321 get_screen_size();
1322 if (screen_width > 0)
1323 width = screen_width;
1324 else
1325 width = 80;
1326 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1327 /* Windows command line is broken (MinGW's rxvt works, but we
1328 * should not depend on that). */
1329 width--;
1330 #endif
1331 line = malloc(width + 1); // one additional char for the terminating null
1333 // Audio time
1334 if (mpctx->sh_audio) {
1335 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1336 if (!sh_video) {
1337 float len = get_time_length(mpctx);
1338 saddf(line, &pos, width, "(");
1339 sadd_hhmmssf(line, &pos, width, a_pos);
1340 saddf(line, &pos, width, ") of %.1f (", len);
1341 sadd_hhmmssf(line, &pos, width, len);
1342 saddf(line, &pos, width, ") ");
1346 // Video time
1347 if (sh_video)
1348 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1350 // A-V sync
1351 if (mpctx->sh_audio && sh_video)
1352 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1353 mpctx->last_av_difference, mpctx->total_avsync_change);
1355 // Video stats
1356 if (sh_video)
1357 saddf(line, &pos, width, "%3d/%3d ",
1358 (int)sh_video->num_frames,
1359 (int)sh_video->num_frames_decoded);
1361 // CPU usage
1362 if (sh_video) {
1363 if (sh_video->timer > 0.5)
1364 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1365 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1366 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1367 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1368 else
1369 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1370 } else if (mpctx->sh_audio) {
1371 if (mpctx->delay > 0.5)
1372 saddf(line, &pos, width, "%4.1f%% ",
1373 100.0*audio_time_usage/(double)mpctx->delay);
1374 else
1375 saddf(line, &pos, width, "??,?%% ");
1378 // VO stats
1379 if (sh_video)
1380 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1382 #ifdef CONFIG_STREAM_CACHE
1383 // cache stats
1384 if (stream_cache_size > 0)
1385 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1386 #endif
1388 // other
1389 if (opts->playback_speed != 1)
1390 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1392 // end
1393 if (erase_to_end_of_line) {
1394 line[pos] = 0;
1395 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1396 } else {
1397 memset(&line[pos], ' ', width - pos);
1398 line[width] = 0;
1399 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1401 free(line);
1405 * \brief build a chain of audio filters that converts the input format
1406 * to the ao's format, taking into account the current playback_speed.
1407 * \param sh_audio describes the requested input format of the chain.
1408 * \param ao_data describes the requested output format of the chain.
1410 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1412 struct MPOpts *opts = &mpctx->opts;
1413 int new_srate;
1414 int result;
1415 if (!sh_audio)
1417 mpctx->mixer.afilter = NULL;
1418 return 0;
1420 if(af_control_any_rev(sh_audio->afilter,
1421 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1422 &opts->playback_speed)) {
1423 new_srate = sh_audio->samplerate;
1424 } else {
1425 new_srate = sh_audio->samplerate * opts->playback_speed;
1426 if (new_srate != ao_data->samplerate) {
1427 // limits are taken from libaf/af_resample.c
1428 if (new_srate < 8000)
1429 new_srate = 8000;
1430 if (new_srate > 192000)
1431 new_srate = 192000;
1432 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1435 result = init_audio_filters(sh_audio, new_srate,
1436 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1437 mpctx->mixer.afilter = sh_audio->afilter;
1438 return result;
1442 typedef struct mp_osd_msg mp_osd_msg_t;
1443 struct mp_osd_msg {
1444 /// Previous message on the stack.
1445 mp_osd_msg_t* prev;
1446 /// Message text.
1447 char msg[128];
1448 int id,level,started;
1449 /// Display duration in ms.
1450 unsigned time;
1453 /// OSD message stack.
1454 static mp_osd_msg_t* osd_msg_stack = NULL;
1457 * \brief Add a message on the OSD message stack
1459 * If a message with the same id is already present in the stack
1460 * it is pulled on top of the stack, otherwise a new message is created.
1463 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1464 va_list ap)
1466 mp_osd_msg_t *msg,*last=NULL;
1467 int r;
1469 // look if the id is already in the stack
1470 for(msg = osd_msg_stack ; msg && msg->id != id ;
1471 last = msg, msg = msg->prev);
1472 // not found: alloc it
1473 if(!msg) {
1474 msg = calloc(1,sizeof(mp_osd_msg_t));
1475 msg->prev = osd_msg_stack;
1476 osd_msg_stack = msg;
1477 } else if(last) { // found, but it's not on top of the stack
1478 last->prev = msg->prev;
1479 msg->prev = osd_msg_stack;
1480 osd_msg_stack = msg;
1482 // write the msg
1483 r = vsnprintf(msg->msg, 128, fmt, ap);
1484 if(r >= 128) msg->msg[127] = 0;
1485 // set id and time
1486 msg->id = id;
1487 msg->level = level;
1488 msg->time = time;
1492 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1494 va_list ap;
1495 va_start(ap, fmt);
1496 set_osd_msg_va(id, level, time, fmt, ap);
1497 va_end(ap);
1500 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1502 va_list ap;
1503 va_start(ap, fmt);
1504 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1505 va_end(ap);
1510 * \brief Remove a message from the OSD stack
1512 * This function can be used to get rid of a message right away.
1516 void rm_osd_msg(int id) {
1517 mp_osd_msg_t *msg,*last=NULL;
1519 // Search for the msg
1520 for(msg = osd_msg_stack ; msg && msg->id != id ;
1521 last = msg, msg = msg->prev);
1522 if(!msg) return;
1524 // Detach it from the stack and free it
1525 if(last)
1526 last->prev = msg->prev;
1527 else
1528 osd_msg_stack = msg->prev;
1529 free(msg);
1533 * \brief Remove all messages from the OSD stack
1537 static void clear_osd_msgs(void) {
1538 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1539 while(msg) {
1540 prev = msg->prev;
1541 free(msg);
1542 msg = prev;
1544 osd_msg_stack = NULL;
1548 * \brief Get the current message from the OSD stack.
1550 * This function decrements the message timer and destroys the old ones.
1551 * The message that should be displayed is returned (if any).
1555 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1557 struct MPOpts *opts = &mpctx->opts;
1558 mp_osd_msg_t *msg,*prev,*last = NULL;
1559 static unsigned last_update = 0;
1560 unsigned now = GetTimerMS();
1561 unsigned diff;
1562 char hidden_dec_done = 0;
1564 if (mpctx->osd_visible) {
1565 // 36000000 means max timed visibility is 1 hour into the future, if
1566 // the difference is greater assume it's wrapped around from below 0
1567 if (mpctx->osd_visible - now > 36000000) {
1568 mpctx->osd_visible = 0;
1569 vo_osd_progbar_type = -1; // disable
1570 vo_osd_changed(OSDTYPE_PROGBAR);
1571 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1574 if (mpctx->osd_show_percentage_until - now > 36000000)
1575 mpctx->osd_show_percentage_until = 0;
1577 if(!last_update) last_update = now;
1578 diff = now >= last_update ? now - last_update : 0;
1580 last_update = now;
1582 // Look for the first message in the stack with high enough level.
1583 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1584 prev = msg->prev;
1585 if (msg->level > opts->osd_level && hidden_dec_done)
1586 continue;
1587 // The message has a high enough level or it is the first hidden one
1588 // in both cases we decrement the timer or kill it.
1589 if(!msg->started || msg->time > diff) {
1590 if(msg->started) msg->time -= diff;
1591 else msg->started = 1;
1592 // display it
1593 if (msg->level <= opts->osd_level)
1594 return msg;
1595 hidden_dec_done = 1;
1596 continue;
1598 // kill the message
1599 free(msg);
1600 if(last) {
1601 last->prev = prev;
1602 msg = last;
1603 } else {
1604 osd_msg_stack = prev;
1605 msg = NULL;
1608 // Nothing found
1609 return NULL;
1613 * \brief Display the OSD bar.
1615 * Display the OSD bar or fall back on a simple message.
1619 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1620 struct MPOpts *opts = &mpctx->opts;
1621 if (opts->osd_level < 1)
1622 return;
1624 if(mpctx->sh_video) {
1625 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1626 vo_osd_progbar_type = type;
1627 vo_osd_progbar_value = 256*(val-min)/(max-min);
1628 vo_osd_changed(OSDTYPE_PROGBAR);
1629 return;
1632 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1633 name, ROUND(100*(val-min)/(max-min)));
1637 * \brief Display text subtitles on the OSD
1639 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1641 int i;
1642 vo_sub = subs;
1643 vo_osd_changed(OSDTYPE_SUBTITLE);
1644 if (!mpctx->sh_video) {
1645 // reverse order, since newest set_osd_msg is displayed first
1646 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1647 if (!subs || i >= subs->lines || !subs->text[i])
1648 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1649 else {
1650 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1651 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1652 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1659 * \brief Update the OSD message line.
1661 * This function displays the current message on the vo OSD or on the term.
1662 * If the stack is empty and the OSD level is high enough the timer
1663 * is displayed (only on the vo OSD).
1667 static void update_osd_msg(struct MPContext *mpctx)
1669 struct MPOpts *opts = &mpctx->opts;
1670 mp_osd_msg_t *msg;
1671 struct osd_state *osd = mpctx->osd;
1672 char osd_text_timer[128];
1674 if (mpctx->add_osd_seek_info) {
1675 double percentage = get_percent_pos(mpctx);
1676 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1677 if (mpctx->sh_video)
1678 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1679 mpctx->add_osd_seek_info = false;
1682 // Look if we have a msg
1683 if((msg = get_osd_msg(mpctx))) {
1684 if (strcmp(osd->osd_text, msg->msg)) {
1685 strncpy(osd->osd_text, msg->msg, 127);
1686 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1687 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1689 return;
1692 if(mpctx->sh_video) {
1693 // fallback on the timer
1694 if (opts->osd_level >= 2) {
1695 int len = get_time_length(mpctx);
1696 int percentage = -1;
1697 char percentage_text[10];
1698 int pts = get_current_time(mpctx);
1700 if (mpctx->osd_show_percentage_until)
1701 percentage = get_percent_pos(mpctx);
1703 if (percentage >= 0)
1704 snprintf(percentage_text, 9, " (%d%%)", percentage);
1705 else
1706 percentage_text[0] = 0;
1708 if (opts->osd_level == 3)
1709 snprintf(osd_text_timer, 63,
1710 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1711 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1712 len/3600,(len/60)%60,len%60,percentage_text);
1713 else
1714 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1715 mpctx->osd_function,pts/3600,(pts/60)%60,
1716 pts%60,percentage_text);
1717 } else
1718 osd_text_timer[0]=0;
1720 if (strcmp(osd->osd_text, osd_text_timer)) {
1721 strncpy(osd->osd_text, osd_text_timer, 63);
1722 vo_osd_changed(OSDTYPE_OSD);
1724 return;
1727 // Clear the term osd line
1728 if (term_osd && osd->osd_text[0]) {
1729 osd->osd_text[0] = 0;
1730 printf("%s\n",term_osd_esc);
1734 ///@}
1735 // OSDMsgStack
1738 void reinit_audio_chain(struct MPContext *mpctx)
1740 struct MPOpts *opts = &mpctx->opts;
1741 if (!mpctx->sh_audio)
1742 return;
1743 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1744 current_module="init_audio_codec";
1745 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1746 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1747 goto init_error;
1749 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1750 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1754 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1755 current_module="af_preinit";
1756 ao_data.samplerate=force_srate;
1757 ao_data.channels=0;
1758 ao_data.format = opts->audio_output_format;
1759 // first init to detect best values
1760 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1761 // input:
1762 mpctx->sh_audio->samplerate,
1763 // output:
1764 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1765 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1766 "pre-init!\n");
1767 exit_player(mpctx, EXIT_ERROR);
1769 current_module="ao2_init";
1770 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1771 0, // plugin flag
1772 ao_data.samplerate,
1773 ao_data.channels,
1774 ao_data.format, 0);
1775 if(!mpctx->audio_out){
1776 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1777 goto init_error;
1779 mpctx->initialized_flags|=INITIALIZED_AO;
1780 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1781 mpctx->audio_out->info->short_name,
1782 ao_data.samplerate, ao_data.channels,
1783 af_fmt2str_short(ao_data.format),
1784 af_fmt2bits(ao_data.format)/8 );
1785 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1786 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1787 if(strlen(mpctx->audio_out->info->comment) > 0)
1788 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1791 // init audio filters:
1792 current_module="af_init";
1793 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1794 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1795 goto init_error;
1797 mpctx->mixer.audio_out = mpctx->audio_out;
1798 mpctx->mixer.volstep = volstep;
1799 return;
1801 init_error:
1802 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1803 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1804 mpctx->d_audio->id = -2;
1808 ///@}
1809 // Command2Property
1812 // Return pts value corresponding to the end point of audio written to the
1813 // ao so far.
1814 static double written_audio_pts(struct MPContext *mpctx)
1816 sh_audio_t *sh_audio = mpctx->sh_audio;
1817 demux_stream_t *d_audio = mpctx->d_audio;
1818 double buffered_output;
1819 // first calculate the end pts of audio that has been output by decoder
1820 double a_pts = sh_audio->pts;
1821 if (a_pts != MP_NOPTS_VALUE)
1822 // Good, decoder supports new way of calculating audio pts.
1823 // sh_audio->pts is the timestamp of the latest input packet with
1824 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1825 // the amount of bytes the decoder has written after that timestamp.
1826 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1827 else {
1828 // Decoder doesn't support new way of calculating pts (or we're
1829 // being called before it has decoded anything with known timestamp).
1830 // Use the old method of audio pts calculation: take the timestamp
1831 // of last packet with known pts the decoder has read data from,
1832 // and add amount of bytes read after the beginning of that packet
1833 // divided by input bps. This will be inaccurate if the input/output
1834 // ratio is not constant for every audio packet or if it is constant
1835 // but not accurately known in sh_audio->i_bps.
1837 a_pts = d_audio->pts;
1838 // ds_tell_pts returns bytes read after last timestamp from
1839 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1840 // it has read but not decoded
1841 if (sh_audio->i_bps)
1842 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1843 (double)sh_audio->i_bps;
1845 // Now a_pts hopefully holds the pts for end of audio from decoder.
1846 // Substract data in buffers between decoder and audio out.
1848 // Decoded but not filtered
1849 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1851 // Data buffered in audio filters, measured in bytes of "missing" output
1852 buffered_output = af_calc_delay(sh_audio->afilter);
1854 // Data that was ready for ao but was buffered because ao didn't fully
1855 // accept everything to internal buffers yet
1856 buffered_output += sh_audio->a_out_buffer_len;
1858 // Filters divide audio length by playback_speed, so multiply by it
1859 // to get the length in original units without speedup or slowdown
1860 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1862 return a_pts + mpctx->video_offset;
1865 // Return pts value corresponding to currently playing audio.
1866 double playing_audio_pts(struct MPContext *mpctx)
1868 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1869 mpctx->audio_out->get_delay();
1872 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1873 struct MPOpts *opts = &mpctx->opts;
1874 // check for frame-drop:
1875 current_module = "check_framedrop";
1876 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1877 static int dropped_frames;
1878 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1879 float d = delay-mpctx->delay;
1880 ++total_frame_cnt;
1881 // we should avoid dropping too many frames in sequence unless we
1882 // are too late. and we allow 100ms A-V delay here:
1883 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1884 && !mpctx->update_video_immediately) {
1885 ++drop_frame_cnt;
1886 ++dropped_frames;
1887 return frame_dropping;
1888 } else
1889 dropped_frames = 0;
1891 return 0;
1895 #ifdef HAVE_RTC
1896 int rtc_fd = -1;
1897 #endif
1899 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1901 #ifdef HAVE_RTC
1902 if (rtc_fd >= 0){
1903 // -------- RTC -----------
1904 current_module="sleep_rtc";
1905 while (time_frame > 0.000) {
1906 unsigned long rtc_ts;
1907 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1908 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1909 time_frame -= get_relative_time(mpctx);
1911 } else
1912 #endif
1914 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1915 // unnecessarily high CPU usage
1916 float margin = softsleep ? 0.011 : 0;
1917 current_module = "sleep_timer";
1918 while (time_frame > margin) {
1919 usec_sleep(1000000 * (time_frame - margin));
1920 time_frame -= get_relative_time(mpctx);
1922 if (softsleep){
1923 current_module = "sleep_soft";
1924 if (time_frame < 0)
1925 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1926 while (time_frame > 0)
1927 time_frame -= get_relative_time(mpctx); // burn the CPU
1930 return time_frame;
1933 static int select_subtitle(MPContext *mpctx)
1935 struct MPOpts *opts = &mpctx->opts;
1936 // find the best sub to use
1937 int id;
1938 int found = 0;
1939 mpctx->global_sub_pos = -1; // no subs by default
1940 if (vobsub_id >= 0) {
1941 // if user asks for a vobsub id, use that first.
1942 id = vobsub_id;
1943 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1946 if (!found && opts->sub_id >= 0) {
1947 // if user asks for a dvd sub id, use that next.
1948 id = opts->sub_id;
1949 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1952 if (!found) {
1953 // if there are text subs to use, use those. (autosubs come last here)
1954 id = 0;
1955 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1958 if (!found && opts->sub_id == -1) {
1959 // finally select subs by language and container hints
1960 if (opts->sub_id == -1 && opts->sub_lang)
1961 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, opts->sub_lang);
1962 if (opts->sub_id == -1)
1963 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
1964 if (opts->sub_id >= 0) {
1965 id = opts->sub_id;
1966 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1969 return found;
1972 #ifdef CONFIG_DVDNAV
1973 #ifndef FF_B_TYPE
1974 #define FF_B_TYPE 3
1975 #endif
1976 /// store decoded video image
1977 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1978 mp_image_t *from_mpi) {
1979 mp_image_t *mpi;
1981 /// Do not store B-frames
1982 if (from_mpi->pict_type == FF_B_TYPE)
1983 return to_mpi;
1985 if (to_mpi &&
1986 to_mpi->w == from_mpi->w &&
1987 to_mpi->h == from_mpi->h &&
1988 to_mpi->imgfmt == from_mpi->imgfmt)
1989 mpi = to_mpi;
1990 else {
1991 if (to_mpi)
1992 free_mp_image(to_mpi);
1993 if (from_mpi->w == 0 || from_mpi->h == 0)
1994 return NULL;
1995 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1998 copy_mpi(mpi,from_mpi);
1999 return mpi;
2002 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2003 struct MPOpts *opts = &ctx->opts;
2004 if (ctx->sh_video) {
2005 /// clear video pts
2006 ctx->d_video->pts = 0.0f;
2007 ctx->sh_video->pts = 0.0f;
2008 ctx->sh_video->i_pts = 0.0f;
2009 ctx->sh_video->last_pts = 0.0f;
2010 ctx->sh_video->num_buffered_pts = 0;
2011 ctx->sh_video->num_frames = 0;
2012 ctx->sh_video->num_frames_decoded = 0;
2013 ctx->sh_video->timer = 0.0f;
2014 ctx->sh_video->stream_delay = 0.0f;
2015 ctx->sh_video->timer = 0;
2016 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2019 if (ctx->sh_audio) {
2020 /// free audio packets and reset
2021 ds_free_packs(ctx->d_audio);
2022 audio_delay -= ctx->sh_audio->stream_delay;
2023 ctx->delay =- audio_delay;
2024 ctx->audio_out->reset();
2025 resync_audio_stream(ctx->sh_audio);
2028 audio_delay = 0.0f;
2029 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2030 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2031 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2032 if (dvdsub_lang_id != opts->sub_id) {
2033 opts->sub_id = dvdsub_lang_id;
2034 select_subtitle(ctx);
2038 /// clear all EOF related flags
2039 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2042 /// Restore last decoded DVDNAV (still frame)
2043 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2044 int *in_size,
2045 unsigned char **start,
2046 mp_image_t *decoded_frame)
2048 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2049 return decoded_frame;
2051 /// a change occured in dvdnav stream
2052 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2053 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2054 mp_dvdnav_context_free(mpctx);
2055 mp_dvdnav_reset_stream(mpctx);
2056 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2057 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2060 if (*in_size < 0) {
2061 float len;
2063 /// Display still frame, if any
2064 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2065 decoded_frame = mpctx->nav_smpi;
2067 /// increment video frame : continue playing after still frame
2068 len = get_time_length(mpctx);
2069 if (mpctx->sh_video->pts >= len &&
2070 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2071 mp_dvdnav_skip_still(mpctx->stream);
2072 mp_dvdnav_skip_wait(mpctx->stream);
2074 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2076 if (mpctx->nav_buffer) {
2077 *start = mpctx->nav_start;
2078 *in_size = mpctx->nav_in_size;
2079 if (mpctx->nav_start)
2080 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2084 return decoded_frame;
2087 /// Save last decoded DVDNAV (still frame)
2088 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2089 unsigned char *start,
2090 mp_image_t *decoded_frame)
2092 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2093 return;
2095 free(mpctx->nav_buffer);
2097 mpctx->nav_buffer = malloc(in_size);
2098 mpctx->nav_start = start;
2099 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2100 if (mpctx->nav_buffer)
2101 memcpy(mpctx->nav_buffer,start,in_size);
2103 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2104 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2106 #endif /* CONFIG_DVDNAV */
2108 /* Modify video timing to match the audio timeline. There are two main
2109 * reasons this is needed. First, video and audio can start from different
2110 * positions at beginning of file or after a seek (MPlayer starts both
2111 * immediately even if they have different pts). Second, the file can have
2112 * audio timestamps that are inconsistent with the duration of the audio
2113 * packets, for example two consecutive timestamp values differing by
2114 * one second but only a packet with enough samples for half a second
2115 * of playback between them.
2117 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2119 current_module = "av_sync";
2121 if (!mpctx->sh_audio)
2122 return;
2124 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2125 double v_pts = mpctx->sh_video->pts;
2126 double av_delay = a_pts - v_pts;
2127 // Try to sync vo_flip() so it will *finish* at given time
2128 av_delay += mpctx->last_vo_flip_duration;
2129 av_delay -= audio_delay; // This much pts difference is desired
2131 double change = av_delay * 0.1;
2132 double max_change = default_max_pts_correction >= 0 ?
2133 default_max_pts_correction : frame_time * 0.1;
2134 if (change < -max_change)
2135 change = -max_change;
2136 else if (change > max_change)
2137 change = max_change;
2138 mpctx->delay += change;
2139 mpctx->total_avsync_change += change;
2142 static int fill_audio_out_buffers(struct MPContext *mpctx)
2144 struct MPOpts *opts = &mpctx->opts;
2145 unsigned int t;
2146 double tt;
2147 int playsize;
2148 int playflags=0;
2149 int audio_eof=0;
2150 bool format_change = false;
2151 sh_audio_t * const sh_audio = mpctx->sh_audio;
2153 current_module="play_audio";
2155 while (1) {
2156 int sleep_time;
2157 // all the current uses of ao_data.pts seem to be in aos that handle
2158 // sync completely wrong; there should be no need to use ao_data.pts
2159 // in get_space()
2160 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2161 playsize = mpctx->audio_out->get_space();
2162 if (mpctx->sh_video || playsize >= ao_data.outburst)
2163 break;
2165 // handle audio-only case:
2166 // this is where mplayer sleeps during audio-only playback
2167 // to avoid 100% CPU use
2168 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2169 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2170 usec_sleep(sleep_time * 1000);
2173 // Fill buffer if needed:
2174 current_module="decode_audio";
2175 t = GetTimer();
2176 int res = decode_audio(sh_audio, playsize);
2177 if (res < 0) { // EOF, error or format change
2178 if (res == -2)
2179 format_change = true;
2180 else if (mpctx->d_audio->eof) {
2181 audio_eof = 1;
2182 if (sh_audio->a_out_buffer_len == 0)
2183 return 0;
2186 t = GetTimer() - t;
2187 tt = t*0.000001f; audio_time_usage+=tt;
2188 if (playsize > sh_audio->a_out_buffer_len) {
2189 playsize = sh_audio->a_out_buffer_len;
2190 if (audio_eof)
2191 playflags |= AOPLAY_FINAL_CHUNK;
2193 if (!playsize)
2194 return 1;
2196 // play audio:
2197 current_module="play_audio";
2199 // Is this pts value actually useful for the aos that access it?
2200 // They're obviously badly broken in the way they handle av sync;
2201 // would not having access to this make them more broken?
2202 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2203 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2205 if (playsize > 0) {
2206 sh_audio->a_out_buffer_len -= playsize;
2207 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2208 sh_audio->a_out_buffer_len);
2209 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2211 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2212 // Sanity check to avoid hanging in case current ao doesn't output
2213 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2214 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2215 sh_audio->a_out_buffer_len = 0;
2218 /* The format change isn't handled too gracefully. A more precise
2219 * implementation would require draining buffered old-format audio
2220 * while displaying video, then doing the output format switch.
2222 if (format_change) {
2223 uninit_player(mpctx, INITIALIZED_AO);
2224 reinit_audio_chain(mpctx);
2227 return 1;
2230 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2231 float *aq_sleep_time)
2233 struct MPOpts *opts = &mpctx->opts;
2234 int frame_time_remaining = 0;
2235 current_module="calc_sleep_time";
2237 *time_frame -= get_relative_time(mpctx); // reset timer
2239 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2240 float delay = mpctx->audio_out->get_delay();
2241 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2243 if (autosync) {
2245 * Adjust this raw delay value by calculating the expected
2246 * delay for this frame and generating a new value which is
2247 * weighted between the two. The higher autosync is, the
2248 * closer to the delay value gets to that which "-nosound"
2249 * would have used, and the longer it will take for A/V
2250 * sync to settle at the right value (but it eventually will.)
2251 * This settling time is very short for values below 100.
2253 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2254 float difference = delay - predicted;
2255 delay = predicted + difference / (float)autosync;
2258 *time_frame = delay - mpctx->delay / opts->playback_speed;
2259 *time_frame -= mpctx->video_out->flip_queue_offset;
2261 // delay = amount of audio buffered in soundcard/driver
2262 if (delay > 0.25) delay=0.25; else
2263 if (delay < 0.10) delay=0.10;
2265 if (*time_frame > delay*0.6) {
2266 // sleep time too big - may cause audio drops (buffer underrun)
2267 frame_time_remaining = 1;
2268 *time_frame = delay*0.5;
2270 } else {
2271 // If we're lagging more than 200 ms behind the right playback rate,
2272 // don't try to "catch up".
2273 // If benchmark is set always output frames as fast as possible
2274 // without sleeping.
2275 if (*time_frame < -0.2 || benchmark)
2276 *time_frame = 0;
2277 *time_frame -= mpctx->video_out->flip_queue_offset;
2280 *aq_sleep_time += *time_frame;
2283 //============================== SLEEP: ===================================
2285 // flag 256 means: libvo driver does its timing (dvb card)
2286 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2287 *time_frame = timing_sleep(mpctx, *time_frame);
2288 *time_frame += mpctx->video_out->flip_queue_offset;
2289 return frame_time_remaining;
2292 int reinit_video_chain(struct MPContext *mpctx)
2294 struct MPOpts *opts = &mpctx->opts;
2295 sh_video_t * const sh_video = mpctx->sh_video;
2296 double ar=-1.0;
2297 //================== Init VIDEO (codec & libvo) ==========================
2298 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2299 current_module="preinit_libvo";
2301 //shouldn't we set dvideo->id=-2 when we fail?
2302 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2303 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2304 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2305 goto err_out;
2307 mpctx->initialized_flags|=INITIALIZED_VO;
2310 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2311 mpctx->sh_video->stream_aspect = ar;
2312 current_module="init_video_filters";
2314 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2315 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2317 #ifdef CONFIG_MENU
2318 if(use_menu) {
2319 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2320 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2321 if(!vf_menu) {
2322 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2323 use_menu = 0;
2326 if(vf_menu)
2327 sh_video->vfilter = vf_menu;
2328 #endif
2330 #ifdef CONFIG_ASS
2331 if(opts->ass_enabled) {
2332 int i;
2333 int insert = 1;
2334 if (opts->vf_settings)
2335 for (i = 0; opts->vf_settings[i].name; ++i)
2336 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2337 insert = 0;
2338 break;
2340 if (insert) {
2341 extern vf_info_t vf_info_ass;
2342 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2343 char* vf_arg[] = {"auto", "1", NULL};
2344 int retcode = 0;
2345 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2346 sh_video->vfilter,
2347 "ass", vf_arg,
2348 &retcode);
2349 if (vf_ass)
2350 sh_video->vfilter = vf_ass;
2351 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2352 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2353 else
2354 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2357 #endif
2359 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2361 #ifdef CONFIG_ASS
2362 if (opts->ass_enabled)
2363 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2364 #endif
2366 current_module="init_video_codec";
2368 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2369 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2370 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2372 if(!sh_video->initialized){
2373 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2374 goto err_out;
2377 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2379 if (sh_video->codec)
2380 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2382 sh_video->last_pts = MP_NOPTS_VALUE;
2383 sh_video->num_buffered_pts = 0;
2384 sh_video->next_frame_time = 0;
2386 if(auto_quality>0){
2387 // Auto quality option enabled
2388 output_quality=get_video_quality_max(sh_video);
2389 if(auto_quality>output_quality) auto_quality=output_quality;
2390 else output_quality=auto_quality;
2391 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2392 set_video_quality(sh_video,output_quality);
2395 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2397 current_module="init_vo";
2399 return 1;
2401 err_out:
2402 mpctx->sh_video = mpctx->d_video->sh = NULL;
2403 return 0;
2406 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2408 struct sh_video *sh_video = mpctx->sh_video;
2409 double frame_time = 0;
2410 struct vo *video_out = mpctx->video_out;
2411 while (!video_out->frame_loaded) {
2412 current_module = "filter_video";
2413 // In nocorrect-pts mode there is no way to properly time these frames
2414 if (vo_get_buffered_frame(video_out, 0) >= 0)
2415 break;
2416 if (vf_output_queued_frame(sh_video->vfilter))
2417 continue;
2418 unsigned char *packet = NULL;
2419 frame_time = sh_video->next_frame_time;
2420 if (mpctx->update_video_immediately)
2421 frame_time = 0;
2422 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2423 &packet, force_fps);
2424 if (in_size < 0) {
2425 #ifdef CONFIG_DVDNAV
2426 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2427 if (mp_dvdnav_is_eof(mpctx->stream))
2428 return -1;
2429 if (mpctx->d_video)
2430 mpctx->d_video->eof = 0;
2431 if (mpctx->d_audio)
2432 mpctx->d_audio->eof = 0;
2433 mpctx->stream->eof = 0;
2434 } else
2435 #endif
2436 return -1;
2438 if (in_size > max_framesize)
2439 max_framesize = in_size;
2440 sh_video->timer += frame_time;
2441 if (mpctx->sh_audio)
2442 mpctx->delay -= frame_time;
2443 // video_read_frame can change fps (e.g. for ASF video)
2444 vo_fps = sh_video->fps;
2445 int framedrop_type = check_framedrop(mpctx, frame_time);
2446 current_module = "decode video";
2448 void *decoded_frame;
2449 #ifdef CONFIG_DVDNAV
2450 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2451 if (in_size >= 0 && !decoded_frame)
2452 #endif
2453 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2454 sh_video->pts);
2455 #ifdef CONFIG_DVDNAV
2456 // Save last still frame for future display
2457 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2458 #endif
2459 if (decoded_frame) {
2460 current_module = "filter video";
2461 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2462 if (!video_out->config_ok)
2463 break;
2466 return frame_time;
2469 static void determine_frame_pts(struct MPContext *mpctx)
2471 struct sh_video *sh_video = mpctx->sh_video;
2472 struct MPOpts *opts = &mpctx->opts;
2474 if (opts->user_pts_assoc_mode) {
2475 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2476 } else if (sh_video->pts_assoc_mode == 0) {
2477 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2478 sh_video->pts_assoc_mode = 1;
2479 else
2480 sh_video->pts_assoc_mode = 2;
2481 } else {
2482 int probcount1 = sh_video->num_reordered_pts_problems;
2483 int probcount2 = sh_video->num_sorted_pts_problems;
2484 if (sh_video->pts_assoc_mode == 2) {
2485 int tmp = probcount1;
2486 probcount1 = probcount2;
2487 probcount2 = tmp;
2489 if (probcount1 >= probcount2 * 1.5 + 2) {
2490 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2491 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2492 "%d.\n", sh_video->pts_assoc_mode);
2495 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2496 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2499 static double update_video(struct MPContext *mpctx)
2501 struct sh_video *sh_video = mpctx->sh_video;
2502 struct vo *video_out = mpctx->video_out;
2503 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2504 mpctx->osd); // hack for vf_expand
2505 if (!mpctx->opts.correct_pts)
2506 return update_video_nocorrect_pts(mpctx);
2508 double pts;
2510 bool hit_eof = false;
2511 while (!video_out->frame_loaded) {
2512 current_module = "filter_video";
2513 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2514 break;
2515 // XXX Time used in this call is not counted in any performance
2516 // timer now, OSD time is not updated correctly for filter-added frames
2517 if (vf_output_queued_frame(sh_video->vfilter))
2518 continue;
2519 if (hit_eof)
2520 return -1;
2521 unsigned char *packet = NULL;
2522 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2523 if (pts != MP_NOPTS_VALUE)
2524 pts += mpctx->video_offset;
2525 if (in_size < 0) {
2526 // try to extract last frames in case of decoder lag
2527 in_size = 0;
2528 pts = MP_NOPTS_VALUE;
2529 hit_eof = true;
2531 if (in_size > max_framesize)
2532 max_framesize = in_size;
2533 current_module = "decode video";
2534 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2535 void *decoded_frame = decode_video(sh_video, packet, in_size,
2536 framedrop_type, pts);
2537 if (decoded_frame) {
2538 determine_frame_pts(mpctx);
2539 current_module = "filter video";
2540 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2541 if (!video_out->config_ok)
2542 break; // We'd likely hang in this loop otherwise
2546 pts = video_out->next_pts;
2547 if (pts == MP_NOPTS_VALUE) {
2548 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2549 // Try to use decoder pts from before filters
2550 pts = sh_video->pts;
2551 if (pts == MP_NOPTS_VALUE)
2552 pts = sh_video->last_pts;
2554 sh_video->pts = pts;
2555 if (sh_video->last_pts == MP_NOPTS_VALUE)
2556 sh_video->last_pts = sh_video->pts;
2557 else if (sh_video->last_pts > sh_video->pts) {
2558 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2559 sh_video->pts, sh_video->last_pts);
2560 /* If the difference in pts is small treat it as jitter around the
2561 * right value (possibly caused by incorrect timestamp ordering) and
2562 * just show this frame immediately after the last one.
2563 * Treat bigger differences as timestamp resets and start counting
2564 * timing of later frames from the position of this one. */
2565 if (sh_video->last_pts - sh_video->pts > 0.5)
2566 sh_video->last_pts = sh_video->pts;
2567 else
2568 sh_video->pts = sh_video->last_pts;
2570 double frame_time = sh_video->pts - sh_video->last_pts;
2571 sh_video->last_pts = sh_video->pts;
2572 sh_video->timer += frame_time;
2573 if (mpctx->sh_audio)
2574 mpctx->delay -= frame_time;
2575 return frame_time;
2578 void pause_player(struct MPContext *mpctx)
2580 if (mpctx->paused)
2581 return;
2582 mpctx->paused = 1;
2583 mpctx->step_frames = 0;
2584 mpctx->time_frame -= get_relative_time(mpctx);
2586 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2587 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2589 if (mpctx->audio_out && mpctx->sh_audio)
2590 mpctx->audio_out->pause(); // pause audio, keep data if possible
2593 void unpause_player(struct MPContext *mpctx)
2595 if (!mpctx->paused)
2596 return;
2597 mpctx->paused = 0;
2599 if (mpctx->audio_out && mpctx->sh_audio)
2600 mpctx->audio_out->resume(); // resume audio
2601 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2602 && !mpctx->step_frames)
2603 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2604 (void)get_relative_time(mpctx); // ignore time that passed during pause
2607 void add_step_frame(struct MPContext *mpctx)
2609 mpctx->step_frames++;
2610 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2611 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2612 unpause_player(mpctx);
2615 static void pause_loop(struct MPContext *mpctx)
2617 mp_cmd_t* cmd;
2618 if (!quiet) {
2619 // Small hack to display the pause message on the OSD line.
2620 // The pause string is: "\n == PAUSE == \r" so we need to
2621 // take the first and the last char out
2622 if (term_osd && !mpctx->sh_video) {
2623 char msg[128] = _("\n ===== PAUSE =====\r");
2624 int mlen = strlen(msg);
2625 msg[mlen-1] = '\0';
2626 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2627 update_osd_msg(mpctx);
2628 } else
2629 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2630 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2633 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2634 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2635 if (cmd) {
2636 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2637 run_command(mpctx, cmd);
2638 mp_cmd_free(cmd);
2639 continue;
2641 if (mpctx->sh_video && mpctx->video_out)
2642 vo_check_events(mpctx->video_out);
2643 #ifdef CONFIG_MENU
2644 if (vf_menu)
2645 vf_menu_pause_update(vf_menu);
2646 #endif
2647 usec_sleep(20000);
2648 update_osd_msg(mpctx);
2649 int hack = vo_osd_changed(0);
2650 vo_osd_changed(hack);
2651 if (hack)
2652 break;
2657 // Find the right mute status and record position for new file position
2658 static void edl_seek_reset(MPContext *mpctx)
2660 mpctx->edl_muted = 0;
2661 next_edl_record = edl_records;
2663 while (next_edl_record) {
2664 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2665 break;
2667 if (next_edl_record->action == EDL_MUTE)
2668 mpctx->edl_muted = !mpctx->edl_muted;
2669 next_edl_record = next_edl_record->next;
2671 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2672 mixer_mute(&mpctx->mixer);
2676 // Execute EDL command for the current position if one exists
2677 static void edl_update(MPContext *mpctx)
2679 if (!next_edl_record)
2680 return;
2682 if (!mpctx->sh_video) {
2683 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2684 free_edl(edl_records);
2685 next_edl_record = NULL;
2686 edl_records = NULL;
2687 return;
2690 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2691 if (next_edl_record->action == EDL_SKIP) {
2692 mpctx->osd_function = OSD_FFW;
2693 mpctx->abs_seek_pos = 0;
2694 mpctx->rel_seek_secs = next_edl_record->length_sec;
2695 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2696 "[%f], length [%f]\n", next_edl_record->start_sec,
2697 next_edl_record->stop_sec, next_edl_record->length_sec);
2699 else if (next_edl_record->action == EDL_MUTE) {
2700 mpctx->edl_muted = !mpctx->edl_muted;
2701 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2702 mixer_mute(&mpctx->mixer);
2703 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2704 next_edl_record->start_sec );
2706 next_edl_record = next_edl_record->next;
2710 static void reinit_decoders(struct MPContext *mpctx)
2712 reinit_video_chain(mpctx);
2713 reinit_audio_chain(mpctx);
2714 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2717 static void seek_reset(struct MPContext *mpctx)
2719 if (mpctx->sh_video) {
2720 current_module = "seek_video_reset";
2721 resync_video_stream(mpctx->sh_video);
2722 mpctx->sh_video->timer = 0;
2723 vo_seek_reset(mpctx->video_out);
2724 mpctx->sh_video->timer = 0;
2725 mpctx->sh_video->num_buffered_pts = 0;
2726 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2727 mpctx->delay = 0;
2728 mpctx->time_frame = 0;
2729 mpctx->update_video_immediately = true;
2730 // Not all demuxers set d_video->pts during seek, so this value
2731 // (which is used by at least vobsub and edl code below) may
2732 // be completely wrong (probably 0).
2733 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2734 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2735 mpctx->sh_video->pts, mpctx->video_offset,
2736 mpctx->d_sub, 1);
2737 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2740 if (mpctx->sh_audio) {
2741 current_module = "seek_audio_reset";
2742 resync_audio_stream(mpctx->sh_audio);
2743 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2744 mpctx->sh_audio->a_buffer_len = 0;
2745 mpctx->sh_audio->a_out_buffer_len = 0;
2746 if (!mpctx->sh_video)
2747 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2748 mpctx->video_offset, mpctx->d_sub, 1);
2751 if (vo_vobsub && mpctx->sh_video) {
2752 current_module = "seek_vobsub_reset";
2753 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2756 edl_seek_reset(mpctx);
2758 mpctx->total_avsync_change = 0;
2759 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2760 drop_frame_cnt = 0;
2762 current_module = NULL;
2765 static bool timeline_set_part(struct MPContext *mpctx, int i)
2767 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2768 struct timeline_part *n = mpctx->timeline + i;
2769 mpctx->timeline_part = i;
2770 mpctx->video_offset = n->start - n->source_start;
2771 if (n->source == p->source)
2772 return false;
2773 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2774 mpctx->demuxer = n->source->demuxer;
2775 mpctx->d_video = mpctx->demuxer->video;
2776 mpctx->d_audio = mpctx->demuxer->audio;
2777 mpctx->d_sub = mpctx->demuxer->sub;
2778 mpctx->sh_video = mpctx->d_video->sh;
2779 mpctx->sh_audio = mpctx->d_audio->sh;
2780 return true;
2783 // Given pts, switch playback to the corresponding part.
2784 // Return offset within that part.
2785 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2786 bool *need_reset)
2788 if (pts < 0)
2789 pts = 0;
2790 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2791 struct timeline_part *p = mpctx->timeline + i;
2792 if (pts < (p+1)->start) {
2793 *need_reset = timeline_set_part(mpctx, i);
2794 return pts - p->start + p->source_start;
2797 return -1;
2801 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2802 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2803 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2804 static int seek(MPContext *mpctx, double amount, int style)
2806 current_module = "seek";
2807 if (mpctx->stop_play == AT_END_OF_FILE)
2808 mpctx->stop_play = KEEP_PLAYING;
2809 if (style & SEEK_FACTOR
2810 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2811 || amount < 0)
2812 mpctx->last_chapter_seek = -1;
2813 if (mpctx->timeline && style & SEEK_FACTOR) {
2814 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2815 style &= ~SEEK_FACTOR;
2817 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2818 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2819 style |= SEEK_ABSOLUTE;
2820 if (amount > 0)
2821 style |= SEEK_FORWARD;
2822 else
2823 style |= SEEK_BACKWARD;
2824 amount += mpctx->sh_video->pts;
2827 /* At least the liba52 decoder wants to read from the input stream
2828 * during initialization, so reinit must be done after the demux_seek()
2829 * call that clears possible stream EOF. */
2830 bool need_reset = false;
2831 if (mpctx->timeline) {
2832 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2833 if (amount == -1) {
2834 mpctx->stop_play = AT_END_OF_FILE;
2835 // Clear audio from current position
2836 if (mpctx->sh_audio) {
2837 mpctx->audio_out->reset();
2838 mpctx->sh_audio->a_buffer_len = 0;
2839 mpctx->sh_audio->a_out_buffer_len = 0;
2841 return -1;
2844 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2845 if (need_reset)
2846 reinit_decoders(mpctx);
2847 if (seekresult == 0)
2848 return -1;
2850 seek_reset(mpctx);
2851 return 0;
2855 double get_time_length(struct MPContext *mpctx)
2857 if (mpctx->timeline)
2858 return mpctx->timeline[mpctx->num_timeline_parts].start;
2860 struct demuxer *demuxer = mpctx->demuxer;
2861 double get_time_ans;
2862 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
2863 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
2864 (void *) &get_time_ans) > 0)
2865 return get_time_ans;
2867 struct sh_video *sh_video = mpctx->d_video->sh;
2868 struct sh_audio *sh_audio = mpctx->d_audio->sh;
2869 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
2870 return (double) (demuxer->movi_end - demuxer->movi_start) /
2871 (sh_video->i_bps + sh_audio->i_bps);
2872 if (sh_video && sh_video->i_bps)
2873 return (double) (demuxer->movi_end - demuxer->movi_start) /
2874 sh_video->i_bps;
2875 if (sh_audio && sh_audio->i_bps)
2876 return (double) (demuxer->movi_end - demuxer->movi_start) /
2877 sh_audio->i_bps;
2878 return 0;
2881 /* If there are timestamps from stream level then use those (for example
2882 * DVDs can have consistent times there while the MPEG-level timestamps
2883 * reset). */
2884 double get_current_time(struct MPContext *mpctx)
2886 struct demuxer *demuxer = mpctx->demuxer;
2887 if (demuxer->stream_pts != MP_NOPTS_VALUE)
2888 return demuxer->stream_pts;
2889 struct sh_video *sh_video = demuxer->video->sh;
2890 if (sh_video)
2891 return sh_video->pts;
2892 return playing_audio_pts(mpctx);
2895 int get_percent_pos(struct MPContext *mpctx)
2897 struct demuxer *demuxer = mpctx->demuxer;
2898 int ans = 0;
2899 if (mpctx->timeline)
2900 ans = get_current_time(mpctx) * 100 /
2901 mpctx->timeline[mpctx->num_timeline_parts].start;
2902 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
2904 else {
2905 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
2906 off_t pos = demuxer->filepos > 0 ?
2907 demuxer->filepos : stream_tell(demuxer->stream);
2908 if (len > 0)
2909 ans = (pos - demuxer->movi_start) / len;
2910 else
2911 ans = 0;
2913 if (ans < 0)
2914 ans = 0;
2915 if (ans > 100)
2916 ans = 100;
2917 return ans;
2920 // -2 is no chapters, -1 is before first chapter
2921 int get_current_chapter(struct MPContext *mpctx)
2923 if (!mpctx->chapters || !mpctx->sh_video)
2924 return FFMAX(mpctx->last_chapter_seek,
2925 demuxer_get_current_chapter(mpctx->demuxer));
2927 int i;
2928 double current_pts = mpctx->sh_video->pts;
2929 for (i = 1; i < mpctx->num_chapters; i++)
2930 if (current_pts < mpctx->chapters[i].start)
2931 break;
2932 return FFMAX(mpctx->last_chapter_seek, i - 1);
2935 // currently returns a string allocated with malloc, not talloc
2936 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2938 if (!mpctx->chapters || !mpctx->sh_video)
2939 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2940 return strdup(mpctx->chapters[chapter].name);
2943 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2944 char **chapter_name)
2946 mpctx->last_chapter_seek = -1;
2947 if (!mpctx->chapters || !mpctx->sh_video) {
2948 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2949 chapter_name);
2950 if (res >= 0) {
2951 if (*seek_pts == -1)
2952 seek_reset(mpctx);
2953 else {
2954 mpctx->last_chapter_seek = res;
2955 mpctx->last_chapter_pts = *seek_pts;
2958 return res;
2961 if (chapter >= mpctx->num_chapters)
2962 return -1;
2963 if (chapter < 0)
2964 chapter = 0;
2965 *seek_pts = mpctx->chapters[chapter].start;
2966 mpctx->last_chapter_seek = chapter;
2967 mpctx->last_chapter_pts = *seek_pts;
2968 if (chapter_name)
2969 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2970 return chapter;
2973 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2974 struct content_source *sources,
2975 int num_sources,
2976 unsigned char uid_map[][16])
2978 int num_filenames = 0;
2979 char **filenames = NULL;
2980 if (num_sources > 1) {
2981 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2982 "other sources.\n");
2983 if (mpctx->stream->type != STREAMTYPE_FILE) {
2984 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2985 "normal disk file. Will not search for related files.\n");
2986 } else {
2987 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2988 "same directory to find referenced sources.\n");
2989 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2990 &num_filenames);
2994 int num_left = num_sources - 1;
2995 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2996 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2997 filename_recode(filenames[i]));
2998 int format;
2999 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3000 if (!s)
3001 continue;
3002 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3003 mpctx->opts.audio_id,
3004 mpctx->opts.video_id,
3005 mpctx->opts.sub_id, filenames[i]);
3006 if (!d) {
3007 free_stream(s);
3008 continue;
3010 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3011 for (int i = 1; i < num_sources; i++) {
3012 if (sources[i].demuxer)
3013 continue;
3014 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3015 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3016 i, filename_recode(d->filename));
3017 sources[i].stream = s;
3018 sources[i].demuxer = d;
3019 num_left--;
3020 goto match;
3024 free_demuxer(d);
3025 free_stream(s);
3026 continue;
3027 match:
3030 talloc_free(filenames);
3031 if (num_left) {
3032 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3033 "There will be parts MISSING from the video!\n");
3034 for (int i = 1, j = 1; i < num_sources; i++)
3035 if (sources[i].demuxer) {
3036 sources[j] = sources[i];
3037 memcpy(uid_map[j], uid_map[i], 16);
3038 j++;
3041 return num_sources - num_left;
3044 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3046 if (!mpctx->opts.ordered_chapters) {
3047 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3048 "you have disabled support for them. Ignoring.\n");
3049 return;
3052 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3053 "edit timeline.\n");
3055 struct demuxer *demuxer = mpctx->demuxer;
3056 struct matroska_data *m = &demuxer->matroska_data;
3058 // +1 because sources/uid_map[0] is original file even if all chapters
3059 // actually use other sources and need separate entries
3060 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3061 m->num_ordered_chapters+1);
3062 sources[0].stream = mpctx->stream;
3063 sources[0].demuxer = mpctx->demuxer;
3064 unsigned char uid_map[m->num_ordered_chapters+1][16];
3065 int num_sources = 1;
3066 memcpy(uid_map[0], m->segment_uid, 16);
3068 for (int i = 0; i < m->num_ordered_chapters; i++) {
3069 struct matroska_chapter *c = m->ordered_chapters + i;
3070 if (!c->has_segment_uid)
3071 memcpy(c->segment_uid, m->segment_uid, 16);
3073 for (int j = 0; j < num_sources; j++)
3074 if (!memcmp(c->segment_uid, uid_map[j], 16))
3075 goto found1;
3076 memcpy(uid_map[num_sources], c->segment_uid, 16);
3077 sources[num_sources] = (struct content_source){};
3078 num_sources++;
3079 found1:
3083 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3084 uid_map);
3087 // +1 for terminating chapter with start time marking end of last real one
3088 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3089 m->num_ordered_chapters + 1);
3090 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3091 m->num_ordered_chapters);
3092 uint64_t starttime = 0;
3093 uint64_t missing_time = 0;
3094 int part_count = 0;
3095 int num_chapters = 0;
3096 uint64_t prev_part_offset = 0;
3097 for (int i = 0; i < m->num_ordered_chapters; i++) {
3098 struct matroska_chapter *c = m->ordered_chapters + i;
3100 int j;
3101 for (j = 0; j < num_sources; j++) {
3102 if (!memcmp(c->segment_uid, uid_map[j], 16))
3103 goto found2;
3105 missing_time += c->end - c->start;
3106 continue;
3107 found2:;
3108 chapters[num_chapters].start = starttime / 1000.;
3109 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3110 /* Only add a separate part if the time or file actually changes.
3111 * Matroska files have chapter divisions that are redundant from
3112 * timeline point of view because the same chapter structure is used
3113 * both to specify the timeline and for normal chapter information.
3114 * Removing a missing inserted external chapter can also cause this. */
3115 if (part_count == 0 || c->start != starttime + prev_part_offset
3116 || sources + j != timeline[part_count - 1].source) {
3117 timeline[part_count].source = sources + j;
3118 timeline[part_count].start = chapters[num_chapters].start;
3119 timeline[part_count].source_start = c->start / 1000.;
3120 prev_part_offset = c->start - starttime;
3121 part_count++;
3123 starttime += c->end - c->start;
3124 num_chapters++;
3126 timeline[part_count].start = starttime / 1000.;
3128 if (!part_count) {
3129 // None of the parts come from the file itself???
3130 talloc_free(sources);
3131 talloc_free(timeline);
3132 talloc_free(chapters);
3133 return;
3136 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3137 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3138 timeline[part_count].start);
3139 if (missing_time)
3140 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3141 "from the timeline!\n", missing_time / 1000.);
3142 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3143 for (int i = 0; i < num_sources; i++)
3144 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3145 filename_recode(sources[i].demuxer->filename));
3146 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3147 "source_start, source):\n");
3148 for (int i = 0; i < part_count; i++) {
3149 struct timeline_part *p = timeline + i;
3150 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3151 p->source_start, p->source - sources);
3153 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3154 mpctx->sources = sources;
3155 mpctx->num_sources = num_sources;
3156 mpctx->timeline = timeline;
3157 mpctx->num_timeline_parts = part_count;
3158 mpctx->num_chapters = num_chapters;
3159 mpctx->chapters = chapters;
3161 mpctx->timeline_part = 0;
3162 mpctx->demuxer = timeline[0].source->demuxer;
3166 static int read_keys(void *ctx, int fd)
3168 getch2(ctx);
3169 return mplayer_get_key(ctx, 0);
3173 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3174 * file for some tools to link against. */
3175 #ifndef DISABLE_MAIN
3176 int main(int argc,char* argv[]){
3179 char * mem_ptr;
3181 // movie info:
3183 /* Flag indicating whether MPlayer should exit without playing anything. */
3184 int opt_exit = 0;
3185 int i;
3187 struct MPContext *mpctx = &(struct MPContext){
3188 .osd_function = OSD_PLAY,
3189 .begin_skip = MP_NOPTS_VALUE,
3190 .play_tree_step = 1,
3191 .global_sub_pos = -1,
3192 .set_of_sub_pos = -1,
3193 .file_format = DEMUXER_TYPE_UNKNOWN,
3194 .last_dvb_step = 1,
3197 InitTimer();
3198 srand(GetTimerMS());
3200 mp_msg_init();
3201 set_av_log_callback();
3203 #ifdef CONFIG_X11
3204 mpctx->x11_state = vo_x11_init_state();
3205 #endif
3206 struct MPOpts *opts = &mpctx->opts;
3207 set_default_mplayer_options(opts);
3208 // Create the config context and register the options
3209 mpctx->mconfig = m_config_new(opts, cfg_include);
3210 m_config_register_options(mpctx->mconfig,mplayer_opts);
3211 m_config_register_options(mpctx->mconfig, common_opts);
3212 mp_input_register_options(mpctx->mconfig);
3214 // Preparse the command line
3215 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3217 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3218 set_path_env();
3219 #endif
3221 #ifdef CONFIG_TV
3222 stream_tv_defaults.immediate = 1;
3223 #endif
3225 parse_cfgfiles(mpctx, mpctx->mconfig);
3227 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3228 if(mpctx->playtree == NULL)
3229 opt_exit = 1;
3230 else {
3231 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3232 if(mpctx->playtree) {
3233 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3234 if(mpctx->playtree_iter) {
3235 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3236 play_tree_iter_free(mpctx->playtree_iter);
3237 mpctx->playtree_iter = NULL;
3239 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3243 mpctx->key_fifo = mp_fifo_create(opts);
3245 print_version("MPlayer");
3247 #if defined(__MINGW32__) || defined(__CYGWIN__)
3249 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3250 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3251 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3252 if (kernel32) {
3253 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3254 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3256 if (setDEP) setDEP(3);
3257 if (setDllDir) setDllDir("");
3259 // stop Windows from showing all kinds of annoying error dialogs
3260 SetErrorMode(0x8003);
3261 // request 1ms timer resolution
3262 timeBeginPeriod(1);
3263 #endif
3265 #ifdef CONFIG_PRIORITY
3266 set_priority();
3267 #endif
3269 if (codec_path)
3270 set_codec_path(codec_path);
3272 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3273 list_video_out();
3274 opt_exit = 1;
3277 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3278 list_audio_out();
3279 opt_exit = 1;
3282 /* Check codecs.conf. */
3283 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3284 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3285 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3286 if(!parse_codec_cfg(NULL)){
3287 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3289 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3292 free( mem_ptr ); // release the buffer created by get_path()
3295 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3296 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3297 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3298 list_codecs(1);
3299 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3300 opt_exit = 1;
3302 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3303 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3304 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3305 list_codecs(0);
3306 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3307 opt_exit = 1;
3309 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3310 vfm_help();
3311 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3312 opt_exit = 1;
3314 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3315 afm_help();
3316 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3317 opt_exit = 1;
3319 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3320 af_help();
3321 printf("\n");
3322 opt_exit = 1;
3324 #ifdef CONFIG_X11
3325 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3326 fstype_help();
3327 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3328 opt_exit = 1;
3330 #endif
3331 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3332 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3333 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3334 demuxer_help();
3335 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3336 opt_exit = 1;
3338 if(list_properties) {
3339 property_print_help();
3340 opt_exit = 1;
3343 if(opt_exit)
3344 exit_player(mpctx, EXIT_NONE);
3346 if(!mpctx->filename && !player_idle_mode){
3347 // no file/vcd/dvd -> show HELP:
3348 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3349 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3352 /* Display what configure line was used */
3353 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3355 // Many users forget to include command line in bugreports...
3356 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3357 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3358 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3359 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3362 //------ load global data first ------
3364 mpctx->osd = osd_create();
3366 // check font
3367 #ifdef CONFIG_FREETYPE
3368 init_freetype();
3369 #endif
3370 #ifdef CONFIG_FONTCONFIG
3371 if(font_fontconfig <= 0)
3373 #endif
3374 #ifdef CONFIG_BITMAP_FONT
3375 if(font_name){
3376 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3377 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3378 filename_recode(font_name));
3379 } else {
3380 // try default:
3381 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3382 free(mem_ptr); // release the buffer created by get_path()
3383 if(!vo_font)
3384 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3386 if (sub_font_name)
3387 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3388 else
3389 mpctx->osd->sub_font = vo_font;
3390 #endif
3391 #ifdef CONFIG_FONTCONFIG
3393 #endif
3395 #ifdef CONFIG_ASS
3396 ass_library = ass_init();
3397 #endif
3399 #ifdef HAVE_RTC
3400 if(!nortc)
3402 // seteuid(0); /* Can't hurt to try to get root here */
3403 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3404 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3405 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3406 else {
3407 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3409 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3410 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3411 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3412 close (rtc_fd);
3413 rtc_fd = -1;
3414 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3415 /* variable only by the root */
3416 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3417 close (rtc_fd);
3418 rtc_fd = -1;
3419 } else
3420 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3423 if(rtc_fd<0)
3424 #endif /* HAVE_RTC */
3425 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3426 softsleep?"software":timer_name);
3428 #ifdef HAVE_TERMCAP
3429 load_termcap(NULL); // load key-codes
3430 #endif
3432 // ========== Init keyboard FIFO (connection to libvo) ============
3434 // Init input system
3435 current_module = "init_input";
3436 mpctx->input = mp_input_init(&opts->input);
3437 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3438 if(slave_mode)
3439 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3440 else if(!noconsolecontrols)
3441 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3442 // Set the libstream interrupt callback
3443 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3445 #ifdef CONFIG_MENU
3446 if(use_menu) {
3447 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3448 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3449 else {
3450 menu_cfg = get_path("menu.conf");
3451 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3452 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3453 else {
3454 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3455 MPLAYER_CONFDIR "/menu.conf"))
3456 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3457 else {
3458 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3459 use_menu = 0;
3464 #endif
3466 current_module = NULL;
3468 /// Catch signals
3469 #ifndef __MINGW32__
3470 signal(SIGCHLD,child_sighandler);
3471 #endif
3473 #ifdef CONFIG_CRASH_DEBUG
3474 prog_path = argv[0];
3475 #endif
3476 //========= Catch terminate signals: ================
3477 // terminate requests:
3478 signal(SIGTERM,exit_sighandler); // kill
3479 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3481 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3483 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3484 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3485 #ifdef CONFIG_SIGHANDLER
3486 // fatal errors:
3487 signal(SIGBUS,exit_sighandler); // bus error
3488 signal(SIGSEGV,exit_sighandler); // segfault
3489 signal(SIGILL,exit_sighandler); // illegal instruction
3490 signal(SIGFPE,exit_sighandler); // floating point exc.
3491 signal(SIGABRT,exit_sighandler); // abort()
3492 #ifdef CONFIG_CRASH_DEBUG
3493 if (crash_debug)
3494 signal(SIGTRAP,exit_sighandler);
3495 #endif
3496 #endif
3498 // ******************* Now, let's see the per-file stuff ********************
3500 play_next_file:
3502 // init global sub numbers
3503 mpctx->global_sub_size = 0;
3504 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3506 if (mpctx->filename) {
3507 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3508 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3509 load_per_file_config (mpctx->mconfig, mpctx->filename);
3512 if (opts->video_driver_list)
3513 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3514 if (opts->audio_driver_list)
3515 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3517 // We must enable getch2 here to be able to interrupt network connection
3518 // or cache filling
3519 if(!noconsolecontrols && !slave_mode){
3520 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3521 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3522 else
3523 getch2_enable(); // prepare stdin for hotkeys...
3524 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3525 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3528 // =================== GUI idle loop (STOP state) ===========================
3529 while (player_idle_mode && !mpctx->filename) {
3530 play_tree_t * entry = NULL;
3531 mp_cmd_t * cmd;
3532 if (mpctx->video_out && mpctx->video_out->config_ok)
3533 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3534 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3535 if (mpctx->video_out)
3536 vo_check_events(mpctx->video_out);
3537 usec_sleep(20000);
3539 switch (cmd->id) {
3540 case MP_CMD_LOADFILE:
3541 // prepare a tree entry with the new filename
3542 entry = play_tree_new();
3543 play_tree_add_file(entry, cmd->args[0].v.s);
3544 // The entry is added to the main playtree after the switch().
3545 break;
3546 case MP_CMD_LOADLIST:
3547 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3548 break;
3549 case MP_CMD_QUIT:
3550 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3551 break;
3552 case MP_CMD_VO_FULLSCREEN:
3553 case MP_CMD_GET_PROPERTY:
3554 case MP_CMD_SET_PROPERTY:
3555 case MP_CMD_STEP_PROPERTY:
3556 run_command(mpctx, cmd);
3557 break;
3560 mp_cmd_free(cmd);
3562 if (entry) { // user entered a command that gave a valid entry
3563 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3564 play_tree_free_list(mpctx->playtree->child, 1);
3565 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3567 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3569 play_tree_set_child(mpctx->playtree, entry);
3571 /* Make iterator start at the top the of tree. */
3572 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3573 if (!mpctx->playtree_iter) continue;
3575 // find the first real item in the tree
3576 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3577 // no items!
3578 play_tree_iter_free(mpctx->playtree_iter);
3579 mpctx->playtree_iter = NULL;
3580 continue; // wait for next command
3582 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3585 //---------------------------------------------------------------------------
3587 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3588 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3590 if (mpctx->filename) {
3591 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3592 filename_recode(mpctx->filename));
3593 if(use_filename_title && opts->vo_wintitle == NULL)
3594 opts->vo_wintitle = strdup(mp_basename2(mpctx->filename));
3597 if (edl_filename) {
3598 if (edl_records) free_edl(edl_records);
3599 next_edl_record = edl_records = edl_parse_file();
3601 if (edl_output_filename) {
3602 if (edl_fd) fclose(edl_fd);
3603 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3605 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3606 filename_recode(edl_output_filename));
3610 //==================== Open VOB-Sub ============================
3612 current_module="vobsub";
3613 if (vobsub_name){
3614 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3615 if(vo_vobsub==NULL)
3616 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3617 filename_recode(vobsub_name));
3618 } else if (sub_auto && mpctx->filename){
3619 /* try to autodetect vobsub from movie filename ::atmos */
3620 char *buf = strdup(mpctx->filename), *psub;
3621 char *pdot = strrchr(buf, '.');
3622 char *pslash = strrchr(buf, '/');
3623 #if defined(__MINGW32__) || defined(__CYGWIN__)
3624 if (!pslash) pslash = strrchr(buf, '\\');
3625 #endif
3626 if (pdot && (!pslash || pdot > pslash))
3627 *pdot = '\0';
3628 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3629 /* try from ~/.mplayer/sub */
3630 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3631 char *bname;
3632 int l;
3633 bname = strrchr(buf,'/');
3634 #if defined(__MINGW32__) || defined(__CYGWIN__)
3635 if(!bname) bname = strrchr(buf,'\\');
3636 #endif
3637 if(bname) bname++;
3638 else bname = buf;
3639 l = strlen(psub) + strlen(bname) + 1;
3640 psub = realloc(psub,l);
3641 strcat(psub,bname);
3642 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3643 free(psub);
3645 free(buf);
3647 if(vo_vobsub){
3648 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3649 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3650 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3652 // setup global sub numbering
3653 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3656 //============ Open & Sync STREAM --- fork cache2 ====================
3658 mpctx->stream=NULL;
3659 mpctx->demuxer=NULL;
3660 if (mpctx->d_audio) {
3661 //free_demuxer_stream(mpctx->d_audio);
3662 mpctx->d_audio=NULL;
3664 if (mpctx->d_video) {
3665 //free_demuxer_stream(d_video);
3666 mpctx->d_video=NULL;
3668 mpctx->sh_audio=NULL;
3669 mpctx->sh_video=NULL;
3671 current_module="open_stream";
3672 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3673 if(!mpctx->stream) { // error...
3674 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3675 goto goto_next_file;
3677 mpctx->initialized_flags|=INITIALIZED_STREAM;
3679 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3680 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3681 "playlist support will not be used automatically.\n"
3682 "MPlayer's playlist code is unsafe and should only be used with "
3683 "trusted sources.\nPlayback will probably fail.\n\n");
3684 #if 0
3685 play_tree_t* entry;
3686 // Handle playlist
3687 current_module="handle_playlist";
3688 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3689 filename_recode(mpctx->filename));
3690 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3691 mpctx->eof=playtree_add_playlist(mpctx, entry);
3692 goto goto_next_file;
3693 #endif
3695 mpctx->stream->start_pos+=seek_to_byte;
3697 if(stream_dump_type==5){
3698 unsigned char buf[4096];
3699 int len;
3700 FILE *f;
3701 current_module="dumpstream";
3702 stream_reset(mpctx->stream);
3703 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3704 f=fopen(opts->stream_dump_name,"wb");
3705 if(!f){
3706 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3707 exit_player(mpctx, EXIT_ERROR);
3709 if (opts->chapterrange[0] > 1) {
3710 int chapter = opts->chapterrange[0] - 1;
3711 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3713 while(!mpctx->stream->eof && !async_quit_request){
3714 len=stream_read(mpctx->stream,buf,4096);
3715 if(len>0) {
3716 if(fwrite(buf,len,1,f) != 1) {
3717 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3718 exit_player(mpctx, EXIT_ERROR);
3721 if (opts->chapterrange[1] > 0) {
3722 int chapter = -1;
3723 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3724 &chapter) == STREAM_OK
3725 && chapter + 1 > opts->chapterrange[1])
3726 break;
3729 if(fclose(f)) {
3730 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3731 exit_player(mpctx, EXIT_ERROR);
3733 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3734 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3737 #ifdef CONFIG_DVDREAD
3738 if(mpctx->stream->type==STREAMTYPE_DVD){
3739 current_module="dvd lang->id";
3740 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3741 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3742 // setup global sub numbering
3743 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3744 current_module=NULL;
3746 #endif
3748 #ifdef CONFIG_DVDNAV
3749 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3750 current_module="dvdnav lang->id";
3751 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3752 dvdsub_lang_id = -3;
3753 if(opts->sub_lang && opts->sub_id==-1)
3754 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3755 // setup global sub numbering
3756 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3757 current_module=NULL;
3759 #endif
3761 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3762 goto_enable_cache:
3763 if(stream_cache_size>0){
3764 int res;
3765 current_module="enable_cache";
3766 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3767 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3768 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3769 if(res == 0)
3770 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3773 //============ Open DEMUXERS --- DETECT file type =======================
3774 current_module="demux_open";
3776 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3778 // HACK to get MOV Reference Files working
3780 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3782 unsigned char* playlist_entry;
3783 play_tree_t *list = NULL, *entry = NULL;
3785 current_module="handle_demux_playlist";
3786 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3788 char *temp, *bname;
3790 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3791 filename_recode(playlist_entry));
3793 bname=mp_basename(playlist_entry);
3794 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3795 continue;
3797 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3798 continue;
3800 entry = play_tree_new();
3802 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3804 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3805 if (temp)
3807 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3808 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3809 strcat(temp, playlist_entry);
3810 if (!strcmp(temp, mpctx->filename)) {
3811 free(temp);
3812 continue;
3814 play_tree_add_file(entry,temp);
3815 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3816 free(temp);
3819 else
3820 play_tree_add_file(entry,playlist_entry);
3822 if(!list)
3823 list = entry;
3824 else
3825 play_tree_append_entry(list,entry);
3827 free_demuxer(mpctx->demuxer);
3828 mpctx->demuxer = NULL;
3830 if (list)
3832 entry = play_tree_new();
3833 play_tree_set_child(entry,list);
3834 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3835 goto goto_next_file;
3839 if(!mpctx->demuxer)
3840 goto goto_next_file;
3842 if (mpctx->demuxer->matroska_data.ordered_chapters)
3843 build_ordered_chapter_timeline(mpctx);
3845 if (!mpctx->sources) {
3846 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3847 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3848 .demuxer = mpctx->demuxer};
3849 mpctx->num_sources = 1;
3852 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3854 #ifdef CONFIG_ASS
3855 if (opts->ass_enabled && ass_library) {
3856 for (int j = 0; j < mpctx->num_sources; j++) {
3857 struct demuxer *d = mpctx->sources[j].demuxer;
3858 for (int i = 0; i < d->num_attachments; i++) {
3859 struct demux_attachment *att = d->attachments + i;
3860 if (use_embedded_fonts && attachment_is_font(att))
3861 ass_add_font(ass_library, att->name, att->data, att->data_size);
3865 #endif
3867 current_module="demux_open2";
3869 mpctx->d_audio=mpctx->demuxer->audio;
3870 mpctx->d_video=mpctx->demuxer->video;
3871 mpctx->d_sub=mpctx->demuxer->sub;
3873 if (ts_prog) {
3874 int tmp = ts_prog;
3875 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3877 // select audio stream
3878 if (mpctx->num_sources)
3879 for (int i = 0; i < mpctx->num_sources; i++)
3880 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3881 opts->audio_lang);
3882 else
3883 select_audio(mpctx->demuxer, opts->audio_id, opts->audio_lang);
3885 // DUMP STREAMS:
3886 if((stream_dump_type)&&(stream_dump_type<4)){
3887 FILE *f;
3888 demux_stream_t *ds=NULL;
3889 current_module="dump";
3890 // select stream to dump
3891 switch(stream_dump_type){
3892 case 1: ds=mpctx->d_audio;break;
3893 case 2: ds=mpctx->d_video;break;
3894 case 3: ds=mpctx->d_sub;break;
3896 if(!ds){
3897 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3898 exit_player(mpctx, EXIT_ERROR);
3900 // disable other streams:
3901 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3902 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3903 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3904 // let's dump it!
3905 f=fopen(opts->stream_dump_name,"wb");
3906 if(!f){
3907 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3908 exit_player(mpctx, EXIT_ERROR);
3910 while(!ds->eof){
3911 unsigned char* start;
3912 int in_size=ds_get_packet(ds,&start);
3913 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3914 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3915 if(in_size>0) fwrite(start,in_size,1,f);
3916 if (opts->chapterrange[1] > 0) {
3917 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3918 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3919 break;
3922 fclose(f);
3923 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3924 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3927 mpctx->sh_audio=mpctx->d_audio->sh;
3928 mpctx->sh_video=mpctx->d_video->sh;
3930 if(mpctx->sh_video){
3932 current_module="video_read_properties";
3933 if(!video_read_properties(mpctx->sh_video)) {
3934 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3935 mpctx->sh_video=mpctx->d_video->sh=NULL;
3936 } else {
3937 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3938 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3939 mpctx->sh_video->fps,mpctx->sh_video->frametime
3942 /* need to set fps here for output encoders to pick it up in their init */
3943 if(force_fps){
3944 mpctx->sh_video->fps=force_fps;
3945 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3947 vo_fps = mpctx->sh_video->fps;
3949 if(!mpctx->sh_video->fps && !force_fps){
3950 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3951 mpctx->opts.correct_pts = 1;
3957 if(!mpctx->sh_video && !mpctx->sh_audio){
3958 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3959 #ifdef CONFIG_DVBIN
3960 if(mpctx->stream->type == STREAMTYPE_DVB)
3962 int dir;
3963 int v = mpctx->last_dvb_step;
3964 if(v > 0)
3965 dir = DVB_CHANNEL_HIGHER;
3966 else
3967 dir = DVB_CHANNEL_LOWER;
3969 if(dvb_step_channel(mpctx->stream, dir)) {
3970 mpctx->stop_play = PT_NEXT_ENTRY;
3971 mpctx->dvbin_reopen = 1;
3974 #endif
3975 goto goto_next_file; // exit_player(_("Fatal error"));
3978 /* display clip info */
3979 demux_info_print(mpctx->demuxer);
3981 //================== Read SUBTITLES (DVD & TEXT) ==========================
3982 if(vo_spudec==NULL &&
3983 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3984 init_vo_spudec(mpctx);
3987 // after reading video params we should load subtitles because
3988 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3989 // check .sub
3990 current_module="read_subtitles_file";
3991 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3992 if(sub_name){
3993 for (i = 0; sub_name[i] != NULL; ++i)
3994 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3996 if(sub_auto) { // auto load sub file ...
3997 char *psub = get_path( "sub/" );
3998 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3999 int i = 0;
4000 free(psub); // release the buffer created by get_path() above
4001 while (tmp[i]) {
4002 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4003 free(tmp[i++]);
4005 free(tmp);
4007 if (mpctx->set_of_sub_size > 0)
4008 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4010 if (select_subtitle(mpctx)) {
4011 if(subdata)
4012 switch (stream_dump_type) {
4013 case 3: list_sub_file(subdata); break;
4014 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
4015 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
4016 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
4017 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
4018 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
4022 print_file_properties(mpctx, mpctx->filename);
4024 if(!mpctx->sh_video) goto main; // audio-only
4026 if(!reinit_video_chain(mpctx)) {
4027 if(!mpctx->sh_video){
4028 if(!mpctx->sh_audio) goto goto_next_file;
4029 goto main; // exit_player(_("Fatal error"));
4033 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4034 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4036 #ifdef CONFIG_FREETYPE
4037 force_load_font = 1;
4038 #endif
4040 //================== MAIN: ==========================
4041 main:
4042 current_module="main";
4044 if(playing_msg) {
4045 char* msg = property_expand_string(mpctx, playing_msg);
4046 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4047 free(msg);
4051 // Disable the term OSD in verbose mode
4052 if(verbose) term_osd = 0;
4055 int frame_time_remaining=0; // flag
4056 int blit_frame=0;
4058 // Make sure old OSD does not stay around,
4059 // e.g. with -fixed-vo and same-resolution files
4060 clear_osd_msgs();
4061 update_osd_msg(mpctx);
4063 //================ SETUP AUDIO ==========================
4065 if(mpctx->sh_audio){
4066 reinit_audio_chain(mpctx);
4067 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4068 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4071 current_module="av_init";
4073 if(mpctx->sh_video){
4074 mpctx->sh_video->timer=0;
4075 if (! ignore_start)
4076 audio_delay += mpctx->sh_video->stream_delay;
4078 if(mpctx->sh_audio){
4079 if (start_volume >= 0)
4080 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4081 if (! ignore_start)
4082 audio_delay -= mpctx->sh_audio->stream_delay;
4083 mpctx->delay=-audio_delay;
4086 if(!mpctx->sh_audio){
4087 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4088 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4089 ds_free_packs(mpctx->d_audio); // free buffered chunks
4090 //mpctx->d_audio->id=-2; // do not read audio chunks
4091 //uninit_player(mpctx, INITIALIZED_AO); // close device
4093 if(!mpctx->sh_video){
4094 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4095 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4096 ds_free_packs(mpctx->d_video);
4097 mpctx->d_video->id=-2;
4098 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4101 if (!mpctx->sh_video && !mpctx->sh_audio)
4102 goto goto_next_file;
4104 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4105 if(force_fps && mpctx->sh_video){
4106 vo_fps = mpctx->sh_video->fps=force_fps;
4107 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4108 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4111 mp_input_set_section(mpctx->input, NULL);
4112 //TODO: add desired (stream-based) sections here
4113 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4114 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4116 //==================== START PLAYING =======================
4118 if(opts->loop_times>1) opts->loop_times--; else
4119 if(opts->loop_times==1) opts->loop_times = -1;
4121 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4123 total_time_usage_start=GetTimer();
4124 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4125 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4126 play_n_frames=play_n_frames_mf;
4128 if(play_n_frames==0){
4129 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4132 // If there's a timeline force an absolute seek to initialize state
4133 if (seek_to_sec || mpctx->timeline) {
4134 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4135 end_at.pos += seek_to_sec;
4137 if (opts->chapterrange[0] > 0) {
4138 double pts;
4139 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4140 && pts > -1.0)
4141 seek(mpctx, pts, SEEK_ABSOLUTE);
4144 if (end_at.type == END_AT_SIZE) {
4145 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4146 end_at.type = END_AT_NONE;
4149 #ifdef CONFIG_DVDNAV
4150 mp_dvdnav_context_free(mpctx);
4151 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4152 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4153 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4155 #endif
4157 get_relative_time(mpctx); // reset current delta
4158 mpctx->time_frame = 0;
4159 mpctx->drop_message_shown = 0;
4160 mpctx->update_video_immediately = true;
4161 mpctx->total_avsync_change = 0;
4162 mpctx->last_chapter_seek = -1;
4163 // Make sure VO knows current pause state
4164 if (mpctx->sh_video)
4165 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4166 NULL);
4168 while(!mpctx->stop_play){
4169 float aq_sleep_time=0;
4171 if (opts->chapterrange[1] > 0) {
4172 int cur_chapter = get_current_chapter(mpctx);
4173 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4174 goto goto_next_file;
4177 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4178 mpctx->sh_audio = mpctx->d_audio->sh;
4179 mpctx->sh_audio->ds = mpctx->d_audio;
4180 reinit_audio_chain(mpctx);
4183 /*========================== PLAY AUDIO ============================*/
4185 if (mpctx->sh_audio && !mpctx->paused)
4186 if (!fill_audio_out_buffers(mpctx))
4187 // at eof, all audio at least written to ao
4188 if (!mpctx->sh_video)
4189 mpctx->stop_play = AT_END_OF_FILE;
4192 if(!mpctx->sh_video) {
4193 // handle audio-only case:
4194 double a_pos=0;
4195 // sh_audio can be NULL due to video stream switching
4196 // TODO: handle this better
4197 if (mpctx->sh_audio)
4198 a_pos = playing_audio_pts(mpctx);
4200 print_status(mpctx, a_pos, false);
4202 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4203 mpctx->stop_play = PT_NEXT_ENTRY;
4204 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4205 mpctx->d_sub, 0);
4206 update_osd_msg(mpctx);
4208 } else {
4210 /*========================== PLAY VIDEO ============================*/
4212 vo_pts=mpctx->sh_video->timer*90000.0;
4213 vo_fps=mpctx->sh_video->fps;
4215 blit_frame = mpctx->video_out->frame_loaded;
4216 if (!blit_frame) {
4217 double frame_time = update_video(mpctx);
4218 blit_frame = mpctx->video_out->frame_loaded;
4219 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4220 if (mpctx->sh_video->vf_initialized < 0) {
4221 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4222 mpctx->stop_play = PT_NEXT_ENTRY;
4223 goto goto_next_file;
4225 if (blit_frame) {
4226 struct sh_video *sh_video = mpctx->sh_video;
4227 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4228 mpctx->video_offset, mpctx->d_sub, 0);
4229 update_teletext(sh_video, mpctx->demuxer, 0);
4230 update_osd_msg(mpctx);
4231 struct vf_instance *vf = mpctx->sh_video->vfilter;
4232 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4233 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4234 vo_osd_changed(0);
4236 if (frame_time < 0)
4237 mpctx->stop_play = AT_END_OF_FILE;
4238 else {
4239 if (mpctx->update_video_immediately) {
4240 // Show this frame immediately, rest normally
4241 mpctx->update_video_immediately = false;
4242 } else {
4243 mpctx->time_frame += frame_time / opts->playback_speed;
4244 adjust_sync(mpctx, frame_time);
4248 if (mpctx->timeline) {
4249 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4250 if (mpctx->sh_video->pts >= next->start
4251 || mpctx->stop_play == AT_END_OF_FILE
4252 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4253 seek(mpctx, next->start, SEEK_ABSOLUTE);
4254 continue;
4258 // ==========================================================================
4260 // current_module="draw_osd";
4261 // if(vo_config_count) mpctx->video_out->draw_osd();
4263 current_module="vo_check_events";
4264 vo_check_events(mpctx->video_out);
4266 #ifdef CONFIG_X11
4267 if (stop_xscreensaver) {
4268 current_module = "stop_xscreensaver";
4269 xscreensaver_heartbeat(mpctx->x11_state);
4271 #endif
4272 if (heartbeat_cmd) {
4273 static unsigned last_heartbeat;
4274 unsigned now = GetTimerMS();
4275 if (now - last_heartbeat > 30000) {
4276 last_heartbeat = now;
4277 system(heartbeat_cmd);
4281 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4283 //====================== FLIP PAGE (VIDEO BLT): =========================
4285 current_module="flip_page";
4286 if (!frame_time_remaining && blit_frame) {
4287 unsigned int t2=GetTimer();
4288 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4289 int duration = -1;
4290 double pts2 = mpctx->video_out->next_pts2;
4291 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4292 // expected A/V sync correction is ignored
4293 double diff = (pts2 - mpctx->sh_video->pts);
4294 diff /= opts->playback_speed;
4295 if (mpctx->time_frame < 0)
4296 diff += mpctx->time_frame;
4297 if (diff < 0)
4298 diff = 0;
4299 if (diff > 10)
4300 diff = 10;
4301 duration = diff * 1e6;
4303 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4305 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4306 vout_time_usage += mpctx->last_vo_flip_duration;
4307 if (mpctx->video_out->driver->flip_page_timed) {
4308 // No need to adjust sync based on flip speed
4309 mpctx->last_vo_flip_duration = 0;
4310 // For print_status - VO call finishing early is OK for sync
4311 mpctx->time_frame -= get_relative_time(mpctx);
4313 print_status(mpctx, MP_NOPTS_VALUE, true);
4315 else
4316 print_status(mpctx, MP_NOPTS_VALUE, false);
4318 //============================ Auto QUALITY ============================
4320 /*Output quality adjustments:*/
4321 if(auto_quality>0){
4322 current_module="autoq";
4323 // float total=0.000001f * (GetTimer()-aq_total_time);
4324 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4325 if(output_quality<auto_quality && aq_sleep_time>0)
4326 ++output_quality;
4327 else
4328 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4329 if(output_quality>1 && aq_sleep_time<0)
4330 --output_quality;
4331 else
4332 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4333 output_quality=0;
4334 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4335 set_video_quality(mpctx->sh_video,output_quality);
4338 if (!frame_time_remaining && blit_frame) {
4339 if (play_n_frames >= 0) {
4340 --play_n_frames;
4341 if (play_n_frames <= 0)
4342 mpctx->stop_play = PT_NEXT_ENTRY;
4344 if (mpctx->step_frames > 0) {
4345 mpctx->step_frames--;
4346 if (mpctx->step_frames == 0)
4347 pause_player(mpctx);
4352 // FIXME: add size based support for -endpos
4353 if (end_at.type == END_AT_TIME &&
4354 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4355 mpctx->stop_play = PT_NEXT_ENTRY;
4357 } // end if(mpctx->sh_video)
4359 #ifdef CONFIG_DVDNAV
4360 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4361 nav_highlight_t hl;
4362 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4363 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4364 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4365 vo_osd_changed (OSDTYPE_DVDNAV);
4366 } else {
4367 osd_set_nav_box(0, 0, 0, 0);
4368 vo_osd_changed(OSDTYPE_DVDNAV);
4369 vo_osd_changed(OSDTYPE_SPU);
4372 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4373 double ar = -1.0;
4374 if (mpctx->sh_video &&
4375 stream_control (mpctx->demuxer->stream,
4376 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4377 != STREAM_UNSUPPORTED)
4378 mpctx->sh_video->stream_aspect = ar;
4381 #endif
4383 //================= Keyboard events, SEEKing ====================
4385 current_module="key_events";
4388 while (1) {
4389 mp_cmd_t* cmd;
4390 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4391 run_command(mpctx, cmd);
4392 mp_cmd_free(cmd);
4393 if (mpctx->stop_play)
4394 break;
4395 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4396 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4397 /* Allow seek commands to be combined, but execute the real seek
4398 * before processing other commands */
4399 if (!cmd || cmd->id != MP_CMD_SEEK)
4400 break;
4403 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4404 || mpctx->abs_seek_pos)
4405 break;
4406 if (mpctx->sh_video) {
4407 update_osd_msg(mpctx);
4408 int hack = vo_osd_changed(0);
4409 vo_osd_changed(hack);
4410 if (hack) {
4411 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4412 add_step_frame(mpctx);
4413 break;
4415 else
4416 vo_osd_changed(0);
4419 pause_loop(mpctx);
4423 // handle -sstep
4424 if (step_sec > 0 && !mpctx->paused) {
4425 mpctx->osd_function=OSD_FFW;
4426 mpctx->rel_seek_secs+=step_sec;
4429 edl_update(mpctx);
4431 /* Looping. */
4432 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4433 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4435 if(opts->loop_times>1) opts->loop_times--; else
4436 if(opts->loop_times==1) opts->loop_times=-1;
4437 play_n_frames=play_n_frames_mf;
4438 mpctx->stop_play=0;
4439 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4442 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4443 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4445 mpctx->rel_seek_secs=0;
4446 mpctx->abs_seek_pos=0;
4449 } // while(!mpctx->stop_play)
4451 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4453 #ifdef CONFIG_DVBIN
4454 if(mpctx->dvbin_reopen)
4456 mpctx->stop_play = 0;
4457 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4458 cache_uninit(mpctx->stream);
4459 mpctx->dvbin_reopen = 0;
4460 goto goto_enable_cache;
4462 #endif
4465 goto_next_file: // don't jump here after ao/vo/getch initialization!
4467 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4469 if(benchmark){
4470 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4471 double total_time_usage;
4472 total_time_usage_start=GetTimer()-total_time_usage_start;
4473 total_time_usage = (float)total_time_usage_start*0.000001;
4474 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4475 video_time_usage,vout_time_usage,audio_time_usage,
4476 total_time_usage-tot,total_time_usage);
4477 if(total_time_usage>0.0)
4478 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4479 100.0*video_time_usage/total_time_usage,
4480 100.0*vout_time_usage/total_time_usage,
4481 100.0*audio_time_usage/total_time_usage,
4482 100.0*(total_time_usage-tot)/total_time_usage,
4483 100.0);
4484 if(total_frame_cnt && frame_dropping)
4485 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4486 total_frame_cnt-drop_frame_cnt,
4487 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4488 drop_frame_cnt,
4489 100*drop_frame_cnt/total_frame_cnt,
4490 total_frame_cnt,
4491 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4494 // time to uninit all, except global stuff:
4495 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4497 if(mpctx->set_of_sub_size > 0) {
4498 current_module="sub_free";
4499 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4500 sub_free(mpctx->set_of_subtitles[i]);
4501 #ifdef CONFIG_ASS
4502 if(mpctx->set_of_ass_tracks[i])
4503 ass_free_track( mpctx->set_of_ass_tracks[i] );
4504 #endif
4506 mpctx->set_of_sub_size = 0;
4508 vo_sub_last = vo_sub=NULL;
4509 subdata=NULL;
4510 #ifdef CONFIG_ASS
4511 ass_track = NULL;
4512 if(ass_library)
4513 ass_clear_fonts(ass_library);
4514 #endif
4516 if (!mpctx->stop_play) // In case some goto jumped here...
4517 mpctx->stop_play = PT_NEXT_ENTRY;
4519 int playtree_direction = 1;
4521 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4522 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4523 play_tree_iter_free(mpctx->playtree_iter);
4524 mpctx->playtree_iter = NULL;
4526 mpctx->play_tree_step = 1;
4527 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4528 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4529 if(mpctx->playtree_iter) {
4530 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4531 play_tree_iter_free(mpctx->playtree_iter);
4532 mpctx->playtree_iter = NULL;
4535 } else if (mpctx->stop_play == PT_STOP) {
4536 play_tree_iter_free(mpctx->playtree_iter);
4537 mpctx->playtree_iter = NULL;
4538 } else { // NEXT PREV SRC
4539 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4542 while(mpctx->playtree_iter != NULL) {
4543 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4544 if(mpctx->filename == NULL) {
4545 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4546 play_tree_iter_free(mpctx->playtree_iter);
4547 mpctx->playtree_iter = NULL;
4549 } else
4550 break;
4553 if(mpctx->playtree_iter != NULL || player_idle_mode){
4554 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4555 mpctx->stop_play = 0;
4556 goto play_next_file;
4560 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4562 return 1;
4564 #endif /* DISABLE_MAIN */