demux_real.c: Remove unused hexdump() forward declaration
[mplayer/glamo.git] / mplayer.c
blob60c42c6539465598357bed9cd4c2fcf36a206a68
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 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
341 static int play_n_frames=-1;
342 static int play_n_frames_mf=-1;
344 // sub:
345 char *font_name=NULL;
346 char *sub_font_name=NULL;
347 extern int font_fontconfig;
348 float font_factor=0.75;
349 char **sub_name=NULL;
350 float sub_delay=0;
351 float sub_fps=0;
352 int sub_auto = 1;
353 char *vobsub_name=NULL;
354 int subcc_enabled=0;
355 int suboverlap_enabled = 1;
357 #include "ass_mp.h"
359 char* current_module=NULL; // for debugging
362 // ---
364 #ifdef CONFIG_MENU
365 #include "m_struct.h"
366 #include "libmenu/menu.h"
367 static const vf_info_t* const libmenu_vfs[] = {
368 &vf_info_menu,
369 NULL
371 static vf_instance_t* vf_menu = NULL;
372 int use_menu = 0;
373 static char* menu_cfg = NULL;
374 static char* menu_root = "main";
375 #endif
378 #ifdef HAVE_RTC
379 static int nortc = 1;
380 static char* rtc_device;
381 #endif
383 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
384 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
385 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
386 int use_filedir_conf;
387 int use_filename_title;
389 #include "mpcommon.h"
390 #include "command.h"
392 #include "metadata.h"
394 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
396 const void *mpctx_get_video_out(MPContext *mpctx)
398 return mpctx->video_out;
401 const void *mpctx_get_audio_out(MPContext *mpctx)
403 return mpctx->audio_out;
406 void *mpctx_get_demuxer(MPContext *mpctx)
408 return mpctx->demuxer;
411 void *mpctx_get_playtree_iter(MPContext *mpctx)
413 return mpctx->playtree_iter;
416 void *mpctx_get_mixer(MPContext *mpctx)
418 return &mpctx->mixer;
421 int mpctx_get_global_sub_size(MPContext *mpctx)
423 return mpctx->global_sub_size;
426 int mpctx_get_osd_function(MPContext *mpctx)
428 return mpctx->osd_function;
431 static float get_relative_time(struct MPContext *mpctx)
433 unsigned int new_time = GetTimer();
434 unsigned int delta = new_time - mpctx->last_time;
435 mpctx->last_time = new_time;
436 return delta * 0.000001;
439 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
440 switch (type)
442 /* check for valid video stream */
443 case META_VIDEO_CODEC:
444 case META_VIDEO_BITRATE:
445 case META_VIDEO_RESOLUTION:
447 if (!mpctx->sh_video)
448 return 0;
449 break;
452 /* check for valid audio stream */
453 case META_AUDIO_CODEC:
454 case META_AUDIO_BITRATE:
455 case META_AUDIO_SAMPLES:
457 if (!mpctx->sh_audio)
458 return 0;
459 break;
462 /* check for valid demuxer */
463 case META_INFO_TITLE:
464 case META_INFO_ARTIST:
465 case META_INFO_ALBUM:
466 case META_INFO_YEAR:
467 case META_INFO_COMMENT:
468 case META_INFO_TRACK:
469 case META_INFO_GENRE:
471 if (!mpctx->demuxer)
472 return 0;
473 break;
476 default:
477 break;
480 return 1;
483 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
484 char **info = mpctx->demuxer->info;
485 int n;
487 if (!info || !tag)
488 return NULL;
490 for (n = 0; info[2*n] != NULL ; n++)
491 if (!strcasecmp (info[2*n], tag))
492 break;
494 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
497 char *get_metadata(struct MPContext *mpctx, metadata_t type)
499 char *meta = NULL;
500 sh_audio_t * const sh_audio = mpctx->sh_audio;
501 sh_video_t * const sh_video = mpctx->sh_video;
503 if (!is_valid_metadata_type(mpctx, type))
504 return NULL;
506 switch (type)
508 case META_NAME:
510 return strdup (mp_basename2 (mpctx->filename));
513 case META_VIDEO_CODEC:
515 if (sh_video->format == 0x10000001)
516 meta = strdup ("mpeg1");
517 else if (sh_video->format == 0x10000002)
518 meta = strdup ("mpeg2");
519 else if (sh_video->format == 0x10000004)
520 meta = strdup ("mpeg4");
521 else if (sh_video->format == 0x10000005)
522 meta = strdup ("h264");
523 else if (sh_video->format >= 0x20202020)
525 meta = malloc (8);
526 sprintf (meta, "%.4s", (char *) &sh_video->format);
528 else
530 meta = malloc (8);
531 sprintf (meta, "0x%08X", sh_video->format);
533 return meta;
536 case META_VIDEO_BITRATE:
538 meta = malloc (16);
539 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
540 return meta;
543 case META_VIDEO_RESOLUTION:
545 meta = malloc (16);
546 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
547 return meta;
550 case META_AUDIO_CODEC:
552 if (sh_audio->codec && sh_audio->codec->name)
553 meta = strdup (sh_audio->codec->name);
554 return meta;
557 case META_AUDIO_BITRATE:
559 meta = malloc (16);
560 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
561 return meta;
564 case META_AUDIO_SAMPLES:
566 meta = malloc (16);
567 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
568 return meta;
571 /* check for valid demuxer */
572 case META_INFO_TITLE:
573 return get_demuxer_info(mpctx, "Title");
575 case META_INFO_ARTIST:
576 return get_demuxer_info(mpctx, "Artist");
578 case META_INFO_ALBUM:
579 return get_demuxer_info(mpctx, "Album");
581 case META_INFO_YEAR:
582 return get_demuxer_info(mpctx, "Year");
584 case META_INFO_COMMENT:
585 return get_demuxer_info(mpctx, "Comment");
587 case META_INFO_TRACK:
588 return get_demuxer_info(mpctx, "Track");
590 case META_INFO_GENRE:
591 return get_demuxer_info(mpctx, "Genre");
593 default:
594 break;
597 return meta;
600 static void print_file_properties(const MPContext *mpctx, const char *filename)
602 double start_pts = MP_NOPTS_VALUE;
603 double video_start_pts = MP_NOPTS_VALUE;
604 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
605 filename_recode(filename));
606 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
607 if (mpctx->sh_video) {
608 /* Assume FOURCC if all bytes >= 0x20 (' ') */
609 if (mpctx->sh_video->format >= 0x20202020)
610 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
611 else
612 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
613 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
614 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
615 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
616 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
617 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
618 video_start_pts = ds_get_next_pts(mpctx->d_video);
620 if (mpctx->sh_audio) {
621 /* Assume FOURCC if all bytes >= 0x20 (' ') */
622 if (mpctx->sh_audio->format >= 0x20202020)
623 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
624 else
625 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
626 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
627 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
628 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
629 start_pts = ds_get_next_pts(mpctx->d_audio);
631 if (video_start_pts != MP_NOPTS_VALUE) {
632 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
633 (mpctx->sh_video && video_start_pts < start_pts))
634 start_pts = video_start_pts;
636 if (start_pts != MP_NOPTS_VALUE)
637 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
638 else
639 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
640 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", mpctx->timeline ?
641 mpctx->timeline[mpctx->num_timeline_parts].start :
642 demuxer_get_time_length(mpctx->demuxer));
643 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
644 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
645 if (mpctx->demuxer) {
646 if (mpctx->demuxer->num_chapters == 0)
647 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
648 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
652 /// step size of mixer changes
653 int volstep = 3;
655 #ifdef CONFIG_DVDNAV
656 static void mp_dvdnav_context_free(MPContext *ctx){
657 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
658 ctx->nav_smpi = NULL;
659 if (ctx->nav_buffer) free(ctx->nav_buffer);
660 ctx->nav_buffer = NULL;
661 ctx->nav_start = NULL;
662 ctx->nav_in_size = 0;
664 #endif
666 void uninit_player(struct MPContext *mpctx, unsigned int mask){
667 mask &= mpctx->initialized_flags;
669 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
671 if(mask&INITIALIZED_ACODEC){
672 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
673 current_module="uninit_acodec";
674 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
675 mpctx->sh_audio=NULL;
676 mpctx->mixer.afilter = NULL;
679 if(mask&INITIALIZED_VCODEC){
680 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
681 current_module="uninit_vcodec";
682 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
683 mpctx->sh_video=NULL;
684 #ifdef CONFIG_MENU
685 vf_menu=NULL;
686 #endif
689 if(mask&INITIALIZED_DEMUXER){
690 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
691 current_module="free_demuxer";
692 if (mpctx->num_sources) {
693 mpctx->demuxer = mpctx->sources[0].demuxer;
694 for (int i = 1; i < mpctx->num_sources; i++) {
695 free_stream(mpctx->sources[i].stream);
696 free_demuxer(mpctx->sources[i].demuxer);
699 talloc_free(mpctx->sources);
700 mpctx->sources = NULL;
701 mpctx->num_sources = 0;
702 talloc_free(mpctx->timeline);
703 mpctx->timeline = NULL;
704 mpctx->num_timeline_parts = 0;
705 talloc_free(mpctx->chapters);
706 mpctx->chapters = NULL;
707 mpctx->num_chapters = 0;
708 mpctx->video_offset = 0;
709 if(mpctx->demuxer){
710 mpctx->stream=mpctx->demuxer->stream;
711 free_demuxer(mpctx->demuxer);
713 mpctx->demuxer=NULL;
716 // kill the cache process:
717 if(mask&INITIALIZED_STREAM){
718 mpctx->initialized_flags&=~INITIALIZED_STREAM;
719 current_module="uninit_stream";
720 if(mpctx->stream) free_stream(mpctx->stream);
721 mpctx->stream=NULL;
724 if(mask&INITIALIZED_VO){
725 mpctx->initialized_flags&=~INITIALIZED_VO;
726 current_module="uninit_vo";
727 vo_destroy(mpctx->video_out);
728 mpctx->video_out=NULL;
729 #ifdef CONFIG_DVDNAV
730 mp_dvdnav_context_free(mpctx);
731 #endif
734 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
735 if(mask&INITIALIZED_GETCH2){
736 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
737 current_module="uninit_getch2";
738 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
739 // restore terminal:
740 getch2_disable();
743 if(mask&INITIALIZED_VOBSUB){
744 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
745 current_module="uninit_vobsub";
746 if(vo_vobsub) vobsub_close(vo_vobsub);
747 vo_vobsub=NULL;
750 if (mask&INITIALIZED_SPUDEC){
751 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
752 current_module="uninit_spudec";
753 spudec_free(vo_spudec);
754 vo_spudec=NULL;
757 if(mask&INITIALIZED_AO){
758 mpctx->initialized_flags&=~INITIALIZED_AO;
759 current_module="uninit_ao";
760 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
761 if (mpctx->audio_out)
762 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
763 mpctx->audio_out=NULL;
766 current_module=NULL;
769 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
771 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
772 uninit_player(mpctx, INITIALIZED_ALL);
773 #if defined(__MINGW32__) || defined(__CYGWIN__)
774 timeEndPeriod(1);
775 #endif
776 #ifdef CONFIG_X11
777 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
778 #endif
780 current_module="uninit_input";
781 mp_input_uninit(mpctx->input);
782 #ifdef CONFIG_MENU
783 if (use_menu)
784 menu_uninit();
785 #endif
787 #ifdef CONFIG_FREETYPE
788 current_module="uninit_font";
789 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
790 free_font_desc(mpctx->osd->sub_font);
791 free_font_desc(vo_font);
792 vo_font = NULL;
793 done_freetype();
794 #endif
795 osd_free(mpctx->osd);
797 #ifdef CONFIG_ASS
798 ass_library_done(ass_library);
799 ass_library = NULL;
800 #endif
802 current_module="exit_player";
804 // free mplayer config
805 if(mpctx->mconfig)
806 m_config_free(mpctx->mconfig);
807 mpctx->mconfig = NULL;
809 if(mpctx->playtree_iter)
810 play_tree_iter_free(mpctx->playtree_iter);
811 mpctx->playtree_iter = NULL;
812 if(mpctx->playtree)
813 play_tree_free(mpctx->playtree, 1);
814 mpctx->playtree = NULL;
816 talloc_free(mpctx->key_fifo);
818 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
819 edl_records = NULL;
820 switch(how) {
821 case EXIT_QUIT:
822 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
823 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
824 break;
825 case EXIT_EOF:
826 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
827 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
828 break;
829 case EXIT_ERROR:
830 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
831 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
832 break;
833 default:
834 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
836 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
838 exit(rc);
841 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
843 exit_player_with_rc(mpctx, how, 1);
846 #ifndef __MINGW32__
847 static void child_sighandler(int x){
848 pid_t pid;
849 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
851 #endif
853 #ifdef CONFIG_CRASH_DEBUG
854 static char *prog_path;
855 static int crash_debug = 0;
856 #endif
858 static void exit_sighandler(int x){
859 static int sig_count=0;
860 #ifdef CONFIG_CRASH_DEBUG
861 if (!crash_debug || x != SIGTRAP)
862 #endif
863 ++sig_count;
864 if(sig_count==5)
866 /* We're crashing bad and can't uninit cleanly :(
867 * by popular request, we make one last (dirty)
868 * effort to restore the user's
869 * terminal. */
870 getch2_disable();
871 exit(1);
873 if(sig_count==6) exit(1);
874 if(sig_count>6){
875 // can't stop :(
876 #ifndef __MINGW32__
877 kill(getpid(),SIGKILL);
878 #endif
880 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
881 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
882 "\nMPlayer interrupted by signal %d in module: %s\n", x,
883 current_module ? current_module : "unknown");
884 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
885 if(sig_count<=1)
886 switch(x){
887 case SIGINT:
888 case SIGPIPE:
889 case SIGQUIT:
890 case SIGTERM:
891 case SIGKILL:
892 async_quit_request = 1;
893 return; // killed from keyboard (^C) or killed [-9]
894 case SIGILL:
895 #if CONFIG_RUNTIME_CPUDETECT
896 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
897 #else
898 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
899 #endif
900 case SIGFPE:
901 case SIGSEGV:
902 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
903 default:
904 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
905 #ifdef CONFIG_CRASH_DEBUG
906 if (crash_debug) {
907 int gdb_pid;
908 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
909 gdb_pid = fork();
910 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
911 if (gdb_pid == 0) { // We are the child
912 char spid[20];
913 snprintf(spid, sizeof(spid), "%i", getppid());
914 getch2_disable(); // allow terminal to work properly with gdb
915 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
916 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
917 } else if (gdb_pid < 0)
918 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
919 else {
920 waitpid(gdb_pid, NULL, 0);
922 if (x == SIGTRAP) return;
924 #endif
926 getch2_disable();
927 exit(1);
930 #include "cfg-mplayer.h"
932 static int cfg_include(m_option_t *conf, char *filename)
934 return m_config_parse_config_file(conf->priv, filename);
937 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
939 char *conffile;
940 int conffile_fd;
941 if (!disable_system_conf &&
942 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
943 exit_player(mpctx, EXIT_NONE);
944 if ((conffile = get_path("")) == NULL) {
945 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
946 } else {
947 #ifdef __MINGW32__
948 mkdir(conffile);
949 #else
950 mkdir(conffile, 0777);
951 #endif
952 free(conffile);
953 if ((conffile = get_path("config")) == NULL) {
954 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
955 } else {
956 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
957 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
958 write(conffile_fd, default_config, strlen(default_config));
959 close(conffile_fd);
961 if (!disable_user_conf &&
962 m_config_parse_config_file(conf, conffile) < 0)
963 exit_player(mpctx, EXIT_NONE);
964 free(conffile);
969 #define PROFILE_CFG_PROTOCOL "protocol."
971 static void load_per_protocol_config (m_config_t* conf, const char *const file)
973 char *str;
974 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
975 m_profile_t *p;
977 /* does filename actually uses a protocol ? */
978 str = strstr (file, "://");
979 if (!str)
980 return;
982 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
983 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
984 p = m_config_get_profile (conf, protocol);
985 if (p)
987 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
988 m_config_set_profile(conf,p);
992 #define PROFILE_CFG_EXTENSION "extension."
994 static void load_per_extension_config (m_config_t* conf, const char *const file)
996 char *str;
997 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
998 m_profile_t *p;
1000 /* does filename actually have an extension ? */
1001 str = strrchr (file, '.');
1002 if (!str)
1003 return;
1005 sprintf (extension, PROFILE_CFG_EXTENSION);
1006 strncat (extension, ++str, 7);
1007 p = m_config_get_profile (conf, extension);
1008 if (p)
1010 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
1011 m_config_set_profile(conf,p);
1015 #define PROFILE_CFG_VO "vo."
1016 #define PROFILE_CFG_AO "ao."
1018 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
1020 char profile[strlen (cfg) + strlen (out) + 1];
1021 m_profile_t *p;
1023 sprintf (profile, "%s%s", cfg, out);
1024 p = m_config_get_profile (conf, profile);
1025 if (p)
1027 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
1028 m_config_set_profile(conf,p);
1033 * Tries to load a config file
1034 * @return 0 if file was not found, 1 otherwise
1036 static int try_load_config(m_config_t *conf, const char *file)
1038 struct stat st;
1039 if (stat(file, &st))
1040 return 0;
1041 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1042 m_config_parse_config_file (conf, file);
1043 return 1;
1046 static void load_per_file_config (m_config_t* conf, const char *const file)
1048 char *confpath;
1049 char cfg[PATH_MAX];
1050 char *name;
1052 if (strlen(file) > PATH_MAX - 14) {
1053 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1054 return;
1056 sprintf (cfg, "%s.conf", file);
1058 name = strrchr(cfg, '/');
1059 if (HAVE_DOS_PATHS) {
1060 char *tmp = strrchr(cfg, '\\');
1061 if (!name || tmp > name)
1062 name = tmp;
1063 tmp = strrchr(cfg, ':');
1064 if (!name || tmp > name)
1065 name = tmp;
1067 if (!name)
1068 name = cfg;
1069 else
1070 name++;
1072 if (use_filedir_conf) {
1073 char dircfg[PATH_MAX];
1074 strcpy(dircfg, cfg);
1075 strcpy(dircfg + (name - cfg), "mplayer.conf");
1076 try_load_config(conf, dircfg);
1078 if (try_load_config(conf, cfg))
1079 return;
1082 if ((confpath = get_path (name)) != NULL)
1084 try_load_config(conf, confpath);
1086 free (confpath);
1090 /* When libmpdemux performs a blocking operation (network connection or
1091 * cache filling) if the operation fails we use this function to check
1092 * if it was interrupted by the user.
1093 * The function returns a new value for eof. */
1094 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1096 mp_cmd_t* cmd;
1097 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1098 switch(cmd->id) {
1099 case MP_CMD_QUIT:
1100 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1101 case MP_CMD_PLAY_TREE_STEP: {
1102 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1103 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1104 } break;
1105 case MP_CMD_PLAY_TREE_UP_STEP: {
1106 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1107 } break;
1108 case MP_CMD_PLAY_ALT_SRC_STEP: {
1109 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1110 } break;
1112 mp_cmd_free(cmd);
1114 return stop_play;
1117 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1119 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1121 play_tree_add_bpf(entry,mpctx->filename);
1124 if(!entry) {
1125 entry = mpctx->playtree_iter->tree;
1126 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1127 return PT_NEXT_ENTRY;
1129 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1130 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1131 return PT_NEXT_ENTRY;
1134 play_tree_remove(entry,1,1);
1135 return PT_NEXT_SRC;
1137 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1138 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1139 entry = mpctx->playtree_iter->tree;
1140 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1141 return PT_NEXT_ENTRY;
1143 play_tree_remove(entry,1,1);
1145 return PT_NEXT_SRC;
1148 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1150 struct MPOpts *opts = &mpctx->opts;
1151 sub_data *subd = NULL;
1152 struct ass_track *asst = NULL;
1154 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1155 return;
1158 #ifdef CONFIG_ASS
1159 if (opts->ass_enabled) {
1160 #ifdef CONFIG_ICONV
1161 asst = ass_read_stream(ass_library, filename, sub_cp);
1162 #else
1163 asst = ass_read_stream(ass_library, filename, 0);
1164 #endif
1165 if (!asst) {
1166 subd = sub_read_file(filename, fps);
1167 if (subd) {
1168 asst = ass_read_subdata(ass_library, subd, fps);
1169 if (asst) {
1170 sub_free(subd);
1171 subd = NULL;
1175 } else
1176 #endif
1177 subd = sub_read_file(filename, fps);
1180 if (!asst && !subd) {
1181 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1182 "Cannot load subtitles: %s\n", filename_recode(filename));
1183 return;
1186 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1187 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1188 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1189 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1190 filename_recode(filename));
1191 ++mpctx->set_of_sub_size;
1192 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1193 filename_recode(filename));
1196 void init_vo_spudec(struct MPContext *mpctx)
1198 if (vo_spudec)
1199 spudec_free(vo_spudec);
1200 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1201 vo_spudec = NULL;
1203 // we currently can't work without video stream
1204 if (!mpctx->sh_video)
1205 return;
1207 if (spudec_ifo) {
1208 unsigned int palette[16], width, height;
1209 current_module="spudec_init_vobsub";
1210 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1211 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1214 #ifdef CONFIG_DVDREAD
1215 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1216 current_module="spudec_init_dvdread";
1217 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1218 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1219 NULL, 0);
1221 #endif
1223 #ifdef CONFIG_DVDNAV
1224 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1225 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1226 current_module="spudec_init_dvdnav";
1227 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1229 #endif
1231 if (vo_spudec==NULL) {
1232 sh_sub_t *sh = mpctx->d_sub->sh;
1233 current_module="spudec_init_normal";
1234 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1235 spudec_set_font_factor(vo_spudec,font_factor);
1238 if (vo_spudec!=NULL) {
1239 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1240 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1245 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1246 * make it all work is to use the builtin SDL-bootstrap code, which
1247 * will be done automatically by replacing our main() if we include SDL.h.
1249 #if defined(__APPLE__) && defined(CONFIG_SDL)
1250 #ifdef CONFIG_SDL_SDL_H
1251 #include <SDL/SDL.h>
1252 #else
1253 #include <SDL.h>
1254 #endif
1255 #endif
1258 * \brief append a formatted string
1259 * \param buf buffer to print into
1260 * \param pos position of terminating 0 in buf
1261 * \param len maximum number of characters in buf, not including terminating 0
1262 * \param format printf format string
1264 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1266 va_list va;
1267 va_start(va, format);
1268 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1269 va_end(va);
1270 if (*pos >= len ) {
1271 buf[len] = 0;
1272 *pos = len;
1277 * \brief append time in the hh:mm:ss.f format
1278 * \param buf buffer to print into
1279 * \param pos position of terminating 0 in buf
1280 * \param len maximum number of characters in buf, not including terminating 0
1281 * \param time time value to convert/append
1283 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1284 int64_t tenths = 10 * time;
1285 int f1 = tenths % 10;
1286 int ss = (tenths / 10) % 60;
1287 int mm = (tenths / 600) % 60;
1288 int hh = tenths / 36000;
1289 if (time <= 0) {
1290 saddf(buf, pos, len, "unknown");
1291 return;
1293 if (hh > 0)
1294 saddf(buf, pos, len, "%2d:", hh);
1295 if (hh > 0 || mm > 0)
1296 saddf(buf, pos, len, "%02d:", mm);
1297 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1300 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1302 struct MPOpts *opts = &mpctx->opts;
1303 sh_video_t * const sh_video = mpctx->sh_video;
1305 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1306 a_pos = playing_audio_pts(mpctx);
1307 if (mpctx->sh_audio && sh_video && at_frame) {
1308 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1309 if (mpctx->time_frame > 0)
1310 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1311 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1312 && !mpctx->drop_message_shown) {
1313 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1314 mpctx->drop_message_shown = true;
1317 if (quiet)
1318 return;
1321 int width;
1322 char *line;
1323 unsigned pos = 0;
1324 get_screen_size();
1325 if (screen_width > 0)
1326 width = screen_width;
1327 else
1328 width = 80;
1329 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1330 /* Windows command line is broken (MinGW's rxvt works, but we
1331 * should not depend on that). */
1332 width--;
1333 #endif
1334 line = malloc(width + 1); // one additional char for the terminating null
1336 // Audio time
1337 if (mpctx->sh_audio) {
1338 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1339 if (!sh_video) {
1340 float len = demuxer_get_time_length(mpctx->demuxer);
1341 saddf(line, &pos, width, "(");
1342 sadd_hhmmssf(line, &pos, width, a_pos);
1343 saddf(line, &pos, width, ") of %.1f (", len);
1344 sadd_hhmmssf(line, &pos, width, len);
1345 saddf(line, &pos, width, ") ");
1349 // Video time
1350 if (sh_video)
1351 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1353 // A-V sync
1354 if (mpctx->sh_audio && sh_video)
1355 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1356 mpctx->last_av_difference, mpctx->total_avsync_change);
1358 // Video stats
1359 if (sh_video)
1360 saddf(line, &pos, width, "%3d/%3d ",
1361 (int)sh_video->num_frames,
1362 (int)sh_video->num_frames_decoded);
1364 // CPU usage
1365 if (sh_video) {
1366 if (sh_video->timer > 0.5)
1367 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1368 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1369 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1370 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1371 else
1372 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1373 } else if (mpctx->sh_audio) {
1374 if (mpctx->delay > 0.5)
1375 saddf(line, &pos, width, "%4.1f%% ",
1376 100.0*audio_time_usage/(double)mpctx->delay);
1377 else
1378 saddf(line, &pos, width, "??,?%% ");
1381 // VO stats
1382 if (sh_video)
1383 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1385 #ifdef CONFIG_STREAM_CACHE
1386 // cache stats
1387 if (stream_cache_size > 0)
1388 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1389 #endif
1391 // other
1392 if (opts->playback_speed != 1)
1393 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1395 // end
1396 if (erase_to_end_of_line) {
1397 line[pos] = 0;
1398 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1399 } else {
1400 memset(&line[pos], ' ', width - pos);
1401 line[width] = 0;
1402 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1404 free(line);
1408 * \brief build a chain of audio filters that converts the input format
1409 * to the ao's format, taking into account the current playback_speed.
1410 * \param sh_audio describes the requested input format of the chain.
1411 * \param ao_data describes the requested output format of the chain.
1413 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1415 struct MPOpts *opts = &mpctx->opts;
1416 int new_srate;
1417 int result;
1418 if (!sh_audio)
1420 mpctx->mixer.afilter = NULL;
1421 return 0;
1423 if(af_control_any_rev(sh_audio->afilter,
1424 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1425 &opts->playback_speed)) {
1426 new_srate = sh_audio->samplerate;
1427 } else {
1428 new_srate = sh_audio->samplerate * opts->playback_speed;
1429 if (new_srate != ao_data->samplerate) {
1430 // limits are taken from libaf/af_resample.c
1431 if (new_srate < 8000)
1432 new_srate = 8000;
1433 if (new_srate > 192000)
1434 new_srate = 192000;
1435 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1438 result = init_audio_filters(sh_audio, new_srate,
1439 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1440 mpctx->mixer.afilter = sh_audio->afilter;
1441 return result;
1445 typedef struct mp_osd_msg mp_osd_msg_t;
1446 struct mp_osd_msg {
1447 /// Previous message on the stack.
1448 mp_osd_msg_t* prev;
1449 /// Message text.
1450 char msg[128];
1451 int id,level,started;
1452 /// Display duration in ms.
1453 unsigned time;
1456 /// OSD message stack.
1457 static mp_osd_msg_t* osd_msg_stack = NULL;
1460 * \brief Add a message on the OSD message stack
1462 * If a message with the same id is already present in the stack
1463 * it is pulled on top of the stack, otherwise a new message is created.
1466 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1467 va_list ap)
1469 mp_osd_msg_t *msg,*last=NULL;
1470 int r;
1472 // look if the id is already in the stack
1473 for(msg = osd_msg_stack ; msg && msg->id != id ;
1474 last = msg, msg = msg->prev);
1475 // not found: alloc it
1476 if(!msg) {
1477 msg = calloc(1,sizeof(mp_osd_msg_t));
1478 msg->prev = osd_msg_stack;
1479 osd_msg_stack = msg;
1480 } else if(last) { // found, but it's not on top of the stack
1481 last->prev = msg->prev;
1482 msg->prev = osd_msg_stack;
1483 osd_msg_stack = msg;
1485 // write the msg
1486 r = vsnprintf(msg->msg, 128, fmt, ap);
1487 if(r >= 128) msg->msg[127] = 0;
1488 // set id and time
1489 msg->id = id;
1490 msg->level = level;
1491 msg->time = time;
1495 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1497 va_list ap;
1498 va_start(ap, fmt);
1499 set_osd_msg_va(id, level, time, fmt, ap);
1500 va_end(ap);
1503 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1505 va_list ap;
1506 va_start(ap, fmt);
1507 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1508 va_end(ap);
1513 * \brief Remove a message from the OSD stack
1515 * This function can be used to get rid of a message right away.
1519 void rm_osd_msg(int id) {
1520 mp_osd_msg_t *msg,*last=NULL;
1522 // Search for the msg
1523 for(msg = osd_msg_stack ; msg && msg->id != id ;
1524 last = msg, msg = msg->prev);
1525 if(!msg) return;
1527 // Detach it from the stack and free it
1528 if(last)
1529 last->prev = msg->prev;
1530 else
1531 osd_msg_stack = msg->prev;
1532 free(msg);
1536 * \brief Remove all messages from the OSD stack
1540 static void clear_osd_msgs(void) {
1541 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1542 while(msg) {
1543 prev = msg->prev;
1544 free(msg);
1545 msg = prev;
1547 osd_msg_stack = NULL;
1551 * \brief Get the current message from the OSD stack.
1553 * This function decrements the message timer and destroys the old ones.
1554 * The message that should be displayed is returned (if any).
1558 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1560 struct MPOpts *opts = &mpctx->opts;
1561 mp_osd_msg_t *msg,*prev,*last = NULL;
1562 static unsigned last_update = 0;
1563 unsigned now = GetTimerMS();
1564 unsigned diff;
1565 char hidden_dec_done = 0;
1567 if (mpctx->osd_visible) {
1568 // 36000000 means max timed visibility is 1 hour into the future, if
1569 // the difference is greater assume it's wrapped around from below 0
1570 if (mpctx->osd_visible - now > 36000000) {
1571 mpctx->osd_visible = 0;
1572 vo_osd_progbar_type = -1; // disable
1573 vo_osd_changed(OSDTYPE_PROGBAR);
1574 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1577 if (mpctx->osd_show_percentage_until - now > 36000000)
1578 mpctx->osd_show_percentage_until = 0;
1580 if(!last_update) last_update = now;
1581 diff = now >= last_update ? now - last_update : 0;
1583 last_update = now;
1585 // Look for the first message in the stack with high enough level.
1586 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1587 prev = msg->prev;
1588 if (msg->level > opts->osd_level && hidden_dec_done)
1589 continue;
1590 // The message has a high enough level or it is the first hidden one
1591 // in both cases we decrement the timer or kill it.
1592 if(!msg->started || msg->time > diff) {
1593 if(msg->started) msg->time -= diff;
1594 else msg->started = 1;
1595 // display it
1596 if (msg->level <= opts->osd_level)
1597 return msg;
1598 hidden_dec_done = 1;
1599 continue;
1601 // kill the message
1602 free(msg);
1603 if(last) {
1604 last->prev = prev;
1605 msg = last;
1606 } else {
1607 osd_msg_stack = prev;
1608 msg = NULL;
1611 // Nothing found
1612 return NULL;
1616 * \brief Display the OSD bar.
1618 * Display the OSD bar or fall back on a simple message.
1622 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1623 struct MPOpts *opts = &mpctx->opts;
1624 if (opts->osd_level < 1)
1625 return;
1627 if(mpctx->sh_video) {
1628 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1629 vo_osd_progbar_type = type;
1630 vo_osd_progbar_value = 256*(val-min)/(max-min);
1631 vo_osd_changed(OSDTYPE_PROGBAR);
1632 return;
1635 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1636 name, ROUND(100*(val-min)/(max-min)));
1640 * \brief Display text subtitles on the OSD
1642 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1644 int i;
1645 vo_sub = subs;
1646 vo_osd_changed(OSDTYPE_SUBTITLE);
1647 if (!mpctx->sh_video) {
1648 // reverse order, since newest set_osd_msg is displayed first
1649 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1650 if (!subs || i >= subs->lines || !subs->text[i])
1651 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1652 else {
1653 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1654 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1655 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1662 * \brief Update the OSD message line.
1664 * This function displays the current message on the vo OSD or on the term.
1665 * If the stack is empty and the OSD level is high enough the timer
1666 * is displayed (only on the vo OSD).
1670 static void update_osd_msg(struct MPContext *mpctx)
1672 struct MPOpts *opts = &mpctx->opts;
1673 mp_osd_msg_t *msg;
1674 struct osd_state *osd = mpctx->osd;
1675 char osd_text_timer[128];
1677 if (mpctx->add_osd_seek_info) {
1678 double percentage;
1679 if (mpctx->timeline && mpctx->sh_video)
1680 percentage = mpctx->sh_video->pts * 100 /
1681 mpctx->timeline[mpctx->num_timeline_parts].start;
1682 else
1683 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1684 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1685 if (mpctx->sh_video)
1686 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1687 mpctx->add_osd_seek_info = false;
1690 // Look if we have a msg
1691 if((msg = get_osd_msg(mpctx))) {
1692 if (strcmp(osd->osd_text, msg->msg)) {
1693 strncpy(osd->osd_text, msg->msg, 127);
1694 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1695 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1697 return;
1700 if(mpctx->sh_video) {
1701 // fallback on the timer
1702 if (opts->osd_level >= 2) {
1703 int len;
1704 if (mpctx->timeline)
1705 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1706 else
1707 len = demuxer_get_time_length(mpctx->demuxer);
1708 int percentage = -1;
1709 char percentage_text[10];
1710 int pts = demuxer_get_current_time(mpctx->demuxer);
1712 if (mpctx->osd_show_percentage_until) {
1713 if (mpctx->timeline)
1714 percentage = mpctx->sh_video->pts * 100 /
1715 mpctx->timeline[mpctx->num_timeline_parts].start;
1716 else
1717 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1720 if (percentage >= 0)
1721 snprintf(percentage_text, 9, " (%d%%)", percentage);
1722 else
1723 percentage_text[0] = 0;
1725 if (opts->osd_level == 3)
1726 snprintf(osd_text_timer, 63,
1727 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1728 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1729 len/3600,(len/60)%60,len%60,percentage_text);
1730 else
1731 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1732 mpctx->osd_function,pts/3600,(pts/60)%60,
1733 pts%60,percentage_text);
1734 } else
1735 osd_text_timer[0]=0;
1737 if (strcmp(osd->osd_text, osd_text_timer)) {
1738 strncpy(osd->osd_text, osd_text_timer, 63);
1739 vo_osd_changed(OSDTYPE_OSD);
1741 return;
1744 // Clear the term osd line
1745 if (term_osd && osd->osd_text[0]) {
1746 osd->osd_text[0] = 0;
1747 printf("%s\n",term_osd_esc);
1751 ///@}
1752 // OSDMsgStack
1755 void reinit_audio_chain(struct MPContext *mpctx)
1757 struct MPOpts *opts = &mpctx->opts;
1758 if (!mpctx->sh_audio)
1759 return;
1760 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1761 current_module="init_audio_codec";
1762 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1763 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1764 goto init_error;
1766 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1767 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1771 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1772 current_module="af_preinit";
1773 ao_data.samplerate=force_srate;
1774 ao_data.channels=0;
1775 ao_data.format = opts->audio_output_format;
1776 // first init to detect best values
1777 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1778 // input:
1779 mpctx->sh_audio->samplerate,
1780 // output:
1781 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1782 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1783 "pre-init!\n");
1784 exit_player(mpctx, EXIT_ERROR);
1786 current_module="ao2_init";
1787 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1788 0, // plugin flag
1789 ao_data.samplerate,
1790 ao_data.channels,
1791 ao_data.format, 0);
1792 if(!mpctx->audio_out){
1793 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1794 goto init_error;
1796 mpctx->initialized_flags|=INITIALIZED_AO;
1797 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1798 mpctx->audio_out->info->short_name,
1799 ao_data.samplerate, ao_data.channels,
1800 af_fmt2str_short(ao_data.format),
1801 af_fmt2bits(ao_data.format)/8 );
1802 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1803 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1804 if(strlen(mpctx->audio_out->info->comment) > 0)
1805 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1808 // init audio filters:
1809 current_module="af_init";
1810 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1811 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1812 goto init_error;
1814 mpctx->mixer.audio_out = mpctx->audio_out;
1815 mpctx->mixer.volstep = volstep;
1816 return;
1818 init_error:
1819 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1820 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1821 mpctx->d_audio->id = -2;
1825 ///@}
1826 // Command2Property
1829 // Return pts value corresponding to the end point of audio written to the
1830 // ao so far.
1831 static double written_audio_pts(struct MPContext *mpctx)
1833 sh_audio_t *sh_audio = mpctx->sh_audio;
1834 demux_stream_t *d_audio = mpctx->d_audio;
1835 double buffered_output;
1836 // first calculate the end pts of audio that has been output by decoder
1837 double a_pts = sh_audio->pts;
1838 if (a_pts != MP_NOPTS_VALUE)
1839 // Good, decoder supports new way of calculating audio pts.
1840 // sh_audio->pts is the timestamp of the latest input packet with
1841 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1842 // the amount of bytes the decoder has written after that timestamp.
1843 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1844 else {
1845 // Decoder doesn't support new way of calculating pts (or we're
1846 // being called before it has decoded anything with known timestamp).
1847 // Use the old method of audio pts calculation: take the timestamp
1848 // of last packet with known pts the decoder has read data from,
1849 // and add amount of bytes read after the beginning of that packet
1850 // divided by input bps. This will be inaccurate if the input/output
1851 // ratio is not constant for every audio packet or if it is constant
1852 // but not accurately known in sh_audio->i_bps.
1854 a_pts = d_audio->pts;
1855 // ds_tell_pts returns bytes read after last timestamp from
1856 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1857 // it has read but not decoded
1858 if (sh_audio->i_bps)
1859 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1860 (double)sh_audio->i_bps;
1862 // Now a_pts hopefully holds the pts for end of audio from decoder.
1863 // Substract data in buffers between decoder and audio out.
1865 // Decoded but not filtered
1866 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1868 // Data buffered in audio filters, measured in bytes of "missing" output
1869 buffered_output = af_calc_delay(sh_audio->afilter);
1871 // Data that was ready for ao but was buffered because ao didn't fully
1872 // accept everything to internal buffers yet
1873 buffered_output += sh_audio->a_out_buffer_len;
1875 // Filters divide audio length by playback_speed, so multiply by it
1876 // to get the length in original units without speedup or slowdown
1877 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1879 return a_pts + mpctx->video_offset;
1882 // Return pts value corresponding to currently playing audio.
1883 double playing_audio_pts(struct MPContext *mpctx)
1885 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1886 mpctx->audio_out->get_delay();
1889 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1890 struct MPOpts *opts = &mpctx->opts;
1891 // check for frame-drop:
1892 current_module = "check_framedrop";
1893 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1894 static int dropped_frames;
1895 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1896 float d = delay-mpctx->delay;
1897 ++total_frame_cnt;
1898 // we should avoid dropping too many frames in sequence unless we
1899 // are too late. and we allow 100ms A-V delay here:
1900 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1901 && !mpctx->update_video_immediately) {
1902 ++drop_frame_cnt;
1903 ++dropped_frames;
1904 return frame_dropping;
1905 } else
1906 dropped_frames = 0;
1908 return 0;
1912 #ifdef HAVE_RTC
1913 int rtc_fd = -1;
1914 #endif
1916 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1918 #ifdef HAVE_RTC
1919 if (rtc_fd >= 0){
1920 // -------- RTC -----------
1921 current_module="sleep_rtc";
1922 while (time_frame > 0.000) {
1923 unsigned long rtc_ts;
1924 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1925 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1926 time_frame -= get_relative_time(mpctx);
1928 } else
1929 #endif
1931 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1932 // unnecessarily high CPU usage
1933 float margin = softsleep ? 0.011 : 0;
1934 current_module = "sleep_timer";
1935 while (time_frame > margin) {
1936 usec_sleep(1000000 * (time_frame - margin));
1937 time_frame -= get_relative_time(mpctx);
1939 if (softsleep){
1940 current_module = "sleep_soft";
1941 if (time_frame < 0)
1942 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1943 while (time_frame > 0)
1944 time_frame -= get_relative_time(mpctx); // burn the CPU
1947 return time_frame;
1950 static int select_subtitle(MPContext *mpctx)
1952 struct MPOpts *opts = &mpctx->opts;
1953 // find the best sub to use
1954 int id;
1955 int found = 0;
1956 mpctx->global_sub_pos = -1; // no subs by default
1957 if (vobsub_id >= 0) {
1958 // if user asks for a vobsub id, use that first.
1959 id = vobsub_id;
1960 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1963 if (!found && opts->sub_id >= 0) {
1964 // if user asks for a dvd sub id, use that next.
1965 id = opts->sub_id;
1966 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1969 if (!found) {
1970 // if there are text subs to use, use those. (autosubs come last here)
1971 id = 0;
1972 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1975 if (!found && opts->sub_id == -1) {
1976 // finally select subs by language and container hints
1977 if (opts->sub_id == -1 && opts->sub_lang)
1978 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, opts->sub_lang);
1979 if (opts->sub_id == -1)
1980 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
1981 if (opts->sub_id >= 0) {
1982 id = opts->sub_id;
1983 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1986 return found;
1989 #ifdef CONFIG_DVDNAV
1990 #ifndef FF_B_TYPE
1991 #define FF_B_TYPE 3
1992 #endif
1993 /// store decoded video image
1994 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1995 mp_image_t *from_mpi) {
1996 mp_image_t *mpi;
1998 /// Do not store B-frames
1999 if (from_mpi->pict_type == FF_B_TYPE)
2000 return to_mpi;
2002 if (to_mpi &&
2003 to_mpi->w == from_mpi->w &&
2004 to_mpi->h == from_mpi->h &&
2005 to_mpi->imgfmt == from_mpi->imgfmt)
2006 mpi = to_mpi;
2007 else {
2008 if (to_mpi)
2009 free_mp_image(to_mpi);
2010 if (from_mpi->w == 0 || from_mpi->h == 0)
2011 return NULL;
2012 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2015 copy_mpi(mpi,from_mpi);
2016 return mpi;
2019 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2020 struct MPOpts *opts = &ctx->opts;
2021 if (ctx->sh_video) {
2022 /// clear video pts
2023 ctx->d_video->pts = 0.0f;
2024 ctx->sh_video->pts = 0.0f;
2025 ctx->sh_video->i_pts = 0.0f;
2026 ctx->sh_video->last_pts = 0.0f;
2027 ctx->sh_video->num_buffered_pts = 0;
2028 ctx->sh_video->num_frames = 0;
2029 ctx->sh_video->num_frames_decoded = 0;
2030 ctx->sh_video->timer = 0.0f;
2031 ctx->sh_video->stream_delay = 0.0f;
2032 ctx->sh_video->timer = 0;
2033 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2036 if (ctx->sh_audio) {
2037 /// free audio packets and reset
2038 ds_free_packs(ctx->d_audio);
2039 audio_delay -= ctx->sh_audio->stream_delay;
2040 ctx->delay =- audio_delay;
2041 ctx->audio_out->reset();
2042 resync_audio_stream(ctx->sh_audio);
2045 audio_delay = 0.0f;
2046 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2047 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2048 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2049 if (dvdsub_lang_id != opts->sub_id) {
2050 opts->sub_id = dvdsub_lang_id;
2051 select_subtitle(ctx);
2055 /// clear all EOF related flags
2056 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2059 /// Restore last decoded DVDNAV (still frame)
2060 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2061 int *in_size,
2062 unsigned char **start,
2063 mp_image_t *decoded_frame)
2065 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2066 return decoded_frame;
2068 /// a change occured in dvdnav stream
2069 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2070 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2071 mp_dvdnav_context_free(mpctx);
2072 mp_dvdnav_reset_stream(mpctx);
2073 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2074 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2077 if (*in_size < 0) {
2078 float len;
2080 /// Display still frame, if any
2081 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2082 decoded_frame = mpctx->nav_smpi;
2084 /// increment video frame : continue playing after still frame
2085 len = demuxer_get_time_length(mpctx->demuxer);
2086 if (mpctx->sh_video->pts >= len &&
2087 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2088 mp_dvdnav_skip_still(mpctx->stream);
2089 mp_dvdnav_skip_wait(mpctx->stream);
2091 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2093 if (mpctx->nav_buffer) {
2094 *start = mpctx->nav_start;
2095 *in_size = mpctx->nav_in_size;
2096 if (mpctx->nav_start)
2097 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2101 return decoded_frame;
2104 /// Save last decoded DVDNAV (still frame)
2105 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2106 unsigned char *start,
2107 mp_image_t *decoded_frame)
2109 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2110 return;
2112 if (mpctx->nav_buffer)
2113 free(mpctx->nav_buffer);
2115 mpctx->nav_buffer = malloc(in_size);
2116 mpctx->nav_start = start;
2117 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2118 if (mpctx->nav_buffer)
2119 memcpy(mpctx->nav_buffer,start,in_size);
2121 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2122 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2124 #endif /* CONFIG_DVDNAV */
2126 /* Modify video timing to match the audio timeline. There are two main
2127 * reasons this is needed. First, video and audio can start from different
2128 * positions at beginning of file or after a seek (MPlayer starts both
2129 * immediately even if they have different pts). Second, the file can have
2130 * audio timestamps that are inconsistent with the duration of the audio
2131 * packets, for example two consecutive timestamp values differing by
2132 * one second but only a packet with enough samples for half a second
2133 * of playback between them.
2135 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2137 current_module = "av_sync";
2139 if (!mpctx->sh_audio)
2140 return;
2142 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2143 double v_pts = mpctx->sh_video->pts;
2144 double av_delay = a_pts - v_pts;
2145 // Try to sync vo_flip() so it will *finish* at given time
2146 av_delay += mpctx->last_vo_flip_duration;
2147 av_delay -= audio_delay; // This much pts difference is desired
2149 double change = av_delay * 0.1;
2150 double max_change = default_max_pts_correction >= 0 ?
2151 default_max_pts_correction : frame_time * 0.1;
2152 if (change < -max_change)
2153 change = -max_change;
2154 else if (change > max_change)
2155 change = max_change;
2156 mpctx->delay += change;
2157 mpctx->total_avsync_change += change;
2160 static int fill_audio_out_buffers(struct MPContext *mpctx)
2162 struct MPOpts *opts = &mpctx->opts;
2163 unsigned int t;
2164 double tt;
2165 int playsize;
2166 int playflags=0;
2167 int audio_eof=0;
2168 bool format_change = false;
2169 sh_audio_t * const sh_audio = mpctx->sh_audio;
2171 current_module="play_audio";
2173 while (1) {
2174 int sleep_time;
2175 // all the current uses of ao_data.pts seem to be in aos that handle
2176 // sync completely wrong; there should be no need to use ao_data.pts
2177 // in get_space()
2178 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2179 playsize = mpctx->audio_out->get_space();
2180 if (mpctx->sh_video || playsize >= ao_data.outburst)
2181 break;
2183 // handle audio-only case:
2184 // this is where mplayer sleeps during audio-only playback
2185 // to avoid 100% CPU use
2186 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2187 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2188 usec_sleep(sleep_time * 1000);
2191 // Fill buffer if needed:
2192 current_module="decode_audio";
2193 t = GetTimer();
2194 int res = decode_audio(sh_audio, playsize);
2195 if (res < 0) { // EOF, error or format change
2196 if (res == -2)
2197 format_change = true;
2198 else if (mpctx->d_audio->eof) {
2199 audio_eof = 1;
2200 if (sh_audio->a_out_buffer_len == 0)
2201 return 0;
2204 t = GetTimer() - t;
2205 tt = t*0.000001f; audio_time_usage+=tt;
2206 if (playsize > sh_audio->a_out_buffer_len) {
2207 playsize = sh_audio->a_out_buffer_len;
2208 if (audio_eof)
2209 playflags |= AOPLAY_FINAL_CHUNK;
2211 if (!playsize)
2212 return 1;
2214 // play audio:
2215 current_module="play_audio";
2217 // Is this pts value actually useful for the aos that access it?
2218 // They're obviously badly broken in the way they handle av sync;
2219 // would not having access to this make them more broken?
2220 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2221 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2223 if (playsize > 0) {
2224 sh_audio->a_out_buffer_len -= playsize;
2225 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2226 sh_audio->a_out_buffer_len);
2227 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2229 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2230 // Sanity check to avoid hanging in case current ao doesn't output
2231 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2232 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2233 sh_audio->a_out_buffer_len = 0;
2236 /* The format change isn't handled too gracefully. A more precise
2237 * implementation would require draining buffered old-format audio
2238 * while displaying video, then doing the output format switch.
2240 if (format_change) {
2241 uninit_player(mpctx, INITIALIZED_AO);
2242 reinit_audio_chain(mpctx);
2245 return 1;
2248 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2249 float *aq_sleep_time)
2251 struct MPOpts *opts = &mpctx->opts;
2252 int frame_time_remaining = 0;
2253 current_module="calc_sleep_time";
2255 *time_frame -= get_relative_time(mpctx); // reset timer
2257 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2258 float delay = mpctx->audio_out->get_delay();
2259 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2261 if (autosync) {
2263 * Adjust this raw delay value by calculating the expected
2264 * delay for this frame and generating a new value which is
2265 * weighted between the two. The higher autosync is, the
2266 * closer to the delay value gets to that which "-nosound"
2267 * would have used, and the longer it will take for A/V
2268 * sync to settle at the right value (but it eventually will.)
2269 * This settling time is very short for values below 100.
2271 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2272 float difference = delay - predicted;
2273 delay = predicted + difference / (float)autosync;
2276 *time_frame = delay - mpctx->delay / opts->playback_speed;
2277 *time_frame -= mpctx->video_out->flip_queue_offset;
2279 // delay = amount of audio buffered in soundcard/driver
2280 if (delay > 0.25) delay=0.25; else
2281 if (delay < 0.10) delay=0.10;
2283 if (*time_frame > delay*0.6) {
2284 // sleep time too big - may cause audio drops (buffer underrun)
2285 frame_time_remaining = 1;
2286 *time_frame = delay*0.5;
2288 } else {
2289 // If we're lagging more than 200 ms behind the right playback rate,
2290 // don't try to "catch up".
2291 // If benchmark is set always output frames as fast as possible
2292 // without sleeping.
2293 if (*time_frame < -0.2 || benchmark)
2294 *time_frame = 0;
2295 *time_frame -= mpctx->video_out->flip_queue_offset;
2298 *aq_sleep_time += *time_frame;
2301 //============================== SLEEP: ===================================
2303 // flag 256 means: libvo driver does its timing (dvb card)
2304 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2305 *time_frame = timing_sleep(mpctx, *time_frame);
2306 *time_frame += mpctx->video_out->flip_queue_offset;
2307 return frame_time_remaining;
2310 int reinit_video_chain(struct MPContext *mpctx)
2312 struct MPOpts *opts = &mpctx->opts;
2313 sh_video_t * const sh_video = mpctx->sh_video;
2314 double ar=-1.0;
2315 //================== Init VIDEO (codec & libvo) ==========================
2316 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2317 current_module="preinit_libvo";
2319 //shouldn't we set dvideo->id=-2 when we fail?
2320 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2321 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2322 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2323 goto err_out;
2325 mpctx->initialized_flags|=INITIALIZED_VO;
2328 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2329 mpctx->sh_video->stream_aspect = ar;
2330 current_module="init_video_filters";
2332 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2333 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2335 #ifdef CONFIG_MENU
2336 if(use_menu) {
2337 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2338 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2339 if(!vf_menu) {
2340 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2341 use_menu = 0;
2344 if(vf_menu)
2345 sh_video->vfilter = vf_menu;
2346 #endif
2348 #ifdef CONFIG_ASS
2349 if(opts->ass_enabled) {
2350 int i;
2351 int insert = 1;
2352 if (opts->vf_settings)
2353 for (i = 0; opts->vf_settings[i].name; ++i)
2354 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2355 insert = 0;
2356 break;
2358 if (insert) {
2359 extern vf_info_t vf_info_ass;
2360 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2361 char* vf_arg[] = {"auto", "1", NULL};
2362 int retcode = 0;
2363 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2364 sh_video->vfilter,
2365 "ass", vf_arg,
2366 &retcode);
2367 if (vf_ass)
2368 sh_video->vfilter = vf_ass;
2369 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2370 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2371 else
2372 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2375 #endif
2377 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2379 #ifdef CONFIG_ASS
2380 if (opts->ass_enabled)
2381 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2382 #endif
2384 current_module="init_video_codec";
2386 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2387 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2388 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2390 if(!sh_video->initialized){
2391 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2392 goto err_out;
2395 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2397 if (sh_video->codec)
2398 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2400 sh_video->last_pts = MP_NOPTS_VALUE;
2401 sh_video->num_buffered_pts = 0;
2402 sh_video->next_frame_time = 0;
2404 if(auto_quality>0){
2405 // Auto quality option enabled
2406 output_quality=get_video_quality_max(sh_video);
2407 if(auto_quality>output_quality) auto_quality=output_quality;
2408 else output_quality=auto_quality;
2409 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2410 set_video_quality(sh_video,output_quality);
2413 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2415 current_module="init_vo";
2417 return 1;
2419 err_out:
2420 mpctx->sh_video = mpctx->d_video->sh = NULL;
2421 return 0;
2424 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2426 struct sh_video *sh_video = mpctx->sh_video;
2427 double frame_time = 0;
2428 struct vo *video_out = mpctx->video_out;
2429 while (!video_out->frame_loaded) {
2430 current_module = "filter_video";
2431 // In nocorrect-pts mode there is no way to properly time these frames
2432 if (vo_get_buffered_frame(video_out, 0) >= 0)
2433 break;
2434 if (vf_output_queued_frame(sh_video->vfilter))
2435 continue;
2436 unsigned char *packet = NULL;
2437 frame_time = sh_video->next_frame_time;
2438 if (mpctx->update_video_immediately)
2439 frame_time = 0;
2440 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2441 &packet, force_fps);
2442 if (in_size < 0) {
2443 #ifdef CONFIG_DVDNAV
2444 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2445 if (mp_dvdnav_is_eof(mpctx->stream))
2446 return -1;
2447 if (mpctx->d_video)
2448 mpctx->d_video->eof = 0;
2449 if (mpctx->d_audio)
2450 mpctx->d_audio->eof = 0;
2451 mpctx->stream->eof = 0;
2452 } else
2453 #endif
2454 return -1;
2456 if (in_size > max_framesize)
2457 max_framesize = in_size;
2458 sh_video->timer += frame_time;
2459 if (mpctx->sh_audio)
2460 mpctx->delay -= frame_time;
2461 // video_read_frame can change fps (e.g. for ASF video)
2462 vo_fps = sh_video->fps;
2463 int framedrop_type = check_framedrop(mpctx, frame_time);
2464 current_module = "decode video";
2466 void *decoded_frame;
2467 #ifdef CONFIG_DVDNAV
2468 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2469 if (in_size >= 0 && !decoded_frame)
2470 #endif
2471 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2472 sh_video->pts);
2473 #ifdef CONFIG_DVDNAV
2474 // Save last still frame for future display
2475 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2476 #endif
2477 if (decoded_frame) {
2478 current_module = "filter video";
2479 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2480 if (!video_out->config_ok)
2481 break;
2484 return frame_time;
2487 static void determine_frame_pts(struct MPContext *mpctx)
2489 struct sh_video *sh_video = mpctx->sh_video;
2490 struct MPOpts *opts = &mpctx->opts;
2492 if (opts->user_pts_assoc_mode) {
2493 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2494 } else if (sh_video->pts_assoc_mode == 0) {
2495 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2496 sh_video->pts_assoc_mode = 1;
2497 else
2498 sh_video->pts_assoc_mode = 2;
2499 } else {
2500 int probcount1 = sh_video->num_reordered_pts_problems;
2501 int probcount2 = sh_video->num_sorted_pts_problems;
2502 if (sh_video->pts_assoc_mode == 2) {
2503 int tmp = probcount1;
2504 probcount1 = probcount2;
2505 probcount2 = tmp;
2507 if (probcount1 >= probcount2 * 1.5 + 2) {
2508 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2509 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2510 "%d.\n", sh_video->pts_assoc_mode);
2513 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2514 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2517 static double update_video(struct MPContext *mpctx)
2519 struct sh_video *sh_video = mpctx->sh_video;
2520 struct vo *video_out = mpctx->video_out;
2521 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2522 mpctx->osd); // hack for vf_expand
2523 if (!mpctx->opts.correct_pts)
2524 return update_video_nocorrect_pts(mpctx);
2526 double pts;
2528 bool hit_eof = false;
2529 while (!video_out->frame_loaded) {
2530 current_module = "filter_video";
2531 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2532 break;
2533 // XXX Time used in this call is not counted in any performance
2534 // timer now, OSD time is not updated correctly for filter-added frames
2535 if (vf_output_queued_frame(sh_video->vfilter))
2536 continue;
2537 if (hit_eof)
2538 return -1;
2539 unsigned char *packet = NULL;
2540 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2541 if (pts != MP_NOPTS_VALUE)
2542 pts += mpctx->video_offset;
2543 if (in_size < 0) {
2544 // try to extract last frames in case of decoder lag
2545 in_size = 0;
2546 pts = MP_NOPTS_VALUE;
2547 hit_eof = true;
2549 if (in_size > max_framesize)
2550 max_framesize = in_size;
2551 current_module = "decode video";
2552 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2553 void *decoded_frame = decode_video(sh_video, packet, in_size,
2554 framedrop_type, pts);
2555 if (decoded_frame) {
2556 determine_frame_pts(mpctx);
2557 current_module = "filter video";
2558 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2559 if (!video_out->config_ok)
2560 break; // We'd likely hang in this loop otherwise
2564 pts = video_out->next_pts;
2565 if (pts == MP_NOPTS_VALUE) {
2566 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2567 // Try to use decoder pts from before filters
2568 pts = sh_video->pts;
2569 if (pts == MP_NOPTS_VALUE)
2570 pts = sh_video->last_pts;
2572 sh_video->pts = pts;
2573 if (sh_video->last_pts == MP_NOPTS_VALUE)
2574 sh_video->last_pts = sh_video->pts;
2575 else if (sh_video->last_pts > sh_video->pts) {
2576 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2577 sh_video->pts, sh_video->last_pts);
2578 /* If the difference in pts is small treat it as jitter around the
2579 * right value (possibly caused by incorrect timestamp ordering) and
2580 * just show this frame immediately after the last one.
2581 * Treat bigger differences as timestamp resets and start counting
2582 * timing of later frames from the position of this one. */
2583 if (sh_video->last_pts - sh_video->pts > 0.5)
2584 sh_video->last_pts = sh_video->pts;
2585 else
2586 sh_video->pts = sh_video->last_pts;
2588 double frame_time = sh_video->pts - sh_video->last_pts;
2589 sh_video->last_pts = sh_video->pts;
2590 sh_video->timer += frame_time;
2591 if (mpctx->sh_audio)
2592 mpctx->delay -= frame_time;
2593 return frame_time;
2596 void pause_player(struct MPContext *mpctx)
2598 if (mpctx->paused)
2599 return;
2600 mpctx->paused = 1;
2601 mpctx->step_frames = 0;
2602 mpctx->time_frame -= get_relative_time(mpctx);
2604 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2605 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2607 if (mpctx->audio_out && mpctx->sh_audio)
2608 mpctx->audio_out->pause(); // pause audio, keep data if possible
2611 void unpause_player(struct MPContext *mpctx)
2613 if (!mpctx->paused)
2614 return;
2615 mpctx->paused = 0;
2617 if (mpctx->audio_out && mpctx->sh_audio)
2618 mpctx->audio_out->resume(); // resume audio
2619 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2620 && !mpctx->step_frames)
2621 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2622 (void)get_relative_time(mpctx); // ignore time that passed during pause
2625 void add_step_frame(struct MPContext *mpctx)
2627 mpctx->step_frames++;
2628 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2629 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2630 unpause_player(mpctx);
2633 static void pause_loop(struct MPContext *mpctx)
2635 mp_cmd_t* cmd;
2636 if (!quiet) {
2637 // Small hack to display the pause message on the OSD line.
2638 // The pause string is: "\n == PAUSE == \r" so we need to
2639 // take the first and the last char out
2640 if (term_osd && !mpctx->sh_video) {
2641 char msg[128] = _("\n ===== PAUSE =====\r");
2642 int mlen = strlen(msg);
2643 msg[mlen-1] = '\0';
2644 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2645 update_osd_msg(mpctx);
2646 } else
2647 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2648 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2651 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2652 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2653 if (cmd) {
2654 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2655 run_command(mpctx, cmd);
2656 mp_cmd_free(cmd);
2657 continue;
2659 if (mpctx->sh_video && mpctx->video_out)
2660 vo_check_events(mpctx->video_out);
2661 #ifdef CONFIG_MENU
2662 if (vf_menu)
2663 vf_menu_pause_update(vf_menu);
2664 #endif
2665 usec_sleep(20000);
2666 update_osd_msg(mpctx);
2667 int hack = vo_osd_changed(0);
2668 vo_osd_changed(hack);
2669 if (hack)
2670 break;
2675 // Find the right mute status and record position for new file position
2676 static void edl_seek_reset(MPContext *mpctx)
2678 mpctx->edl_muted = 0;
2679 next_edl_record = edl_records;
2681 while (next_edl_record) {
2682 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2683 break;
2685 if (next_edl_record->action == EDL_MUTE)
2686 mpctx->edl_muted = !mpctx->edl_muted;
2687 next_edl_record = next_edl_record->next;
2689 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2690 mixer_mute(&mpctx->mixer);
2694 // Execute EDL command for the current position if one exists
2695 static void edl_update(MPContext *mpctx)
2697 if (!next_edl_record)
2698 return;
2700 if (!mpctx->sh_video) {
2701 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2702 free_edl(edl_records);
2703 next_edl_record = NULL;
2704 edl_records = NULL;
2705 return;
2708 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2709 if (next_edl_record->action == EDL_SKIP) {
2710 mpctx->osd_function = OSD_FFW;
2711 mpctx->abs_seek_pos = 0;
2712 mpctx->rel_seek_secs = next_edl_record->length_sec;
2713 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2714 "[%f], length [%f]\n", next_edl_record->start_sec,
2715 next_edl_record->stop_sec, next_edl_record->length_sec);
2717 else if (next_edl_record->action == EDL_MUTE) {
2718 mpctx->edl_muted = !mpctx->edl_muted;
2719 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2720 mixer_mute(&mpctx->mixer);
2721 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2722 next_edl_record->start_sec );
2724 next_edl_record = next_edl_record->next;
2728 static void reinit_decoders(struct MPContext *mpctx)
2730 reinit_video_chain(mpctx);
2731 reinit_audio_chain(mpctx);
2732 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2735 static void seek_reset(struct MPContext *mpctx)
2737 if (mpctx->sh_video) {
2738 current_module = "seek_video_reset";
2739 resync_video_stream(mpctx->sh_video);
2740 mpctx->sh_video->timer = 0;
2741 vo_seek_reset(mpctx->video_out);
2742 mpctx->sh_video->timer = 0;
2743 mpctx->sh_video->num_buffered_pts = 0;
2744 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2745 mpctx->delay = 0;
2746 mpctx->time_frame = 0;
2747 mpctx->update_video_immediately = true;
2748 // Not all demuxers set d_video->pts during seek, so this value
2749 // (which is used by at least vobsub and edl code below) may
2750 // be completely wrong (probably 0).
2751 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2752 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2753 mpctx->sh_video->pts, mpctx->video_offset,
2754 mpctx->d_sub, 1);
2755 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2758 if (mpctx->sh_audio) {
2759 current_module = "seek_audio_reset";
2760 resync_audio_stream(mpctx->sh_audio);
2761 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2762 mpctx->sh_audio->a_buffer_len = 0;
2763 mpctx->sh_audio->a_out_buffer_len = 0;
2764 if (!mpctx->sh_video)
2765 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2766 mpctx->video_offset, mpctx->d_sub, 1);
2769 if (vo_vobsub && mpctx->sh_video) {
2770 current_module = "seek_vobsub_reset";
2771 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2774 edl_seek_reset(mpctx);
2776 mpctx->total_avsync_change = 0;
2777 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2778 drop_frame_cnt = 0;
2780 current_module = NULL;
2783 static bool timeline_set_part(struct MPContext *mpctx, int i)
2785 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2786 struct timeline_part *n = mpctx->timeline + i;
2787 mpctx->timeline_part = i;
2788 mpctx->video_offset = n->start - n->source_start;
2789 if (n->source == p->source)
2790 return false;
2791 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2792 mpctx->demuxer = n->source->demuxer;
2793 mpctx->d_video = mpctx->demuxer->video;
2794 mpctx->d_audio = mpctx->demuxer->audio;
2795 mpctx->d_sub = mpctx->demuxer->sub;
2796 mpctx->sh_video = mpctx->d_video->sh;
2797 mpctx->sh_audio = mpctx->d_audio->sh;
2798 return true;
2801 // Given pts, switch playback to the corresponding part.
2802 // Return offset within that part.
2803 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2804 bool *need_reset)
2806 if (pts < 0)
2807 pts = 0;
2808 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2809 struct timeline_part *p = mpctx->timeline + i;
2810 if (pts < (p+1)->start) {
2811 *need_reset = timeline_set_part(mpctx, i);
2812 return pts - p->start + p->source_start;
2815 return -1;
2819 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2820 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2821 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2822 static int seek(MPContext *mpctx, double amount, int style)
2824 current_module = "seek";
2825 if (mpctx->stop_play == AT_END_OF_FILE)
2826 mpctx->stop_play = KEEP_PLAYING;
2827 if (style & SEEK_FACTOR
2828 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2829 || amount < 0)
2830 mpctx->last_chapter_seek = -1;
2831 if (mpctx->timeline && style & SEEK_FACTOR) {
2832 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2833 style &= ~SEEK_FACTOR;
2835 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2836 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2837 style |= SEEK_ABSOLUTE;
2838 if (amount > 0)
2839 style |= SEEK_FORWARD;
2840 else
2841 style |= SEEK_BACKWARD;
2842 amount += mpctx->sh_video->pts;
2845 /* At least the liba52 decoder wants to read from the input stream
2846 * during initialization, so reinit must be done after the demux_seek()
2847 * call that clears possible stream EOF. */
2848 bool need_reset = false;
2849 if (mpctx->timeline) {
2850 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2851 if (amount == -1) {
2852 mpctx->stop_play = AT_END_OF_FILE;
2853 // Clear audio from current position
2854 if (mpctx->sh_audio) {
2855 mpctx->audio_out->reset();
2856 mpctx->sh_audio->a_buffer_len = 0;
2857 mpctx->sh_audio->a_out_buffer_len = 0;
2859 return -1;
2862 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2863 if (need_reset)
2864 reinit_decoders(mpctx);
2865 if (seekresult == 0)
2866 return -1;
2868 seek_reset(mpctx);
2869 return 0;
2872 // -2 is no chapters, -1 is before first chapter
2873 int get_current_chapter(struct MPContext *mpctx)
2875 if (!mpctx->chapters || !mpctx->sh_video)
2876 return FFMAX(mpctx->last_chapter_seek,
2877 demuxer_get_current_chapter(mpctx->demuxer));
2879 int i;
2880 double current_pts = mpctx->sh_video->pts;
2881 for (i = 1; i < mpctx->num_chapters; i++)
2882 if (current_pts < mpctx->chapters[i].start)
2883 break;
2884 return FFMAX(mpctx->last_chapter_seek, i - 1);
2887 // currently returns a string allocated with malloc, not talloc
2888 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2890 if (!mpctx->chapters || !mpctx->sh_video)
2891 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2892 return strdup(mpctx->chapters[chapter].name);
2895 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2896 char **chapter_name)
2898 mpctx->last_chapter_seek = -1;
2899 if (!mpctx->chapters || !mpctx->sh_video) {
2900 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2901 chapter_name);
2902 if (res >= 0) {
2903 if (*seek_pts == -1)
2904 seek_reset(mpctx);
2905 else {
2906 mpctx->last_chapter_seek = res;
2907 mpctx->last_chapter_pts = *seek_pts;
2910 return res;
2913 if (chapter >= mpctx->num_chapters)
2914 return -1;
2915 if (chapter < 0)
2916 chapter = 0;
2917 *seek_pts = mpctx->chapters[chapter].start;
2918 mpctx->last_chapter_seek = chapter;
2919 mpctx->last_chapter_pts = *seek_pts;
2920 if (chapter_name)
2921 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2922 return chapter;
2925 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2926 struct content_source *sources,
2927 int num_sources,
2928 unsigned char uid_map[][16])
2930 int num_filenames = 0;
2931 char **filenames = NULL;
2932 if (num_sources > 1) {
2933 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2934 "other sources.\n");
2935 if (mpctx->stream->type != STREAMTYPE_FILE) {
2936 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2937 "normal disk file. Will not search for related files.\n");
2938 } else {
2939 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2940 "same directory to find referenced sources.\n");
2941 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2942 &num_filenames);
2946 int num_left = num_sources - 1;
2947 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2948 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2949 filename_recode(filenames[i]));
2950 int format;
2951 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2952 if (!s)
2953 continue;
2954 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2955 mpctx->opts.audio_id,
2956 mpctx->opts.video_id,
2957 mpctx->opts.sub_id, filenames[i]);
2958 if (!d) {
2959 free_stream(s);
2960 continue;
2962 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2963 for (int i = 1; i < num_sources; i++) {
2964 if (sources[i].demuxer)
2965 continue;
2966 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2967 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2968 i, filename_recode(d->filename));
2969 sources[i].stream = s;
2970 sources[i].demuxer = d;
2971 num_left--;
2972 goto match;
2976 free_demuxer(d);
2977 free_stream(s);
2978 continue;
2979 match:
2982 talloc_free(filenames);
2983 if (num_left) {
2984 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2985 "There will be parts MISSING from the video!\n");
2986 for (int i = 1, j = 1; i < num_sources; i++)
2987 if (sources[i].demuxer) {
2988 sources[j] = sources[i];
2989 memcpy(uid_map[j], uid_map[i], 16);
2990 j++;
2993 return num_sources - num_left;
2996 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2998 if (!mpctx->opts.ordered_chapters) {
2999 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3000 "you have disabled support for them. Ignoring.\n");
3001 return;
3004 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3005 "edit timeline.\n");
3007 struct demuxer *demuxer = mpctx->demuxer;
3008 struct matroska_data *m = &demuxer->matroska_data;
3010 // +1 because sources/uid_map[0] is original file even if all chapters
3011 // actually use other sources and need separate entries
3012 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3013 m->num_ordered_chapters+1);
3014 sources[0].stream = mpctx->stream;
3015 sources[0].demuxer = mpctx->demuxer;
3016 unsigned char uid_map[m->num_ordered_chapters+1][16];
3017 int num_sources = 1;
3018 memcpy(uid_map[0], m->segment_uid, 16);
3020 for (int i = 0; i < m->num_ordered_chapters; i++) {
3021 struct matroska_chapter *c = m->ordered_chapters + i;
3022 if (!c->has_segment_uid)
3023 memcpy(c->segment_uid, m->segment_uid, 16);
3025 for (int j = 0; j < num_sources; j++)
3026 if (!memcmp(c->segment_uid, uid_map[j], 16))
3027 goto found1;
3028 memcpy(uid_map[num_sources], c->segment_uid, 16);
3029 sources[num_sources] = (struct content_source){};
3030 num_sources++;
3031 found1:
3035 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3036 uid_map);
3039 // +1 for terminating chapter with start time marking end of last real one
3040 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3041 m->num_ordered_chapters + 1);
3042 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3043 m->num_ordered_chapters);
3044 uint64_t starttime = 0;
3045 uint64_t missing_time = 0;
3046 int part_count = 0;
3047 int num_chapters = 0;
3048 uint64_t prev_part_offset = 0;
3049 for (int i = 0; i < m->num_ordered_chapters; i++) {
3050 struct matroska_chapter *c = m->ordered_chapters + i;
3052 int j;
3053 for (j = 0; j < num_sources; j++) {
3054 if (!memcmp(c->segment_uid, uid_map[j], 16))
3055 goto found2;
3057 missing_time += c->end - c->start;
3058 continue;
3059 found2:;
3060 chapters[num_chapters].start = starttime / 1000.;
3061 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3062 /* Only add a separate part if the time or file actually changes.
3063 * Matroska files have chapter divisions that are redundant from
3064 * timeline point of view because the same chapter structure is used
3065 * both to specify the timeline and for normal chapter information.
3066 * Removing a missing inserted external chapter can also cause this. */
3067 if (part_count == 0 || c->start != starttime + prev_part_offset
3068 || sources + j != timeline[part_count - 1].source) {
3069 timeline[part_count].source = sources + j;
3070 timeline[part_count].start = chapters[num_chapters].start;
3071 timeline[part_count].source_start = c->start / 1000.;
3072 prev_part_offset = c->start - starttime;
3073 part_count++;
3075 starttime += c->end - c->start;
3076 num_chapters++;
3078 timeline[part_count].start = starttime / 1000.;
3080 if (!part_count) {
3081 // None of the parts come from the file itself???
3082 talloc_free(sources);
3083 talloc_free(timeline);
3084 talloc_free(chapters);
3085 return;
3088 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3089 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3090 timeline[part_count].start);
3091 if (missing_time)
3092 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3093 "from the timeline!\n", missing_time / 1000.);
3094 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3095 for (int i = 0; i < num_sources; i++)
3096 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3097 filename_recode(sources[i].demuxer->filename));
3098 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3099 "source_start, source):\n");
3100 for (int i = 0; i < part_count; i++) {
3101 struct timeline_part *p = timeline + i;
3102 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3103 p->source_start, p->source - sources);
3105 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3106 mpctx->sources = sources;
3107 mpctx->num_sources = num_sources;
3108 mpctx->timeline = timeline;
3109 mpctx->num_timeline_parts = part_count;
3110 mpctx->num_chapters = num_chapters;
3111 mpctx->chapters = chapters;
3113 mpctx->timeline_part = 0;
3114 mpctx->demuxer = timeline[0].source->demuxer;
3118 static int read_keys(void *ctx, int fd)
3120 getch2(ctx);
3121 return mplayer_get_key(ctx, 0);
3125 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3126 * file for some tools to link against. */
3127 #ifndef DISABLE_MAIN
3128 int main(int argc,char* argv[]){
3131 char * mem_ptr;
3133 // movie info:
3135 /* Flag indicating whether MPlayer should exit without playing anything. */
3136 int opt_exit = 0;
3137 int i;
3139 struct MPContext *mpctx = &(struct MPContext){
3140 .osd_function = OSD_PLAY,
3141 .begin_skip = MP_NOPTS_VALUE,
3142 .play_tree_step = 1,
3143 .global_sub_pos = -1,
3144 .set_of_sub_pos = -1,
3145 .file_format = DEMUXER_TYPE_UNKNOWN,
3146 .last_dvb_step = 1,
3149 InitTimer();
3150 srand(GetTimerMS());
3152 mp_msg_init();
3153 set_av_log_callback();
3155 #ifdef CONFIG_X11
3156 mpctx->x11_state = vo_x11_init_state();
3157 #endif
3158 struct MPOpts *opts = &mpctx->opts;
3159 set_default_mplayer_options(opts);
3160 // Create the config context and register the options
3161 mpctx->mconfig = m_config_new(opts, cfg_include);
3162 m_config_register_options(mpctx->mconfig,mplayer_opts);
3163 m_config_register_options(mpctx->mconfig, common_opts);
3164 mp_input_register_options(mpctx->mconfig);
3166 // Preparse the command line
3167 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3169 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3170 set_path_env();
3171 #endif
3173 #ifdef CONFIG_TV
3174 stream_tv_defaults.immediate = 1;
3175 #endif
3177 parse_cfgfiles(mpctx, mpctx->mconfig);
3179 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3180 if(mpctx->playtree == NULL)
3181 opt_exit = 1;
3182 else {
3183 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3184 if(mpctx->playtree) {
3185 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3186 if(mpctx->playtree_iter) {
3187 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3188 play_tree_iter_free(mpctx->playtree_iter);
3189 mpctx->playtree_iter = NULL;
3191 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3195 mpctx->key_fifo = mp_fifo_create(opts);
3197 print_version("MPlayer");
3199 #if defined(__MINGW32__) || defined(__CYGWIN__)
3201 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3202 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3203 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3204 if (kernel32) {
3205 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3206 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3208 if (setDEP) setDEP(3);
3209 if (setDllDir) setDllDir("");
3211 // stop Windows from showing all kinds of annoying error dialogs
3212 SetErrorMode(0x8003);
3213 // request 1ms timer resolution
3214 timeBeginPeriod(1);
3215 #endif
3217 #ifdef CONFIG_PRIORITY
3218 set_priority();
3219 #endif
3221 if (codec_path)
3222 set_codec_path(codec_path);
3224 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3225 list_video_out();
3226 opt_exit = 1;
3229 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3230 list_audio_out();
3231 opt_exit = 1;
3234 /* Check codecs.conf. */
3235 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3236 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3237 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3238 if(!parse_codec_cfg(NULL)){
3239 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3241 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3244 free( mem_ptr ); // release the buffer created by get_path()
3247 #if 0
3248 if(video_codec_list){
3249 int i;
3250 video_codec=video_codec_list[0];
3251 for(i=0;video_codec_list[i];i++)
3252 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
3254 #endif
3255 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3256 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3257 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3258 list_codecs(1);
3259 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3260 opt_exit = 1;
3262 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3263 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3264 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3265 list_codecs(0);
3266 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3267 opt_exit = 1;
3269 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3270 vfm_help();
3271 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3272 opt_exit = 1;
3274 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3275 afm_help();
3276 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3277 opt_exit = 1;
3279 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3280 af_help();
3281 printf("\n");
3282 opt_exit = 1;
3284 #ifdef CONFIG_X11
3285 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3286 fstype_help();
3287 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3288 opt_exit = 1;
3290 #endif
3291 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3292 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3293 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3294 demuxer_help();
3295 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3296 opt_exit = 1;
3298 if(list_properties) {
3299 property_print_help();
3300 opt_exit = 1;
3303 if(opt_exit)
3304 exit_player(mpctx, EXIT_NONE);
3306 if(!mpctx->filename && !player_idle_mode){
3307 // no file/vcd/dvd -> show HELP:
3308 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3309 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3312 /* Display what configure line was used */
3313 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3315 // Many users forget to include command line in bugreports...
3316 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3317 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3318 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3319 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3322 //------ load global data first ------
3324 mpctx->osd = osd_create();
3326 // check font
3327 #ifdef CONFIG_FREETYPE
3328 init_freetype();
3329 #endif
3330 #ifdef CONFIG_FONTCONFIG
3331 if(font_fontconfig <= 0)
3333 #endif
3334 #ifdef CONFIG_BITMAP_FONT
3335 if(font_name){
3336 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3337 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3338 filename_recode(font_name));
3339 } else {
3340 // try default:
3341 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3342 free(mem_ptr); // release the buffer created by get_path()
3343 if(!vo_font)
3344 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3346 if (sub_font_name)
3347 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3348 else
3349 mpctx->osd->sub_font = vo_font;
3350 #endif
3351 #ifdef CONFIG_FONTCONFIG
3353 #endif
3355 #ifdef CONFIG_ASS
3356 ass_library = ass_init();
3357 #endif
3359 #ifdef HAVE_RTC
3360 if(!nortc)
3362 // seteuid(0); /* Can't hurt to try to get root here */
3363 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3364 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3365 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3366 else {
3367 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3369 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3370 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3371 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3372 close (rtc_fd);
3373 rtc_fd = -1;
3374 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3375 /* variable only by the root */
3376 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3377 close (rtc_fd);
3378 rtc_fd = -1;
3379 } else
3380 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3383 if(rtc_fd<0)
3384 #endif /* HAVE_RTC */
3385 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3386 softsleep?"software":timer_name);
3388 #ifdef HAVE_TERMCAP
3389 load_termcap(NULL); // load key-codes
3390 #endif
3392 // ========== Init keyboard FIFO (connection to libvo) ============
3394 // Init input system
3395 current_module = "init_input";
3396 mpctx->input = mp_input_init(&opts->input);
3397 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3398 if(slave_mode)
3399 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3400 else if(!noconsolecontrols)
3401 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3402 // Set the libstream interrupt callback
3403 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3405 #ifdef CONFIG_MENU
3406 if(use_menu) {
3407 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3408 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3409 else {
3410 menu_cfg = get_path("menu.conf");
3411 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3412 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3413 else {
3414 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3415 MPLAYER_CONFDIR "/menu.conf"))
3416 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3417 else {
3418 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3419 use_menu = 0;
3424 #endif
3426 current_module = NULL;
3428 /// Catch signals
3429 #ifndef __MINGW32__
3430 signal(SIGCHLD,child_sighandler);
3431 #endif
3433 #ifdef CONFIG_CRASH_DEBUG
3434 prog_path = argv[0];
3435 #endif
3436 //========= Catch terminate signals: ================
3437 // terminate requests:
3438 signal(SIGTERM,exit_sighandler); // kill
3439 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3441 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3443 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3444 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3445 #ifdef CONFIG_SIGHANDLER
3446 // fatal errors:
3447 signal(SIGBUS,exit_sighandler); // bus error
3448 signal(SIGSEGV,exit_sighandler); // segfault
3449 signal(SIGILL,exit_sighandler); // illegal instruction
3450 signal(SIGFPE,exit_sighandler); // floating point exc.
3451 signal(SIGABRT,exit_sighandler); // abort()
3452 #ifdef CONFIG_CRASH_DEBUG
3453 if (crash_debug)
3454 signal(SIGTRAP,exit_sighandler);
3455 #endif
3456 #endif
3458 // ******************* Now, let's see the per-file stuff ********************
3460 play_next_file:
3462 // init global sub numbers
3463 mpctx->global_sub_size = 0;
3464 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3466 if (mpctx->filename) {
3467 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3468 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3469 load_per_file_config (mpctx->mconfig, mpctx->filename);
3472 if (opts->video_driver_list)
3473 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3474 if (opts->audio_driver_list)
3475 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3477 // We must enable getch2 here to be able to interrupt network connection
3478 // or cache filling
3479 if(!noconsolecontrols && !slave_mode){
3480 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3481 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3482 else
3483 getch2_enable(); // prepare stdin for hotkeys...
3484 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3485 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3488 // =================== GUI idle loop (STOP state) ===========================
3489 while (player_idle_mode && !mpctx->filename) {
3490 play_tree_t * entry = NULL;
3491 mp_cmd_t * cmd;
3492 if (mpctx->video_out && mpctx->video_out->config_ok)
3493 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3494 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3495 if (mpctx->video_out)
3496 vo_check_events(mpctx->video_out);
3497 usec_sleep(20000);
3499 switch (cmd->id) {
3500 case MP_CMD_LOADFILE:
3501 // prepare a tree entry with the new filename
3502 entry = play_tree_new();
3503 play_tree_add_file(entry, cmd->args[0].v.s);
3504 // The entry is added to the main playtree after the switch().
3505 break;
3506 case MP_CMD_LOADLIST:
3507 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3508 break;
3509 case MP_CMD_QUIT:
3510 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3511 break;
3512 case MP_CMD_VO_FULLSCREEN:
3513 case MP_CMD_GET_PROPERTY:
3514 case MP_CMD_SET_PROPERTY:
3515 case MP_CMD_STEP_PROPERTY:
3516 run_command(mpctx, cmd);
3517 break;
3520 mp_cmd_free(cmd);
3522 if (entry) { // user entered a command that gave a valid entry
3523 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3524 play_tree_free_list(mpctx->playtree->child, 1);
3525 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3527 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3529 play_tree_set_child(mpctx->playtree, entry);
3531 /* Make iterator start at the top the of tree. */
3532 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3533 if (!mpctx->playtree_iter) continue;
3535 // find the first real item in the tree
3536 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3537 // no items!
3538 play_tree_iter_free(mpctx->playtree_iter);
3539 mpctx->playtree_iter = NULL;
3540 continue; // wait for next command
3542 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3545 //---------------------------------------------------------------------------
3547 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3548 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3550 if (mpctx->filename) {
3551 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3552 filename_recode(mpctx->filename));
3553 if(use_filename_title && vo_wintitle == NULL)
3554 vo_wintitle = strdup(mp_basename2(mpctx->filename));
3557 if (edl_filename) {
3558 if (edl_records) free_edl(edl_records);
3559 next_edl_record = edl_records = edl_parse_file();
3561 if (edl_output_filename) {
3562 if (edl_fd) fclose(edl_fd);
3563 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3565 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3566 filename_recode(edl_output_filename));
3570 //==================== Open VOB-Sub ============================
3572 current_module="vobsub";
3573 if (vobsub_name){
3574 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3575 if(vo_vobsub==NULL)
3576 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3577 filename_recode(vobsub_name));
3578 } else if (sub_auto && mpctx->filename){
3579 /* try to autodetect vobsub from movie filename ::atmos */
3580 char *buf = strdup(mpctx->filename), *psub;
3581 char *pdot = strrchr(buf, '.');
3582 char *pslash = strrchr(buf, '/');
3583 #if defined(__MINGW32__) || defined(__CYGWIN__)
3584 if (!pslash) pslash = strrchr(buf, '\\');
3585 #endif
3586 if (pdot && (!pslash || pdot > pslash))
3587 *pdot = '\0';
3588 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3589 /* try from ~/.mplayer/sub */
3590 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3591 char *bname;
3592 int l;
3593 bname = strrchr(buf,'/');
3594 #if defined(__MINGW32__) || defined(__CYGWIN__)
3595 if(!bname) bname = strrchr(buf,'\\');
3596 #endif
3597 if(bname) bname++;
3598 else bname = buf;
3599 l = strlen(psub) + strlen(bname) + 1;
3600 psub = realloc(psub,l);
3601 strcat(psub,bname);
3602 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3603 free(psub);
3605 free(buf);
3607 if(vo_vobsub){
3608 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3609 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3610 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3612 // setup global sub numbering
3613 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3616 //============ Open & Sync STREAM --- fork cache2 ====================
3618 mpctx->stream=NULL;
3619 mpctx->demuxer=NULL;
3620 if (mpctx->d_audio) {
3621 //free_demuxer_stream(mpctx->d_audio);
3622 mpctx->d_audio=NULL;
3624 if (mpctx->d_video) {
3625 //free_demuxer_stream(d_video);
3626 mpctx->d_video=NULL;
3628 mpctx->sh_audio=NULL;
3629 mpctx->sh_video=NULL;
3631 current_module="open_stream";
3632 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3633 if(!mpctx->stream) { // error...
3634 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3635 goto goto_next_file;
3637 mpctx->initialized_flags|=INITIALIZED_STREAM;
3639 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3640 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3641 "playlist support will not be used automatically.\n"
3642 "MPlayer's playlist code is unsafe and should only be used with "
3643 "trusted sources.\nPlayback will probably fail.\n\n");
3644 #if 0
3645 play_tree_t* entry;
3646 // Handle playlist
3647 current_module="handle_playlist";
3648 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3649 filename_recode(mpctx->filename));
3650 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3651 mpctx->eof=playtree_add_playlist(mpctx, entry);
3652 goto goto_next_file;
3653 #endif
3655 mpctx->stream->start_pos+=seek_to_byte;
3657 if(stream_dump_type==5){
3658 unsigned char buf[4096];
3659 int len;
3660 FILE *f;
3661 current_module="dumpstream";
3662 stream_reset(mpctx->stream);
3663 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3664 f=fopen(stream_dump_name,"wb");
3665 if(!f){
3666 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3667 exit_player(mpctx, EXIT_ERROR);
3669 if (opts->chapterrange[0] > 1) {
3670 int chapter = opts->chapterrange[0] - 1;
3671 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3673 while(!mpctx->stream->eof && !async_quit_request){
3674 len=stream_read(mpctx->stream,buf,4096);
3675 if(len>0) {
3676 if(fwrite(buf,len,1,f) != 1) {
3677 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3678 exit_player(mpctx, EXIT_ERROR);
3681 if (opts->chapterrange[1] > 0) {
3682 int chapter = -1;
3683 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3684 &chapter) == STREAM_OK
3685 && chapter + 1 > opts->chapterrange[1])
3686 break;
3689 if(fclose(f)) {
3690 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3691 exit_player(mpctx, EXIT_ERROR);
3693 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3694 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3697 #ifdef CONFIG_DVDREAD
3698 if(mpctx->stream->type==STREAMTYPE_DVD){
3699 current_module="dvd lang->id";
3700 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3701 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3702 // setup global sub numbering
3703 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3704 current_module=NULL;
3706 #endif
3708 #ifdef CONFIG_DVDNAV
3709 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3710 current_module="dvdnav lang->id";
3711 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3712 dvdsub_lang_id = -3;
3713 if(opts->sub_lang && opts->sub_id==-1)
3714 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3715 // setup global sub numbering
3716 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3717 current_module=NULL;
3719 #endif
3721 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3722 goto_enable_cache:
3723 if(stream_cache_size>0){
3724 int res;
3725 current_module="enable_cache";
3726 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3727 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3728 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3729 if(res == 0)
3730 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3733 //============ Open DEMUXERS --- DETECT file type =======================
3734 current_module="demux_open";
3736 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3738 // HACK to get MOV Reference Files working
3740 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3742 unsigned char* playlist_entry;
3743 play_tree_t *list = NULL, *entry = NULL;
3745 current_module="handle_demux_playlist";
3746 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3748 char *temp, *bname;
3750 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3751 filename_recode(playlist_entry));
3753 bname=mp_basename(playlist_entry);
3754 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3755 continue;
3757 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3758 continue;
3760 entry = play_tree_new();
3762 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3764 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3765 if (temp)
3767 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3768 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3769 strcat(temp, playlist_entry);
3770 if (!strcmp(temp, mpctx->filename)) {
3771 free(temp);
3772 continue;
3774 play_tree_add_file(entry,temp);
3775 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3776 free(temp);
3779 else
3780 play_tree_add_file(entry,playlist_entry);
3782 if(!list)
3783 list = entry;
3784 else
3785 play_tree_append_entry(list,entry);
3787 free_demuxer(mpctx->demuxer);
3788 mpctx->demuxer = NULL;
3790 if (list)
3792 entry = play_tree_new();
3793 play_tree_set_child(entry,list);
3794 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3795 goto goto_next_file;
3799 if(!mpctx->demuxer)
3800 goto goto_next_file;
3802 if (mpctx->demuxer->matroska_data.ordered_chapters)
3803 build_ordered_chapter_timeline(mpctx);
3805 if (!mpctx->sources) {
3806 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3807 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3808 .demuxer = mpctx->demuxer};
3809 mpctx->num_sources = 1;
3812 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3814 #ifdef CONFIG_ASS
3815 if (opts->ass_enabled && ass_library) {
3816 for (int j = 0; j < mpctx->num_sources; j++) {
3817 struct demuxer *d = mpctx->sources[j].demuxer;
3818 for (int i = 0; i < d->num_attachments; i++) {
3819 struct demux_attachment *att = d->attachments + i;
3820 if (use_embedded_fonts && attachment_is_font(att))
3821 ass_add_font(ass_library, att->name, att->data, att->data_size);
3825 #endif
3827 current_module="demux_open2";
3829 mpctx->d_audio=mpctx->demuxer->audio;
3830 mpctx->d_video=mpctx->demuxer->video;
3831 mpctx->d_sub=mpctx->demuxer->sub;
3833 if (ts_prog) {
3834 int tmp = ts_prog;
3835 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3837 // select audio stream
3838 if (mpctx->num_sources)
3839 for (int i = 0; i < mpctx->num_sources; i++)
3840 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3841 opts->audio_lang);
3842 else
3843 select_audio(mpctx->demuxer, opts->audio_id, opts->audio_lang);
3845 // DUMP STREAMS:
3846 if((stream_dump_type)&&(stream_dump_type<4)){
3847 FILE *f;
3848 demux_stream_t *ds=NULL;
3849 current_module="dump";
3850 // select stream to dump
3851 switch(stream_dump_type){
3852 case 1: ds=mpctx->d_audio;break;
3853 case 2: ds=mpctx->d_video;break;
3854 case 3: ds=mpctx->d_sub;break;
3856 if(!ds){
3857 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3858 exit_player(mpctx, EXIT_ERROR);
3860 // disable other streams:
3861 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3862 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3863 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3864 // let's dump it!
3865 f=fopen(stream_dump_name,"wb");
3866 if(!f){
3867 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3868 exit_player(mpctx, EXIT_ERROR);
3870 while(!ds->eof){
3871 unsigned char* start;
3872 int in_size=ds_get_packet(ds,&start);
3873 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3874 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3875 if(in_size>0) fwrite(start,in_size,1,f);
3876 if (opts->chapterrange[1] > 0) {
3877 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3878 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3879 break;
3882 fclose(f);
3883 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3884 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3887 mpctx->sh_audio=mpctx->d_audio->sh;
3888 mpctx->sh_video=mpctx->d_video->sh;
3890 if(mpctx->sh_video){
3892 current_module="video_read_properties";
3893 if(!video_read_properties(mpctx->sh_video)) {
3894 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3895 mpctx->sh_video=mpctx->d_video->sh=NULL;
3896 } else {
3897 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3898 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3899 mpctx->sh_video->fps,mpctx->sh_video->frametime
3902 /* need to set fps here for output encoders to pick it up in their init */
3903 if(force_fps){
3904 mpctx->sh_video->fps=force_fps;
3905 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3907 vo_fps = mpctx->sh_video->fps;
3909 if(!mpctx->sh_video->fps && !force_fps){
3910 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3911 mpctx->opts.correct_pts = 1;
3917 if(!mpctx->sh_video && !mpctx->sh_audio){
3918 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3919 #ifdef CONFIG_DVBIN
3920 if(mpctx->stream->type == STREAMTYPE_DVB)
3922 int dir;
3923 int v = mpctx->last_dvb_step;
3924 if(v > 0)
3925 dir = DVB_CHANNEL_HIGHER;
3926 else
3927 dir = DVB_CHANNEL_LOWER;
3929 if(dvb_step_channel(mpctx->stream, dir)) {
3930 mpctx->stop_play = PT_NEXT_ENTRY;
3931 mpctx->dvbin_reopen = 1;
3934 #endif
3935 goto goto_next_file; // exit_player(_("Fatal error"));
3938 /* display clip info */
3939 demux_info_print(mpctx->demuxer);
3941 //================== Read SUBTITLES (DVD & TEXT) ==========================
3942 if(vo_spudec==NULL &&
3943 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3944 init_vo_spudec(mpctx);
3947 // after reading video params we should load subtitles because
3948 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3949 // check .sub
3950 current_module="read_subtitles_file";
3951 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3952 if(sub_name){
3953 for (i = 0; sub_name[i] != NULL; ++i)
3954 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3956 if(sub_auto) { // auto load sub file ...
3957 char *psub = get_path( "sub/" );
3958 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3959 int i = 0;
3960 free(psub); // release the buffer created by get_path() above
3961 while (tmp[i]) {
3962 add_subtitles(mpctx, tmp[i], sub_fps, 1);
3963 free(tmp[i++]);
3965 free(tmp);
3967 if (mpctx->set_of_sub_size > 0)
3968 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
3970 if (select_subtitle(mpctx)) {
3971 if(subdata)
3972 switch (stream_dump_type) {
3973 case 3: list_sub_file(subdata); break;
3974 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3975 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3976 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3977 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3978 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3982 print_file_properties(mpctx, mpctx->filename);
3984 if(!mpctx->sh_video) goto main; // audio-only
3986 if(!reinit_video_chain(mpctx)) {
3987 if(!mpctx->sh_video){
3988 if(!mpctx->sh_audio) goto goto_next_file;
3989 goto main; // exit_player(_("Fatal error"));
3993 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
3994 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3996 #ifdef CONFIG_FREETYPE
3997 force_load_font = 1;
3998 #endif
4000 //================== MAIN: ==========================
4001 main:
4002 current_module="main";
4004 if(playing_msg) {
4005 char* msg = property_expand_string(mpctx, playing_msg);
4006 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4007 free(msg);
4011 // Disable the term OSD in verbose mode
4012 if(verbose) term_osd = 0;
4015 int frame_time_remaining=0; // flag
4016 int blit_frame=0;
4018 // Make sure old OSD does not stay around,
4019 // e.g. with -fixed-vo and same-resolution files
4020 clear_osd_msgs();
4021 update_osd_msg(mpctx);
4023 //================ SETUP AUDIO ==========================
4025 if(mpctx->sh_audio){
4026 reinit_audio_chain(mpctx);
4027 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4028 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4031 current_module="av_init";
4033 if(mpctx->sh_video){
4034 mpctx->sh_video->timer=0;
4035 if (! ignore_start)
4036 audio_delay += mpctx->sh_video->stream_delay;
4038 if(mpctx->sh_audio){
4039 if (start_volume >= 0)
4040 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4041 if (! ignore_start)
4042 audio_delay -= mpctx->sh_audio->stream_delay;
4043 mpctx->delay=-audio_delay;
4046 if(!mpctx->sh_audio){
4047 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4048 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4049 ds_free_packs(mpctx->d_audio); // free buffered chunks
4050 //mpctx->d_audio->id=-2; // do not read audio chunks
4051 //uninit_player(mpctx, INITIALIZED_AO); // close device
4053 if(!mpctx->sh_video){
4054 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4055 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4056 ds_free_packs(mpctx->d_video);
4057 mpctx->d_video->id=-2;
4058 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4061 if (!mpctx->sh_video && !mpctx->sh_audio)
4062 goto goto_next_file;
4064 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4065 if(force_fps && mpctx->sh_video){
4066 vo_fps = mpctx->sh_video->fps=force_fps;
4067 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4068 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4071 mp_input_set_section(mpctx->input, NULL);
4072 //TODO: add desired (stream-based) sections here
4073 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4074 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4076 //==================== START PLAYING =======================
4078 if(opts->loop_times>1) opts->loop_times--; else
4079 if(opts->loop_times==1) opts->loop_times = -1;
4081 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4083 total_time_usage_start=GetTimer();
4084 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4085 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4086 play_n_frames=play_n_frames_mf;
4088 if(play_n_frames==0){
4089 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4092 // If there's a timeline force an absolute seek to initialize state
4093 if (seek_to_sec || mpctx->timeline) {
4094 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4095 end_at.pos += seek_to_sec;
4097 if (opts->chapterrange[0] > 0) {
4098 double pts;
4099 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4100 && pts > -1.0)
4101 seek(mpctx, pts, SEEK_ABSOLUTE);
4104 if (end_at.type == END_AT_SIZE) {
4105 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4106 end_at.type = END_AT_NONE;
4109 #ifdef CONFIG_DVDNAV
4110 mp_dvdnav_context_free(mpctx);
4111 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4112 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4113 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4115 #endif
4117 get_relative_time(mpctx); // reset current delta
4118 mpctx->time_frame = 0;
4119 mpctx->drop_message_shown = 0;
4120 mpctx->update_video_immediately = true;
4121 mpctx->total_avsync_change = 0;
4122 mpctx->last_chapter_seek = -1;
4123 // Make sure VO knows current pause state
4124 if (mpctx->sh_video)
4125 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4126 NULL);
4128 while(!mpctx->stop_play){
4129 float aq_sleep_time=0;
4131 if (opts->chapterrange[1] > 0) {
4132 int cur_chapter = get_current_chapter(mpctx);
4133 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4134 goto goto_next_file;
4137 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4138 mpctx->sh_audio = mpctx->d_audio->sh;
4139 mpctx->sh_audio->ds = mpctx->d_audio;
4140 reinit_audio_chain(mpctx);
4143 /*========================== PLAY AUDIO ============================*/
4145 if (mpctx->sh_audio && !mpctx->paused)
4146 if (!fill_audio_out_buffers(mpctx))
4147 // at eof, all audio at least written to ao
4148 if (!mpctx->sh_video)
4149 mpctx->stop_play = AT_END_OF_FILE;
4152 if(!mpctx->sh_video) {
4153 // handle audio-only case:
4154 double a_pos=0;
4155 // sh_audio can be NULL due to video stream switching
4156 // TODO: handle this better
4157 if (mpctx->sh_audio)
4158 a_pos = playing_audio_pts(mpctx);
4160 print_status(mpctx, a_pos, false);
4162 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4163 mpctx->stop_play = PT_NEXT_ENTRY;
4164 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4165 mpctx->d_sub, 0);
4166 update_osd_msg(mpctx);
4168 } else {
4170 /*========================== PLAY VIDEO ============================*/
4172 vo_pts=mpctx->sh_video->timer*90000.0;
4173 vo_fps=mpctx->sh_video->fps;
4175 blit_frame = mpctx->video_out->frame_loaded;
4176 if (!blit_frame) {
4177 double frame_time = update_video(mpctx);
4178 blit_frame = mpctx->video_out->frame_loaded;
4179 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4180 if (mpctx->sh_video->vf_initialized < 0) {
4181 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4182 mpctx->stop_play = PT_NEXT_ENTRY;
4183 goto goto_next_file;
4185 if (blit_frame) {
4186 struct sh_video *sh_video = mpctx->sh_video;
4187 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4188 mpctx->video_offset, mpctx->d_sub, 0);
4189 update_teletext(sh_video, mpctx->demuxer, 0);
4190 update_osd_msg(mpctx);
4191 struct vf_instance *vf = mpctx->sh_video->vfilter;
4192 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4193 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4194 vo_osd_changed(0);
4196 if (frame_time < 0)
4197 mpctx->stop_play = AT_END_OF_FILE;
4198 else {
4199 if (mpctx->update_video_immediately) {
4200 // Show this frame immediately, rest normally
4201 mpctx->update_video_immediately = false;
4202 } else {
4203 mpctx->time_frame += frame_time / opts->playback_speed;
4204 adjust_sync(mpctx, frame_time);
4208 if (mpctx->timeline) {
4209 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4210 if (mpctx->sh_video->pts >= next->start
4211 || mpctx->stop_play == AT_END_OF_FILE
4212 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4213 seek(mpctx, next->start, SEEK_ABSOLUTE);
4214 continue;
4218 // ==========================================================================
4220 // current_module="draw_osd";
4221 // if(vo_config_count) mpctx->video_out->draw_osd();
4223 current_module="vo_check_events";
4224 vo_check_events(mpctx->video_out);
4226 #ifdef CONFIG_X11
4227 if (stop_xscreensaver) {
4228 current_module = "stop_xscreensaver";
4229 xscreensaver_heartbeat(mpctx->x11_state);
4231 #endif
4232 if (heartbeat_cmd) {
4233 static unsigned last_heartbeat;
4234 unsigned now = GetTimerMS();
4235 if (now - last_heartbeat > 30000) {
4236 last_heartbeat = now;
4237 system(heartbeat_cmd);
4241 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4243 //====================== FLIP PAGE (VIDEO BLT): =========================
4245 current_module="flip_page";
4246 if (!frame_time_remaining && blit_frame) {
4247 unsigned int t2=GetTimer();
4248 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4249 int duration = -1;
4250 double pts2 = mpctx->video_out->next_pts2;
4251 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4252 // expected A/V sync correction is ignored
4253 double diff = (pts2 - mpctx->sh_video->pts);
4254 diff /= opts->playback_speed;
4255 if (mpctx->time_frame < 0)
4256 diff += mpctx->time_frame;
4257 if (diff < 0)
4258 diff = 0;
4259 if (diff > 10)
4260 diff = 10;
4261 duration = diff * 1e6;
4263 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4265 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4266 vout_time_usage += mpctx->last_vo_flip_duration;
4267 if (mpctx->video_out->driver->flip_page_timed) {
4268 // No need to adjust sync based on flip speed
4269 mpctx->last_vo_flip_duration = 0;
4270 // For print_status - VO call finishing early is OK for sync
4271 mpctx->time_frame -= get_relative_time(mpctx);
4273 print_status(mpctx, MP_NOPTS_VALUE, true);
4275 else
4276 print_status(mpctx, MP_NOPTS_VALUE, false);
4278 //============================ Auto QUALITY ============================
4280 /*Output quality adjustments:*/
4281 if(auto_quality>0){
4282 current_module="autoq";
4283 // float total=0.000001f * (GetTimer()-aq_total_time);
4284 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4285 if(output_quality<auto_quality && aq_sleep_time>0)
4286 ++output_quality;
4287 else
4288 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4289 if(output_quality>1 && aq_sleep_time<0)
4290 --output_quality;
4291 else
4292 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4293 output_quality=0;
4294 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4295 set_video_quality(mpctx->sh_video,output_quality);
4298 if (!frame_time_remaining && blit_frame) {
4299 if (play_n_frames >= 0) {
4300 --play_n_frames;
4301 if (play_n_frames <= 0)
4302 mpctx->stop_play = PT_NEXT_ENTRY;
4304 if (mpctx->step_frames > 0) {
4305 mpctx->step_frames--;
4306 if (mpctx->step_frames == 0)
4307 pause_player(mpctx);
4312 // FIXME: add size based support for -endpos
4313 if (end_at.type == END_AT_TIME &&
4314 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4315 mpctx->stop_play = PT_NEXT_ENTRY;
4317 } // end if(mpctx->sh_video)
4319 #ifdef CONFIG_DVDNAV
4320 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4321 nav_highlight_t hl;
4322 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4323 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4324 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4325 vo_osd_changed (OSDTYPE_DVDNAV);
4326 } else {
4327 osd_set_nav_box(0, 0, 0, 0);
4328 vo_osd_changed(OSDTYPE_DVDNAV);
4329 vo_osd_changed(OSDTYPE_SPU);
4332 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4333 double ar = -1.0;
4334 if (mpctx->sh_video &&
4335 stream_control (mpctx->demuxer->stream,
4336 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4337 != STREAM_UNSUPPORTED)
4338 mpctx->sh_video->stream_aspect = ar;
4341 #endif
4343 //================= Keyboard events, SEEKing ====================
4345 current_module="key_events";
4348 while (1) {
4349 mp_cmd_t* cmd;
4350 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4351 run_command(mpctx, cmd);
4352 mp_cmd_free(cmd);
4353 if (mpctx->stop_play)
4354 break;
4355 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4356 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4357 /* Allow seek commands to be combined, but execute the real seek
4358 * before processing other commands */
4359 if (!cmd || cmd->id != MP_CMD_SEEK)
4360 break;
4363 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4364 || mpctx->abs_seek_pos)
4365 break;
4366 if (mpctx->sh_video) {
4367 update_osd_msg(mpctx);
4368 int hack = vo_osd_changed(0);
4369 vo_osd_changed(hack);
4370 if (hack) {
4371 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4372 add_step_frame(mpctx);
4373 break;
4375 else
4376 vo_osd_changed(0);
4379 pause_loop(mpctx);
4383 // handle -sstep
4384 if (step_sec > 0 && !mpctx->paused) {
4385 mpctx->osd_function=OSD_FFW;
4386 mpctx->rel_seek_secs+=step_sec;
4389 edl_update(mpctx);
4391 /* Looping. */
4392 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4393 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4395 if(opts->loop_times>1) opts->loop_times--; else
4396 if(opts->loop_times==1) opts->loop_times=-1;
4397 play_n_frames=play_n_frames_mf;
4398 mpctx->stop_play=0;
4399 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4402 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4403 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4405 mpctx->rel_seek_secs=0;
4406 mpctx->abs_seek_pos=0;
4409 } // while(!mpctx->stop_play)
4411 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4413 #ifdef CONFIG_DVBIN
4414 if(mpctx->dvbin_reopen)
4416 mpctx->stop_play = 0;
4417 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4418 cache_uninit(mpctx->stream);
4419 mpctx->dvbin_reopen = 0;
4420 goto goto_enable_cache;
4422 #endif
4425 goto_next_file: // don't jump here after ao/vo/getch initialization!
4427 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4429 if(benchmark){
4430 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4431 double total_time_usage;
4432 total_time_usage_start=GetTimer()-total_time_usage_start;
4433 total_time_usage = (float)total_time_usage_start*0.000001;
4434 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4435 video_time_usage,vout_time_usage,audio_time_usage,
4436 total_time_usage-tot,total_time_usage);
4437 if(total_time_usage>0.0)
4438 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4439 100.0*video_time_usage/total_time_usage,
4440 100.0*vout_time_usage/total_time_usage,
4441 100.0*audio_time_usage/total_time_usage,
4442 100.0*(total_time_usage-tot)/total_time_usage,
4443 100.0);
4444 if(total_frame_cnt && frame_dropping)
4445 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4446 total_frame_cnt-drop_frame_cnt,
4447 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4448 drop_frame_cnt,
4449 100*drop_frame_cnt/total_frame_cnt,
4450 total_frame_cnt,
4451 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4454 // time to uninit all, except global stuff:
4455 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4457 if(mpctx->set_of_sub_size > 0) {
4458 current_module="sub_free";
4459 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4460 sub_free(mpctx->set_of_subtitles[i]);
4461 #ifdef CONFIG_ASS
4462 if(mpctx->set_of_ass_tracks[i])
4463 ass_free_track( mpctx->set_of_ass_tracks[i] );
4464 #endif
4466 mpctx->set_of_sub_size = 0;
4468 vo_sub_last = vo_sub=NULL;
4469 subdata=NULL;
4470 #ifdef CONFIG_ASS
4471 ass_track = NULL;
4472 if(ass_library)
4473 ass_clear_fonts(ass_library);
4474 #endif
4476 if (!mpctx->stop_play) // In case some goto jumped here...
4477 mpctx->stop_play = PT_NEXT_ENTRY;
4479 int playtree_direction = 1;
4481 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4482 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4483 play_tree_iter_free(mpctx->playtree_iter);
4484 mpctx->playtree_iter = NULL;
4486 mpctx->play_tree_step = 1;
4487 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4488 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4489 if(mpctx->playtree_iter) {
4490 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4491 play_tree_iter_free(mpctx->playtree_iter);
4492 mpctx->playtree_iter = NULL;
4495 } else if (mpctx->stop_play == PT_STOP) {
4496 play_tree_iter_free(mpctx->playtree_iter);
4497 mpctx->playtree_iter = NULL;
4498 } else { // NEXT PREV SRC
4499 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4502 while(mpctx->playtree_iter != NULL) {
4503 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4504 if(mpctx->filename == NULL) {
4505 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4506 play_tree_iter_free(mpctx->playtree_iter);
4507 mpctx->playtree_iter = NULL;
4509 } else
4510 break;
4513 if(mpctx->playtree_iter != NULL || player_idle_mode){
4514 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4515 mpctx->stop_play = 0;
4516 goto play_next_file;
4520 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4522 return 1;
4524 #endif /* DISABLE_MAIN */