configure: Ignore possible errors from dvdread-config invocation
[mplayer/glamo.git] / mplayer.c
blob0e5b21ba49981443bb667adcd65897d6d3007c15
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 static char *stream_dump_name="stream.dump";
329 int stream_dump_type=0;
331 // A-V sync:
332 static float default_max_pts_correction=-1;//0.01f;
333 float audio_delay=0;
334 static int ignore_start=0;
336 static int softsleep=0;
338 double force_fps=0;
339 static int force_srate=0;
340 static int audio_output_format=-1; // AF_FORMAT_UNKNOWN
341 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
342 static int play_n_frames=-1;
343 static int play_n_frames_mf=-1;
345 // sub:
346 char *font_name=NULL;
347 char *sub_font_name=NULL;
348 extern int font_fontconfig;
349 float font_factor=0.75;
350 char **sub_name=NULL;
351 float sub_delay=0;
352 float sub_fps=0;
353 int sub_auto = 1;
354 char *vobsub_name=NULL;
355 /*DSP!!char *dsp=NULL;*/
356 int subcc_enabled=0;
357 int suboverlap_enabled = 1;
359 #include "ass_mp.h"
361 char* current_module=NULL; // for debugging
364 // ---
366 #ifdef CONFIG_MENU
367 #include "m_struct.h"
368 #include "libmenu/menu.h"
369 static const vf_info_t* const libmenu_vfs[] = {
370 &vf_info_menu,
371 NULL
373 static vf_instance_t* vf_menu = NULL;
374 int use_menu = 0;
375 static char* menu_cfg = NULL;
376 static char* menu_root = "main";
377 #endif
380 #ifdef HAVE_RTC
381 static int nortc = 1;
382 static char* rtc_device;
383 #endif
385 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
386 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
387 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
388 int use_filedir_conf;
389 int use_filename_title;
391 #include "mpcommon.h"
392 #include "command.h"
394 #include "metadata.h"
396 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
398 const void *mpctx_get_video_out(MPContext *mpctx)
400 return mpctx->video_out;
403 const void *mpctx_get_audio_out(MPContext *mpctx)
405 return mpctx->audio_out;
408 void *mpctx_get_demuxer(MPContext *mpctx)
410 return mpctx->demuxer;
413 void *mpctx_get_playtree_iter(MPContext *mpctx)
415 return mpctx->playtree_iter;
418 void *mpctx_get_mixer(MPContext *mpctx)
420 return &mpctx->mixer;
423 int mpctx_get_global_sub_size(MPContext *mpctx)
425 return mpctx->global_sub_size;
428 int mpctx_get_osd_function(MPContext *mpctx)
430 return mpctx->osd_function;
433 static float get_relative_time(struct MPContext *mpctx)
435 unsigned int new_time = GetTimer();
436 unsigned int delta = new_time - mpctx->last_time;
437 mpctx->last_time = new_time;
438 return delta * 0.000001;
441 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
442 switch (type)
444 /* check for valid video stream */
445 case META_VIDEO_CODEC:
446 case META_VIDEO_BITRATE:
447 case META_VIDEO_RESOLUTION:
449 if (!mpctx->sh_video)
450 return 0;
451 break;
454 /* check for valid audio stream */
455 case META_AUDIO_CODEC:
456 case META_AUDIO_BITRATE:
457 case META_AUDIO_SAMPLES:
459 if (!mpctx->sh_audio)
460 return 0;
461 break;
464 /* check for valid demuxer */
465 case META_INFO_TITLE:
466 case META_INFO_ARTIST:
467 case META_INFO_ALBUM:
468 case META_INFO_YEAR:
469 case META_INFO_COMMENT:
470 case META_INFO_TRACK:
471 case META_INFO_GENRE:
473 if (!mpctx->demuxer)
474 return 0;
475 break;
478 default:
479 break;
482 return 1;
485 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
486 char **info = mpctx->demuxer->info;
487 int n;
489 if (!info || !tag)
490 return NULL;
492 for (n = 0; info[2*n] != NULL ; n++)
493 if (!strcasecmp (info[2*n], tag))
494 break;
496 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
499 char *get_metadata(struct MPContext *mpctx, metadata_t type)
501 char *meta = NULL;
502 sh_audio_t * const sh_audio = mpctx->sh_audio;
503 sh_video_t * const sh_video = mpctx->sh_video;
505 if (!is_valid_metadata_type(mpctx, type))
506 return NULL;
508 switch (type)
510 case META_NAME:
512 return strdup (mp_basename2 (mpctx->filename));
515 case META_VIDEO_CODEC:
517 if (sh_video->format == 0x10000001)
518 meta = strdup ("mpeg1");
519 else if (sh_video->format == 0x10000002)
520 meta = strdup ("mpeg2");
521 else if (sh_video->format == 0x10000004)
522 meta = strdup ("mpeg4");
523 else if (sh_video->format == 0x10000005)
524 meta = strdup ("h264");
525 else if (sh_video->format >= 0x20202020)
527 meta = malloc (8);
528 sprintf (meta, "%.4s", (char *) &sh_video->format);
530 else
532 meta = malloc (8);
533 sprintf (meta, "0x%08X", sh_video->format);
535 return meta;
538 case META_VIDEO_BITRATE:
540 meta = malloc (16);
541 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
542 return meta;
545 case META_VIDEO_RESOLUTION:
547 meta = malloc (16);
548 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
549 return meta;
552 case META_AUDIO_CODEC:
554 if (sh_audio->codec && sh_audio->codec->name)
555 meta = strdup (sh_audio->codec->name);
556 return meta;
559 case META_AUDIO_BITRATE:
561 meta = malloc (16);
562 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
563 return meta;
566 case META_AUDIO_SAMPLES:
568 meta = malloc (16);
569 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
570 return meta;
573 /* check for valid demuxer */
574 case META_INFO_TITLE:
575 return get_demuxer_info(mpctx, "Title");
577 case META_INFO_ARTIST:
578 return get_demuxer_info(mpctx, "Artist");
580 case META_INFO_ALBUM:
581 return get_demuxer_info(mpctx, "Album");
583 case META_INFO_YEAR:
584 return get_demuxer_info(mpctx, "Year");
586 case META_INFO_COMMENT:
587 return get_demuxer_info(mpctx, "Comment");
589 case META_INFO_TRACK:
590 return get_demuxer_info(mpctx, "Track");
592 case META_INFO_GENRE:
593 return get_demuxer_info(mpctx, "Genre");
595 default:
596 break;
599 return meta;
602 static void print_file_properties(const MPContext *mpctx, const char *filename)
604 double start_pts = MP_NOPTS_VALUE;
605 double video_start_pts = MP_NOPTS_VALUE;
606 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
607 filename_recode(filename));
608 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
609 if (mpctx->sh_video) {
610 /* Assume FOURCC if all bytes >= 0x20 (' ') */
611 if (mpctx->sh_video->format >= 0x20202020)
612 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
613 else
614 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
615 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
616 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
617 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
618 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
619 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
620 video_start_pts = ds_get_next_pts(mpctx->d_video);
622 if (mpctx->sh_audio) {
623 /* Assume FOURCC if all bytes >= 0x20 (' ') */
624 if (mpctx->sh_audio->format >= 0x20202020)
625 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
626 else
627 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
628 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
629 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
630 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
631 start_pts = ds_get_next_pts(mpctx->d_audio);
633 if (video_start_pts != MP_NOPTS_VALUE) {
634 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
635 (mpctx->sh_video && video_start_pts < start_pts))
636 start_pts = video_start_pts;
638 if (start_pts != MP_NOPTS_VALUE)
639 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
640 else
641 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
642 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", mpctx->timeline ?
643 mpctx->timeline[mpctx->num_timeline_parts].start :
644 demuxer_get_time_length(mpctx->demuxer));
645 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
646 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
647 if (mpctx->demuxer) {
648 if (mpctx->demuxer->num_chapters == 0)
649 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
650 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
654 /// step size of mixer changes
655 int volstep = 3;
657 #ifdef CONFIG_DVDNAV
658 static void mp_dvdnav_context_free(MPContext *ctx){
659 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
660 ctx->nav_smpi = NULL;
661 if (ctx->nav_buffer) free(ctx->nav_buffer);
662 ctx->nav_buffer = NULL;
663 ctx->nav_start = NULL;
664 ctx->nav_in_size = 0;
666 #endif
668 void uninit_player(struct MPContext *mpctx, unsigned int mask){
669 mask &= mpctx->initialized_flags;
671 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
673 if(mask&INITIALIZED_ACODEC){
674 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
675 current_module="uninit_acodec";
676 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
677 mpctx->sh_audio=NULL;
678 mpctx->mixer.afilter = NULL;
681 if(mask&INITIALIZED_VCODEC){
682 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
683 current_module="uninit_vcodec";
684 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
685 mpctx->sh_video=NULL;
686 #ifdef CONFIG_MENU
687 vf_menu=NULL;
688 #endif
691 if(mask&INITIALIZED_DEMUXER){
692 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
693 current_module="free_demuxer";
694 if (mpctx->num_sources) {
695 mpctx->demuxer = mpctx->sources[0].demuxer;
696 for (int i = 1; i < mpctx->num_sources; i++) {
697 free_stream(mpctx->sources[i].stream);
698 free_demuxer(mpctx->sources[i].demuxer);
701 talloc_free(mpctx->sources);
702 mpctx->sources = NULL;
703 mpctx->num_sources = 0;
704 talloc_free(mpctx->timeline);
705 mpctx->timeline = NULL;
706 mpctx->num_timeline_parts = 0;
707 talloc_free(mpctx->chapters);
708 mpctx->chapters = NULL;
709 mpctx->num_chapters = 0;
710 mpctx->video_offset = 0;
711 if(mpctx->demuxer){
712 mpctx->stream=mpctx->demuxer->stream;
713 free_demuxer(mpctx->demuxer);
715 mpctx->demuxer=NULL;
718 // kill the cache process:
719 if(mask&INITIALIZED_STREAM){
720 mpctx->initialized_flags&=~INITIALIZED_STREAM;
721 current_module="uninit_stream";
722 if(mpctx->stream) free_stream(mpctx->stream);
723 mpctx->stream=NULL;
726 if(mask&INITIALIZED_VO){
727 mpctx->initialized_flags&=~INITIALIZED_VO;
728 current_module="uninit_vo";
729 vo_destroy(mpctx->video_out);
730 mpctx->video_out=NULL;
731 #ifdef CONFIG_DVDNAV
732 mp_dvdnav_context_free(mpctx);
733 #endif
736 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
737 if(mask&INITIALIZED_GETCH2){
738 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
739 current_module="uninit_getch2";
740 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
741 // restore terminal:
742 getch2_disable();
745 if(mask&INITIALIZED_VOBSUB){
746 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
747 current_module="uninit_vobsub";
748 if(vo_vobsub) vobsub_close(vo_vobsub);
749 vo_vobsub=NULL;
752 if (mask&INITIALIZED_SPUDEC){
753 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
754 current_module="uninit_spudec";
755 spudec_free(vo_spudec);
756 vo_spudec=NULL;
759 if(mask&INITIALIZED_AO){
760 mpctx->initialized_flags&=~INITIALIZED_AO;
761 current_module="uninit_ao";
762 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
763 if (mpctx->audio_out)
764 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
765 mpctx->audio_out=NULL;
768 current_module=NULL;
771 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
773 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
774 uninit_player(mpctx, INITIALIZED_ALL);
775 #if defined(__MINGW32__) || defined(__CYGWIN__)
776 timeEndPeriod(1);
777 #endif
778 #ifdef CONFIG_X11
779 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
780 #endif
782 current_module="uninit_input";
783 mp_input_uninit(mpctx->input);
784 #ifdef CONFIG_MENU
785 if (use_menu)
786 menu_uninit();
787 #endif
789 #ifdef CONFIG_FREETYPE
790 current_module="uninit_font";
791 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
792 free_font_desc(mpctx->osd->sub_font);
793 free_font_desc(vo_font);
794 vo_font = NULL;
795 done_freetype();
796 #endif
797 osd_free(mpctx->osd);
799 #ifdef CONFIG_ASS
800 ass_library_done(ass_library);
801 ass_library = NULL;
802 #endif
804 current_module="exit_player";
806 // free mplayer config
807 if(mpctx->mconfig)
808 m_config_free(mpctx->mconfig);
809 mpctx->mconfig = NULL;
811 if(mpctx->playtree_iter)
812 play_tree_iter_free(mpctx->playtree_iter);
813 mpctx->playtree_iter = NULL;
814 if(mpctx->playtree)
815 play_tree_free(mpctx->playtree, 1);
816 mpctx->playtree = NULL;
818 talloc_free(mpctx->key_fifo);
820 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
821 edl_records = NULL;
822 switch(how) {
823 case EXIT_QUIT:
824 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
825 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
826 break;
827 case EXIT_EOF:
828 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
829 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
830 break;
831 case EXIT_ERROR:
832 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
833 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
834 break;
835 default:
836 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
838 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
840 exit(rc);
843 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
845 exit_player_with_rc(mpctx, how, 1);
848 #ifndef __MINGW32__
849 static void child_sighandler(int x){
850 pid_t pid;
851 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
853 #endif
855 #ifdef CONFIG_CRASH_DEBUG
856 static char *prog_path;
857 static int crash_debug = 0;
858 #endif
860 static void exit_sighandler(int x){
861 static int sig_count=0;
862 #ifdef CONFIG_CRASH_DEBUG
863 if (!crash_debug || x != SIGTRAP)
864 #endif
865 ++sig_count;
866 if(sig_count==5)
868 /* We're crashing bad and can't uninit cleanly :(
869 * by popular request, we make one last (dirty)
870 * effort to restore the user's
871 * terminal. */
872 getch2_disable();
873 exit(1);
875 if(sig_count==6) exit(1);
876 if(sig_count>6){
877 // can't stop :(
878 #ifndef __MINGW32__
879 kill(getpid(),SIGKILL);
880 #endif
882 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
883 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
884 "\nMPlayer interrupted by signal %d in module: %s\n", x,
885 current_module ? current_module : "unknown");
886 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
887 if(sig_count<=1)
888 switch(x){
889 case SIGINT:
890 case SIGPIPE:
891 case SIGQUIT:
892 case SIGTERM:
893 case SIGKILL:
894 async_quit_request = 1;
895 return; // killed from keyboard (^C) or killed [-9]
896 case SIGILL:
897 #if CONFIG_RUNTIME_CPUDETECT
898 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
899 #else
900 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
901 #endif
902 case SIGFPE:
903 case SIGSEGV:
904 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
905 default:
906 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
907 #ifdef CONFIG_CRASH_DEBUG
908 if (crash_debug) {
909 int gdb_pid;
910 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
911 gdb_pid = fork();
912 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
913 if (gdb_pid == 0) { // We are the child
914 char spid[20];
915 snprintf(spid, sizeof(spid), "%i", getppid());
916 getch2_disable(); // allow terminal to work properly with gdb
917 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
918 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
919 } else if (gdb_pid < 0)
920 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
921 else {
922 waitpid(gdb_pid, NULL, 0);
924 if (x == SIGTRAP) return;
926 #endif
928 getch2_disable();
929 exit(1);
932 #include "cfg-mplayer.h"
934 static int cfg_include(m_option_t *conf, char *filename)
936 return m_config_parse_config_file(conf->priv, filename);
939 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
941 char *conffile;
942 int conffile_fd;
943 if (!disable_system_conf &&
944 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
945 exit_player(mpctx, EXIT_NONE);
946 if ((conffile = get_path("")) == NULL) {
947 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
948 } else {
949 #ifdef __MINGW32__
950 mkdir(conffile);
951 #else
952 mkdir(conffile, 0777);
953 #endif
954 free(conffile);
955 if ((conffile = get_path("config")) == NULL) {
956 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
957 } else {
958 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
959 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
960 write(conffile_fd, default_config, strlen(default_config));
961 close(conffile_fd);
963 if (!disable_user_conf &&
964 m_config_parse_config_file(conf, conffile) < 0)
965 exit_player(mpctx, EXIT_NONE);
966 free(conffile);
971 #define PROFILE_CFG_PROTOCOL "protocol."
973 static void load_per_protocol_config (m_config_t* conf, const char *const file)
975 char *str;
976 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
977 m_profile_t *p;
979 /* does filename actually uses a protocol ? */
980 str = strstr (file, "://");
981 if (!str)
982 return;
984 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
985 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
986 p = m_config_get_profile (conf, protocol);
987 if (p)
989 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
990 m_config_set_profile(conf,p);
994 #define PROFILE_CFG_EXTENSION "extension."
996 static void load_per_extension_config (m_config_t* conf, const char *const file)
998 char *str;
999 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
1000 m_profile_t *p;
1002 /* does filename actually have an extension ? */
1003 str = strrchr (file, '.');
1004 if (!str)
1005 return;
1007 sprintf (extension, PROFILE_CFG_EXTENSION);
1008 strncat (extension, ++str, 7);
1009 p = m_config_get_profile (conf, extension);
1010 if (p)
1012 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
1013 m_config_set_profile(conf,p);
1017 #define PROFILE_CFG_VO "vo."
1018 #define PROFILE_CFG_AO "ao."
1020 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
1022 char profile[strlen (cfg) + strlen (out) + 1];
1023 m_profile_t *p;
1025 sprintf (profile, "%s%s", cfg, out);
1026 p = m_config_get_profile (conf, profile);
1027 if (p)
1029 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
1030 m_config_set_profile(conf,p);
1035 * Tries to load a config file
1036 * @return 0 if file was not found, 1 otherwise
1038 static int try_load_config(m_config_t *conf, const char *file)
1040 struct stat st;
1041 if (stat(file, &st))
1042 return 0;
1043 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1044 m_config_parse_config_file (conf, file);
1045 return 1;
1048 static void load_per_file_config (m_config_t* conf, const char *const file)
1050 char *confpath;
1051 char cfg[PATH_MAX];
1052 char *name;
1054 if (strlen(file) > PATH_MAX - 14) {
1055 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1056 return;
1058 sprintf (cfg, "%s.conf", file);
1060 name = strrchr(cfg, '/');
1061 if (HAVE_DOS_PATHS) {
1062 char *tmp = strrchr(cfg, '\\');
1063 if (!name || tmp > name)
1064 name = tmp;
1065 tmp = strrchr(cfg, ':');
1066 if (!name || tmp > name)
1067 name = tmp;
1069 if (!name)
1070 name = cfg;
1071 else
1072 name++;
1074 if (use_filedir_conf) {
1075 char dircfg[PATH_MAX];
1076 strcpy(dircfg, cfg);
1077 strcpy(dircfg + (name - cfg), "mplayer.conf");
1078 try_load_config(conf, dircfg);
1080 if (try_load_config(conf, cfg))
1081 return;
1084 if ((confpath = get_path (name)) != NULL)
1086 try_load_config(conf, confpath);
1088 free (confpath);
1092 /* When libmpdemux performs a blocking operation (network connection or
1093 * cache filling) if the operation fails we use this function to check
1094 * if it was interrupted by the user.
1095 * The function returns a new value for eof. */
1096 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1098 mp_cmd_t* cmd;
1099 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1100 switch(cmd->id) {
1101 case MP_CMD_QUIT:
1102 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1103 case MP_CMD_PLAY_TREE_STEP: {
1104 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1105 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1106 } break;
1107 case MP_CMD_PLAY_TREE_UP_STEP: {
1108 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1109 } break;
1110 case MP_CMD_PLAY_ALT_SRC_STEP: {
1111 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1112 } break;
1114 mp_cmd_free(cmd);
1116 return stop_play;
1119 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1121 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1123 play_tree_add_bpf(entry,mpctx->filename);
1126 if(!entry) {
1127 entry = mpctx->playtree_iter->tree;
1128 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1129 return PT_NEXT_ENTRY;
1131 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1132 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1133 return PT_NEXT_ENTRY;
1136 play_tree_remove(entry,1,1);
1137 return PT_NEXT_SRC;
1139 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1140 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1141 entry = mpctx->playtree_iter->tree;
1142 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1143 return PT_NEXT_ENTRY;
1145 play_tree_remove(entry,1,1);
1147 return PT_NEXT_SRC;
1150 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1152 struct MPOpts *opts = &mpctx->opts;
1153 sub_data *subd = NULL;
1154 struct ass_track *asst = NULL;
1156 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1157 return;
1160 #ifdef CONFIG_ASS
1161 if (opts->ass_enabled) {
1162 #ifdef CONFIG_ICONV
1163 asst = ass_read_stream(ass_library, filename, sub_cp);
1164 #else
1165 asst = ass_read_stream(ass_library, filename, 0);
1166 #endif
1167 if (!asst) {
1168 subd = sub_read_file(filename, fps);
1169 if (subd) {
1170 asst = ass_read_subdata(ass_library, subd, fps);
1171 if (asst) {
1172 sub_free(subd);
1173 subd = NULL;
1177 } else
1178 #endif
1179 subd = sub_read_file(filename, fps);
1182 if (!asst && !subd) {
1183 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1184 "Cannot load subtitles: %s\n", filename_recode(filename));
1185 return;
1188 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1189 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1190 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1191 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1192 filename_recode(filename));
1193 ++mpctx->set_of_sub_size;
1194 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1195 filename_recode(filename));
1198 void init_vo_spudec(struct MPContext *mpctx)
1200 if (vo_spudec)
1201 spudec_free(vo_spudec);
1202 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1203 vo_spudec = NULL;
1205 // we currently can't work without video stream
1206 if (!mpctx->sh_video)
1207 return;
1209 if (spudec_ifo) {
1210 unsigned int palette[16], width, height;
1211 current_module="spudec_init_vobsub";
1212 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1213 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1216 #ifdef CONFIG_DVDREAD
1217 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1218 current_module="spudec_init_dvdread";
1219 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1220 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1221 NULL, 0);
1223 #endif
1225 #ifdef CONFIG_DVDNAV
1226 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1227 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1228 current_module="spudec_init_dvdnav";
1229 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1231 #endif
1233 if (vo_spudec==NULL) {
1234 sh_sub_t *sh = mpctx->d_sub->sh;
1235 current_module="spudec_init_normal";
1236 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1237 spudec_set_font_factor(vo_spudec,font_factor);
1240 if (vo_spudec!=NULL) {
1241 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1242 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1247 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1248 * make it all work is to use the builtin SDL-bootstrap code, which
1249 * will be done automatically by replacing our main() if we include SDL.h.
1251 #if defined(__APPLE__) && defined(CONFIG_SDL)
1252 #ifdef CONFIG_SDL_SDL_H
1253 #include <SDL/SDL.h>
1254 #else
1255 #include <SDL.h>
1256 #endif
1257 #endif
1260 * \brief append a formatted string
1261 * \param buf buffer to print into
1262 * \param pos position of terminating 0 in buf
1263 * \param len maximum number of characters in buf, not including terminating 0
1264 * \param format printf format string
1266 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1268 va_list va;
1269 va_start(va, format);
1270 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1271 va_end(va);
1272 if (*pos >= len ) {
1273 buf[len] = 0;
1274 *pos = len;
1279 * \brief append time in the hh:mm:ss.f format
1280 * \param buf buffer to print into
1281 * \param pos position of terminating 0 in buf
1282 * \param len maximum number of characters in buf, not including terminating 0
1283 * \param time time value to convert/append
1285 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1286 int64_t tenths = 10 * time;
1287 int f1 = tenths % 10;
1288 int ss = (tenths / 10) % 60;
1289 int mm = (tenths / 600) % 60;
1290 int hh = tenths / 36000;
1291 if (time <= 0) {
1292 saddf(buf, pos, len, "unknown");
1293 return;
1295 if (hh > 0)
1296 saddf(buf, pos, len, "%2d:", hh);
1297 if (hh > 0 || mm > 0)
1298 saddf(buf, pos, len, "%02d:", mm);
1299 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1302 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1304 struct MPOpts *opts = &mpctx->opts;
1305 sh_video_t * const sh_video = mpctx->sh_video;
1307 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1308 a_pos = playing_audio_pts(mpctx);
1309 if (mpctx->sh_audio && sh_video && at_frame) {
1310 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1311 if (mpctx->time_frame > 0)
1312 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1313 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1314 && !mpctx->drop_message_shown) {
1315 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1316 mpctx->drop_message_shown = true;
1319 if (quiet)
1320 return;
1323 int width;
1324 char *line;
1325 unsigned pos = 0;
1326 get_screen_size();
1327 if (screen_width > 0)
1328 width = screen_width;
1329 else
1330 width = 80;
1331 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1332 /* Windows command line is broken (MinGW's rxvt works, but we
1333 * should not depend on that). */
1334 width--;
1335 #endif
1336 line = malloc(width + 1); // one additional char for the terminating null
1338 // Audio time
1339 if (mpctx->sh_audio) {
1340 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1341 if (!sh_video) {
1342 float len = demuxer_get_time_length(mpctx->demuxer);
1343 saddf(line, &pos, width, "(");
1344 sadd_hhmmssf(line, &pos, width, a_pos);
1345 saddf(line, &pos, width, ") of %.1f (", len);
1346 sadd_hhmmssf(line, &pos, width, len);
1347 saddf(line, &pos, width, ") ");
1351 // Video time
1352 if (sh_video)
1353 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1355 // A-V sync
1356 if (mpctx->sh_audio && sh_video)
1357 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1358 mpctx->last_av_difference, mpctx->total_avsync_change);
1360 // Video stats
1361 if (sh_video)
1362 saddf(line, &pos, width, "%3d/%3d ",
1363 (int)sh_video->num_frames,
1364 (int)sh_video->num_frames_decoded);
1366 // CPU usage
1367 if (sh_video) {
1368 if (sh_video->timer > 0.5)
1369 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1370 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1371 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1372 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1373 else
1374 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1375 } else if (mpctx->sh_audio) {
1376 if (mpctx->delay > 0.5)
1377 saddf(line, &pos, width, "%4.1f%% ",
1378 100.0*audio_time_usage/(double)mpctx->delay);
1379 else
1380 saddf(line, &pos, width, "??,?%% ");
1383 // VO stats
1384 if (sh_video)
1385 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1387 #ifdef CONFIG_STREAM_CACHE
1388 // cache stats
1389 if (stream_cache_size > 0)
1390 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1391 #endif
1393 // other
1394 if (opts->playback_speed != 1)
1395 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1397 // end
1398 if (erase_to_end_of_line) {
1399 line[pos] = 0;
1400 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1401 } else {
1402 memset(&line[pos], ' ', width - pos);
1403 line[width] = 0;
1404 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1406 free(line);
1410 * \brief build a chain of audio filters that converts the input format
1411 * to the ao's format, taking into account the current playback_speed.
1412 * \param sh_audio describes the requested input format of the chain.
1413 * \param ao_data describes the requested output format of the chain.
1415 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1417 struct MPOpts *opts = &mpctx->opts;
1418 int new_srate;
1419 int result;
1420 if (!sh_audio)
1422 mpctx->mixer.afilter = NULL;
1423 return 0;
1425 if(af_control_any_rev(sh_audio->afilter,
1426 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1427 &opts->playback_speed)) {
1428 new_srate = sh_audio->samplerate;
1429 } else {
1430 new_srate = sh_audio->samplerate * opts->playback_speed;
1431 if (new_srate != ao_data->samplerate) {
1432 // limits are taken from libaf/af_resample.c
1433 if (new_srate < 8000)
1434 new_srate = 8000;
1435 if (new_srate > 192000)
1436 new_srate = 192000;
1437 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1440 result = init_audio_filters(sh_audio, new_srate,
1441 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1442 mpctx->mixer.afilter = sh_audio->afilter;
1443 return result;
1447 typedef struct mp_osd_msg mp_osd_msg_t;
1448 struct mp_osd_msg {
1449 /// Previous message on the stack.
1450 mp_osd_msg_t* prev;
1451 /// Message text.
1452 char msg[128];
1453 int id,level,started;
1454 /// Display duration in ms.
1455 unsigned time;
1458 /// OSD message stack.
1459 static mp_osd_msg_t* osd_msg_stack = NULL;
1462 * \brief Add a message on the OSD message stack
1464 * If a message with the same id is already present in the stack
1465 * it is pulled on top of the stack, otherwise a new message is created.
1468 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1469 va_list ap)
1471 mp_osd_msg_t *msg,*last=NULL;
1472 int r;
1474 // look if the id is already in the stack
1475 for(msg = osd_msg_stack ; msg && msg->id != id ;
1476 last = msg, msg = msg->prev);
1477 // not found: alloc it
1478 if(!msg) {
1479 msg = calloc(1,sizeof(mp_osd_msg_t));
1480 msg->prev = osd_msg_stack;
1481 osd_msg_stack = msg;
1482 } else if(last) { // found, but it's not on top of the stack
1483 last->prev = msg->prev;
1484 msg->prev = osd_msg_stack;
1485 osd_msg_stack = msg;
1487 // write the msg
1488 r = vsnprintf(msg->msg, 128, fmt, ap);
1489 if(r >= 128) msg->msg[127] = 0;
1490 // set id and time
1491 msg->id = id;
1492 msg->level = level;
1493 msg->time = time;
1497 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1499 va_list ap;
1500 va_start(ap, fmt);
1501 set_osd_msg_va(id, level, time, fmt, ap);
1502 va_end(ap);
1505 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1507 va_list ap;
1508 va_start(ap, fmt);
1509 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1510 va_end(ap);
1515 * \brief Remove a message from the OSD stack
1517 * This function can be used to get rid of a message right away.
1521 void rm_osd_msg(int id) {
1522 mp_osd_msg_t *msg,*last=NULL;
1524 // Search for the msg
1525 for(msg = osd_msg_stack ; msg && msg->id != id ;
1526 last = msg, msg = msg->prev);
1527 if(!msg) return;
1529 // Detach it from the stack and free it
1530 if(last)
1531 last->prev = msg->prev;
1532 else
1533 osd_msg_stack = msg->prev;
1534 free(msg);
1538 * \brief Remove all messages from the OSD stack
1542 static void clear_osd_msgs(void) {
1543 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1544 while(msg) {
1545 prev = msg->prev;
1546 free(msg);
1547 msg = prev;
1549 osd_msg_stack = NULL;
1553 * \brief Get the current message from the OSD stack.
1555 * This function decrements the message timer and destroys the old ones.
1556 * The message that should be displayed is returned (if any).
1560 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1562 struct MPOpts *opts = &mpctx->opts;
1563 mp_osd_msg_t *msg,*prev,*last = NULL;
1564 static unsigned last_update = 0;
1565 unsigned now = GetTimerMS();
1566 unsigned diff;
1567 char hidden_dec_done = 0;
1569 if (mpctx->osd_visible) {
1570 // 36000000 means max timed visibility is 1 hour into the future, if
1571 // the difference is greater assume it's wrapped around from below 0
1572 if (mpctx->osd_visible - now > 36000000) {
1573 mpctx->osd_visible = 0;
1574 vo_osd_progbar_type = -1; // disable
1575 vo_osd_changed(OSDTYPE_PROGBAR);
1576 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1579 if (mpctx->osd_show_percentage_until - now > 36000000)
1580 mpctx->osd_show_percentage_until = 0;
1582 if(!last_update) last_update = now;
1583 diff = now >= last_update ? now - last_update : 0;
1585 last_update = now;
1587 // Look for the first message in the stack with high enough level.
1588 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1589 prev = msg->prev;
1590 if (msg->level > opts->osd_level && hidden_dec_done)
1591 continue;
1592 // The message has a high enough level or it is the first hidden one
1593 // in both cases we decrement the timer or kill it.
1594 if(!msg->started || msg->time > diff) {
1595 if(msg->started) msg->time -= diff;
1596 else msg->started = 1;
1597 // display it
1598 if (msg->level <= opts->osd_level)
1599 return msg;
1600 hidden_dec_done = 1;
1601 continue;
1603 // kill the message
1604 free(msg);
1605 if(last) {
1606 last->prev = prev;
1607 msg = last;
1608 } else {
1609 osd_msg_stack = prev;
1610 msg = NULL;
1613 // Nothing found
1614 return NULL;
1618 * \brief Display the OSD bar.
1620 * Display the OSD bar or fall back on a simple message.
1624 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1625 struct MPOpts *opts = &mpctx->opts;
1626 if (opts->osd_level < 1)
1627 return;
1629 if(mpctx->sh_video) {
1630 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1631 vo_osd_progbar_type = type;
1632 vo_osd_progbar_value = 256*(val-min)/(max-min);
1633 vo_osd_changed(OSDTYPE_PROGBAR);
1634 return;
1637 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1638 name, ROUND(100*(val-min)/(max-min)));
1642 * \brief Display text subtitles on the OSD
1644 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1646 int i;
1647 vo_sub = subs;
1648 vo_osd_changed(OSDTYPE_SUBTITLE);
1649 if (!mpctx->sh_video) {
1650 // reverse order, since newest set_osd_msg is displayed first
1651 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1652 if (!subs || i >= subs->lines || !subs->text[i])
1653 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1654 else {
1655 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1656 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1657 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1664 * \brief Update the OSD message line.
1666 * This function displays the current message on the vo OSD or on the term.
1667 * If the stack is empty and the OSD level is high enough the timer
1668 * is displayed (only on the vo OSD).
1672 static void update_osd_msg(struct MPContext *mpctx)
1674 struct MPOpts *opts = &mpctx->opts;
1675 mp_osd_msg_t *msg;
1676 struct osd_state *osd = mpctx->osd;
1677 char osd_text_timer[128];
1679 if (mpctx->add_osd_seek_info) {
1680 double percentage;
1681 if (mpctx->timeline && mpctx->sh_video)
1682 percentage = mpctx->sh_video->pts * 100 /
1683 mpctx->timeline[mpctx->num_timeline_parts].start;
1684 else
1685 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1686 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1687 if (mpctx->sh_video)
1688 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1689 mpctx->add_osd_seek_info = false;
1692 // Look if we have a msg
1693 if((msg = get_osd_msg(mpctx))) {
1694 if (strcmp(osd->osd_text, msg->msg)) {
1695 strncpy(osd->osd_text, msg->msg, 127);
1696 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1697 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1699 return;
1702 if(mpctx->sh_video) {
1703 // fallback on the timer
1704 if (opts->osd_level >= 2) {
1705 int len;
1706 if (mpctx->timeline)
1707 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1708 else
1709 len = demuxer_get_time_length(mpctx->demuxer);
1710 int percentage = -1;
1711 char percentage_text[10];
1712 int pts = demuxer_get_current_time(mpctx->demuxer);
1714 if (mpctx->osd_show_percentage_until) {
1715 if (mpctx->timeline)
1716 percentage = mpctx->sh_video->pts * 100 /
1717 mpctx->timeline[mpctx->num_timeline_parts].start;
1718 else
1719 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1722 if (percentage >= 0)
1723 snprintf(percentage_text, 9, " (%d%%)", percentage);
1724 else
1725 percentage_text[0] = 0;
1727 if (opts->osd_level == 3)
1728 snprintf(osd_text_timer, 63,
1729 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1730 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1731 len/3600,(len/60)%60,len%60,percentage_text);
1732 else
1733 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1734 mpctx->osd_function,pts/3600,(pts/60)%60,
1735 pts%60,percentage_text);
1736 } else
1737 osd_text_timer[0]=0;
1739 if (strcmp(osd->osd_text, osd_text_timer)) {
1740 strncpy(osd->osd_text, osd_text_timer, 63);
1741 vo_osd_changed(OSDTYPE_OSD);
1743 return;
1746 // Clear the term osd line
1747 if (term_osd && osd->osd_text[0]) {
1748 osd->osd_text[0] = 0;
1749 printf("%s\n",term_osd_esc);
1753 ///@}
1754 // OSDMsgStack
1757 void reinit_audio_chain(struct MPContext *mpctx)
1759 struct MPOpts *opts = &mpctx->opts;
1760 if (!mpctx->sh_audio)
1761 return;
1762 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1763 current_module="init_audio_codec";
1764 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1765 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1766 goto init_error;
1768 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1769 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1773 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1774 current_module="af_preinit";
1775 ao_data.samplerate=force_srate;
1776 ao_data.channels=0;
1777 ao_data.format=audio_output_format;
1778 // first init to detect best values
1779 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1780 // input:
1781 mpctx->sh_audio->samplerate,
1782 // output:
1783 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1784 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1785 "pre-init!\n");
1786 exit_player(mpctx, EXIT_ERROR);
1788 current_module="ao2_init";
1789 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1790 0, // plugin flag
1791 ao_data.samplerate,
1792 ao_data.channels,
1793 ao_data.format, 0);
1794 if(!mpctx->audio_out){
1795 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1796 goto init_error;
1798 mpctx->initialized_flags|=INITIALIZED_AO;
1799 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1800 mpctx->audio_out->info->short_name,
1801 ao_data.samplerate, ao_data.channels,
1802 af_fmt2str_short(ao_data.format),
1803 af_fmt2bits(ao_data.format)/8 );
1804 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1805 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1806 if(strlen(mpctx->audio_out->info->comment) > 0)
1807 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1810 // init audio filters:
1811 current_module="af_init";
1812 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1813 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1814 goto init_error;
1816 mpctx->mixer.audio_out = mpctx->audio_out;
1817 mpctx->mixer.volstep = volstep;
1818 return;
1820 init_error:
1821 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1822 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1823 mpctx->d_audio->id = -2;
1827 ///@}
1828 // Command2Property
1831 // Return pts value corresponding to the end point of audio written to the
1832 // ao so far.
1833 static double written_audio_pts(struct MPContext *mpctx)
1835 sh_audio_t *sh_audio = mpctx->sh_audio;
1836 demux_stream_t *d_audio = mpctx->d_audio;
1837 double buffered_output;
1838 // first calculate the end pts of audio that has been output by decoder
1839 double a_pts = sh_audio->pts;
1840 if (a_pts != MP_NOPTS_VALUE)
1841 // Good, decoder supports new way of calculating audio pts.
1842 // sh_audio->pts is the timestamp of the latest input packet with
1843 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1844 // the amount of bytes the decoder has written after that timestamp.
1845 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1846 else {
1847 // Decoder doesn't support new way of calculating pts (or we're
1848 // being called before it has decoded anything with known timestamp).
1849 // Use the old method of audio pts calculation: take the timestamp
1850 // of last packet with known pts the decoder has read data from,
1851 // and add amount of bytes read after the beginning of that packet
1852 // divided by input bps. This will be inaccurate if the input/output
1853 // ratio is not constant for every audio packet or if it is constant
1854 // but not accurately known in sh_audio->i_bps.
1856 a_pts = d_audio->pts;
1857 // ds_tell_pts returns bytes read after last timestamp from
1858 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1859 // it has read but not decoded
1860 if (sh_audio->i_bps)
1861 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1862 (double)sh_audio->i_bps;
1864 // Now a_pts hopefully holds the pts for end of audio from decoder.
1865 // Substract data in buffers between decoder and audio out.
1867 // Decoded but not filtered
1868 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1870 // Data buffered in audio filters, measured in bytes of "missing" output
1871 buffered_output = af_calc_delay(sh_audio->afilter);
1873 // Data that was ready for ao but was buffered because ao didn't fully
1874 // accept everything to internal buffers yet
1875 buffered_output += sh_audio->a_out_buffer_len;
1877 // Filters divide audio length by playback_speed, so multiply by it
1878 // to get the length in original units without speedup or slowdown
1879 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1881 return a_pts + mpctx->video_offset;
1884 // Return pts value corresponding to currently playing audio.
1885 double playing_audio_pts(struct MPContext *mpctx)
1887 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1888 mpctx->audio_out->get_delay();
1891 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1892 struct MPOpts *opts = &mpctx->opts;
1893 // check for frame-drop:
1894 current_module = "check_framedrop";
1895 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1896 static int dropped_frames;
1897 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1898 float d = delay-mpctx->delay;
1899 ++total_frame_cnt;
1900 // we should avoid dropping too many frames in sequence unless we
1901 // are too late. and we allow 100ms A-V delay here:
1902 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1903 && !mpctx->update_video_immediately) {
1904 ++drop_frame_cnt;
1905 ++dropped_frames;
1906 return frame_dropping;
1907 } else
1908 dropped_frames = 0;
1910 return 0;
1914 #ifdef HAVE_RTC
1915 int rtc_fd = -1;
1916 #endif
1918 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1920 #ifdef HAVE_RTC
1921 if (rtc_fd >= 0){
1922 // -------- RTC -----------
1923 current_module="sleep_rtc";
1924 while (time_frame > 0.000) {
1925 unsigned long rtc_ts;
1926 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1927 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1928 time_frame -= get_relative_time(mpctx);
1930 } else
1931 #endif
1933 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1934 // unnecessarily high CPU usage
1935 float margin = softsleep ? 0.011 : 0;
1936 current_module = "sleep_timer";
1937 while (time_frame > margin) {
1938 usec_sleep(1000000 * (time_frame - margin));
1939 time_frame -= get_relative_time(mpctx);
1941 if (softsleep){
1942 current_module = "sleep_soft";
1943 if (time_frame < 0)
1944 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1945 while (time_frame > 0)
1946 time_frame -= get_relative_time(mpctx); // burn the CPU
1949 return time_frame;
1952 static int select_subtitle(MPContext *mpctx)
1954 struct MPOpts *opts = &mpctx->opts;
1955 // find the best sub to use
1956 int id;
1957 int found = 0;
1958 mpctx->global_sub_pos = -1; // no subs by default
1959 if (vobsub_id >= 0) {
1960 // if user asks for a vobsub id, use that first.
1961 id = vobsub_id;
1962 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1965 if (!found && opts->sub_id >= 0) {
1966 // if user asks for a dvd sub id, use that next.
1967 id = opts->sub_id;
1968 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1971 if (!found) {
1972 // if there are text subs to use, use those. (autosubs come last here)
1973 id = 0;
1974 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1977 if (!found && opts->sub_id == -1) {
1978 // finally select subs by language and container hints
1979 if (opts->sub_id == -1 && opts->sub_lang)
1980 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, opts->sub_lang);
1981 if (opts->sub_id == -1)
1982 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
1983 if (opts->sub_id >= 0) {
1984 id = opts->sub_id;
1985 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1988 return found;
1991 #ifdef CONFIG_DVDNAV
1992 #ifndef FF_B_TYPE
1993 #define FF_B_TYPE 3
1994 #endif
1995 /// store decoded video image
1996 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1997 mp_image_t *from_mpi) {
1998 mp_image_t *mpi;
2000 /// Do not store B-frames
2001 if (from_mpi->pict_type == FF_B_TYPE)
2002 return to_mpi;
2004 if (to_mpi &&
2005 to_mpi->w == from_mpi->w &&
2006 to_mpi->h == from_mpi->h &&
2007 to_mpi->imgfmt == from_mpi->imgfmt)
2008 mpi = to_mpi;
2009 else {
2010 if (to_mpi)
2011 free_mp_image(to_mpi);
2012 if (from_mpi->w == 0 || from_mpi->h == 0)
2013 return NULL;
2014 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2017 copy_mpi(mpi,from_mpi);
2018 return mpi;
2021 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2022 struct MPOpts *opts = &ctx->opts;
2023 if (ctx->sh_video) {
2024 /// clear video pts
2025 ctx->d_video->pts = 0.0f;
2026 ctx->sh_video->pts = 0.0f;
2027 ctx->sh_video->i_pts = 0.0f;
2028 ctx->sh_video->last_pts = 0.0f;
2029 ctx->sh_video->num_buffered_pts = 0;
2030 ctx->sh_video->num_frames = 0;
2031 ctx->sh_video->num_frames_decoded = 0;
2032 ctx->sh_video->timer = 0.0f;
2033 ctx->sh_video->stream_delay = 0.0f;
2034 ctx->sh_video->timer = 0;
2035 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2038 if (ctx->sh_audio) {
2039 /// free audio packets and reset
2040 ds_free_packs(ctx->d_audio);
2041 audio_delay -= ctx->sh_audio->stream_delay;
2042 ctx->delay =- audio_delay;
2043 ctx->audio_out->reset();
2044 resync_audio_stream(ctx->sh_audio);
2047 audio_delay = 0.0f;
2048 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2049 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2050 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2051 if (dvdsub_lang_id != opts->sub_id) {
2052 opts->sub_id = dvdsub_lang_id;
2053 select_subtitle(ctx);
2057 /// clear all EOF related flags
2058 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2061 /// Restore last decoded DVDNAV (still frame)
2062 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2063 int *in_size,
2064 unsigned char **start,
2065 mp_image_t *decoded_frame)
2067 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2068 return decoded_frame;
2070 /// a change occured in dvdnav stream
2071 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2072 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2073 mp_dvdnav_context_free(mpctx);
2074 mp_dvdnav_reset_stream(mpctx);
2075 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2076 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2079 if (*in_size < 0) {
2080 float len;
2082 /// Display still frame, if any
2083 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2084 decoded_frame = mpctx->nav_smpi;
2086 /// increment video frame : continue playing after still frame
2087 len = demuxer_get_time_length(mpctx->demuxer);
2088 if (mpctx->sh_video->pts >= len &&
2089 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2090 mp_dvdnav_skip_still(mpctx->stream);
2091 mp_dvdnav_skip_wait(mpctx->stream);
2093 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2095 if (mpctx->nav_buffer) {
2096 *start = mpctx->nav_start;
2097 *in_size = mpctx->nav_in_size;
2098 if (mpctx->nav_start)
2099 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2103 return decoded_frame;
2106 /// Save last decoded DVDNAV (still frame)
2107 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2108 unsigned char *start,
2109 mp_image_t *decoded_frame)
2111 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2112 return;
2114 if (mpctx->nav_buffer)
2115 free(mpctx->nav_buffer);
2117 mpctx->nav_buffer = malloc(in_size);
2118 mpctx->nav_start = start;
2119 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2120 if (mpctx->nav_buffer)
2121 memcpy(mpctx->nav_buffer,start,in_size);
2123 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2124 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2126 #endif /* CONFIG_DVDNAV */
2128 /* Modify video timing to match the audio timeline. There are two main
2129 * reasons this is needed. First, video and audio can start from different
2130 * positions at beginning of file or after a seek (MPlayer starts both
2131 * immediately even if they have different pts). Second, the file can have
2132 * audio timestamps that are inconsistent with the duration of the audio
2133 * packets, for example two consecutive timestamp values differing by
2134 * one second but only a packet with enough samples for half a second
2135 * of playback between them.
2137 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2139 current_module = "av_sync";
2141 if (!mpctx->sh_audio)
2142 return;
2144 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2145 double v_pts = mpctx->sh_video->pts;
2146 double av_delay = a_pts - v_pts;
2147 // Try to sync vo_flip() so it will *finish* at given time
2148 av_delay += mpctx->last_vo_flip_duration;
2149 av_delay -= audio_delay; // This much pts difference is desired
2151 double change = av_delay * 0.1;
2152 double max_change = default_max_pts_correction >= 0 ?
2153 default_max_pts_correction : frame_time * 0.1;
2154 if (change < -max_change)
2155 change = -max_change;
2156 else if (change > max_change)
2157 change = max_change;
2158 mpctx->delay += change;
2159 mpctx->total_avsync_change += change;
2162 static int fill_audio_out_buffers(struct MPContext *mpctx)
2164 struct MPOpts *opts = &mpctx->opts;
2165 unsigned int t;
2166 double tt;
2167 int playsize;
2168 int playflags=0;
2169 int audio_eof=0;
2170 bool format_change = false;
2171 sh_audio_t * const sh_audio = mpctx->sh_audio;
2173 current_module="play_audio";
2175 while (1) {
2176 int sleep_time;
2177 // all the current uses of ao_data.pts seem to be in aos that handle
2178 // sync completely wrong; there should be no need to use ao_data.pts
2179 // in get_space()
2180 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2181 playsize = mpctx->audio_out->get_space();
2182 if (mpctx->sh_video || playsize >= ao_data.outburst)
2183 break;
2185 // handle audio-only case:
2186 // this is where mplayer sleeps during audio-only playback
2187 // to avoid 100% CPU use
2188 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2189 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2190 usec_sleep(sleep_time * 1000);
2193 // Fill buffer if needed:
2194 current_module="decode_audio";
2195 t = GetTimer();
2196 int res = decode_audio(sh_audio, playsize);
2197 if (res < 0) { // EOF, error or format change
2198 if (res == -2)
2199 format_change = true;
2200 else if (mpctx->d_audio->eof) {
2201 audio_eof = 1;
2202 if (sh_audio->a_out_buffer_len == 0)
2203 return 0;
2206 t = GetTimer() - t;
2207 tt = t*0.000001f; audio_time_usage+=tt;
2208 if (playsize > sh_audio->a_out_buffer_len) {
2209 playsize = sh_audio->a_out_buffer_len;
2210 if (audio_eof)
2211 playflags |= AOPLAY_FINAL_CHUNK;
2213 if (!playsize)
2214 return 1;
2216 // play audio:
2217 current_module="play_audio";
2219 // Is this pts value actually useful for the aos that access it?
2220 // They're obviously badly broken in the way they handle av sync;
2221 // would not having access to this make them more broken?
2222 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2223 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2225 if (playsize > 0) {
2226 sh_audio->a_out_buffer_len -= playsize;
2227 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2228 sh_audio->a_out_buffer_len);
2229 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2231 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2232 // Sanity check to avoid hanging in case current ao doesn't output
2233 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2234 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2235 sh_audio->a_out_buffer_len = 0;
2238 /* The format change isn't handled too gracefully. A more precise
2239 * implementation would require draining buffered old-format audio
2240 * while displaying video, then doing the output format switch.
2242 if (format_change) {
2243 uninit_player(mpctx, INITIALIZED_AO);
2244 reinit_audio_chain(mpctx);
2247 return 1;
2250 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2251 float *aq_sleep_time)
2253 struct MPOpts *opts = &mpctx->opts;
2254 int frame_time_remaining = 0;
2255 current_module="calc_sleep_time";
2257 *time_frame -= get_relative_time(mpctx); // reset timer
2259 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2260 float delay = mpctx->audio_out->get_delay();
2261 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2263 if (autosync) {
2265 * Adjust this raw delay value by calculating the expected
2266 * delay for this frame and generating a new value which is
2267 * weighted between the two. The higher autosync is, the
2268 * closer to the delay value gets to that which "-nosound"
2269 * would have used, and the longer it will take for A/V
2270 * sync to settle at the right value (but it eventually will.)
2271 * This settling time is very short for values below 100.
2273 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2274 float difference = delay - predicted;
2275 delay = predicted + difference / (float)autosync;
2278 *time_frame = delay - mpctx->delay / opts->playback_speed;
2279 *time_frame -= mpctx->video_out->flip_queue_offset;
2281 // delay = amount of audio buffered in soundcard/driver
2282 if (delay > 0.25) delay=0.25; else
2283 if (delay < 0.10) delay=0.10;
2285 if (*time_frame > delay*0.6) {
2286 // sleep time too big - may cause audio drops (buffer underrun)
2287 frame_time_remaining = 1;
2288 *time_frame = delay*0.5;
2290 } else {
2291 // If we're lagging more than 200 ms behind the right playback rate,
2292 // don't try to "catch up".
2293 // If benchmark is set always output frames as fast as possible
2294 // without sleeping.
2295 if (*time_frame < -0.2 || benchmark)
2296 *time_frame = 0;
2297 *time_frame -= mpctx->video_out->flip_queue_offset;
2300 *aq_sleep_time += *time_frame;
2303 //============================== SLEEP: ===================================
2305 // flag 256 means: libvo driver does its timing (dvb card)
2306 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2307 *time_frame = timing_sleep(mpctx, *time_frame);
2308 *time_frame += mpctx->video_out->flip_queue_offset;
2309 return frame_time_remaining;
2312 int reinit_video_chain(struct MPContext *mpctx)
2314 struct MPOpts *opts = &mpctx->opts;
2315 sh_video_t * const sh_video = mpctx->sh_video;
2316 double ar=-1.0;
2317 //================== Init VIDEO (codec & libvo) ==========================
2318 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2319 current_module="preinit_libvo";
2321 //shouldn't we set dvideo->id=-2 when we fail?
2322 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2323 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2324 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2325 goto err_out;
2327 mpctx->initialized_flags|=INITIALIZED_VO;
2330 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2331 mpctx->sh_video->stream_aspect = ar;
2332 current_module="init_video_filters";
2334 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2335 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2337 #ifdef CONFIG_MENU
2338 if(use_menu) {
2339 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2340 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2341 if(!vf_menu) {
2342 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2343 use_menu = 0;
2346 if(vf_menu)
2347 sh_video->vfilter = vf_menu;
2348 #endif
2350 #ifdef CONFIG_ASS
2351 if(opts->ass_enabled) {
2352 int i;
2353 int insert = 1;
2354 if (opts->vf_settings)
2355 for (i = 0; opts->vf_settings[i].name; ++i)
2356 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2357 insert = 0;
2358 break;
2360 if (insert) {
2361 extern vf_info_t vf_info_ass;
2362 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2363 char* vf_arg[] = {"auto", "1", NULL};
2364 int retcode = 0;
2365 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2366 sh_video->vfilter,
2367 "ass", vf_arg,
2368 &retcode);
2369 if (vf_ass)
2370 sh_video->vfilter = vf_ass;
2371 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2372 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2373 else
2374 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2377 #endif
2379 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2381 #ifdef CONFIG_ASS
2382 if (opts->ass_enabled)
2383 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2384 #endif
2386 current_module="init_video_codec";
2388 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2389 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2390 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2392 if(!sh_video->initialized){
2393 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2394 goto err_out;
2397 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2399 if (sh_video->codec)
2400 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2402 sh_video->last_pts = MP_NOPTS_VALUE;
2403 sh_video->num_buffered_pts = 0;
2404 sh_video->next_frame_time = 0;
2406 if(auto_quality>0){
2407 // Auto quality option enabled
2408 output_quality=get_video_quality_max(sh_video);
2409 if(auto_quality>output_quality) auto_quality=output_quality;
2410 else output_quality=auto_quality;
2411 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2412 set_video_quality(sh_video,output_quality);
2415 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2417 current_module="init_vo";
2419 return 1;
2421 err_out:
2422 mpctx->sh_video = mpctx->d_video->sh = NULL;
2423 return 0;
2426 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2428 struct sh_video *sh_video = mpctx->sh_video;
2429 double frame_time = 0;
2430 struct vo *video_out = mpctx->video_out;
2431 while (!video_out->frame_loaded) {
2432 current_module = "filter_video";
2433 // In nocorrect-pts mode there is no way to properly time these frames
2434 if (vo_get_buffered_frame(video_out, 0) >= 0)
2435 break;
2436 if (vf_output_queued_frame(sh_video->vfilter))
2437 continue;
2438 unsigned char *packet = NULL;
2439 frame_time = sh_video->next_frame_time;
2440 if (mpctx->update_video_immediately)
2441 frame_time = 0;
2442 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2443 &packet, force_fps);
2444 if (in_size < 0) {
2445 #ifdef CONFIG_DVDNAV
2446 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2447 if (mp_dvdnav_is_eof(mpctx->stream))
2448 return -1;
2449 if (mpctx->d_video)
2450 mpctx->d_video->eof = 0;
2451 if (mpctx->d_audio)
2452 mpctx->d_audio->eof = 0;
2453 mpctx->stream->eof = 0;
2454 } else
2455 #endif
2456 return -1;
2458 if (in_size > max_framesize)
2459 max_framesize = in_size;
2460 sh_video->timer += frame_time;
2461 if (mpctx->sh_audio)
2462 mpctx->delay -= frame_time;
2463 // video_read_frame can change fps (e.g. for ASF video)
2464 vo_fps = sh_video->fps;
2465 int framedrop_type = check_framedrop(mpctx, frame_time);
2466 current_module = "decode video";
2468 void *decoded_frame;
2469 #ifdef CONFIG_DVDNAV
2470 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2471 if (in_size >= 0 && !decoded_frame)
2472 #endif
2473 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2474 sh_video->pts);
2475 #ifdef CONFIG_DVDNAV
2476 // Save last still frame for future display
2477 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2478 #endif
2479 if (decoded_frame) {
2480 current_module = "filter video";
2481 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2482 if (!video_out->config_ok)
2483 break;
2486 return frame_time;
2489 static void determine_frame_pts(struct MPContext *mpctx)
2491 struct sh_video *sh_video = mpctx->sh_video;
2492 struct MPOpts *opts = &mpctx->opts;
2494 if (opts->user_pts_assoc_mode) {
2495 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2496 } else if (sh_video->pts_assoc_mode == 0) {
2497 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2498 sh_video->pts_assoc_mode = 1;
2499 else
2500 sh_video->pts_assoc_mode = 2;
2501 } else {
2502 int probcount1 = sh_video->num_reordered_pts_problems;
2503 int probcount2 = sh_video->num_sorted_pts_problems;
2504 if (sh_video->pts_assoc_mode == 2) {
2505 int tmp = probcount1;
2506 probcount1 = probcount2;
2507 probcount2 = tmp;
2509 if (probcount1 >= probcount2 * 1.5 + 2) {
2510 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2511 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2512 "%d.\n", sh_video->pts_assoc_mode);
2515 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2516 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2519 static double update_video(struct MPContext *mpctx)
2521 struct sh_video *sh_video = mpctx->sh_video;
2522 struct vo *video_out = mpctx->video_out;
2523 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2524 mpctx->osd); // hack for vf_expand
2525 if (!mpctx->opts.correct_pts)
2526 return update_video_nocorrect_pts(mpctx);
2528 double pts;
2530 bool hit_eof = false;
2531 while (!video_out->frame_loaded) {
2532 current_module = "filter_video";
2533 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2534 break;
2535 // XXX Time used in this call is not counted in any performance
2536 // timer now, OSD time is not updated correctly for filter-added frames
2537 if (vf_output_queued_frame(sh_video->vfilter))
2538 continue;
2539 if (hit_eof)
2540 return -1;
2541 unsigned char *packet = NULL;
2542 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2543 if (pts != MP_NOPTS_VALUE)
2544 pts += mpctx->video_offset;
2545 if (in_size < 0) {
2546 // try to extract last frames in case of decoder lag
2547 in_size = 0;
2548 pts = MP_NOPTS_VALUE;
2549 hit_eof = true;
2551 if (in_size > max_framesize)
2552 max_framesize = in_size;
2553 current_module = "decode video";
2554 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2555 void *decoded_frame = decode_video(sh_video, packet, in_size,
2556 framedrop_type, pts);
2557 if (decoded_frame) {
2558 determine_frame_pts(mpctx);
2559 current_module = "filter video";
2560 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2561 if (!video_out->config_ok)
2562 break; // We'd likely hang in this loop otherwise
2566 pts = video_out->next_pts;
2567 if (pts == MP_NOPTS_VALUE) {
2568 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2569 // Try to use decoder pts from before filters
2570 pts = sh_video->pts;
2571 if (pts == MP_NOPTS_VALUE)
2572 pts = sh_video->last_pts;
2574 sh_video->pts = pts;
2575 if (sh_video->last_pts == MP_NOPTS_VALUE)
2576 sh_video->last_pts = sh_video->pts;
2577 else if (sh_video->last_pts > sh_video->pts) {
2578 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2579 sh_video->pts, sh_video->last_pts);
2580 /* If the difference in pts is small treat it as jitter around the
2581 * right value (possibly caused by incorrect timestamp ordering) and
2582 * just show this frame immediately after the last one.
2583 * Treat bigger differences as timestamp resets and start counting
2584 * timing of later frames from the position of this one. */
2585 if (sh_video->last_pts - sh_video->pts > 0.5)
2586 sh_video->last_pts = sh_video->pts;
2587 else
2588 sh_video->pts = sh_video->last_pts;
2590 double frame_time = sh_video->pts - sh_video->last_pts;
2591 sh_video->last_pts = sh_video->pts;
2592 sh_video->timer += frame_time;
2593 if (mpctx->sh_audio)
2594 mpctx->delay -= frame_time;
2595 return frame_time;
2598 void pause_player(struct MPContext *mpctx)
2600 if (mpctx->paused)
2601 return;
2602 mpctx->paused = 1;
2603 mpctx->step_frames = 0;
2604 mpctx->time_frame -= get_relative_time(mpctx);
2606 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2607 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2609 if (mpctx->audio_out && mpctx->sh_audio)
2610 mpctx->audio_out->pause(); // pause audio, keep data if possible
2613 void unpause_player(struct MPContext *mpctx)
2615 if (!mpctx->paused)
2616 return;
2617 mpctx->paused = 0;
2619 if (mpctx->audio_out && mpctx->sh_audio)
2620 mpctx->audio_out->resume(); // resume audio
2621 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2622 && !mpctx->step_frames)
2623 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2624 (void)get_relative_time(mpctx); // ignore time that passed during pause
2627 void add_step_frame(struct MPContext *mpctx)
2629 mpctx->step_frames++;
2630 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2631 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2632 unpause_player(mpctx);
2635 static void pause_loop(struct MPContext *mpctx)
2637 mp_cmd_t* cmd;
2638 if (!quiet) {
2639 // Small hack to display the pause message on the OSD line.
2640 // The pause string is: "\n == PAUSE == \r" so we need to
2641 // take the first and the last char out
2642 if (term_osd && !mpctx->sh_video) {
2643 char msg[128] = _("\n ===== PAUSE =====\r");
2644 int mlen = strlen(msg);
2645 msg[mlen-1] = '\0';
2646 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2647 update_osd_msg(mpctx);
2648 } else
2649 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2650 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2653 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2654 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2655 if (cmd) {
2656 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2657 run_command(mpctx, cmd);
2658 mp_cmd_free(cmd);
2659 continue;
2661 if (mpctx->sh_video && mpctx->video_out)
2662 vo_check_events(mpctx->video_out);
2663 #ifdef CONFIG_MENU
2664 if (vf_menu)
2665 vf_menu_pause_update(vf_menu);
2666 #endif
2667 usec_sleep(20000);
2668 update_osd_msg(mpctx);
2669 int hack = vo_osd_changed(0);
2670 vo_osd_changed(hack);
2671 if (hack)
2672 break;
2677 // Find the right mute status and record position for new file position
2678 static void edl_seek_reset(MPContext *mpctx)
2680 mpctx->edl_muted = 0;
2681 next_edl_record = edl_records;
2683 while (next_edl_record) {
2684 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2685 break;
2687 if (next_edl_record->action == EDL_MUTE)
2688 mpctx->edl_muted = !mpctx->edl_muted;
2689 next_edl_record = next_edl_record->next;
2691 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2692 mixer_mute(&mpctx->mixer);
2696 // Execute EDL command for the current position if one exists
2697 static void edl_update(MPContext *mpctx)
2699 if (!next_edl_record)
2700 return;
2702 if (!mpctx->sh_video) {
2703 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2704 free_edl(edl_records);
2705 next_edl_record = NULL;
2706 edl_records = NULL;
2707 return;
2710 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2711 if (next_edl_record->action == EDL_SKIP) {
2712 mpctx->osd_function = OSD_FFW;
2713 mpctx->abs_seek_pos = 0;
2714 mpctx->rel_seek_secs = next_edl_record->length_sec;
2715 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2716 "[%f], length [%f]\n", next_edl_record->start_sec,
2717 next_edl_record->stop_sec, next_edl_record->length_sec);
2719 else if (next_edl_record->action == EDL_MUTE) {
2720 mpctx->edl_muted = !mpctx->edl_muted;
2721 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2722 mixer_mute(&mpctx->mixer);
2723 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2724 next_edl_record->start_sec );
2726 next_edl_record = next_edl_record->next;
2730 static void reinit_decoders(struct MPContext *mpctx)
2732 reinit_video_chain(mpctx);
2733 reinit_audio_chain(mpctx);
2734 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2737 static void seek_reset(struct MPContext *mpctx)
2739 if (mpctx->sh_video) {
2740 current_module = "seek_video_reset";
2741 resync_video_stream(mpctx->sh_video);
2742 mpctx->sh_video->timer = 0;
2743 vo_seek_reset(mpctx->video_out);
2744 mpctx->sh_video->timer = 0;
2745 mpctx->sh_video->num_buffered_pts = 0;
2746 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2747 mpctx->delay = 0;
2748 mpctx->time_frame = 0;
2749 mpctx->update_video_immediately = true;
2750 // Not all demuxers set d_video->pts during seek, so this value
2751 // (which is used by at least vobsub and edl code below) may
2752 // be completely wrong (probably 0).
2753 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2754 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2755 mpctx->sh_video->pts, mpctx->video_offset,
2756 mpctx->d_sub, 1);
2757 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2760 if (mpctx->sh_audio) {
2761 current_module = "seek_audio_reset";
2762 resync_audio_stream(mpctx->sh_audio);
2763 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2764 mpctx->sh_audio->a_buffer_len = 0;
2765 mpctx->sh_audio->a_out_buffer_len = 0;
2766 if (!mpctx->sh_video)
2767 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2768 mpctx->video_offset, mpctx->d_sub, 1);
2771 if (vo_vobsub && mpctx->sh_video) {
2772 current_module = "seek_vobsub_reset";
2773 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2776 edl_seek_reset(mpctx);
2778 mpctx->total_avsync_change = 0;
2779 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2780 drop_frame_cnt = 0;
2782 current_module = NULL;
2785 static bool timeline_set_part(struct MPContext *mpctx, int i)
2787 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2788 struct timeline_part *n = mpctx->timeline + i;
2789 mpctx->timeline_part = i;
2790 mpctx->video_offset = n->start - n->source_start;
2791 if (n->source == p->source)
2792 return false;
2793 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2794 mpctx->demuxer = n->source->demuxer;
2795 mpctx->d_video = mpctx->demuxer->video;
2796 mpctx->d_audio = mpctx->demuxer->audio;
2797 mpctx->d_sub = mpctx->demuxer->sub;
2798 mpctx->sh_video = mpctx->d_video->sh;
2799 mpctx->sh_audio = mpctx->d_audio->sh;
2800 return true;
2803 // Given pts, switch playback to the corresponding part.
2804 // Return offset within that part.
2805 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2806 bool *need_reset)
2808 if (pts < 0)
2809 pts = 0;
2810 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2811 struct timeline_part *p = mpctx->timeline + i;
2812 if (pts < (p+1)->start) {
2813 *need_reset = timeline_set_part(mpctx, i);
2814 return pts - p->start + p->source_start;
2817 return -1;
2821 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2822 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2823 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2824 static int seek(MPContext *mpctx, double amount, int style)
2826 current_module = "seek";
2827 if (mpctx->stop_play == AT_END_OF_FILE)
2828 mpctx->stop_play = KEEP_PLAYING;
2829 if (style & SEEK_FACTOR
2830 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2831 || amount < 0)
2832 mpctx->last_chapter_seek = -1;
2833 if (mpctx->timeline && style & SEEK_FACTOR) {
2834 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2835 style &= ~SEEK_FACTOR;
2837 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2838 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2839 style |= SEEK_ABSOLUTE;
2840 if (amount > 0)
2841 style |= SEEK_FORWARD;
2842 else
2843 style |= SEEK_BACKWARD;
2844 amount += mpctx->sh_video->pts;
2847 /* At least the liba52 decoder wants to read from the input stream
2848 * during initialization, so reinit must be done after the demux_seek()
2849 * call that clears possible stream EOF. */
2850 bool need_reset = false;
2851 if (mpctx->timeline) {
2852 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2853 if (amount == -1) {
2854 mpctx->stop_play = AT_END_OF_FILE;
2855 // Clear audio from current position
2856 if (mpctx->sh_audio) {
2857 mpctx->audio_out->reset();
2858 mpctx->sh_audio->a_buffer_len = 0;
2859 mpctx->sh_audio->a_out_buffer_len = 0;
2861 return -1;
2864 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2865 if (need_reset)
2866 reinit_decoders(mpctx);
2867 if (seekresult == 0)
2868 return -1;
2870 seek_reset(mpctx);
2871 return 0;
2874 // -2 is no chapters, -1 is before first chapter
2875 int get_current_chapter(struct MPContext *mpctx)
2877 if (!mpctx->chapters || !mpctx->sh_video)
2878 return FFMAX(mpctx->last_chapter_seek,
2879 demuxer_get_current_chapter(mpctx->demuxer));
2881 int i;
2882 double current_pts = mpctx->sh_video->pts;
2883 for (i = 1; i < mpctx->num_chapters; i++)
2884 if (current_pts < mpctx->chapters[i].start)
2885 break;
2886 return FFMAX(mpctx->last_chapter_seek, i - 1);
2889 // currently returns a string allocated with malloc, not talloc
2890 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2892 if (!mpctx->chapters || !mpctx->sh_video)
2893 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2894 return strdup(mpctx->chapters[chapter].name);
2897 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2898 char **chapter_name)
2900 mpctx->last_chapter_seek = -1;
2901 if (!mpctx->chapters || !mpctx->sh_video) {
2902 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2903 chapter_name);
2904 if (res >= 0) {
2905 if (*seek_pts == -1)
2906 seek_reset(mpctx);
2907 else {
2908 mpctx->last_chapter_seek = res;
2909 mpctx->last_chapter_pts = *seek_pts;
2912 return res;
2915 if (chapter >= mpctx->num_chapters)
2916 return -1;
2917 if (chapter < 0)
2918 chapter = 0;
2919 *seek_pts = mpctx->chapters[chapter].start;
2920 mpctx->last_chapter_seek = chapter;
2921 mpctx->last_chapter_pts = *seek_pts;
2922 if (chapter_name)
2923 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2924 return chapter;
2927 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2928 struct content_source *sources,
2929 int num_sources,
2930 unsigned char uid_map[][16])
2932 int num_filenames = 0;
2933 char **filenames = NULL;
2934 if (num_sources > 1) {
2935 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2936 "other sources.\n");
2937 if (mpctx->stream->type != STREAMTYPE_FILE) {
2938 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2939 "normal disk file. Will not search for related files.\n");
2940 } else {
2941 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2942 "same directory to find referenced sources.\n");
2943 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2944 &num_filenames);
2948 int num_left = num_sources - 1;
2949 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2950 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2951 filename_recode(filenames[i]));
2952 int format;
2953 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2954 if (!s)
2955 continue;
2956 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2957 mpctx->opts.audio_id,
2958 mpctx->opts.video_id,
2959 mpctx->opts.sub_id, filenames[i]);
2960 if (!d) {
2961 free_stream(s);
2962 continue;
2964 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2965 for (int i = 1; i < num_sources; i++) {
2966 if (sources[i].demuxer)
2967 continue;
2968 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2969 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2970 i, filename_recode(d->filename));
2971 sources[i].stream = s;
2972 sources[i].demuxer = d;
2973 num_left--;
2974 goto match;
2978 free_demuxer(d);
2979 free_stream(s);
2980 continue;
2981 match:
2984 talloc_free(filenames);
2985 if (num_left) {
2986 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2987 "There will be parts MISSING from the video!\n");
2988 for (int i = 1, j = 1; i < num_sources; i++)
2989 if (sources[i].demuxer) {
2990 sources[j] = sources[i];
2991 memcpy(uid_map[j], uid_map[i], 16);
2992 j++;
2995 return num_sources - num_left;
2998 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3000 if (!mpctx->opts.ordered_chapters) {
3001 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3002 "you have disabled support for them. Ignoring.\n");
3003 return;
3006 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3007 "edit timeline.\n");
3009 struct demuxer *demuxer = mpctx->demuxer;
3010 struct matroska_data *m = &demuxer->matroska_data;
3012 // +1 because sources/uid_map[0] is original file even if all chapters
3013 // actually use other sources and need separate entries
3014 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3015 m->num_ordered_chapters+1);
3016 sources[0].stream = mpctx->stream;
3017 sources[0].demuxer = mpctx->demuxer;
3018 unsigned char uid_map[m->num_ordered_chapters+1][16];
3019 int num_sources = 1;
3020 memcpy(uid_map[0], m->segment_uid, 16);
3022 for (int i = 0; i < m->num_ordered_chapters; i++) {
3023 struct matroska_chapter *c = m->ordered_chapters + i;
3024 if (!c->has_segment_uid)
3025 memcpy(c->segment_uid, m->segment_uid, 16);
3027 for (int j = 0; j < num_sources; j++)
3028 if (!memcmp(c->segment_uid, uid_map[j], 16))
3029 goto found1;
3030 memcpy(uid_map[num_sources], c->segment_uid, 16);
3031 sources[num_sources] = (struct content_source){};
3032 num_sources++;
3033 found1:
3037 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3038 uid_map);
3041 // +1 for terminating chapter with start time marking end of last real one
3042 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3043 m->num_ordered_chapters + 1);
3044 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3045 m->num_ordered_chapters);
3046 uint64_t starttime = 0;
3047 uint64_t missing_time = 0;
3048 int part_count = 0;
3049 int num_chapters = 0;
3050 uint64_t prev_part_offset = 0;
3051 for (int i = 0; i < m->num_ordered_chapters; i++) {
3052 struct matroska_chapter *c = m->ordered_chapters + i;
3054 int j;
3055 for (j = 0; j < num_sources; j++) {
3056 if (!memcmp(c->segment_uid, uid_map[j], 16))
3057 goto found2;
3059 missing_time += c->end - c->start;
3060 continue;
3061 found2:;
3062 chapters[num_chapters].start = starttime / 1000.;
3063 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3064 /* Only add a separate part if the time or file actually changes.
3065 * Matroska files have chapter divisions that are redundant from
3066 * timeline point of view because the same chapter structure is used
3067 * both to specify the timeline and for normal chapter information.
3068 * Removing a missing inserted external chapter can also cause this. */
3069 if (part_count == 0 || c->start != starttime + prev_part_offset
3070 || sources + j != timeline[part_count - 1].source) {
3071 timeline[part_count].source = sources + j;
3072 timeline[part_count].start = chapters[num_chapters].start;
3073 timeline[part_count].source_start = c->start / 1000.;
3074 prev_part_offset = c->start - starttime;
3075 part_count++;
3077 starttime += c->end - c->start;
3078 num_chapters++;
3080 timeline[part_count].start = starttime / 1000.;
3082 if (!part_count) {
3083 // None of the parts come from the file itself???
3084 talloc_free(sources);
3085 talloc_free(timeline);
3086 talloc_free(chapters);
3087 return;
3090 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3091 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3092 timeline[part_count].start);
3093 if (missing_time)
3094 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3095 "from the timeline!\n", missing_time / 1000.);
3096 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3097 for (int i = 0; i < num_sources; i++)
3098 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3099 filename_recode(sources[i].demuxer->filename));
3100 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3101 "source_start, source):\n");
3102 for (int i = 0; i < part_count; i++) {
3103 struct timeline_part *p = timeline + i;
3104 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3105 p->source_start, p->source - sources);
3107 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3108 mpctx->sources = sources;
3109 mpctx->num_sources = num_sources;
3110 mpctx->timeline = timeline;
3111 mpctx->num_timeline_parts = part_count;
3112 mpctx->num_chapters = num_chapters;
3113 mpctx->chapters = chapters;
3115 mpctx->timeline_part = 0;
3116 mpctx->demuxer = timeline[0].source->demuxer;
3120 static int read_keys(void *ctx, int fd)
3122 getch2(ctx);
3123 return mplayer_get_key(ctx, 0);
3127 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3128 * file for some tools to link against. */
3129 #ifndef DISABLE_MAIN
3130 int main(int argc,char* argv[]){
3133 char * mem_ptr;
3135 // movie info:
3137 /* Flag indicating whether MPlayer should exit without playing anything. */
3138 int opt_exit = 0;
3140 //float a_frame=0; // Audio
3142 int i;
3144 struct MPContext *mpctx = &(struct MPContext){
3145 .osd_function = OSD_PLAY,
3146 .begin_skip = MP_NOPTS_VALUE,
3147 .play_tree_step = 1,
3148 .global_sub_pos = -1,
3149 .set_of_sub_pos = -1,
3150 .file_format = DEMUXER_TYPE_UNKNOWN,
3151 .last_dvb_step = 1,
3154 InitTimer();
3155 srand(GetTimerMS());
3157 mp_msg_init();
3158 set_av_log_callback();
3160 #ifdef CONFIG_X11
3161 mpctx->x11_state = vo_x11_init_state();
3162 #endif
3163 struct MPOpts *opts = &mpctx->opts;
3164 set_default_mplayer_options(opts);
3165 // Create the config context and register the options
3166 mpctx->mconfig = m_config_new(opts, cfg_include);
3167 m_config_register_options(mpctx->mconfig,mplayer_opts);
3168 m_config_register_options(mpctx->mconfig, common_opts);
3169 mp_input_register_options(mpctx->mconfig);
3171 // Preparse the command line
3172 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3174 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3175 set_path_env();
3176 #endif
3178 #ifdef CONFIG_TV
3179 stream_tv_defaults.immediate = 1;
3180 #endif
3182 parse_cfgfiles(mpctx, mpctx->mconfig);
3184 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3185 if(mpctx->playtree == NULL)
3186 opt_exit = 1;
3187 else {
3188 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3189 if(mpctx->playtree) {
3190 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3191 if(mpctx->playtree_iter) {
3192 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3193 play_tree_iter_free(mpctx->playtree_iter);
3194 mpctx->playtree_iter = NULL;
3196 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3200 mpctx->key_fifo = mp_fifo_create(opts);
3202 print_version("MPlayer");
3204 #if defined(__MINGW32__) || defined(__CYGWIN__)
3206 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3207 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3208 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3209 if (kernel32) {
3210 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3211 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3213 if (setDEP) setDEP(3);
3214 if (setDllDir) setDllDir("");
3216 // stop Windows from showing all kinds of annoying error dialogs
3217 SetErrorMode(0x8003);
3218 // request 1ms timer resolution
3219 timeBeginPeriod(1);
3220 #endif
3222 #ifdef CONFIG_PRIORITY
3223 set_priority();
3224 #endif
3226 if (codec_path)
3227 set_codec_path(codec_path);
3229 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3230 list_video_out();
3231 opt_exit = 1;
3234 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3235 list_audio_out();
3236 opt_exit = 1;
3239 /* Check codecs.conf. */
3240 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3241 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3242 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3243 if(!parse_codec_cfg(NULL)){
3244 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3246 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3249 free( mem_ptr ); // release the buffer created by get_path()
3252 #if 0
3253 if(video_codec_list){
3254 int i;
3255 video_codec=video_codec_list[0];
3256 for(i=0;video_codec_list[i];i++)
3257 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
3259 #endif
3260 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3261 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3262 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3263 list_codecs(1);
3264 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3265 opt_exit = 1;
3267 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3268 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3269 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3270 list_codecs(0);
3271 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3272 opt_exit = 1;
3274 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3275 vfm_help();
3276 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3277 opt_exit = 1;
3279 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3280 afm_help();
3281 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3282 opt_exit = 1;
3284 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3285 af_help();
3286 printf("\n");
3287 opt_exit = 1;
3289 #ifdef CONFIG_X11
3290 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3291 fstype_help();
3292 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3293 opt_exit = 1;
3295 #endif
3296 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3297 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3298 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3299 demuxer_help();
3300 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3301 opt_exit = 1;
3303 if(list_properties) {
3304 property_print_help();
3305 opt_exit = 1;
3308 if(opt_exit)
3309 exit_player(mpctx, EXIT_NONE);
3311 if(!mpctx->filename && !player_idle_mode){
3312 // no file/vcd/dvd -> show HELP:
3313 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3314 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3317 /* Display what configure line was used */
3318 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3320 // Many users forget to include command line in bugreports...
3321 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3322 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3323 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3324 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3327 //------ load global data first ------
3329 mpctx->osd = osd_create();
3331 // check font
3332 #ifdef CONFIG_FREETYPE
3333 init_freetype();
3334 #endif
3335 #ifdef CONFIG_FONTCONFIG
3336 if(font_fontconfig <= 0)
3338 #endif
3339 #ifdef CONFIG_BITMAP_FONT
3340 if(font_name){
3341 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3342 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3343 filename_recode(font_name));
3344 } else {
3345 // try default:
3346 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3347 free(mem_ptr); // release the buffer created by get_path()
3348 if(!vo_font)
3349 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3351 if (sub_font_name)
3352 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3353 else
3354 mpctx->osd->sub_font = vo_font;
3355 #endif
3356 #ifdef CONFIG_FONTCONFIG
3358 #endif
3360 #ifdef CONFIG_ASS
3361 ass_library = ass_init();
3362 #endif
3364 #ifdef HAVE_RTC
3365 if(!nortc)
3367 // seteuid(0); /* Can't hurt to try to get root here */
3368 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3369 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3370 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3371 else {
3372 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3374 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3375 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3376 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3377 close (rtc_fd);
3378 rtc_fd = -1;
3379 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3380 /* variable only by the root */
3381 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3382 close (rtc_fd);
3383 rtc_fd = -1;
3384 } else
3385 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3388 if(rtc_fd<0)
3389 #endif /* HAVE_RTC */
3390 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3391 softsleep?"software":timer_name);
3393 #ifdef HAVE_TERMCAP
3394 load_termcap(NULL); // load key-codes
3395 #endif
3397 // ========== Init keyboard FIFO (connection to libvo) ============
3399 // Init input system
3400 current_module = "init_input";
3401 mpctx->input = mp_input_init(&opts->input);
3402 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3403 if(slave_mode)
3404 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3405 else if(!noconsolecontrols)
3406 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3407 // Set the libstream interrupt callback
3408 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3410 #ifdef CONFIG_MENU
3411 if(use_menu) {
3412 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3413 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3414 else {
3415 menu_cfg = get_path("menu.conf");
3416 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3417 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3418 else {
3419 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3420 MPLAYER_CONFDIR "/menu.conf"))
3421 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3422 else {
3423 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3424 use_menu = 0;
3429 #endif
3431 current_module = NULL;
3433 /// Catch signals
3434 #ifndef __MINGW32__
3435 signal(SIGCHLD,child_sighandler);
3436 #endif
3438 #ifdef CONFIG_CRASH_DEBUG
3439 prog_path = argv[0];
3440 #endif
3441 //========= Catch terminate signals: ================
3442 // terminate requests:
3443 signal(SIGTERM,exit_sighandler); // kill
3444 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3446 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3448 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3449 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3450 #ifdef CONFIG_SIGHANDLER
3451 // fatal errors:
3452 signal(SIGBUS,exit_sighandler); // bus error
3453 signal(SIGSEGV,exit_sighandler); // segfault
3454 signal(SIGILL,exit_sighandler); // illegal instruction
3455 signal(SIGFPE,exit_sighandler); // floating point exc.
3456 signal(SIGABRT,exit_sighandler); // abort()
3457 #ifdef CONFIG_CRASH_DEBUG
3458 if (crash_debug)
3459 signal(SIGTRAP,exit_sighandler);
3460 #endif
3461 #endif
3463 // ******************* Now, let's see the per-file stuff ********************
3465 play_next_file:
3467 // init global sub numbers
3468 mpctx->global_sub_size = 0;
3469 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3471 if (mpctx->filename) {
3472 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3473 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3474 load_per_file_config (mpctx->mconfig, mpctx->filename);
3477 if (opts->video_driver_list)
3478 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3479 if (opts->audio_driver_list)
3480 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3482 // We must enable getch2 here to be able to interrupt network connection
3483 // or cache filling
3484 if(!noconsolecontrols && !slave_mode){
3485 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3486 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3487 else
3488 getch2_enable(); // prepare stdin for hotkeys...
3489 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3490 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3493 // =================== GUI idle loop (STOP state) ===========================
3494 while (player_idle_mode && !mpctx->filename) {
3495 play_tree_t * entry = NULL;
3496 mp_cmd_t * cmd;
3497 if (mpctx->video_out && mpctx->video_out->config_ok)
3498 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3499 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3500 if (mpctx->video_out)
3501 vo_check_events(mpctx->video_out);
3502 usec_sleep(20000);
3504 switch (cmd->id) {
3505 case MP_CMD_LOADFILE:
3506 // prepare a tree entry with the new filename
3507 entry = play_tree_new();
3508 play_tree_add_file(entry, cmd->args[0].v.s);
3509 // The entry is added to the main playtree after the switch().
3510 break;
3511 case MP_CMD_LOADLIST:
3512 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3513 break;
3514 case MP_CMD_QUIT:
3515 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3516 break;
3517 case MP_CMD_VO_FULLSCREEN:
3518 case MP_CMD_GET_PROPERTY:
3519 case MP_CMD_SET_PROPERTY:
3520 case MP_CMD_STEP_PROPERTY:
3521 run_command(mpctx, cmd);
3522 break;
3525 mp_cmd_free(cmd);
3527 if (entry) { // user entered a command that gave a valid entry
3528 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3529 play_tree_free_list(mpctx->playtree->child, 1);
3530 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3532 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3534 play_tree_set_child(mpctx->playtree, entry);
3536 /* Make iterator start at the top the of tree. */
3537 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3538 if (!mpctx->playtree_iter) continue;
3540 // find the first real item in the tree
3541 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3542 // no items!
3543 play_tree_iter_free(mpctx->playtree_iter);
3544 mpctx->playtree_iter = NULL;
3545 continue; // wait for next command
3547 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3550 //---------------------------------------------------------------------------
3552 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3553 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3555 if (mpctx->filename) {
3556 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3557 filename_recode(mpctx->filename));
3558 if(use_filename_title && vo_wintitle == NULL)
3559 vo_wintitle = strdup(mp_basename2(mpctx->filename));
3562 if (edl_filename) {
3563 if (edl_records) free_edl(edl_records);
3564 next_edl_record = edl_records = edl_parse_file();
3566 if (edl_output_filename) {
3567 if (edl_fd) fclose(edl_fd);
3568 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3570 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3571 filename_recode(edl_output_filename));
3575 //==================== Open VOB-Sub ============================
3577 current_module="vobsub";
3578 if (vobsub_name){
3579 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3580 if(vo_vobsub==NULL)
3581 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3582 filename_recode(vobsub_name));
3583 } else if (sub_auto && mpctx->filename){
3584 /* try to autodetect vobsub from movie filename ::atmos */
3585 char *buf = strdup(mpctx->filename), *psub;
3586 char *pdot = strrchr(buf, '.');
3587 char *pslash = strrchr(buf, '/');
3588 #if defined(__MINGW32__) || defined(__CYGWIN__)
3589 if (!pslash) pslash = strrchr(buf, '\\');
3590 #endif
3591 if (pdot && (!pslash || pdot > pslash))
3592 *pdot = '\0';
3593 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3594 /* try from ~/.mplayer/sub */
3595 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3596 char *bname;
3597 int l;
3598 bname = strrchr(buf,'/');
3599 #if defined(__MINGW32__) || defined(__CYGWIN__)
3600 if(!bname) bname = strrchr(buf,'\\');
3601 #endif
3602 if(bname) bname++;
3603 else bname = buf;
3604 l = strlen(psub) + strlen(bname) + 1;
3605 psub = realloc(psub,l);
3606 strcat(psub,bname);
3607 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3608 free(psub);
3610 free(buf);
3612 if(vo_vobsub){
3613 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3614 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3615 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3617 // setup global sub numbering
3618 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3621 //============ Open & Sync STREAM --- fork cache2 ====================
3623 mpctx->stream=NULL;
3624 mpctx->demuxer=NULL;
3625 if (mpctx->d_audio) {
3626 //free_demuxer_stream(mpctx->d_audio);
3627 mpctx->d_audio=NULL;
3629 if (mpctx->d_video) {
3630 //free_demuxer_stream(d_video);
3631 mpctx->d_video=NULL;
3633 mpctx->sh_audio=NULL;
3634 mpctx->sh_video=NULL;
3636 current_module="open_stream";
3637 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3638 if(!mpctx->stream) { // error...
3639 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3640 goto goto_next_file;
3642 mpctx->initialized_flags|=INITIALIZED_STREAM;
3644 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3645 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3646 "playlist support will not be used automatically.\n"
3647 "MPlayer's playlist code is unsafe and should only be used with "
3648 "trusted sources.\nPlayback will probably fail.\n\n");
3649 #if 0
3650 play_tree_t* entry;
3651 // Handle playlist
3652 current_module="handle_playlist";
3653 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3654 filename_recode(mpctx->filename));
3655 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3656 mpctx->eof=playtree_add_playlist(mpctx, entry);
3657 goto goto_next_file;
3658 #endif
3660 mpctx->stream->start_pos+=seek_to_byte;
3662 if(stream_dump_type==5){
3663 unsigned char buf[4096];
3664 int len;
3665 FILE *f;
3666 current_module="dumpstream";
3667 stream_reset(mpctx->stream);
3668 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3669 f=fopen(stream_dump_name,"wb");
3670 if(!f){
3671 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3672 exit_player(mpctx, EXIT_ERROR);
3674 if (opts->chapterrange[0] > 1) {
3675 int chapter = opts->chapterrange[0] - 1;
3676 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3678 while(!mpctx->stream->eof && !async_quit_request){
3679 len=stream_read(mpctx->stream,buf,4096);
3680 if(len>0) {
3681 if(fwrite(buf,len,1,f) != 1) {
3682 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3683 exit_player(mpctx, EXIT_ERROR);
3686 if (opts->chapterrange[1] > 0) {
3687 int chapter = -1;
3688 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3689 &chapter) == STREAM_OK
3690 && chapter + 1 > opts->chapterrange[1])
3691 break;
3694 if(fclose(f)) {
3695 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3696 exit_player(mpctx, EXIT_ERROR);
3698 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3699 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3702 #ifdef CONFIG_DVDREAD
3703 if(mpctx->stream->type==STREAMTYPE_DVD){
3704 current_module="dvd lang->id";
3705 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3706 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3707 // setup global sub numbering
3708 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3709 current_module=NULL;
3711 #endif
3713 #ifdef CONFIG_DVDNAV
3714 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3715 current_module="dvdnav lang->id";
3716 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3717 dvdsub_lang_id = -3;
3718 if(opts->sub_lang && opts->sub_id==-1)
3719 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3720 // setup global sub numbering
3721 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3722 current_module=NULL;
3724 #endif
3726 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3727 goto_enable_cache:
3728 if(stream_cache_size>0){
3729 int res;
3730 current_module="enable_cache";
3731 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3732 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3733 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3734 if(res == 0)
3735 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3738 //============ Open DEMUXERS --- DETECT file type =======================
3739 current_module="demux_open";
3741 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3743 // HACK to get MOV Reference Files working
3745 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3747 unsigned char* playlist_entry;
3748 play_tree_t *list = NULL, *entry = NULL;
3750 current_module="handle_demux_playlist";
3751 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3753 char *temp, *bname;
3755 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3756 filename_recode(playlist_entry));
3758 bname=mp_basename(playlist_entry);
3759 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3760 continue;
3762 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3763 continue;
3765 entry = play_tree_new();
3767 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3769 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3770 if (temp)
3772 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3773 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3774 strcat(temp, playlist_entry);
3775 if (!strcmp(temp, mpctx->filename)) {
3776 free(temp);
3777 continue;
3779 play_tree_add_file(entry,temp);
3780 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3781 free(temp);
3784 else
3785 play_tree_add_file(entry,playlist_entry);
3787 if(!list)
3788 list = entry;
3789 else
3790 play_tree_append_entry(list,entry);
3792 free_demuxer(mpctx->demuxer);
3793 mpctx->demuxer = NULL;
3795 if (list)
3797 entry = play_tree_new();
3798 play_tree_set_child(entry,list);
3799 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3800 goto goto_next_file;
3804 if(!mpctx->demuxer)
3805 goto goto_next_file;
3807 if (mpctx->demuxer->matroska_data.ordered_chapters)
3808 build_ordered_chapter_timeline(mpctx);
3810 if (!mpctx->sources) {
3811 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3812 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3813 .demuxer = mpctx->demuxer};
3814 mpctx->num_sources = 1;
3817 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3819 #ifdef CONFIG_ASS
3820 if (opts->ass_enabled && ass_library) {
3821 for (int j = 0; j < mpctx->num_sources; j++) {
3822 struct demuxer *d = mpctx->sources[j].demuxer;
3823 for (int i = 0; i < d->num_attachments; i++) {
3824 struct demux_attachment *att = d->attachments + i;
3825 if (use_embedded_fonts && attachment_is_font(att))
3826 ass_add_font(ass_library, att->name, att->data, att->data_size);
3830 #endif
3832 current_module="demux_open2";
3834 //file_format=demuxer->file_format;
3836 mpctx->d_audio=mpctx->demuxer->audio;
3837 mpctx->d_video=mpctx->demuxer->video;
3838 mpctx->d_sub=mpctx->demuxer->sub;
3840 if (ts_prog) {
3841 int tmp = ts_prog;
3842 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3844 // select audio stream
3845 if (mpctx->num_sources)
3846 for (int i = 0; i < mpctx->num_sources; i++)
3847 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3848 opts->audio_lang);
3849 else
3850 select_audio(mpctx->demuxer, opts->audio_id, opts->audio_lang);
3852 // DUMP STREAMS:
3853 if((stream_dump_type)&&(stream_dump_type<4)){
3854 FILE *f;
3855 demux_stream_t *ds=NULL;
3856 current_module="dump";
3857 // select stream to dump
3858 switch(stream_dump_type){
3859 case 1: ds=mpctx->d_audio;break;
3860 case 2: ds=mpctx->d_video;break;
3861 case 3: ds=mpctx->d_sub;break;
3863 if(!ds){
3864 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3865 exit_player(mpctx, EXIT_ERROR);
3867 // disable other streams:
3868 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3869 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3870 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3871 // let's dump it!
3872 f=fopen(stream_dump_name,"wb");
3873 if(!f){
3874 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3875 exit_player(mpctx, EXIT_ERROR);
3877 while(!ds->eof){
3878 unsigned char* start;
3879 int in_size=ds_get_packet(ds,&start);
3880 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3881 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3882 if(in_size>0) fwrite(start,in_size,1,f);
3883 if (opts->chapterrange[1] > 0) {
3884 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3885 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3886 break;
3889 fclose(f);
3890 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3891 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3894 mpctx->sh_audio=mpctx->d_audio->sh;
3895 mpctx->sh_video=mpctx->d_video->sh;
3897 if(mpctx->sh_video){
3899 current_module="video_read_properties";
3900 if(!video_read_properties(mpctx->sh_video)) {
3901 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3902 mpctx->sh_video=mpctx->d_video->sh=NULL;
3903 } else {
3904 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3905 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3906 mpctx->sh_video->fps,mpctx->sh_video->frametime
3909 /* need to set fps here for output encoders to pick it up in their init */
3910 if(force_fps){
3911 mpctx->sh_video->fps=force_fps;
3912 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3914 vo_fps = mpctx->sh_video->fps;
3916 if(!mpctx->sh_video->fps && !force_fps){
3917 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3918 mpctx->opts.correct_pts = 1;
3924 if(!mpctx->sh_video && !mpctx->sh_audio){
3925 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3926 #ifdef CONFIG_DVBIN
3927 if(mpctx->stream->type == STREAMTYPE_DVB)
3929 int dir;
3930 int v = mpctx->last_dvb_step;
3931 if(v > 0)
3932 dir = DVB_CHANNEL_HIGHER;
3933 else
3934 dir = DVB_CHANNEL_LOWER;
3936 if(dvb_step_channel(mpctx->stream, dir)) {
3937 mpctx->stop_play = PT_NEXT_ENTRY;
3938 mpctx->dvbin_reopen = 1;
3941 #endif
3942 goto goto_next_file; // exit_player(_("Fatal error"));
3945 /* display clip info */
3946 demux_info_print(mpctx->demuxer);
3948 //================== Read SUBTITLES (DVD & TEXT) ==========================
3949 if(vo_spudec==NULL &&
3950 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3951 init_vo_spudec(mpctx);
3954 // after reading video params we should load subtitles because
3955 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3956 // check .sub
3957 current_module="read_subtitles_file";
3958 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3959 if(sub_name){
3960 for (i = 0; sub_name[i] != NULL; ++i)
3961 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3963 if(sub_auto) { // auto load sub file ...
3964 char *psub = get_path( "sub/" );
3965 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3966 int i = 0;
3967 free(psub); // release the buffer created by get_path() above
3968 while (tmp[i]) {
3969 add_subtitles(mpctx, tmp[i], sub_fps, 1);
3970 free(tmp[i++]);
3972 free(tmp);
3974 if (mpctx->set_of_sub_size > 0)
3975 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
3977 if (select_subtitle(mpctx)) {
3978 if(subdata)
3979 switch (stream_dump_type) {
3980 case 3: list_sub_file(subdata); break;
3981 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3982 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3983 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3984 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3985 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3989 print_file_properties(mpctx, mpctx->filename);
3991 if(!mpctx->sh_video) goto main; // audio-only
3993 if(!reinit_video_chain(mpctx)) {
3994 if(!mpctx->sh_video){
3995 if(!mpctx->sh_audio) goto goto_next_file;
3996 goto main; // exit_player(_("Fatal error"));
4000 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4001 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4003 #ifdef CONFIG_FREETYPE
4004 force_load_font = 1;
4005 #endif
4007 //================== MAIN: ==========================
4008 main:
4009 current_module="main";
4011 if(playing_msg) {
4012 char* msg = property_expand_string(mpctx, playing_msg);
4013 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4014 free(msg);
4018 // Disable the term OSD in verbose mode
4019 if(verbose) term_osd = 0;
4022 //int frame_corr_num=0; //
4023 //float v_frame=0; // Video
4024 //float num_frames=0; // number of frames played
4026 int frame_time_remaining=0; // flag
4027 int blit_frame=0;
4029 // Make sure old OSD does not stay around,
4030 // e.g. with -fixed-vo and same-resolution files
4031 clear_osd_msgs();
4032 update_osd_msg(mpctx);
4034 //================ SETUP AUDIO ==========================
4036 if(mpctx->sh_audio){
4037 reinit_audio_chain(mpctx);
4038 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4039 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4042 current_module="av_init";
4044 if(mpctx->sh_video){
4045 mpctx->sh_video->timer=0;
4046 if (! ignore_start)
4047 audio_delay += mpctx->sh_video->stream_delay;
4049 if(mpctx->sh_audio){
4050 if (start_volume >= 0)
4051 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4052 if (! ignore_start)
4053 audio_delay -= mpctx->sh_audio->stream_delay;
4054 mpctx->delay=-audio_delay;
4057 if(!mpctx->sh_audio){
4058 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4059 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4060 ds_free_packs(mpctx->d_audio); // free buffered chunks
4061 //mpctx->d_audio->id=-2; // do not read audio chunks
4062 //uninit_player(mpctx, INITIALIZED_AO); // close device
4064 if(!mpctx->sh_video){
4065 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4066 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4067 ds_free_packs(mpctx->d_video);
4068 mpctx->d_video->id=-2;
4069 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4072 if (!mpctx->sh_video && !mpctx->sh_audio)
4073 goto goto_next_file;
4075 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4076 if(force_fps && mpctx->sh_video){
4077 vo_fps = mpctx->sh_video->fps=force_fps;
4078 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4079 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4082 mp_input_set_section(mpctx->input, NULL);
4083 //TODO: add desired (stream-based) sections here
4084 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4085 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4087 //==================== START PLAYING =======================
4089 if(opts->loop_times>1) opts->loop_times--; else
4090 if(opts->loop_times==1) opts->loop_times = -1;
4092 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4094 total_time_usage_start=GetTimer();
4095 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4096 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4097 play_n_frames=play_n_frames_mf;
4099 if(play_n_frames==0){
4100 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4103 // If there's a timeline force an absolute seek to initialize state
4104 if (seek_to_sec || mpctx->timeline) {
4105 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4106 end_at.pos += seek_to_sec;
4108 if (opts->chapterrange[0] > 0) {
4109 double pts;
4110 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4111 && pts > -1.0)
4112 seek(mpctx, pts, SEEK_ABSOLUTE);
4115 if (end_at.type == END_AT_SIZE) {
4116 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4117 end_at.type = END_AT_NONE;
4120 #ifdef CONFIG_DVDNAV
4121 mp_dvdnav_context_free(mpctx);
4122 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4123 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4124 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4126 #endif
4128 get_relative_time(mpctx); // reset current delta
4129 mpctx->time_frame = 0;
4130 mpctx->drop_message_shown = 0;
4131 mpctx->update_video_immediately = true;
4132 mpctx->total_avsync_change = 0;
4133 mpctx->last_chapter_seek = -1;
4134 // Make sure VO knows current pause state
4135 if (mpctx->sh_video)
4136 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4137 NULL);
4139 while(!mpctx->stop_play){
4140 float aq_sleep_time=0;
4142 if (opts->chapterrange[1] > 0) {
4143 int cur_chapter = get_current_chapter(mpctx);
4144 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4145 goto goto_next_file;
4148 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4149 mpctx->sh_audio = mpctx->d_audio->sh;
4150 mpctx->sh_audio->ds = mpctx->d_audio;
4151 reinit_audio_chain(mpctx);
4154 /*========================== PLAY AUDIO ============================*/
4156 if (mpctx->sh_audio && !mpctx->paused)
4157 if (!fill_audio_out_buffers(mpctx))
4158 // at eof, all audio at least written to ao
4159 if (!mpctx->sh_video)
4160 mpctx->stop_play = AT_END_OF_FILE;
4163 if(!mpctx->sh_video) {
4164 // handle audio-only case:
4165 double a_pos=0;
4166 // sh_audio can be NULL due to video stream switching
4167 // TODO: handle this better
4168 if (mpctx->sh_audio)
4169 a_pos = playing_audio_pts(mpctx);
4171 print_status(mpctx, a_pos, false);
4173 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4174 mpctx->stop_play = PT_NEXT_ENTRY;
4175 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4176 mpctx->d_sub, 0);
4177 update_osd_msg(mpctx);
4179 } else {
4181 /*========================== PLAY VIDEO ============================*/
4183 vo_pts=mpctx->sh_video->timer*90000.0;
4184 vo_fps=mpctx->sh_video->fps;
4186 blit_frame = mpctx->video_out->frame_loaded;
4187 if (!blit_frame) {
4188 double frame_time = update_video(mpctx);
4189 blit_frame = mpctx->video_out->frame_loaded;
4190 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4191 if (mpctx->sh_video->vf_initialized < 0) {
4192 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4193 mpctx->stop_play = PT_NEXT_ENTRY;
4194 goto goto_next_file;
4196 if (blit_frame) {
4197 struct sh_video *sh_video = mpctx->sh_video;
4198 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4199 mpctx->video_offset, mpctx->d_sub, 0);
4200 update_teletext(sh_video, mpctx->demuxer, 0);
4201 update_osd_msg(mpctx);
4202 struct vf_instance *vf = mpctx->sh_video->vfilter;
4203 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4204 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4205 vo_osd_changed(0);
4207 if (frame_time < 0)
4208 mpctx->stop_play = AT_END_OF_FILE;
4209 else {
4210 if (mpctx->update_video_immediately) {
4211 // Show this frame immediately, rest normally
4212 mpctx->update_video_immediately = false;
4213 } else {
4214 mpctx->time_frame += frame_time / opts->playback_speed;
4215 adjust_sync(mpctx, frame_time);
4219 if (mpctx->timeline) {
4220 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4221 if (mpctx->sh_video->pts >= next->start
4222 || mpctx->stop_play == AT_END_OF_FILE
4223 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4224 seek(mpctx, next->start, SEEK_ABSOLUTE);
4225 continue;
4229 // ==========================================================================
4231 // current_module="draw_osd";
4232 // if(vo_config_count) mpctx->video_out->draw_osd();
4234 current_module="vo_check_events";
4235 vo_check_events(mpctx->video_out);
4237 #ifdef CONFIG_X11
4238 if (stop_xscreensaver) {
4239 current_module = "stop_xscreensaver";
4240 xscreensaver_heartbeat(mpctx->x11_state);
4242 #endif
4243 if (heartbeat_cmd) {
4244 static unsigned last_heartbeat;
4245 unsigned now = GetTimerMS();
4246 if (now - last_heartbeat > 30000) {
4247 last_heartbeat = now;
4248 system(heartbeat_cmd);
4252 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4254 //====================== FLIP PAGE (VIDEO BLT): =========================
4256 current_module="flip_page";
4257 if (!frame_time_remaining && blit_frame) {
4258 unsigned int t2=GetTimer();
4259 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4260 int duration = -1;
4261 double pts2 = mpctx->video_out->next_pts2;
4262 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4263 // expected A/V sync correction is ignored
4264 double diff = (pts2 - mpctx->sh_video->pts);
4265 diff /= opts->playback_speed;
4266 if (mpctx->time_frame < 0)
4267 diff += mpctx->time_frame;
4268 if (diff < 0)
4269 diff = 0;
4270 if (diff > 10)
4271 diff = 10;
4272 duration = diff * 1e6;
4274 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4276 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4277 vout_time_usage += mpctx->last_vo_flip_duration;
4278 if (mpctx->video_out->driver->flip_page_timed) {
4279 // No need to adjust sync based on flip speed
4280 mpctx->last_vo_flip_duration = 0;
4281 // For print_status - VO call finishing early is OK for sync
4282 mpctx->time_frame -= get_relative_time(mpctx);
4284 print_status(mpctx, MP_NOPTS_VALUE, true);
4286 else
4287 print_status(mpctx, MP_NOPTS_VALUE, false);
4289 //============================ Auto QUALITY ============================
4291 /*Output quality adjustments:*/
4292 if(auto_quality>0){
4293 current_module="autoq";
4294 // float total=0.000001f * (GetTimer()-aq_total_time);
4295 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4296 if(output_quality<auto_quality && aq_sleep_time>0)
4297 ++output_quality;
4298 else
4299 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4300 if(output_quality>1 && aq_sleep_time<0)
4301 --output_quality;
4302 else
4303 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4304 output_quality=0;
4305 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4306 set_video_quality(mpctx->sh_video,output_quality);
4309 if (!frame_time_remaining && blit_frame) {
4310 if (play_n_frames >= 0) {
4311 --play_n_frames;
4312 if (play_n_frames <= 0)
4313 mpctx->stop_play = PT_NEXT_ENTRY;
4315 if (mpctx->step_frames > 0) {
4316 mpctx->step_frames--;
4317 if (mpctx->step_frames == 0)
4318 pause_player(mpctx);
4323 // FIXME: add size based support for -endpos
4324 if (end_at.type == END_AT_TIME &&
4325 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4326 mpctx->stop_play = PT_NEXT_ENTRY;
4328 } // end if(mpctx->sh_video)
4330 #ifdef CONFIG_DVDNAV
4331 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4332 nav_highlight_t hl;
4333 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4334 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4335 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4336 vo_osd_changed (OSDTYPE_DVDNAV);
4337 } else {
4338 osd_set_nav_box(0, 0, 0, 0);
4339 vo_osd_changed(OSDTYPE_DVDNAV);
4340 vo_osd_changed(OSDTYPE_SPU);
4343 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4344 double ar = -1.0;
4345 if (mpctx->sh_video &&
4346 stream_control (mpctx->demuxer->stream,
4347 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4348 != STREAM_UNSUPPORTED)
4349 mpctx->sh_video->stream_aspect = ar;
4352 #endif
4354 //================= Keyboard events, SEEKing ====================
4356 current_module="key_events";
4359 while (1) {
4360 mp_cmd_t* cmd;
4361 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4362 run_command(mpctx, cmd);
4363 mp_cmd_free(cmd);
4364 if (mpctx->stop_play)
4365 break;
4366 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4367 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4368 /* Allow seek commands to be combined, but execute the real seek
4369 * before processing other commands */
4370 if (!cmd || cmd->id != MP_CMD_SEEK)
4371 break;
4374 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4375 || mpctx->abs_seek_pos)
4376 break;
4377 if (mpctx->sh_video) {
4378 update_osd_msg(mpctx);
4379 int hack = vo_osd_changed(0);
4380 vo_osd_changed(hack);
4381 if (hack) {
4382 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4383 add_step_frame(mpctx);
4384 break;
4386 else
4387 vo_osd_changed(0);
4390 pause_loop(mpctx);
4394 // handle -sstep
4395 if (step_sec > 0 && !mpctx->paused) {
4396 mpctx->osd_function=OSD_FFW;
4397 mpctx->rel_seek_secs+=step_sec;
4400 edl_update(mpctx);
4402 /* Looping. */
4403 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4404 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4406 if(opts->loop_times>1) opts->loop_times--; else
4407 if(opts->loop_times==1) opts->loop_times=-1;
4408 play_n_frames=play_n_frames_mf;
4409 mpctx->stop_play=0;
4410 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4413 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4414 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4416 mpctx->rel_seek_secs=0;
4417 mpctx->abs_seek_pos=0;
4420 } // while(!mpctx->stop_play)
4422 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4424 #ifdef CONFIG_DVBIN
4425 if(mpctx->dvbin_reopen)
4427 mpctx->stop_play = 0;
4428 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4429 cache_uninit(mpctx->stream);
4430 mpctx->dvbin_reopen = 0;
4431 goto goto_enable_cache;
4433 #endif
4436 goto_next_file: // don't jump here after ao/vo/getch initialization!
4438 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4440 if(benchmark){
4441 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4442 double total_time_usage;
4443 total_time_usage_start=GetTimer()-total_time_usage_start;
4444 total_time_usage = (float)total_time_usage_start*0.000001;
4445 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4446 video_time_usage,vout_time_usage,audio_time_usage,
4447 total_time_usage-tot,total_time_usage);
4448 if(total_time_usage>0.0)
4449 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4450 100.0*video_time_usage/total_time_usage,
4451 100.0*vout_time_usage/total_time_usage,
4452 100.0*audio_time_usage/total_time_usage,
4453 100.0*(total_time_usage-tot)/total_time_usage,
4454 100.0);
4455 if(total_frame_cnt && frame_dropping)
4456 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4457 total_frame_cnt-drop_frame_cnt,
4458 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4459 drop_frame_cnt,
4460 100*drop_frame_cnt/total_frame_cnt,
4461 total_frame_cnt,
4462 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4465 // time to uninit all, except global stuff:
4466 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4468 if(mpctx->set_of_sub_size > 0) {
4469 current_module="sub_free";
4470 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4471 sub_free(mpctx->set_of_subtitles[i]);
4472 #ifdef CONFIG_ASS
4473 if(mpctx->set_of_ass_tracks[i])
4474 ass_free_track( mpctx->set_of_ass_tracks[i] );
4475 #endif
4477 mpctx->set_of_sub_size = 0;
4479 vo_sub_last = vo_sub=NULL;
4480 subdata=NULL;
4481 #ifdef CONFIG_ASS
4482 ass_track = NULL;
4483 if(ass_library)
4484 ass_clear_fonts(ass_library);
4485 #endif
4487 if (!mpctx->stop_play) // In case some goto jumped here...
4488 mpctx->stop_play = PT_NEXT_ENTRY;
4490 int playtree_direction = 1;
4492 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4493 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4494 play_tree_iter_free(mpctx->playtree_iter);
4495 mpctx->playtree_iter = NULL;
4497 mpctx->play_tree_step = 1;
4498 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4499 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4500 if(mpctx->playtree_iter) {
4501 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4502 play_tree_iter_free(mpctx->playtree_iter);
4503 mpctx->playtree_iter = NULL;
4506 } else if (mpctx->stop_play == PT_STOP) {
4507 play_tree_iter_free(mpctx->playtree_iter);
4508 mpctx->playtree_iter = NULL;
4509 } else { // NEXT PREV SRC
4510 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4513 while(mpctx->playtree_iter != NULL) {
4514 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4515 if(mpctx->filename == NULL) {
4516 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4517 play_tree_iter_free(mpctx->playtree_iter);
4518 mpctx->playtree_iter = NULL;
4520 } else
4521 break;
4524 if(mpctx->playtree_iter != NULL || player_idle_mode){
4525 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4526 mpctx->stop_play = 0;
4527 goto play_next_file;
4531 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4533 return 1;
4535 #endif /* DISABLE_MAIN */