audio: auto-add downmix filter when stereo output is requested
[mplayer/greg.git] / mplayer.c
blob1fda090641b368baac689c3726579e05940f2545
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 /*DSP!!char *dsp=NULL;*/
355 int subcc_enabled=0;
356 int suboverlap_enabled = 1;
358 #include "ass_mp.h"
360 char* current_module=NULL; // for debugging
363 // ---
365 #ifdef CONFIG_MENU
366 #include "m_struct.h"
367 #include "libmenu/menu.h"
368 static const vf_info_t* const libmenu_vfs[] = {
369 &vf_info_menu,
370 NULL
372 static vf_instance_t* vf_menu = NULL;
373 int use_menu = 0;
374 static char* menu_cfg = NULL;
375 static char* menu_root = "main";
376 #endif
379 #ifdef HAVE_RTC
380 static int nortc = 1;
381 static char* rtc_device;
382 #endif
384 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
385 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
386 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
387 int use_filedir_conf;
388 int use_filename_title;
390 #include "mpcommon.h"
391 #include "command.h"
393 #include "metadata.h"
395 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
397 const void *mpctx_get_video_out(MPContext *mpctx)
399 return mpctx->video_out;
402 const void *mpctx_get_audio_out(MPContext *mpctx)
404 return mpctx->audio_out;
407 void *mpctx_get_demuxer(MPContext *mpctx)
409 return mpctx->demuxer;
412 void *mpctx_get_playtree_iter(MPContext *mpctx)
414 return mpctx->playtree_iter;
417 void *mpctx_get_mixer(MPContext *mpctx)
419 return &mpctx->mixer;
422 int mpctx_get_global_sub_size(MPContext *mpctx)
424 return mpctx->global_sub_size;
427 int mpctx_get_osd_function(MPContext *mpctx)
429 return mpctx->osd_function;
432 static float get_relative_time(struct MPContext *mpctx)
434 unsigned int new_time = GetTimer();
435 unsigned int delta = new_time - mpctx->last_time;
436 mpctx->last_time = new_time;
437 return delta * 0.000001;
440 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
441 switch (type)
443 /* check for valid video stream */
444 case META_VIDEO_CODEC:
445 case META_VIDEO_BITRATE:
446 case META_VIDEO_RESOLUTION:
448 if (!mpctx->sh_video)
449 return 0;
450 break;
453 /* check for valid audio stream */
454 case META_AUDIO_CODEC:
455 case META_AUDIO_BITRATE:
456 case META_AUDIO_SAMPLES:
458 if (!mpctx->sh_audio)
459 return 0;
460 break;
463 /* check for valid demuxer */
464 case META_INFO_TITLE:
465 case META_INFO_ARTIST:
466 case META_INFO_ALBUM:
467 case META_INFO_YEAR:
468 case META_INFO_COMMENT:
469 case META_INFO_TRACK:
470 case META_INFO_GENRE:
472 if (!mpctx->demuxer)
473 return 0;
474 break;
477 default:
478 break;
481 return 1;
484 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
485 char **info = mpctx->demuxer->info;
486 int n;
488 if (!info || !tag)
489 return NULL;
491 for (n = 0; info[2*n] != NULL ; n++)
492 if (!strcasecmp (info[2*n], tag))
493 break;
495 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
498 char *get_metadata(struct MPContext *mpctx, metadata_t type)
500 char *meta = NULL;
501 sh_audio_t * const sh_audio = mpctx->sh_audio;
502 sh_video_t * const sh_video = mpctx->sh_video;
504 if (!is_valid_metadata_type(mpctx, type))
505 return NULL;
507 switch (type)
509 case META_NAME:
511 return strdup (mp_basename2 (mpctx->filename));
514 case META_VIDEO_CODEC:
516 if (sh_video->format == 0x10000001)
517 meta = strdup ("mpeg1");
518 else if (sh_video->format == 0x10000002)
519 meta = strdup ("mpeg2");
520 else if (sh_video->format == 0x10000004)
521 meta = strdup ("mpeg4");
522 else if (sh_video->format == 0x10000005)
523 meta = strdup ("h264");
524 else if (sh_video->format >= 0x20202020)
526 meta = malloc (8);
527 sprintf (meta, "%.4s", (char *) &sh_video->format);
529 else
531 meta = malloc (8);
532 sprintf (meta, "0x%08X", sh_video->format);
534 return meta;
537 case META_VIDEO_BITRATE:
539 meta = malloc (16);
540 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
541 return meta;
544 case META_VIDEO_RESOLUTION:
546 meta = malloc (16);
547 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
548 return meta;
551 case META_AUDIO_CODEC:
553 if (sh_audio->codec && sh_audio->codec->name)
554 meta = strdup (sh_audio->codec->name);
555 return meta;
558 case META_AUDIO_BITRATE:
560 meta = malloc (16);
561 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
562 return meta;
565 case META_AUDIO_SAMPLES:
567 meta = malloc (16);
568 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
569 return meta;
572 /* check for valid demuxer */
573 case META_INFO_TITLE:
574 return get_demuxer_info(mpctx, "Title");
576 case META_INFO_ARTIST:
577 return get_demuxer_info(mpctx, "Artist");
579 case META_INFO_ALBUM:
580 return get_demuxer_info(mpctx, "Album");
582 case META_INFO_YEAR:
583 return get_demuxer_info(mpctx, "Year");
585 case META_INFO_COMMENT:
586 return get_demuxer_info(mpctx, "Comment");
588 case META_INFO_TRACK:
589 return get_demuxer_info(mpctx, "Track");
591 case META_INFO_GENRE:
592 return get_demuxer_info(mpctx, "Genre");
594 default:
595 break;
598 return meta;
601 static void print_file_properties(const MPContext *mpctx, const char *filename)
603 double start_pts = MP_NOPTS_VALUE;
604 double video_start_pts = MP_NOPTS_VALUE;
605 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
606 filename_recode(filename));
607 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
608 if (mpctx->sh_video) {
609 /* Assume FOURCC if all bytes >= 0x20 (' ') */
610 if (mpctx->sh_video->format >= 0x20202020)
611 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
612 else
613 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
614 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
615 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
616 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
617 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
618 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
619 video_start_pts = ds_get_next_pts(mpctx->d_video);
621 if (mpctx->sh_audio) {
622 /* Assume FOURCC if all bytes >= 0x20 (' ') */
623 if (mpctx->sh_audio->format >= 0x20202020)
624 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
625 else
626 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
627 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
628 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
629 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
630 start_pts = ds_get_next_pts(mpctx->d_audio);
632 if (video_start_pts != MP_NOPTS_VALUE) {
633 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
634 (mpctx->sh_video && video_start_pts < start_pts))
635 start_pts = video_start_pts;
637 if (start_pts != MP_NOPTS_VALUE)
638 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
639 else
640 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
641 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", mpctx->timeline ?
642 mpctx->timeline[mpctx->num_timeline_parts].start :
643 demuxer_get_time_length(mpctx->demuxer));
644 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
645 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
646 if (mpctx->demuxer) {
647 if (mpctx->demuxer->num_chapters == 0)
648 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
649 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
653 /// step size of mixer changes
654 int volstep = 3;
656 #ifdef CONFIG_DVDNAV
657 static void mp_dvdnav_context_free(MPContext *ctx){
658 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
659 ctx->nav_smpi = NULL;
660 if (ctx->nav_buffer) free(ctx->nav_buffer);
661 ctx->nav_buffer = NULL;
662 ctx->nav_start = NULL;
663 ctx->nav_in_size = 0;
665 #endif
667 void uninit_player(struct MPContext *mpctx, unsigned int mask){
668 mask &= mpctx->initialized_flags;
670 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
672 if(mask&INITIALIZED_ACODEC){
673 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
674 current_module="uninit_acodec";
675 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
676 mpctx->sh_audio=NULL;
677 mpctx->mixer.afilter = NULL;
680 if(mask&INITIALIZED_VCODEC){
681 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
682 current_module="uninit_vcodec";
683 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
684 mpctx->sh_video=NULL;
685 #ifdef CONFIG_MENU
686 vf_menu=NULL;
687 #endif
690 if(mask&INITIALIZED_DEMUXER){
691 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
692 current_module="free_demuxer";
693 if (mpctx->num_sources) {
694 mpctx->demuxer = mpctx->sources[0].demuxer;
695 for (int i = 1; i < mpctx->num_sources; i++) {
696 free_stream(mpctx->sources[i].stream);
697 free_demuxer(mpctx->sources[i].demuxer);
700 talloc_free(mpctx->sources);
701 mpctx->sources = NULL;
702 mpctx->num_sources = 0;
703 talloc_free(mpctx->timeline);
704 mpctx->timeline = NULL;
705 mpctx->num_timeline_parts = 0;
706 talloc_free(mpctx->chapters);
707 mpctx->chapters = NULL;
708 mpctx->num_chapters = 0;
709 mpctx->video_offset = 0;
710 if(mpctx->demuxer){
711 mpctx->stream=mpctx->demuxer->stream;
712 free_demuxer(mpctx->demuxer);
714 mpctx->demuxer=NULL;
717 // kill the cache process:
718 if(mask&INITIALIZED_STREAM){
719 mpctx->initialized_flags&=~INITIALIZED_STREAM;
720 current_module="uninit_stream";
721 if(mpctx->stream) free_stream(mpctx->stream);
722 mpctx->stream=NULL;
725 if(mask&INITIALIZED_VO){
726 mpctx->initialized_flags&=~INITIALIZED_VO;
727 current_module="uninit_vo";
728 vo_destroy(mpctx->video_out);
729 mpctx->video_out=NULL;
730 #ifdef CONFIG_DVDNAV
731 mp_dvdnav_context_free(mpctx);
732 #endif
735 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
736 if(mask&INITIALIZED_GETCH2){
737 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
738 current_module="uninit_getch2";
739 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
740 // restore terminal:
741 getch2_disable();
744 if(mask&INITIALIZED_VOBSUB){
745 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
746 current_module="uninit_vobsub";
747 if(vo_vobsub) vobsub_close(vo_vobsub);
748 vo_vobsub=NULL;
751 if (mask&INITIALIZED_SPUDEC){
752 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
753 current_module="uninit_spudec";
754 spudec_free(vo_spudec);
755 vo_spudec=NULL;
758 if(mask&INITIALIZED_AO){
759 mpctx->initialized_flags&=~INITIALIZED_AO;
760 current_module="uninit_ao";
761 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
762 if (mpctx->audio_out)
763 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
764 mpctx->audio_out=NULL;
767 current_module=NULL;
770 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
772 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
773 uninit_player(mpctx, INITIALIZED_ALL);
774 #if defined(__MINGW32__) || defined(__CYGWIN__)
775 timeEndPeriod(1);
776 #endif
777 #ifdef CONFIG_X11
778 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
779 #endif
781 current_module="uninit_input";
782 mp_input_uninit(mpctx->input);
783 #ifdef CONFIG_MENU
784 if (use_menu)
785 menu_uninit();
786 #endif
788 #ifdef CONFIG_FREETYPE
789 current_module="uninit_font";
790 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
791 free_font_desc(mpctx->osd->sub_font);
792 free_font_desc(vo_font);
793 vo_font = NULL;
794 done_freetype();
795 #endif
796 osd_free(mpctx->osd);
798 #ifdef CONFIG_ASS
799 ass_library_done(ass_library);
800 ass_library = NULL;
801 #endif
803 current_module="exit_player";
805 // free mplayer config
806 if(mpctx->mconfig)
807 m_config_free(mpctx->mconfig);
808 mpctx->mconfig = NULL;
810 if(mpctx->playtree_iter)
811 play_tree_iter_free(mpctx->playtree_iter);
812 mpctx->playtree_iter = NULL;
813 if(mpctx->playtree)
814 play_tree_free(mpctx->playtree, 1);
815 mpctx->playtree = NULL;
817 talloc_free(mpctx->key_fifo);
819 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
820 edl_records = NULL;
821 switch(how) {
822 case EXIT_QUIT:
823 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
824 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
825 break;
826 case EXIT_EOF:
827 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
828 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
829 break;
830 case EXIT_ERROR:
831 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
832 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
833 break;
834 default:
835 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
837 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
839 exit(rc);
842 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
844 exit_player_with_rc(mpctx, how, 1);
847 #ifndef __MINGW32__
848 static void child_sighandler(int x){
849 pid_t pid;
850 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
852 #endif
854 #ifdef CONFIG_CRASH_DEBUG
855 static char *prog_path;
856 static int crash_debug = 0;
857 #endif
859 static void exit_sighandler(int x){
860 static int sig_count=0;
861 #ifdef CONFIG_CRASH_DEBUG
862 if (!crash_debug || x != SIGTRAP)
863 #endif
864 ++sig_count;
865 if(sig_count==5)
867 /* We're crashing bad and can't uninit cleanly :(
868 * by popular request, we make one last (dirty)
869 * effort to restore the user's
870 * terminal. */
871 getch2_disable();
872 exit(1);
874 if(sig_count==6) exit(1);
875 if(sig_count>6){
876 // can't stop :(
877 #ifndef __MINGW32__
878 kill(getpid(),SIGKILL);
879 #endif
881 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
882 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
883 "\nMPlayer interrupted by signal %d in module: %s\n", x,
884 current_module ? current_module : "unknown");
885 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
886 if(sig_count<=1)
887 switch(x){
888 case SIGINT:
889 case SIGPIPE:
890 case SIGQUIT:
891 case SIGTERM:
892 case SIGKILL:
893 async_quit_request = 1;
894 return; // killed from keyboard (^C) or killed [-9]
895 case SIGILL:
896 #if CONFIG_RUNTIME_CPUDETECT
897 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
898 #else
899 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
900 #endif
901 case SIGFPE:
902 case SIGSEGV:
903 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
904 default:
905 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
906 #ifdef CONFIG_CRASH_DEBUG
907 if (crash_debug) {
908 int gdb_pid;
909 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
910 gdb_pid = fork();
911 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
912 if (gdb_pid == 0) { // We are the child
913 char spid[20];
914 snprintf(spid, sizeof(spid), "%i", getppid());
915 getch2_disable(); // allow terminal to work properly with gdb
916 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
917 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
918 } else if (gdb_pid < 0)
919 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
920 else {
921 waitpid(gdb_pid, NULL, 0);
923 if (x == SIGTRAP) return;
925 #endif
927 getch2_disable();
928 exit(1);
931 #include "cfg-mplayer.h"
933 static int cfg_include(m_option_t *conf, char *filename)
935 return m_config_parse_config_file(conf->priv, filename);
938 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
940 char *conffile;
941 int conffile_fd;
942 if (!disable_system_conf &&
943 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
944 exit_player(mpctx, EXIT_NONE);
945 if ((conffile = get_path("")) == NULL) {
946 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
947 } else {
948 #ifdef __MINGW32__
949 mkdir(conffile);
950 #else
951 mkdir(conffile, 0777);
952 #endif
953 free(conffile);
954 if ((conffile = get_path("config")) == NULL) {
955 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
956 } else {
957 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
958 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
959 write(conffile_fd, default_config, strlen(default_config));
960 close(conffile_fd);
962 if (!disable_user_conf &&
963 m_config_parse_config_file(conf, conffile) < 0)
964 exit_player(mpctx, EXIT_NONE);
965 free(conffile);
970 #define PROFILE_CFG_PROTOCOL "protocol."
972 static void load_per_protocol_config (m_config_t* conf, const char *const file)
974 char *str;
975 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
976 m_profile_t *p;
978 /* does filename actually uses a protocol ? */
979 str = strstr (file, "://");
980 if (!str)
981 return;
983 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
984 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
985 p = m_config_get_profile (conf, protocol);
986 if (p)
988 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
989 m_config_set_profile(conf,p);
993 #define PROFILE_CFG_EXTENSION "extension."
995 static void load_per_extension_config (m_config_t* conf, const char *const file)
997 char *str;
998 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
999 m_profile_t *p;
1001 /* does filename actually have an extension ? */
1002 str = strrchr (file, '.');
1003 if (!str)
1004 return;
1006 sprintf (extension, PROFILE_CFG_EXTENSION);
1007 strncat (extension, ++str, 7);
1008 p = m_config_get_profile (conf, extension);
1009 if (p)
1011 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
1012 m_config_set_profile(conf,p);
1016 #define PROFILE_CFG_VO "vo."
1017 #define PROFILE_CFG_AO "ao."
1019 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
1021 char profile[strlen (cfg) + strlen (out) + 1];
1022 m_profile_t *p;
1024 sprintf (profile, "%s%s", cfg, out);
1025 p = m_config_get_profile (conf, profile);
1026 if (p)
1028 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
1029 m_config_set_profile(conf,p);
1034 * Tries to load a config file
1035 * @return 0 if file was not found, 1 otherwise
1037 static int try_load_config(m_config_t *conf, const char *file)
1039 struct stat st;
1040 if (stat(file, &st))
1041 return 0;
1042 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1043 m_config_parse_config_file (conf, file);
1044 return 1;
1047 static void load_per_file_config (m_config_t* conf, const char *const file)
1049 char *confpath;
1050 char cfg[PATH_MAX];
1051 char *name;
1053 if (strlen(file) > PATH_MAX - 14) {
1054 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1055 return;
1057 sprintf (cfg, "%s.conf", file);
1059 name = strrchr(cfg, '/');
1060 if (HAVE_DOS_PATHS) {
1061 char *tmp = strrchr(cfg, '\\');
1062 if (!name || tmp > name)
1063 name = tmp;
1064 tmp = strrchr(cfg, ':');
1065 if (!name || tmp > name)
1066 name = tmp;
1068 if (!name)
1069 name = cfg;
1070 else
1071 name++;
1073 if (use_filedir_conf) {
1074 char dircfg[PATH_MAX];
1075 strcpy(dircfg, cfg);
1076 strcpy(dircfg + (name - cfg), "mplayer.conf");
1077 try_load_config(conf, dircfg);
1079 if (try_load_config(conf, cfg))
1080 return;
1083 if ((confpath = get_path (name)) != NULL)
1085 try_load_config(conf, confpath);
1087 free (confpath);
1091 /* When libmpdemux performs a blocking operation (network connection or
1092 * cache filling) if the operation fails we use this function to check
1093 * if it was interrupted by the user.
1094 * The function returns a new value for eof. */
1095 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1097 mp_cmd_t* cmd;
1098 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1099 switch(cmd->id) {
1100 case MP_CMD_QUIT:
1101 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1102 case MP_CMD_PLAY_TREE_STEP: {
1103 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1104 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1105 } break;
1106 case MP_CMD_PLAY_TREE_UP_STEP: {
1107 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1108 } break;
1109 case MP_CMD_PLAY_ALT_SRC_STEP: {
1110 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1111 } break;
1113 mp_cmd_free(cmd);
1115 return stop_play;
1118 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1120 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1122 play_tree_add_bpf(entry,mpctx->filename);
1125 if(!entry) {
1126 entry = mpctx->playtree_iter->tree;
1127 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1128 return PT_NEXT_ENTRY;
1130 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1131 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1132 return PT_NEXT_ENTRY;
1135 play_tree_remove(entry,1,1);
1136 return PT_NEXT_SRC;
1138 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1139 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1140 entry = mpctx->playtree_iter->tree;
1141 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1142 return PT_NEXT_ENTRY;
1144 play_tree_remove(entry,1,1);
1146 return PT_NEXT_SRC;
1149 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1151 struct MPOpts *opts = &mpctx->opts;
1152 sub_data *subd = NULL;
1153 struct ass_track *asst = NULL;
1155 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1156 return;
1159 #ifdef CONFIG_ASS
1160 if (opts->ass_enabled) {
1161 #ifdef CONFIG_ICONV
1162 asst = ass_read_stream(ass_library, filename, sub_cp);
1163 #else
1164 asst = ass_read_stream(ass_library, filename, 0);
1165 #endif
1166 if (!asst) {
1167 subd = sub_read_file(filename, fps);
1168 if (subd) {
1169 asst = ass_read_subdata(ass_library, subd, fps);
1170 if (asst) {
1171 sub_free(subd);
1172 subd = NULL;
1176 } else
1177 #endif
1178 subd = sub_read_file(filename, fps);
1181 if (!asst && !subd) {
1182 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1183 "Cannot load subtitles: %s\n", filename_recode(filename));
1184 return;
1187 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1188 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1189 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1190 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1191 filename_recode(filename));
1192 ++mpctx->set_of_sub_size;
1193 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1194 filename_recode(filename));
1197 void init_vo_spudec(struct MPContext *mpctx)
1199 if (vo_spudec)
1200 spudec_free(vo_spudec);
1201 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1202 vo_spudec = NULL;
1204 // we currently can't work without video stream
1205 if (!mpctx->sh_video)
1206 return;
1208 if (spudec_ifo) {
1209 unsigned int palette[16], width, height;
1210 current_module="spudec_init_vobsub";
1211 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1212 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1215 #ifdef CONFIG_DVDREAD
1216 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1217 current_module="spudec_init_dvdread";
1218 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1219 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1220 NULL, 0);
1222 #endif
1224 #ifdef CONFIG_DVDNAV
1225 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1226 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1227 current_module="spudec_init_dvdnav";
1228 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1230 #endif
1232 if (vo_spudec==NULL) {
1233 sh_sub_t *sh = mpctx->d_sub->sh;
1234 current_module="spudec_init_normal";
1235 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1236 spudec_set_font_factor(vo_spudec,font_factor);
1239 if (vo_spudec!=NULL) {
1240 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1241 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1246 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1247 * make it all work is to use the builtin SDL-bootstrap code, which
1248 * will be done automatically by replacing our main() if we include SDL.h.
1250 #if defined(__APPLE__) && defined(CONFIG_SDL)
1251 #ifdef CONFIG_SDL_SDL_H
1252 #include <SDL/SDL.h>
1253 #else
1254 #include <SDL.h>
1255 #endif
1256 #endif
1259 * \brief append a formatted string
1260 * \param buf buffer to print into
1261 * \param pos position of terminating 0 in buf
1262 * \param len maximum number of characters in buf, not including terminating 0
1263 * \param format printf format string
1265 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1267 va_list va;
1268 va_start(va, format);
1269 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1270 va_end(va);
1271 if (*pos >= len ) {
1272 buf[len] = 0;
1273 *pos = len;
1278 * \brief append time in the hh:mm:ss.f format
1279 * \param buf buffer to print into
1280 * \param pos position of terminating 0 in buf
1281 * \param len maximum number of characters in buf, not including terminating 0
1282 * \param time time value to convert/append
1284 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1285 int64_t tenths = 10 * time;
1286 int f1 = tenths % 10;
1287 int ss = (tenths / 10) % 60;
1288 int mm = (tenths / 600) % 60;
1289 int hh = tenths / 36000;
1290 if (time <= 0) {
1291 saddf(buf, pos, len, "unknown");
1292 return;
1294 if (hh > 0)
1295 saddf(buf, pos, len, "%2d:", hh);
1296 if (hh > 0 || mm > 0)
1297 saddf(buf, pos, len, "%02d:", mm);
1298 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1301 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1303 struct MPOpts *opts = &mpctx->opts;
1304 sh_video_t * const sh_video = mpctx->sh_video;
1306 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1307 a_pos = playing_audio_pts(mpctx);
1308 if (mpctx->sh_audio && sh_video && at_frame) {
1309 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1310 if (mpctx->time_frame > 0)
1311 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1312 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1313 && !mpctx->drop_message_shown) {
1314 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1315 mpctx->drop_message_shown = true;
1318 if (quiet)
1319 return;
1322 int width;
1323 char *line;
1324 unsigned pos = 0;
1325 get_screen_size();
1326 if (screen_width > 0)
1327 width = screen_width;
1328 else
1329 width = 80;
1330 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1331 /* Windows command line is broken (MinGW's rxvt works, but we
1332 * should not depend on that). */
1333 width--;
1334 #endif
1335 line = malloc(width + 1); // one additional char for the terminating null
1337 // Audio time
1338 if (mpctx->sh_audio) {
1339 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1340 if (!sh_video) {
1341 float len = demuxer_get_time_length(mpctx->demuxer);
1342 saddf(line, &pos, width, "(");
1343 sadd_hhmmssf(line, &pos, width, a_pos);
1344 saddf(line, &pos, width, ") of %.1f (", len);
1345 sadd_hhmmssf(line, &pos, width, len);
1346 saddf(line, &pos, width, ") ");
1350 // Video time
1351 if (sh_video)
1352 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1354 // A-V sync
1355 if (mpctx->sh_audio && sh_video)
1356 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1357 mpctx->last_av_difference, mpctx->total_avsync_change);
1359 // Video stats
1360 if (sh_video)
1361 saddf(line, &pos, width, "%3d/%3d ",
1362 (int)sh_video->num_frames,
1363 (int)sh_video->num_frames_decoded);
1365 // CPU usage
1366 if (sh_video) {
1367 if (sh_video->timer > 0.5)
1368 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1369 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1370 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1371 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1372 else
1373 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1374 } else if (mpctx->sh_audio) {
1375 if (mpctx->delay > 0.5)
1376 saddf(line, &pos, width, "%4.1f%% ",
1377 100.0*audio_time_usage/(double)mpctx->delay);
1378 else
1379 saddf(line, &pos, width, "??,?%% ");
1382 // VO stats
1383 if (sh_video)
1384 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1386 #ifdef CONFIG_STREAM_CACHE
1387 // cache stats
1388 if (stream_cache_size > 0)
1389 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1390 #endif
1392 // other
1393 if (opts->playback_speed != 1)
1394 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1396 // end
1397 if (erase_to_end_of_line) {
1398 line[pos] = 0;
1399 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1400 } else {
1401 memset(&line[pos], ' ', width - pos);
1402 line[width] = 0;
1403 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1405 free(line);
1409 * \brief build a chain of audio filters that converts the input format
1410 * to the ao's format, taking into account the current playback_speed.
1411 * \param sh_audio describes the requested input format of the chain.
1412 * \param ao_data describes the requested output format of the chain.
1414 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1416 struct MPOpts *opts = &mpctx->opts;
1417 int new_srate;
1418 int result;
1419 if (!sh_audio)
1421 mpctx->mixer.afilter = NULL;
1422 return 0;
1424 if(af_control_any_rev(sh_audio->afilter,
1425 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1426 &opts->playback_speed)) {
1427 new_srate = sh_audio->samplerate;
1428 } else {
1429 new_srate = sh_audio->samplerate * opts->playback_speed;
1430 if (new_srate != ao_data->samplerate) {
1431 // limits are taken from libaf/af_resample.c
1432 if (new_srate < 8000)
1433 new_srate = 8000;
1434 if (new_srate > 192000)
1435 new_srate = 192000;
1436 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1439 result = init_audio_filters(sh_audio, new_srate,
1440 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1441 mpctx->mixer.afilter = sh_audio->afilter;
1442 return result;
1446 typedef struct mp_osd_msg mp_osd_msg_t;
1447 struct mp_osd_msg {
1448 /// Previous message on the stack.
1449 mp_osd_msg_t* prev;
1450 /// Message text.
1451 char msg[128];
1452 int id,level,started;
1453 /// Display duration in ms.
1454 unsigned time;
1457 /// OSD message stack.
1458 static mp_osd_msg_t* osd_msg_stack = NULL;
1461 * \brief Add a message on the OSD message stack
1463 * If a message with the same id is already present in the stack
1464 * it is pulled on top of the stack, otherwise a new message is created.
1467 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1468 va_list ap)
1470 mp_osd_msg_t *msg,*last=NULL;
1471 int r;
1473 // look if the id is already in the stack
1474 for(msg = osd_msg_stack ; msg && msg->id != id ;
1475 last = msg, msg = msg->prev);
1476 // not found: alloc it
1477 if(!msg) {
1478 msg = calloc(1,sizeof(mp_osd_msg_t));
1479 msg->prev = osd_msg_stack;
1480 osd_msg_stack = msg;
1481 } else if(last) { // found, but it's not on top of the stack
1482 last->prev = msg->prev;
1483 msg->prev = osd_msg_stack;
1484 osd_msg_stack = msg;
1486 // write the msg
1487 r = vsnprintf(msg->msg, 128, fmt, ap);
1488 if(r >= 128) msg->msg[127] = 0;
1489 // set id and time
1490 msg->id = id;
1491 msg->level = level;
1492 msg->time = time;
1496 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1498 va_list ap;
1499 va_start(ap, fmt);
1500 set_osd_msg_va(id, level, time, fmt, ap);
1501 va_end(ap);
1504 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1506 va_list ap;
1507 va_start(ap, fmt);
1508 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1509 va_end(ap);
1514 * \brief Remove a message from the OSD stack
1516 * This function can be used to get rid of a message right away.
1520 void rm_osd_msg(int id) {
1521 mp_osd_msg_t *msg,*last=NULL;
1523 // Search for the msg
1524 for(msg = osd_msg_stack ; msg && msg->id != id ;
1525 last = msg, msg = msg->prev);
1526 if(!msg) return;
1528 // Detach it from the stack and free it
1529 if(last)
1530 last->prev = msg->prev;
1531 else
1532 osd_msg_stack = msg->prev;
1533 free(msg);
1537 * \brief Remove all messages from the OSD stack
1541 static void clear_osd_msgs(void) {
1542 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1543 while(msg) {
1544 prev = msg->prev;
1545 free(msg);
1546 msg = prev;
1548 osd_msg_stack = NULL;
1552 * \brief Get the current message from the OSD stack.
1554 * This function decrements the message timer and destroys the old ones.
1555 * The message that should be displayed is returned (if any).
1559 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1561 struct MPOpts *opts = &mpctx->opts;
1562 mp_osd_msg_t *msg,*prev,*last = NULL;
1563 static unsigned last_update = 0;
1564 unsigned now = GetTimerMS();
1565 unsigned diff;
1566 char hidden_dec_done = 0;
1568 if (mpctx->osd_visible) {
1569 // 36000000 means max timed visibility is 1 hour into the future, if
1570 // the difference is greater assume it's wrapped around from below 0
1571 if (mpctx->osd_visible - now > 36000000) {
1572 mpctx->osd_visible = 0;
1573 vo_osd_progbar_type = -1; // disable
1574 vo_osd_changed(OSDTYPE_PROGBAR);
1575 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1578 if (mpctx->osd_show_percentage_until - now > 36000000)
1579 mpctx->osd_show_percentage_until = 0;
1581 if(!last_update) last_update = now;
1582 diff = now >= last_update ? now - last_update : 0;
1584 last_update = now;
1586 // Look for the first message in the stack with high enough level.
1587 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1588 prev = msg->prev;
1589 if (msg->level > opts->osd_level && hidden_dec_done)
1590 continue;
1591 // The message has a high enough level or it is the first hidden one
1592 // in both cases we decrement the timer or kill it.
1593 if(!msg->started || msg->time > diff) {
1594 if(msg->started) msg->time -= diff;
1595 else msg->started = 1;
1596 // display it
1597 if (msg->level <= opts->osd_level)
1598 return msg;
1599 hidden_dec_done = 1;
1600 continue;
1602 // kill the message
1603 free(msg);
1604 if(last) {
1605 last->prev = prev;
1606 msg = last;
1607 } else {
1608 osd_msg_stack = prev;
1609 msg = NULL;
1612 // Nothing found
1613 return NULL;
1617 * \brief Display the OSD bar.
1619 * Display the OSD bar or fall back on a simple message.
1623 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1624 struct MPOpts *opts = &mpctx->opts;
1625 if (opts->osd_level < 1)
1626 return;
1628 if(mpctx->sh_video) {
1629 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1630 vo_osd_progbar_type = type;
1631 vo_osd_progbar_value = 256*(val-min)/(max-min);
1632 vo_osd_changed(OSDTYPE_PROGBAR);
1633 return;
1636 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1637 name, ROUND(100*(val-min)/(max-min)));
1641 * \brief Display text subtitles on the OSD
1643 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1645 int i;
1646 vo_sub = subs;
1647 vo_osd_changed(OSDTYPE_SUBTITLE);
1648 if (!mpctx->sh_video) {
1649 // reverse order, since newest set_osd_msg is displayed first
1650 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1651 if (!subs || i >= subs->lines || !subs->text[i])
1652 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1653 else {
1654 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1655 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1656 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1663 * \brief Update the OSD message line.
1665 * This function displays the current message on the vo OSD or on the term.
1666 * If the stack is empty and the OSD level is high enough the timer
1667 * is displayed (only on the vo OSD).
1671 static void update_osd_msg(struct MPContext *mpctx)
1673 struct MPOpts *opts = &mpctx->opts;
1674 mp_osd_msg_t *msg;
1675 struct osd_state *osd = mpctx->osd;
1676 char osd_text_timer[128];
1678 if (mpctx->add_osd_seek_info) {
1679 double percentage;
1680 if (mpctx->timeline && mpctx->sh_video)
1681 percentage = mpctx->sh_video->pts * 100 /
1682 mpctx->timeline[mpctx->num_timeline_parts].start;
1683 else
1684 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1685 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1686 if (mpctx->sh_video)
1687 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1688 mpctx->add_osd_seek_info = false;
1691 // Look if we have a msg
1692 if((msg = get_osd_msg(mpctx))) {
1693 if (strcmp(osd->osd_text, msg->msg)) {
1694 strncpy(osd->osd_text, msg->msg, 127);
1695 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1696 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1698 return;
1701 if(mpctx->sh_video) {
1702 // fallback on the timer
1703 if (opts->osd_level >= 2) {
1704 int len;
1705 if (mpctx->timeline)
1706 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1707 else
1708 len = demuxer_get_time_length(mpctx->demuxer);
1709 int percentage = -1;
1710 char percentage_text[10];
1711 int pts = demuxer_get_current_time(mpctx->demuxer);
1713 if (mpctx->osd_show_percentage_until) {
1714 if (mpctx->timeline)
1715 percentage = mpctx->sh_video->pts * 100 /
1716 mpctx->timeline[mpctx->num_timeline_parts].start;
1717 else
1718 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1721 if (percentage >= 0)
1722 snprintf(percentage_text, 9, " (%d%%)", percentage);
1723 else
1724 percentage_text[0] = 0;
1726 if (opts->osd_level == 3)
1727 snprintf(osd_text_timer, 63,
1728 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1729 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1730 len/3600,(len/60)%60,len%60,percentage_text);
1731 else
1732 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1733 mpctx->osd_function,pts/3600,(pts/60)%60,
1734 pts%60,percentage_text);
1735 } else
1736 osd_text_timer[0]=0;
1738 if (strcmp(osd->osd_text, osd_text_timer)) {
1739 strncpy(osd->osd_text, osd_text_timer, 63);
1740 vo_osd_changed(OSDTYPE_OSD);
1742 return;
1745 // Clear the term osd line
1746 if (term_osd && osd->osd_text[0]) {
1747 osd->osd_text[0] = 0;
1748 printf("%s\n",term_osd_esc);
1752 ///@}
1753 // OSDMsgStack
1756 void reinit_audio_chain(struct MPContext *mpctx)
1758 struct MPOpts *opts = &mpctx->opts;
1759 if (!mpctx->sh_audio)
1760 return;
1761 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1762 current_module="init_audio_codec";
1763 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1764 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1765 goto init_error;
1767 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1768 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1772 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1773 current_module="af_preinit";
1774 ao_data.samplerate=force_srate;
1775 ao_data.channels=0;
1776 ao_data.format = opts->audio_output_format;
1777 // first init to detect best values
1778 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1779 // input:
1780 mpctx->sh_audio->samplerate,
1781 // output:
1782 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1783 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1784 "pre-init!\n");
1785 exit_player(mpctx, EXIT_ERROR);
1787 current_module="ao2_init";
1788 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1789 0, // plugin flag
1790 ao_data.samplerate,
1791 ao_data.channels,
1792 ao_data.format, 0);
1793 if(!mpctx->audio_out){
1794 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1795 goto init_error;
1797 mpctx->initialized_flags|=INITIALIZED_AO;
1798 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1799 mpctx->audio_out->info->short_name,
1800 ao_data.samplerate, ao_data.channels,
1801 af_fmt2str_short(ao_data.format),
1802 af_fmt2bits(ao_data.format)/8 );
1803 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1804 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1805 if(strlen(mpctx->audio_out->info->comment) > 0)
1806 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1809 // init audio filters:
1810 current_module="af_init";
1811 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1812 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1813 goto init_error;
1815 mpctx->mixer.audio_out = mpctx->audio_out;
1816 mpctx->mixer.volstep = volstep;
1817 return;
1819 init_error:
1820 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1821 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1822 mpctx->d_audio->id = -2;
1826 ///@}
1827 // Command2Property
1830 // Return pts value corresponding to the end point of audio written to the
1831 // ao so far.
1832 static double written_audio_pts(struct MPContext *mpctx)
1834 sh_audio_t *sh_audio = mpctx->sh_audio;
1835 demux_stream_t *d_audio = mpctx->d_audio;
1836 double buffered_output;
1837 // first calculate the end pts of audio that has been output by decoder
1838 double a_pts = sh_audio->pts;
1839 if (a_pts != MP_NOPTS_VALUE)
1840 // Good, decoder supports new way of calculating audio pts.
1841 // sh_audio->pts is the timestamp of the latest input packet with
1842 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1843 // the amount of bytes the decoder has written after that timestamp.
1844 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1845 else {
1846 // Decoder doesn't support new way of calculating pts (or we're
1847 // being called before it has decoded anything with known timestamp).
1848 // Use the old method of audio pts calculation: take the timestamp
1849 // of last packet with known pts the decoder has read data from,
1850 // and add amount of bytes read after the beginning of that packet
1851 // divided by input bps. This will be inaccurate if the input/output
1852 // ratio is not constant for every audio packet or if it is constant
1853 // but not accurately known in sh_audio->i_bps.
1855 a_pts = d_audio->pts;
1856 // ds_tell_pts returns bytes read after last timestamp from
1857 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1858 // it has read but not decoded
1859 if (sh_audio->i_bps)
1860 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1861 (double)sh_audio->i_bps;
1863 // Now a_pts hopefully holds the pts for end of audio from decoder.
1864 // Substract data in buffers between decoder and audio out.
1866 // Decoded but not filtered
1867 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1869 // Data buffered in audio filters, measured in bytes of "missing" output
1870 buffered_output = af_calc_delay(sh_audio->afilter);
1872 // Data that was ready for ao but was buffered because ao didn't fully
1873 // accept everything to internal buffers yet
1874 buffered_output += sh_audio->a_out_buffer_len;
1876 // Filters divide audio length by playback_speed, so multiply by it
1877 // to get the length in original units without speedup or slowdown
1878 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1880 return a_pts + mpctx->video_offset;
1883 // Return pts value corresponding to currently playing audio.
1884 double playing_audio_pts(struct MPContext *mpctx)
1886 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1887 mpctx->audio_out->get_delay();
1890 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1891 struct MPOpts *opts = &mpctx->opts;
1892 // check for frame-drop:
1893 current_module = "check_framedrop";
1894 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1895 static int dropped_frames;
1896 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1897 float d = delay-mpctx->delay;
1898 ++total_frame_cnt;
1899 // we should avoid dropping too many frames in sequence unless we
1900 // are too late. and we allow 100ms A-V delay here:
1901 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1902 && !mpctx->update_video_immediately) {
1903 ++drop_frame_cnt;
1904 ++dropped_frames;
1905 return frame_dropping;
1906 } else
1907 dropped_frames = 0;
1909 return 0;
1913 #ifdef HAVE_RTC
1914 int rtc_fd = -1;
1915 #endif
1917 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1919 #ifdef HAVE_RTC
1920 if (rtc_fd >= 0){
1921 // -------- RTC -----------
1922 current_module="sleep_rtc";
1923 while (time_frame > 0.000) {
1924 unsigned long rtc_ts;
1925 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1926 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1927 time_frame -= get_relative_time(mpctx);
1929 } else
1930 #endif
1932 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1933 // unnecessarily high CPU usage
1934 float margin = softsleep ? 0.011 : 0;
1935 current_module = "sleep_timer";
1936 while (time_frame > margin) {
1937 usec_sleep(1000000 * (time_frame - margin));
1938 time_frame -= get_relative_time(mpctx);
1940 if (softsleep){
1941 current_module = "sleep_soft";
1942 if (time_frame < 0)
1943 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1944 while (time_frame > 0)
1945 time_frame -= get_relative_time(mpctx); // burn the CPU
1948 return time_frame;
1951 static int select_subtitle(MPContext *mpctx)
1953 struct MPOpts *opts = &mpctx->opts;
1954 // find the best sub to use
1955 int id;
1956 int found = 0;
1957 mpctx->global_sub_pos = -1; // no subs by default
1958 if (vobsub_id >= 0) {
1959 // if user asks for a vobsub id, use that first.
1960 id = vobsub_id;
1961 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1964 if (!found && opts->sub_id >= 0) {
1965 // if user asks for a dvd sub id, use that next.
1966 id = opts->sub_id;
1967 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1970 if (!found) {
1971 // if there are text subs to use, use those. (autosubs come last here)
1972 id = 0;
1973 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1976 if (!found && opts->sub_id == -1) {
1977 // finally select subs by language and container hints
1978 if (opts->sub_id == -1 && opts->sub_lang)
1979 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, opts->sub_lang);
1980 if (opts->sub_id == -1)
1981 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
1982 if (opts->sub_id >= 0) {
1983 id = opts->sub_id;
1984 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1987 return found;
1990 #ifdef CONFIG_DVDNAV
1991 #ifndef FF_B_TYPE
1992 #define FF_B_TYPE 3
1993 #endif
1994 /// store decoded video image
1995 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1996 mp_image_t *from_mpi) {
1997 mp_image_t *mpi;
1999 /// Do not store B-frames
2000 if (from_mpi->pict_type == FF_B_TYPE)
2001 return to_mpi;
2003 if (to_mpi &&
2004 to_mpi->w == from_mpi->w &&
2005 to_mpi->h == from_mpi->h &&
2006 to_mpi->imgfmt == from_mpi->imgfmt)
2007 mpi = to_mpi;
2008 else {
2009 if (to_mpi)
2010 free_mp_image(to_mpi);
2011 if (from_mpi->w == 0 || from_mpi->h == 0)
2012 return NULL;
2013 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2016 copy_mpi(mpi,from_mpi);
2017 return mpi;
2020 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2021 struct MPOpts *opts = &ctx->opts;
2022 if (ctx->sh_video) {
2023 /// clear video pts
2024 ctx->d_video->pts = 0.0f;
2025 ctx->sh_video->pts = 0.0f;
2026 ctx->sh_video->i_pts = 0.0f;
2027 ctx->sh_video->last_pts = 0.0f;
2028 ctx->sh_video->num_buffered_pts = 0;
2029 ctx->sh_video->num_frames = 0;
2030 ctx->sh_video->num_frames_decoded = 0;
2031 ctx->sh_video->timer = 0.0f;
2032 ctx->sh_video->stream_delay = 0.0f;
2033 ctx->sh_video->timer = 0;
2034 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2037 if (ctx->sh_audio) {
2038 /// free audio packets and reset
2039 ds_free_packs(ctx->d_audio);
2040 audio_delay -= ctx->sh_audio->stream_delay;
2041 ctx->delay =- audio_delay;
2042 ctx->audio_out->reset();
2043 resync_audio_stream(ctx->sh_audio);
2046 audio_delay = 0.0f;
2047 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2048 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2049 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2050 if (dvdsub_lang_id != opts->sub_id) {
2051 opts->sub_id = dvdsub_lang_id;
2052 select_subtitle(ctx);
2056 /// clear all EOF related flags
2057 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2060 /// Restore last decoded DVDNAV (still frame)
2061 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2062 int *in_size,
2063 unsigned char **start,
2064 mp_image_t *decoded_frame)
2066 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2067 return decoded_frame;
2069 /// a change occured in dvdnav stream
2070 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2071 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2072 mp_dvdnav_context_free(mpctx);
2073 mp_dvdnav_reset_stream(mpctx);
2074 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2075 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2078 if (*in_size < 0) {
2079 float len;
2081 /// Display still frame, if any
2082 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2083 decoded_frame = mpctx->nav_smpi;
2085 /// increment video frame : continue playing after still frame
2086 len = demuxer_get_time_length(mpctx->demuxer);
2087 if (mpctx->sh_video->pts >= len &&
2088 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2089 mp_dvdnav_skip_still(mpctx->stream);
2090 mp_dvdnav_skip_wait(mpctx->stream);
2092 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2094 if (mpctx->nav_buffer) {
2095 *start = mpctx->nav_start;
2096 *in_size = mpctx->nav_in_size;
2097 if (mpctx->nav_start)
2098 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2102 return decoded_frame;
2105 /// Save last decoded DVDNAV (still frame)
2106 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2107 unsigned char *start,
2108 mp_image_t *decoded_frame)
2110 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2111 return;
2113 if (mpctx->nav_buffer)
2114 free(mpctx->nav_buffer);
2116 mpctx->nav_buffer = malloc(in_size);
2117 mpctx->nav_start = start;
2118 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2119 if (mpctx->nav_buffer)
2120 memcpy(mpctx->nav_buffer,start,in_size);
2122 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2123 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2125 #endif /* CONFIG_DVDNAV */
2127 /* Modify video timing to match the audio timeline. There are two main
2128 * reasons this is needed. First, video and audio can start from different
2129 * positions at beginning of file or after a seek (MPlayer starts both
2130 * immediately even if they have different pts). Second, the file can have
2131 * audio timestamps that are inconsistent with the duration of the audio
2132 * packets, for example two consecutive timestamp values differing by
2133 * one second but only a packet with enough samples for half a second
2134 * of playback between them.
2136 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2138 current_module = "av_sync";
2140 if (!mpctx->sh_audio)
2141 return;
2143 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2144 double v_pts = mpctx->sh_video->pts;
2145 double av_delay = a_pts - v_pts;
2146 // Try to sync vo_flip() so it will *finish* at given time
2147 av_delay += mpctx->last_vo_flip_duration;
2148 av_delay -= audio_delay; // This much pts difference is desired
2150 double change = av_delay * 0.1;
2151 double max_change = default_max_pts_correction >= 0 ?
2152 default_max_pts_correction : frame_time * 0.1;
2153 if (change < -max_change)
2154 change = -max_change;
2155 else if (change > max_change)
2156 change = max_change;
2157 mpctx->delay += change;
2158 mpctx->total_avsync_change += change;
2161 static int fill_audio_out_buffers(struct MPContext *mpctx)
2163 struct MPOpts *opts = &mpctx->opts;
2164 unsigned int t;
2165 double tt;
2166 int playsize;
2167 int playflags=0;
2168 int audio_eof=0;
2169 bool format_change = false;
2170 sh_audio_t * const sh_audio = mpctx->sh_audio;
2172 current_module="play_audio";
2174 while (1) {
2175 int sleep_time;
2176 // all the current uses of ao_data.pts seem to be in aos that handle
2177 // sync completely wrong; there should be no need to use ao_data.pts
2178 // in get_space()
2179 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2180 playsize = mpctx->audio_out->get_space();
2181 if (mpctx->sh_video || playsize >= ao_data.outburst)
2182 break;
2184 // handle audio-only case:
2185 // this is where mplayer sleeps during audio-only playback
2186 // to avoid 100% CPU use
2187 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2188 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2189 usec_sleep(sleep_time * 1000);
2192 // Fill buffer if needed:
2193 current_module="decode_audio";
2194 t = GetTimer();
2195 int res = decode_audio(sh_audio, playsize);
2196 if (res < 0) { // EOF, error or format change
2197 if (res == -2)
2198 format_change = true;
2199 else if (mpctx->d_audio->eof) {
2200 audio_eof = 1;
2201 if (sh_audio->a_out_buffer_len == 0)
2202 return 0;
2205 t = GetTimer() - t;
2206 tt = t*0.000001f; audio_time_usage+=tt;
2207 if (playsize > sh_audio->a_out_buffer_len) {
2208 playsize = sh_audio->a_out_buffer_len;
2209 if (audio_eof)
2210 playflags |= AOPLAY_FINAL_CHUNK;
2212 if (!playsize)
2213 return 1;
2215 // play audio:
2216 current_module="play_audio";
2218 // Is this pts value actually useful for the aos that access it?
2219 // They're obviously badly broken in the way they handle av sync;
2220 // would not having access to this make them more broken?
2221 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2222 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2224 if (playsize > 0) {
2225 sh_audio->a_out_buffer_len -= playsize;
2226 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2227 sh_audio->a_out_buffer_len);
2228 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2230 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2231 // Sanity check to avoid hanging in case current ao doesn't output
2232 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2233 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2234 sh_audio->a_out_buffer_len = 0;
2237 /* The format change isn't handled too gracefully. A more precise
2238 * implementation would require draining buffered old-format audio
2239 * while displaying video, then doing the output format switch.
2241 if (format_change) {
2242 uninit_player(mpctx, INITIALIZED_AO);
2243 reinit_audio_chain(mpctx);
2246 return 1;
2249 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2250 float *aq_sleep_time)
2252 struct MPOpts *opts = &mpctx->opts;
2253 int frame_time_remaining = 0;
2254 current_module="calc_sleep_time";
2256 *time_frame -= get_relative_time(mpctx); // reset timer
2258 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2259 float delay = mpctx->audio_out->get_delay();
2260 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2262 if (autosync) {
2264 * Adjust this raw delay value by calculating the expected
2265 * delay for this frame and generating a new value which is
2266 * weighted between the two. The higher autosync is, the
2267 * closer to the delay value gets to that which "-nosound"
2268 * would have used, and the longer it will take for A/V
2269 * sync to settle at the right value (but it eventually will.)
2270 * This settling time is very short for values below 100.
2272 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2273 float difference = delay - predicted;
2274 delay = predicted + difference / (float)autosync;
2277 *time_frame = delay - mpctx->delay / opts->playback_speed;
2278 *time_frame -= mpctx->video_out->flip_queue_offset;
2280 // delay = amount of audio buffered in soundcard/driver
2281 if (delay > 0.25) delay=0.25; else
2282 if (delay < 0.10) delay=0.10;
2284 if (*time_frame > delay*0.6) {
2285 // sleep time too big - may cause audio drops (buffer underrun)
2286 frame_time_remaining = 1;
2287 *time_frame = delay*0.5;
2289 } else {
2290 // If we're lagging more than 200 ms behind the right playback rate,
2291 // don't try to "catch up".
2292 // If benchmark is set always output frames as fast as possible
2293 // without sleeping.
2294 if (*time_frame < -0.2 || benchmark)
2295 *time_frame = 0;
2296 *time_frame -= mpctx->video_out->flip_queue_offset;
2299 *aq_sleep_time += *time_frame;
2302 //============================== SLEEP: ===================================
2304 // flag 256 means: libvo driver does its timing (dvb card)
2305 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2306 *time_frame = timing_sleep(mpctx, *time_frame);
2307 *time_frame += mpctx->video_out->flip_queue_offset;
2308 return frame_time_remaining;
2311 int reinit_video_chain(struct MPContext *mpctx)
2313 struct MPOpts *opts = &mpctx->opts;
2314 sh_video_t * const sh_video = mpctx->sh_video;
2315 double ar=-1.0;
2316 //================== Init VIDEO (codec & libvo) ==========================
2317 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2318 current_module="preinit_libvo";
2320 //shouldn't we set dvideo->id=-2 when we fail?
2321 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2322 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2323 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2324 goto err_out;
2326 mpctx->initialized_flags|=INITIALIZED_VO;
2329 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2330 mpctx->sh_video->stream_aspect = ar;
2331 current_module="init_video_filters";
2333 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2334 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2336 #ifdef CONFIG_MENU
2337 if(use_menu) {
2338 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2339 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2340 if(!vf_menu) {
2341 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2342 use_menu = 0;
2345 if(vf_menu)
2346 sh_video->vfilter = vf_menu;
2347 #endif
2349 #ifdef CONFIG_ASS
2350 if(opts->ass_enabled) {
2351 int i;
2352 int insert = 1;
2353 if (opts->vf_settings)
2354 for (i = 0; opts->vf_settings[i].name; ++i)
2355 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2356 insert = 0;
2357 break;
2359 if (insert) {
2360 extern vf_info_t vf_info_ass;
2361 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2362 char* vf_arg[] = {"auto", "1", NULL};
2363 int retcode = 0;
2364 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2365 sh_video->vfilter,
2366 "ass", vf_arg,
2367 &retcode);
2368 if (vf_ass)
2369 sh_video->vfilter = vf_ass;
2370 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2371 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2372 else
2373 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2376 #endif
2378 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2380 #ifdef CONFIG_ASS
2381 if (opts->ass_enabled)
2382 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2383 #endif
2385 current_module="init_video_codec";
2387 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2388 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2389 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2391 if(!sh_video->initialized){
2392 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2393 goto err_out;
2396 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2398 if (sh_video->codec)
2399 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2401 sh_video->last_pts = MP_NOPTS_VALUE;
2402 sh_video->num_buffered_pts = 0;
2403 sh_video->next_frame_time = 0;
2405 if(auto_quality>0){
2406 // Auto quality option enabled
2407 output_quality=get_video_quality_max(sh_video);
2408 if(auto_quality>output_quality) auto_quality=output_quality;
2409 else output_quality=auto_quality;
2410 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2411 set_video_quality(sh_video,output_quality);
2414 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2416 current_module="init_vo";
2418 return 1;
2420 err_out:
2421 mpctx->sh_video = mpctx->d_video->sh = NULL;
2422 return 0;
2425 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2427 struct sh_video *sh_video = mpctx->sh_video;
2428 double frame_time = 0;
2429 struct vo *video_out = mpctx->video_out;
2430 while (!video_out->frame_loaded) {
2431 current_module = "filter_video";
2432 // In nocorrect-pts mode there is no way to properly time these frames
2433 if (vo_get_buffered_frame(video_out, 0) >= 0)
2434 break;
2435 if (vf_output_queued_frame(sh_video->vfilter))
2436 continue;
2437 unsigned char *packet = NULL;
2438 frame_time = sh_video->next_frame_time;
2439 if (mpctx->update_video_immediately)
2440 frame_time = 0;
2441 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2442 &packet, force_fps);
2443 if (in_size < 0) {
2444 #ifdef CONFIG_DVDNAV
2445 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2446 if (mp_dvdnav_is_eof(mpctx->stream))
2447 return -1;
2448 if (mpctx->d_video)
2449 mpctx->d_video->eof = 0;
2450 if (mpctx->d_audio)
2451 mpctx->d_audio->eof = 0;
2452 mpctx->stream->eof = 0;
2453 } else
2454 #endif
2455 return -1;
2457 if (in_size > max_framesize)
2458 max_framesize = in_size;
2459 sh_video->timer += frame_time;
2460 if (mpctx->sh_audio)
2461 mpctx->delay -= frame_time;
2462 // video_read_frame can change fps (e.g. for ASF video)
2463 vo_fps = sh_video->fps;
2464 int framedrop_type = check_framedrop(mpctx, frame_time);
2465 current_module = "decode video";
2467 void *decoded_frame;
2468 #ifdef CONFIG_DVDNAV
2469 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2470 if (in_size >= 0 && !decoded_frame)
2471 #endif
2472 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2473 sh_video->pts);
2474 #ifdef CONFIG_DVDNAV
2475 // Save last still frame for future display
2476 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2477 #endif
2478 if (decoded_frame) {
2479 current_module = "filter video";
2480 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2481 if (!video_out->config_ok)
2482 break;
2485 return frame_time;
2488 static void determine_frame_pts(struct MPContext *mpctx)
2490 struct sh_video *sh_video = mpctx->sh_video;
2491 struct MPOpts *opts = &mpctx->opts;
2493 if (opts->user_pts_assoc_mode) {
2494 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2495 } else if (sh_video->pts_assoc_mode == 0) {
2496 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2497 sh_video->pts_assoc_mode = 1;
2498 else
2499 sh_video->pts_assoc_mode = 2;
2500 } else {
2501 int probcount1 = sh_video->num_reordered_pts_problems;
2502 int probcount2 = sh_video->num_sorted_pts_problems;
2503 if (sh_video->pts_assoc_mode == 2) {
2504 int tmp = probcount1;
2505 probcount1 = probcount2;
2506 probcount2 = tmp;
2508 if (probcount1 >= probcount2 * 1.5 + 2) {
2509 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2510 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2511 "%d.\n", sh_video->pts_assoc_mode);
2514 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2515 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2518 static double update_video(struct MPContext *mpctx)
2520 struct sh_video *sh_video = mpctx->sh_video;
2521 struct vo *video_out = mpctx->video_out;
2522 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2523 mpctx->osd); // hack for vf_expand
2524 if (!mpctx->opts.correct_pts)
2525 return update_video_nocorrect_pts(mpctx);
2527 double pts;
2529 bool hit_eof = false;
2530 while (!video_out->frame_loaded) {
2531 current_module = "filter_video";
2532 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2533 break;
2534 // XXX Time used in this call is not counted in any performance
2535 // timer now, OSD time is not updated correctly for filter-added frames
2536 if (vf_output_queued_frame(sh_video->vfilter))
2537 continue;
2538 if (hit_eof)
2539 return -1;
2540 unsigned char *packet = NULL;
2541 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2542 if (pts != MP_NOPTS_VALUE)
2543 pts += mpctx->video_offset;
2544 if (in_size < 0) {
2545 // try to extract last frames in case of decoder lag
2546 in_size = 0;
2547 pts = MP_NOPTS_VALUE;
2548 hit_eof = true;
2550 if (in_size > max_framesize)
2551 max_framesize = in_size;
2552 current_module = "decode video";
2553 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2554 void *decoded_frame = decode_video(sh_video, packet, in_size,
2555 framedrop_type, pts);
2556 if (decoded_frame) {
2557 determine_frame_pts(mpctx);
2558 current_module = "filter video";
2559 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2560 if (!video_out->config_ok)
2561 break; // We'd likely hang in this loop otherwise
2565 pts = video_out->next_pts;
2566 if (pts == MP_NOPTS_VALUE) {
2567 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2568 // Try to use decoder pts from before filters
2569 pts = sh_video->pts;
2570 if (pts == MP_NOPTS_VALUE)
2571 pts = sh_video->last_pts;
2573 sh_video->pts = pts;
2574 if (sh_video->last_pts == MP_NOPTS_VALUE)
2575 sh_video->last_pts = sh_video->pts;
2576 else if (sh_video->last_pts > sh_video->pts) {
2577 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2578 sh_video->pts, sh_video->last_pts);
2579 /* If the difference in pts is small treat it as jitter around the
2580 * right value (possibly caused by incorrect timestamp ordering) and
2581 * just show this frame immediately after the last one.
2582 * Treat bigger differences as timestamp resets and start counting
2583 * timing of later frames from the position of this one. */
2584 if (sh_video->last_pts - sh_video->pts > 0.5)
2585 sh_video->last_pts = sh_video->pts;
2586 else
2587 sh_video->pts = sh_video->last_pts;
2589 double frame_time = sh_video->pts - sh_video->last_pts;
2590 sh_video->last_pts = sh_video->pts;
2591 sh_video->timer += frame_time;
2592 if (mpctx->sh_audio)
2593 mpctx->delay -= frame_time;
2594 return frame_time;
2597 void pause_player(struct MPContext *mpctx)
2599 if (mpctx->paused)
2600 return;
2601 mpctx->paused = 1;
2602 mpctx->step_frames = 0;
2603 mpctx->time_frame -= get_relative_time(mpctx);
2605 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2606 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2608 if (mpctx->audio_out && mpctx->sh_audio)
2609 mpctx->audio_out->pause(); // pause audio, keep data if possible
2612 void unpause_player(struct MPContext *mpctx)
2614 if (!mpctx->paused)
2615 return;
2616 mpctx->paused = 0;
2618 if (mpctx->audio_out && mpctx->sh_audio)
2619 mpctx->audio_out->resume(); // resume audio
2620 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2621 && !mpctx->step_frames)
2622 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2623 (void)get_relative_time(mpctx); // ignore time that passed during pause
2626 void add_step_frame(struct MPContext *mpctx)
2628 mpctx->step_frames++;
2629 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2630 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2631 unpause_player(mpctx);
2634 static void pause_loop(struct MPContext *mpctx)
2636 mp_cmd_t* cmd;
2637 if (!quiet) {
2638 // Small hack to display the pause message on the OSD line.
2639 // The pause string is: "\n == PAUSE == \r" so we need to
2640 // take the first and the last char out
2641 if (term_osd && !mpctx->sh_video) {
2642 char msg[128] = _("\n ===== PAUSE =====\r");
2643 int mlen = strlen(msg);
2644 msg[mlen-1] = '\0';
2645 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2646 update_osd_msg(mpctx);
2647 } else
2648 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2649 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2652 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2653 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2654 if (cmd) {
2655 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2656 run_command(mpctx, cmd);
2657 mp_cmd_free(cmd);
2658 continue;
2660 if (mpctx->sh_video && mpctx->video_out)
2661 vo_check_events(mpctx->video_out);
2662 #ifdef CONFIG_MENU
2663 if (vf_menu)
2664 vf_menu_pause_update(vf_menu);
2665 #endif
2666 usec_sleep(20000);
2667 update_osd_msg(mpctx);
2668 int hack = vo_osd_changed(0);
2669 vo_osd_changed(hack);
2670 if (hack)
2671 break;
2676 // Find the right mute status and record position for new file position
2677 static void edl_seek_reset(MPContext *mpctx)
2679 mpctx->edl_muted = 0;
2680 next_edl_record = edl_records;
2682 while (next_edl_record) {
2683 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2684 break;
2686 if (next_edl_record->action == EDL_MUTE)
2687 mpctx->edl_muted = !mpctx->edl_muted;
2688 next_edl_record = next_edl_record->next;
2690 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2691 mixer_mute(&mpctx->mixer);
2695 // Execute EDL command for the current position if one exists
2696 static void edl_update(MPContext *mpctx)
2698 if (!next_edl_record)
2699 return;
2701 if (!mpctx->sh_video) {
2702 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2703 free_edl(edl_records);
2704 next_edl_record = NULL;
2705 edl_records = NULL;
2706 return;
2709 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2710 if (next_edl_record->action == EDL_SKIP) {
2711 mpctx->osd_function = OSD_FFW;
2712 mpctx->abs_seek_pos = 0;
2713 mpctx->rel_seek_secs = next_edl_record->length_sec;
2714 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2715 "[%f], length [%f]\n", next_edl_record->start_sec,
2716 next_edl_record->stop_sec, next_edl_record->length_sec);
2718 else if (next_edl_record->action == EDL_MUTE) {
2719 mpctx->edl_muted = !mpctx->edl_muted;
2720 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2721 mixer_mute(&mpctx->mixer);
2722 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2723 next_edl_record->start_sec );
2725 next_edl_record = next_edl_record->next;
2729 static void reinit_decoders(struct MPContext *mpctx)
2731 reinit_video_chain(mpctx);
2732 reinit_audio_chain(mpctx);
2733 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2736 static void seek_reset(struct MPContext *mpctx)
2738 if (mpctx->sh_video) {
2739 current_module = "seek_video_reset";
2740 resync_video_stream(mpctx->sh_video);
2741 mpctx->sh_video->timer = 0;
2742 vo_seek_reset(mpctx->video_out);
2743 mpctx->sh_video->timer = 0;
2744 mpctx->sh_video->num_buffered_pts = 0;
2745 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2746 mpctx->delay = 0;
2747 mpctx->time_frame = 0;
2748 mpctx->update_video_immediately = true;
2749 // Not all demuxers set d_video->pts during seek, so this value
2750 // (which is used by at least vobsub and edl code below) may
2751 // be completely wrong (probably 0).
2752 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2753 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2754 mpctx->sh_video->pts, mpctx->video_offset,
2755 mpctx->d_sub, 1);
2756 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2759 if (mpctx->sh_audio) {
2760 current_module = "seek_audio_reset";
2761 resync_audio_stream(mpctx->sh_audio);
2762 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2763 mpctx->sh_audio->a_buffer_len = 0;
2764 mpctx->sh_audio->a_out_buffer_len = 0;
2765 if (!mpctx->sh_video)
2766 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2767 mpctx->video_offset, mpctx->d_sub, 1);
2770 if (vo_vobsub && mpctx->sh_video) {
2771 current_module = "seek_vobsub_reset";
2772 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2775 edl_seek_reset(mpctx);
2777 mpctx->total_avsync_change = 0;
2778 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2779 drop_frame_cnt = 0;
2781 current_module = NULL;
2784 static bool timeline_set_part(struct MPContext *mpctx, int i)
2786 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2787 struct timeline_part *n = mpctx->timeline + i;
2788 mpctx->timeline_part = i;
2789 mpctx->video_offset = n->start - n->source_start;
2790 if (n->source == p->source)
2791 return false;
2792 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2793 mpctx->demuxer = n->source->demuxer;
2794 mpctx->d_video = mpctx->demuxer->video;
2795 mpctx->d_audio = mpctx->demuxer->audio;
2796 mpctx->d_sub = mpctx->demuxer->sub;
2797 mpctx->sh_video = mpctx->d_video->sh;
2798 mpctx->sh_audio = mpctx->d_audio->sh;
2799 return true;
2802 // Given pts, switch playback to the corresponding part.
2803 // Return offset within that part.
2804 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2805 bool *need_reset)
2807 if (pts < 0)
2808 pts = 0;
2809 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2810 struct timeline_part *p = mpctx->timeline + i;
2811 if (pts < (p+1)->start) {
2812 *need_reset = timeline_set_part(mpctx, i);
2813 return pts - p->start + p->source_start;
2816 return -1;
2820 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2821 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2822 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2823 static int seek(MPContext *mpctx, double amount, int style)
2825 current_module = "seek";
2826 if (mpctx->stop_play == AT_END_OF_FILE)
2827 mpctx->stop_play = KEEP_PLAYING;
2828 if (style & SEEK_FACTOR
2829 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2830 || amount < 0)
2831 mpctx->last_chapter_seek = -1;
2832 if (mpctx->timeline && style & SEEK_FACTOR) {
2833 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2834 style &= ~SEEK_FACTOR;
2836 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2837 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2838 style |= SEEK_ABSOLUTE;
2839 if (amount > 0)
2840 style |= SEEK_FORWARD;
2841 else
2842 style |= SEEK_BACKWARD;
2843 amount += mpctx->sh_video->pts;
2846 /* At least the liba52 decoder wants to read from the input stream
2847 * during initialization, so reinit must be done after the demux_seek()
2848 * call that clears possible stream EOF. */
2849 bool need_reset = false;
2850 if (mpctx->timeline) {
2851 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2852 if (amount == -1) {
2853 mpctx->stop_play = AT_END_OF_FILE;
2854 // Clear audio from current position
2855 if (mpctx->sh_audio) {
2856 mpctx->audio_out->reset();
2857 mpctx->sh_audio->a_buffer_len = 0;
2858 mpctx->sh_audio->a_out_buffer_len = 0;
2860 return -1;
2863 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2864 if (need_reset)
2865 reinit_decoders(mpctx);
2866 if (seekresult == 0)
2867 return -1;
2869 seek_reset(mpctx);
2870 return 0;
2873 // -2 is no chapters, -1 is before first chapter
2874 int get_current_chapter(struct MPContext *mpctx)
2876 if (!mpctx->chapters || !mpctx->sh_video)
2877 return FFMAX(mpctx->last_chapter_seek,
2878 demuxer_get_current_chapter(mpctx->demuxer));
2880 int i;
2881 double current_pts = mpctx->sh_video->pts;
2882 for (i = 1; i < mpctx->num_chapters; i++)
2883 if (current_pts < mpctx->chapters[i].start)
2884 break;
2885 return FFMAX(mpctx->last_chapter_seek, i - 1);
2888 // currently returns a string allocated with malloc, not talloc
2889 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2891 if (!mpctx->chapters || !mpctx->sh_video)
2892 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2893 return strdup(mpctx->chapters[chapter].name);
2896 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2897 char **chapter_name)
2899 mpctx->last_chapter_seek = -1;
2900 if (!mpctx->chapters || !mpctx->sh_video) {
2901 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2902 chapter_name);
2903 if (res >= 0) {
2904 if (*seek_pts == -1)
2905 seek_reset(mpctx);
2906 else {
2907 mpctx->last_chapter_seek = res;
2908 mpctx->last_chapter_pts = *seek_pts;
2911 return res;
2914 if (chapter >= mpctx->num_chapters)
2915 return -1;
2916 if (chapter < 0)
2917 chapter = 0;
2918 *seek_pts = mpctx->chapters[chapter].start;
2919 mpctx->last_chapter_seek = chapter;
2920 mpctx->last_chapter_pts = *seek_pts;
2921 if (chapter_name)
2922 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2923 return chapter;
2926 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2927 struct content_source *sources,
2928 int num_sources,
2929 unsigned char uid_map[][16])
2931 int num_filenames = 0;
2932 char **filenames = NULL;
2933 if (num_sources > 1) {
2934 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2935 "other sources.\n");
2936 if (mpctx->stream->type != STREAMTYPE_FILE) {
2937 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2938 "normal disk file. Will not search for related files.\n");
2939 } else {
2940 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2941 "same directory to find referenced sources.\n");
2942 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2943 &num_filenames);
2947 int num_left = num_sources - 1;
2948 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2949 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2950 filename_recode(filenames[i]));
2951 int format;
2952 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2953 if (!s)
2954 continue;
2955 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2956 mpctx->opts.audio_id,
2957 mpctx->opts.video_id,
2958 mpctx->opts.sub_id, filenames[i]);
2959 if (!d) {
2960 free_stream(s);
2961 continue;
2963 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2964 for (int i = 1; i < num_sources; i++) {
2965 if (sources[i].demuxer)
2966 continue;
2967 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2968 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2969 i, filename_recode(d->filename));
2970 sources[i].stream = s;
2971 sources[i].demuxer = d;
2972 num_left--;
2973 goto match;
2977 free_demuxer(d);
2978 free_stream(s);
2979 continue;
2980 match:
2983 talloc_free(filenames);
2984 if (num_left) {
2985 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2986 "There will be parts MISSING from the video!\n");
2987 for (int i = 1, j = 1; i < num_sources; i++)
2988 if (sources[i].demuxer) {
2989 sources[j] = sources[i];
2990 memcpy(uid_map[j], uid_map[i], 16);
2991 j++;
2994 return num_sources - num_left;
2997 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2999 if (!mpctx->opts.ordered_chapters) {
3000 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3001 "you have disabled support for them. Ignoring.\n");
3002 return;
3005 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3006 "edit timeline.\n");
3008 struct demuxer *demuxer = mpctx->demuxer;
3009 struct matroska_data *m = &demuxer->matroska_data;
3011 // +1 because sources/uid_map[0] is original file even if all chapters
3012 // actually use other sources and need separate entries
3013 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3014 m->num_ordered_chapters+1);
3015 sources[0].stream = mpctx->stream;
3016 sources[0].demuxer = mpctx->demuxer;
3017 unsigned char uid_map[m->num_ordered_chapters+1][16];
3018 int num_sources = 1;
3019 memcpy(uid_map[0], m->segment_uid, 16);
3021 for (int i = 0; i < m->num_ordered_chapters; i++) {
3022 struct matroska_chapter *c = m->ordered_chapters + i;
3023 if (!c->has_segment_uid)
3024 memcpy(c->segment_uid, m->segment_uid, 16);
3026 for (int j = 0; j < num_sources; j++)
3027 if (!memcmp(c->segment_uid, uid_map[j], 16))
3028 goto found1;
3029 memcpy(uid_map[num_sources], c->segment_uid, 16);
3030 sources[num_sources] = (struct content_source){};
3031 num_sources++;
3032 found1:
3036 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3037 uid_map);
3040 // +1 for terminating chapter with start time marking end of last real one
3041 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3042 m->num_ordered_chapters + 1);
3043 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3044 m->num_ordered_chapters);
3045 uint64_t starttime = 0;
3046 uint64_t missing_time = 0;
3047 int part_count = 0;
3048 int num_chapters = 0;
3049 uint64_t prev_part_offset = 0;
3050 for (int i = 0; i < m->num_ordered_chapters; i++) {
3051 struct matroska_chapter *c = m->ordered_chapters + i;
3053 int j;
3054 for (j = 0; j < num_sources; j++) {
3055 if (!memcmp(c->segment_uid, uid_map[j], 16))
3056 goto found2;
3058 missing_time += c->end - c->start;
3059 continue;
3060 found2:;
3061 chapters[num_chapters].start = starttime / 1000.;
3062 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3063 /* Only add a separate part if the time or file actually changes.
3064 * Matroska files have chapter divisions that are redundant from
3065 * timeline point of view because the same chapter structure is used
3066 * both to specify the timeline and for normal chapter information.
3067 * Removing a missing inserted external chapter can also cause this. */
3068 if (part_count == 0 || c->start != starttime + prev_part_offset
3069 || sources + j != timeline[part_count - 1].source) {
3070 timeline[part_count].source = sources + j;
3071 timeline[part_count].start = chapters[num_chapters].start;
3072 timeline[part_count].source_start = c->start / 1000.;
3073 prev_part_offset = c->start - starttime;
3074 part_count++;
3076 starttime += c->end - c->start;
3077 num_chapters++;
3079 timeline[part_count].start = starttime / 1000.;
3081 if (!part_count) {
3082 // None of the parts come from the file itself???
3083 talloc_free(sources);
3084 talloc_free(timeline);
3085 talloc_free(chapters);
3086 return;
3089 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3090 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3091 timeline[part_count].start);
3092 if (missing_time)
3093 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3094 "from the timeline!\n", missing_time / 1000.);
3095 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3096 for (int i = 0; i < num_sources; i++)
3097 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3098 filename_recode(sources[i].demuxer->filename));
3099 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3100 "source_start, source):\n");
3101 for (int i = 0; i < part_count; i++) {
3102 struct timeline_part *p = timeline + i;
3103 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3104 p->source_start, p->source - sources);
3106 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3107 mpctx->sources = sources;
3108 mpctx->num_sources = num_sources;
3109 mpctx->timeline = timeline;
3110 mpctx->num_timeline_parts = part_count;
3111 mpctx->num_chapters = num_chapters;
3112 mpctx->chapters = chapters;
3114 mpctx->timeline_part = 0;
3115 mpctx->demuxer = timeline[0].source->demuxer;
3119 static int read_keys(void *ctx, int fd)
3121 getch2(ctx);
3122 return mplayer_get_key(ctx, 0);
3126 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3127 * file for some tools to link against. */
3128 #ifndef DISABLE_MAIN
3129 int main(int argc,char* argv[]){
3132 char * mem_ptr;
3134 // movie info:
3136 /* Flag indicating whether MPlayer should exit without playing anything. */
3137 int opt_exit = 0;
3139 //float a_frame=0; // Audio
3141 int i;
3143 struct MPContext *mpctx = &(struct MPContext){
3144 .osd_function = OSD_PLAY,
3145 .begin_skip = MP_NOPTS_VALUE,
3146 .play_tree_step = 1,
3147 .global_sub_pos = -1,
3148 .set_of_sub_pos = -1,
3149 .file_format = DEMUXER_TYPE_UNKNOWN,
3150 .last_dvb_step = 1,
3153 InitTimer();
3154 srand(GetTimerMS());
3156 mp_msg_init();
3157 set_av_log_callback();
3159 #ifdef CONFIG_X11
3160 mpctx->x11_state = vo_x11_init_state();
3161 #endif
3162 struct MPOpts *opts = &mpctx->opts;
3163 set_default_mplayer_options(opts);
3164 // Create the config context and register the options
3165 mpctx->mconfig = m_config_new(opts, cfg_include);
3166 m_config_register_options(mpctx->mconfig,mplayer_opts);
3167 m_config_register_options(mpctx->mconfig, common_opts);
3168 mp_input_register_options(mpctx->mconfig);
3170 // Preparse the command line
3171 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3173 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3174 set_path_env();
3175 #endif
3177 #ifdef CONFIG_TV
3178 stream_tv_defaults.immediate = 1;
3179 #endif
3181 parse_cfgfiles(mpctx, mpctx->mconfig);
3183 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3184 if(mpctx->playtree == NULL)
3185 opt_exit = 1;
3186 else {
3187 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3188 if(mpctx->playtree) {
3189 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3190 if(mpctx->playtree_iter) {
3191 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3192 play_tree_iter_free(mpctx->playtree_iter);
3193 mpctx->playtree_iter = NULL;
3195 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3199 mpctx->key_fifo = mp_fifo_create(opts);
3201 print_version("MPlayer");
3203 #if defined(__MINGW32__) || defined(__CYGWIN__)
3205 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3206 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3207 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3208 if (kernel32) {
3209 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3210 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3212 if (setDEP) setDEP(3);
3213 if (setDllDir) setDllDir("");
3215 // stop Windows from showing all kinds of annoying error dialogs
3216 SetErrorMode(0x8003);
3217 // request 1ms timer resolution
3218 timeBeginPeriod(1);
3219 #endif
3221 #ifdef CONFIG_PRIORITY
3222 set_priority();
3223 #endif
3225 if (codec_path)
3226 set_codec_path(codec_path);
3228 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3229 list_video_out();
3230 opt_exit = 1;
3233 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3234 list_audio_out();
3235 opt_exit = 1;
3238 /* Check codecs.conf. */
3239 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3240 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3241 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3242 if(!parse_codec_cfg(NULL)){
3243 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3245 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3248 free( mem_ptr ); // release the buffer created by get_path()
3251 #if 0
3252 if(video_codec_list){
3253 int i;
3254 video_codec=video_codec_list[0];
3255 for(i=0;video_codec_list[i];i++)
3256 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
3258 #endif
3259 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3260 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3261 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3262 list_codecs(1);
3263 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3264 opt_exit = 1;
3266 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3267 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3268 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3269 list_codecs(0);
3270 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3271 opt_exit = 1;
3273 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3274 vfm_help();
3275 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3276 opt_exit = 1;
3278 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3279 afm_help();
3280 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3281 opt_exit = 1;
3283 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3284 af_help();
3285 printf("\n");
3286 opt_exit = 1;
3288 #ifdef CONFIG_X11
3289 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3290 fstype_help();
3291 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3292 opt_exit = 1;
3294 #endif
3295 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3296 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3297 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3298 demuxer_help();
3299 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3300 opt_exit = 1;
3302 if(list_properties) {
3303 property_print_help();
3304 opt_exit = 1;
3307 if(opt_exit)
3308 exit_player(mpctx, EXIT_NONE);
3310 if(!mpctx->filename && !player_idle_mode){
3311 // no file/vcd/dvd -> show HELP:
3312 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3313 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3316 /* Display what configure line was used */
3317 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3319 // Many users forget to include command line in bugreports...
3320 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3321 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3322 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3323 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3326 //------ load global data first ------
3328 mpctx->osd = osd_create();
3330 // check font
3331 #ifdef CONFIG_FREETYPE
3332 init_freetype();
3333 #endif
3334 #ifdef CONFIG_FONTCONFIG
3335 if(font_fontconfig <= 0)
3337 #endif
3338 #ifdef CONFIG_BITMAP_FONT
3339 if(font_name){
3340 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3341 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3342 filename_recode(font_name));
3343 } else {
3344 // try default:
3345 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3346 free(mem_ptr); // release the buffer created by get_path()
3347 if(!vo_font)
3348 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3350 if (sub_font_name)
3351 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3352 else
3353 mpctx->osd->sub_font = vo_font;
3354 #endif
3355 #ifdef CONFIG_FONTCONFIG
3357 #endif
3359 #ifdef CONFIG_ASS
3360 ass_library = ass_init();
3361 #endif
3363 #ifdef HAVE_RTC
3364 if(!nortc)
3366 // seteuid(0); /* Can't hurt to try to get root here */
3367 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3368 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3369 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3370 else {
3371 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3373 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3374 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3375 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3376 close (rtc_fd);
3377 rtc_fd = -1;
3378 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3379 /* variable only by the root */
3380 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3381 close (rtc_fd);
3382 rtc_fd = -1;
3383 } else
3384 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3387 if(rtc_fd<0)
3388 #endif /* HAVE_RTC */
3389 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3390 softsleep?"software":timer_name);
3392 #ifdef HAVE_TERMCAP
3393 load_termcap(NULL); // load key-codes
3394 #endif
3396 // ========== Init keyboard FIFO (connection to libvo) ============
3398 // Init input system
3399 current_module = "init_input";
3400 mpctx->input = mp_input_init(&opts->input);
3401 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3402 if(slave_mode)
3403 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3404 else if(!noconsolecontrols)
3405 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3406 // Set the libstream interrupt callback
3407 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3409 #ifdef CONFIG_MENU
3410 if(use_menu) {
3411 if(menu_cfg && 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 menu_cfg = get_path("menu.conf");
3415 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3416 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3417 else {
3418 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3419 MPLAYER_CONFDIR "/menu.conf"))
3420 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3421 else {
3422 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3423 use_menu = 0;
3428 #endif
3430 current_module = NULL;
3432 /// Catch signals
3433 #ifndef __MINGW32__
3434 signal(SIGCHLD,child_sighandler);
3435 #endif
3437 #ifdef CONFIG_CRASH_DEBUG
3438 prog_path = argv[0];
3439 #endif
3440 //========= Catch terminate signals: ================
3441 // terminate requests:
3442 signal(SIGTERM,exit_sighandler); // kill
3443 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3445 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3447 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3448 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3449 #ifdef CONFIG_SIGHANDLER
3450 // fatal errors:
3451 signal(SIGBUS,exit_sighandler); // bus error
3452 signal(SIGSEGV,exit_sighandler); // segfault
3453 signal(SIGILL,exit_sighandler); // illegal instruction
3454 signal(SIGFPE,exit_sighandler); // floating point exc.
3455 signal(SIGABRT,exit_sighandler); // abort()
3456 #ifdef CONFIG_CRASH_DEBUG
3457 if (crash_debug)
3458 signal(SIGTRAP,exit_sighandler);
3459 #endif
3460 #endif
3462 // ******************* Now, let's see the per-file stuff ********************
3464 play_next_file:
3466 // init global sub numbers
3467 mpctx->global_sub_size = 0;
3468 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3470 if (mpctx->filename) {
3471 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3472 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3473 load_per_file_config (mpctx->mconfig, mpctx->filename);
3476 if (opts->video_driver_list)
3477 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3478 if (opts->audio_driver_list)
3479 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3481 // We must enable getch2 here to be able to interrupt network connection
3482 // or cache filling
3483 if(!noconsolecontrols && !slave_mode){
3484 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3485 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3486 else
3487 getch2_enable(); // prepare stdin for hotkeys...
3488 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3489 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3492 // =================== GUI idle loop (STOP state) ===========================
3493 while (player_idle_mode && !mpctx->filename) {
3494 play_tree_t * entry = NULL;
3495 mp_cmd_t * cmd;
3496 if (mpctx->video_out && mpctx->video_out->config_ok)
3497 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3498 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3499 if (mpctx->video_out)
3500 vo_check_events(mpctx->video_out);
3501 usec_sleep(20000);
3503 switch (cmd->id) {
3504 case MP_CMD_LOADFILE:
3505 // prepare a tree entry with the new filename
3506 entry = play_tree_new();
3507 play_tree_add_file(entry, cmd->args[0].v.s);
3508 // The entry is added to the main playtree after the switch().
3509 break;
3510 case MP_CMD_LOADLIST:
3511 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3512 break;
3513 case MP_CMD_QUIT:
3514 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3515 break;
3516 case MP_CMD_VO_FULLSCREEN:
3517 case MP_CMD_GET_PROPERTY:
3518 case MP_CMD_SET_PROPERTY:
3519 case MP_CMD_STEP_PROPERTY:
3520 run_command(mpctx, cmd);
3521 break;
3524 mp_cmd_free(cmd);
3526 if (entry) { // user entered a command that gave a valid entry
3527 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3528 play_tree_free_list(mpctx->playtree->child, 1);
3529 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3531 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3533 play_tree_set_child(mpctx->playtree, entry);
3535 /* Make iterator start at the top the of tree. */
3536 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3537 if (!mpctx->playtree_iter) continue;
3539 // find the first real item in the tree
3540 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3541 // no items!
3542 play_tree_iter_free(mpctx->playtree_iter);
3543 mpctx->playtree_iter = NULL;
3544 continue; // wait for next command
3546 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3549 //---------------------------------------------------------------------------
3551 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3552 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3554 if (mpctx->filename) {
3555 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3556 filename_recode(mpctx->filename));
3557 if(use_filename_title && vo_wintitle == NULL)
3558 vo_wintitle = strdup(mp_basename2(mpctx->filename));
3561 if (edl_filename) {
3562 if (edl_records) free_edl(edl_records);
3563 next_edl_record = edl_records = edl_parse_file();
3565 if (edl_output_filename) {
3566 if (edl_fd) fclose(edl_fd);
3567 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3569 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3570 filename_recode(edl_output_filename));
3574 //==================== Open VOB-Sub ============================
3576 current_module="vobsub";
3577 if (vobsub_name){
3578 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3579 if(vo_vobsub==NULL)
3580 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3581 filename_recode(vobsub_name));
3582 } else if (sub_auto && mpctx->filename){
3583 /* try to autodetect vobsub from movie filename ::atmos */
3584 char *buf = strdup(mpctx->filename), *psub;
3585 char *pdot = strrchr(buf, '.');
3586 char *pslash = strrchr(buf, '/');
3587 #if defined(__MINGW32__) || defined(__CYGWIN__)
3588 if (!pslash) pslash = strrchr(buf, '\\');
3589 #endif
3590 if (pdot && (!pslash || pdot > pslash))
3591 *pdot = '\0';
3592 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3593 /* try from ~/.mplayer/sub */
3594 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3595 char *bname;
3596 int l;
3597 bname = strrchr(buf,'/');
3598 #if defined(__MINGW32__) || defined(__CYGWIN__)
3599 if(!bname) bname = strrchr(buf,'\\');
3600 #endif
3601 if(bname) bname++;
3602 else bname = buf;
3603 l = strlen(psub) + strlen(bname) + 1;
3604 psub = realloc(psub,l);
3605 strcat(psub,bname);
3606 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3607 free(psub);
3609 free(buf);
3611 if(vo_vobsub){
3612 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3613 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3614 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3616 // setup global sub numbering
3617 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3620 //============ Open & Sync STREAM --- fork cache2 ====================
3622 mpctx->stream=NULL;
3623 mpctx->demuxer=NULL;
3624 if (mpctx->d_audio) {
3625 //free_demuxer_stream(mpctx->d_audio);
3626 mpctx->d_audio=NULL;
3628 if (mpctx->d_video) {
3629 //free_demuxer_stream(d_video);
3630 mpctx->d_video=NULL;
3632 mpctx->sh_audio=NULL;
3633 mpctx->sh_video=NULL;
3635 current_module="open_stream";
3636 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3637 if(!mpctx->stream) { // error...
3638 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3639 goto goto_next_file;
3641 mpctx->initialized_flags|=INITIALIZED_STREAM;
3643 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3644 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3645 "playlist support will not be used automatically.\n"
3646 "MPlayer's playlist code is unsafe and should only be used with "
3647 "trusted sources.\nPlayback will probably fail.\n\n");
3648 #if 0
3649 play_tree_t* entry;
3650 // Handle playlist
3651 current_module="handle_playlist";
3652 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3653 filename_recode(mpctx->filename));
3654 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3655 mpctx->eof=playtree_add_playlist(mpctx, entry);
3656 goto goto_next_file;
3657 #endif
3659 mpctx->stream->start_pos+=seek_to_byte;
3661 if(stream_dump_type==5){
3662 unsigned char buf[4096];
3663 int len;
3664 FILE *f;
3665 current_module="dumpstream";
3666 stream_reset(mpctx->stream);
3667 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3668 f=fopen(stream_dump_name,"wb");
3669 if(!f){
3670 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3671 exit_player(mpctx, EXIT_ERROR);
3673 if (opts->chapterrange[0] > 1) {
3674 int chapter = opts->chapterrange[0] - 1;
3675 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3677 while(!mpctx->stream->eof && !async_quit_request){
3678 len=stream_read(mpctx->stream,buf,4096);
3679 if(len>0) {
3680 if(fwrite(buf,len,1,f) != 1) {
3681 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3682 exit_player(mpctx, EXIT_ERROR);
3685 if (opts->chapterrange[1] > 0) {
3686 int chapter = -1;
3687 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3688 &chapter) == STREAM_OK
3689 && chapter + 1 > opts->chapterrange[1])
3690 break;
3693 if(fclose(f)) {
3694 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3695 exit_player(mpctx, EXIT_ERROR);
3697 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3698 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3701 #ifdef CONFIG_DVDREAD
3702 if(mpctx->stream->type==STREAMTYPE_DVD){
3703 current_module="dvd lang->id";
3704 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3705 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3706 // setup global sub numbering
3707 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3708 current_module=NULL;
3710 #endif
3712 #ifdef CONFIG_DVDNAV
3713 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3714 current_module="dvdnav lang->id";
3715 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3716 dvdsub_lang_id = -3;
3717 if(opts->sub_lang && opts->sub_id==-1)
3718 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3719 // setup global sub numbering
3720 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3721 current_module=NULL;
3723 #endif
3725 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3726 goto_enable_cache:
3727 if(stream_cache_size>0){
3728 int res;
3729 current_module="enable_cache";
3730 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3731 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3732 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3733 if(res == 0)
3734 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3737 //============ Open DEMUXERS --- DETECT file type =======================
3738 current_module="demux_open";
3740 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3742 // HACK to get MOV Reference Files working
3744 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3746 unsigned char* playlist_entry;
3747 play_tree_t *list = NULL, *entry = NULL;
3749 current_module="handle_demux_playlist";
3750 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3752 char *temp, *bname;
3754 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3755 filename_recode(playlist_entry));
3757 bname=mp_basename(playlist_entry);
3758 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3759 continue;
3761 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3762 continue;
3764 entry = play_tree_new();
3766 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3768 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3769 if (temp)
3771 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3772 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3773 strcat(temp, playlist_entry);
3774 if (!strcmp(temp, mpctx->filename)) {
3775 free(temp);
3776 continue;
3778 play_tree_add_file(entry,temp);
3779 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3780 free(temp);
3783 else
3784 play_tree_add_file(entry,playlist_entry);
3786 if(!list)
3787 list = entry;
3788 else
3789 play_tree_append_entry(list,entry);
3791 free_demuxer(mpctx->demuxer);
3792 mpctx->demuxer = NULL;
3794 if (list)
3796 entry = play_tree_new();
3797 play_tree_set_child(entry,list);
3798 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3799 goto goto_next_file;
3803 if(!mpctx->demuxer)
3804 goto goto_next_file;
3806 if (mpctx->demuxer->matroska_data.ordered_chapters)
3807 build_ordered_chapter_timeline(mpctx);
3809 if (!mpctx->sources) {
3810 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3811 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3812 .demuxer = mpctx->demuxer};
3813 mpctx->num_sources = 1;
3816 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3818 #ifdef CONFIG_ASS
3819 if (opts->ass_enabled && ass_library) {
3820 for (int j = 0; j < mpctx->num_sources; j++) {
3821 struct demuxer *d = mpctx->sources[j].demuxer;
3822 for (int i = 0; i < d->num_attachments; i++) {
3823 struct demux_attachment *att = d->attachments + i;
3824 if (use_embedded_fonts && attachment_is_font(att))
3825 ass_add_font(ass_library, att->name, att->data, att->data_size);
3829 #endif
3831 current_module="demux_open2";
3833 //file_format=demuxer->file_format;
3835 mpctx->d_audio=mpctx->demuxer->audio;
3836 mpctx->d_video=mpctx->demuxer->video;
3837 mpctx->d_sub=mpctx->demuxer->sub;
3839 if (ts_prog) {
3840 int tmp = ts_prog;
3841 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3843 // select audio stream
3844 if (mpctx->num_sources)
3845 for (int i = 0; i < mpctx->num_sources; i++)
3846 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3847 opts->audio_lang);
3848 else
3849 select_audio(mpctx->demuxer, opts->audio_id, opts->audio_lang);
3851 // DUMP STREAMS:
3852 if((stream_dump_type)&&(stream_dump_type<4)){
3853 FILE *f;
3854 demux_stream_t *ds=NULL;
3855 current_module="dump";
3856 // select stream to dump
3857 switch(stream_dump_type){
3858 case 1: ds=mpctx->d_audio;break;
3859 case 2: ds=mpctx->d_video;break;
3860 case 3: ds=mpctx->d_sub;break;
3862 if(!ds){
3863 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3864 exit_player(mpctx, EXIT_ERROR);
3866 // disable other streams:
3867 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3868 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3869 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3870 // let's dump it!
3871 f=fopen(stream_dump_name,"wb");
3872 if(!f){
3873 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3874 exit_player(mpctx, EXIT_ERROR);
3876 while(!ds->eof){
3877 unsigned char* start;
3878 int in_size=ds_get_packet(ds,&start);
3879 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3880 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3881 if(in_size>0) fwrite(start,in_size,1,f);
3882 if (opts->chapterrange[1] > 0) {
3883 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3884 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3885 break;
3888 fclose(f);
3889 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3890 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3893 mpctx->sh_audio=mpctx->d_audio->sh;
3894 mpctx->sh_video=mpctx->d_video->sh;
3896 if(mpctx->sh_video){
3898 current_module="video_read_properties";
3899 if(!video_read_properties(mpctx->sh_video)) {
3900 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3901 mpctx->sh_video=mpctx->d_video->sh=NULL;
3902 } else {
3903 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3904 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3905 mpctx->sh_video->fps,mpctx->sh_video->frametime
3908 /* need to set fps here for output encoders to pick it up in their init */
3909 if(force_fps){
3910 mpctx->sh_video->fps=force_fps;
3911 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3913 vo_fps = mpctx->sh_video->fps;
3915 if(!mpctx->sh_video->fps && !force_fps){
3916 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3917 mpctx->opts.correct_pts = 1;
3923 if(!mpctx->sh_video && !mpctx->sh_audio){
3924 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3925 #ifdef CONFIG_DVBIN
3926 if(mpctx->stream->type == STREAMTYPE_DVB)
3928 int dir;
3929 int v = mpctx->last_dvb_step;
3930 if(v > 0)
3931 dir = DVB_CHANNEL_HIGHER;
3932 else
3933 dir = DVB_CHANNEL_LOWER;
3935 if(dvb_step_channel(mpctx->stream, dir)) {
3936 mpctx->stop_play = PT_NEXT_ENTRY;
3937 mpctx->dvbin_reopen = 1;
3940 #endif
3941 goto goto_next_file; // exit_player(_("Fatal error"));
3944 /* display clip info */
3945 demux_info_print(mpctx->demuxer);
3947 //================== Read SUBTITLES (DVD & TEXT) ==========================
3948 if(vo_spudec==NULL &&
3949 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3950 init_vo_spudec(mpctx);
3953 // after reading video params we should load subtitles because
3954 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3955 // check .sub
3956 current_module="read_subtitles_file";
3957 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3958 if(sub_name){
3959 for (i = 0; sub_name[i] != NULL; ++i)
3960 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3962 if(sub_auto) { // auto load sub file ...
3963 char *psub = get_path( "sub/" );
3964 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3965 int i = 0;
3966 free(psub); // release the buffer created by get_path() above
3967 while (tmp[i]) {
3968 add_subtitles(mpctx, tmp[i], sub_fps, 1);
3969 free(tmp[i++]);
3971 free(tmp);
3973 if (mpctx->set_of_sub_size > 0)
3974 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
3976 if (select_subtitle(mpctx)) {
3977 if(subdata)
3978 switch (stream_dump_type) {
3979 case 3: list_sub_file(subdata); break;
3980 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3981 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3982 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3983 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3984 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3988 print_file_properties(mpctx, mpctx->filename);
3990 if(!mpctx->sh_video) goto main; // audio-only
3992 if(!reinit_video_chain(mpctx)) {
3993 if(!mpctx->sh_video){
3994 if(!mpctx->sh_audio) goto goto_next_file;
3995 goto main; // exit_player(_("Fatal error"));
3999 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4000 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4002 #ifdef CONFIG_FREETYPE
4003 force_load_font = 1;
4004 #endif
4006 //================== MAIN: ==========================
4007 main:
4008 current_module="main";
4010 if(playing_msg) {
4011 char* msg = property_expand_string(mpctx, playing_msg);
4012 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4013 free(msg);
4017 // Disable the term OSD in verbose mode
4018 if(verbose) term_osd = 0;
4021 //int frame_corr_num=0; //
4022 //float v_frame=0; // Video
4023 //float num_frames=0; // number of frames played
4025 int frame_time_remaining=0; // flag
4026 int blit_frame=0;
4028 // Make sure old OSD does not stay around,
4029 // e.g. with -fixed-vo and same-resolution files
4030 clear_osd_msgs();
4031 update_osd_msg(mpctx);
4033 //================ SETUP AUDIO ==========================
4035 if(mpctx->sh_audio){
4036 reinit_audio_chain(mpctx);
4037 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4038 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4041 current_module="av_init";
4043 if(mpctx->sh_video){
4044 mpctx->sh_video->timer=0;
4045 if (! ignore_start)
4046 audio_delay += mpctx->sh_video->stream_delay;
4048 if(mpctx->sh_audio){
4049 if (start_volume >= 0)
4050 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4051 if (! ignore_start)
4052 audio_delay -= mpctx->sh_audio->stream_delay;
4053 mpctx->delay=-audio_delay;
4056 if(!mpctx->sh_audio){
4057 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4058 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4059 ds_free_packs(mpctx->d_audio); // free buffered chunks
4060 //mpctx->d_audio->id=-2; // do not read audio chunks
4061 //uninit_player(mpctx, INITIALIZED_AO); // close device
4063 if(!mpctx->sh_video){
4064 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4065 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4066 ds_free_packs(mpctx->d_video);
4067 mpctx->d_video->id=-2;
4068 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4071 if (!mpctx->sh_video && !mpctx->sh_audio)
4072 goto goto_next_file;
4074 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4075 if(force_fps && mpctx->sh_video){
4076 vo_fps = mpctx->sh_video->fps=force_fps;
4077 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4078 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4081 mp_input_set_section(mpctx->input, NULL);
4082 //TODO: add desired (stream-based) sections here
4083 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4084 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4086 //==================== START PLAYING =======================
4088 if(opts->loop_times>1) opts->loop_times--; else
4089 if(opts->loop_times==1) opts->loop_times = -1;
4091 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4093 total_time_usage_start=GetTimer();
4094 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4095 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4096 play_n_frames=play_n_frames_mf;
4098 if(play_n_frames==0){
4099 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4102 // If there's a timeline force an absolute seek to initialize state
4103 if (seek_to_sec || mpctx->timeline) {
4104 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4105 end_at.pos += seek_to_sec;
4107 if (opts->chapterrange[0] > 0) {
4108 double pts;
4109 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4110 && pts > -1.0)
4111 seek(mpctx, pts, SEEK_ABSOLUTE);
4114 if (end_at.type == END_AT_SIZE) {
4115 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4116 end_at.type = END_AT_NONE;
4119 #ifdef CONFIG_DVDNAV
4120 mp_dvdnav_context_free(mpctx);
4121 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4122 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4123 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4125 #endif
4127 get_relative_time(mpctx); // reset current delta
4128 mpctx->time_frame = 0;
4129 mpctx->drop_message_shown = 0;
4130 mpctx->update_video_immediately = true;
4131 mpctx->total_avsync_change = 0;
4132 mpctx->last_chapter_seek = -1;
4133 // Make sure VO knows current pause state
4134 if (mpctx->sh_video)
4135 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4136 NULL);
4138 while(!mpctx->stop_play){
4139 float aq_sleep_time=0;
4141 if (opts->chapterrange[1] > 0) {
4142 int cur_chapter = get_current_chapter(mpctx);
4143 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4144 goto goto_next_file;
4147 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4148 mpctx->sh_audio = mpctx->d_audio->sh;
4149 mpctx->sh_audio->ds = mpctx->d_audio;
4150 reinit_audio_chain(mpctx);
4153 /*========================== PLAY AUDIO ============================*/
4155 if (mpctx->sh_audio && !mpctx->paused)
4156 if (!fill_audio_out_buffers(mpctx))
4157 // at eof, all audio at least written to ao
4158 if (!mpctx->sh_video)
4159 mpctx->stop_play = AT_END_OF_FILE;
4162 if(!mpctx->sh_video) {
4163 // handle audio-only case:
4164 double a_pos=0;
4165 // sh_audio can be NULL due to video stream switching
4166 // TODO: handle this better
4167 if (mpctx->sh_audio)
4168 a_pos = playing_audio_pts(mpctx);
4170 print_status(mpctx, a_pos, false);
4172 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4173 mpctx->stop_play = PT_NEXT_ENTRY;
4174 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4175 mpctx->d_sub, 0);
4176 update_osd_msg(mpctx);
4178 } else {
4180 /*========================== PLAY VIDEO ============================*/
4182 vo_pts=mpctx->sh_video->timer*90000.0;
4183 vo_fps=mpctx->sh_video->fps;
4185 blit_frame = mpctx->video_out->frame_loaded;
4186 if (!blit_frame) {
4187 double frame_time = update_video(mpctx);
4188 blit_frame = mpctx->video_out->frame_loaded;
4189 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4190 if (mpctx->sh_video->vf_initialized < 0) {
4191 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4192 mpctx->stop_play = PT_NEXT_ENTRY;
4193 goto goto_next_file;
4195 if (blit_frame) {
4196 struct sh_video *sh_video = mpctx->sh_video;
4197 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4198 mpctx->video_offset, mpctx->d_sub, 0);
4199 update_teletext(sh_video, mpctx->demuxer, 0);
4200 update_osd_msg(mpctx);
4201 struct vf_instance *vf = mpctx->sh_video->vfilter;
4202 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4203 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4204 vo_osd_changed(0);
4206 if (frame_time < 0)
4207 mpctx->stop_play = AT_END_OF_FILE;
4208 else {
4209 if (mpctx->update_video_immediately) {
4210 // Show this frame immediately, rest normally
4211 mpctx->update_video_immediately = false;
4212 } else {
4213 mpctx->time_frame += frame_time / opts->playback_speed;
4214 adjust_sync(mpctx, frame_time);
4218 if (mpctx->timeline) {
4219 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4220 if (mpctx->sh_video->pts >= next->start
4221 || mpctx->stop_play == AT_END_OF_FILE
4222 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4223 seek(mpctx, next->start, SEEK_ABSOLUTE);
4224 continue;
4228 // ==========================================================================
4230 // current_module="draw_osd";
4231 // if(vo_config_count) mpctx->video_out->draw_osd();
4233 current_module="vo_check_events";
4234 vo_check_events(mpctx->video_out);
4236 #ifdef CONFIG_X11
4237 if (stop_xscreensaver) {
4238 current_module = "stop_xscreensaver";
4239 xscreensaver_heartbeat(mpctx->x11_state);
4241 #endif
4242 if (heartbeat_cmd) {
4243 static unsigned last_heartbeat;
4244 unsigned now = GetTimerMS();
4245 if (now - last_heartbeat > 30000) {
4246 last_heartbeat = now;
4247 system(heartbeat_cmd);
4251 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4253 //====================== FLIP PAGE (VIDEO BLT): =========================
4255 current_module="flip_page";
4256 if (!frame_time_remaining && blit_frame) {
4257 unsigned int t2=GetTimer();
4258 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4259 int duration = -1;
4260 double pts2 = mpctx->video_out->next_pts2;
4261 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4262 // expected A/V sync correction is ignored
4263 double diff = (pts2 - mpctx->sh_video->pts);
4264 diff /= opts->playback_speed;
4265 if (mpctx->time_frame < 0)
4266 diff += mpctx->time_frame;
4267 if (diff < 0)
4268 diff = 0;
4269 if (diff > 10)
4270 diff = 10;
4271 duration = diff * 1e6;
4273 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4275 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4276 vout_time_usage += mpctx->last_vo_flip_duration;
4277 if (mpctx->video_out->driver->flip_page_timed) {
4278 // No need to adjust sync based on flip speed
4279 mpctx->last_vo_flip_duration = 0;
4280 // For print_status - VO call finishing early is OK for sync
4281 mpctx->time_frame -= get_relative_time(mpctx);
4283 print_status(mpctx, MP_NOPTS_VALUE, true);
4285 else
4286 print_status(mpctx, MP_NOPTS_VALUE, false);
4288 //============================ Auto QUALITY ============================
4290 /*Output quality adjustments:*/
4291 if(auto_quality>0){
4292 current_module="autoq";
4293 // float total=0.000001f * (GetTimer()-aq_total_time);
4294 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4295 if(output_quality<auto_quality && aq_sleep_time>0)
4296 ++output_quality;
4297 else
4298 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4299 if(output_quality>1 && aq_sleep_time<0)
4300 --output_quality;
4301 else
4302 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4303 output_quality=0;
4304 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4305 set_video_quality(mpctx->sh_video,output_quality);
4308 if (!frame_time_remaining && blit_frame) {
4309 if (play_n_frames >= 0) {
4310 --play_n_frames;
4311 if (play_n_frames <= 0)
4312 mpctx->stop_play = PT_NEXT_ENTRY;
4314 if (mpctx->step_frames > 0) {
4315 mpctx->step_frames--;
4316 if (mpctx->step_frames == 0)
4317 pause_player(mpctx);
4322 // FIXME: add size based support for -endpos
4323 if (end_at.type == END_AT_TIME &&
4324 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4325 mpctx->stop_play = PT_NEXT_ENTRY;
4327 } // end if(mpctx->sh_video)
4329 #ifdef CONFIG_DVDNAV
4330 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4331 nav_highlight_t hl;
4332 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4333 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4334 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4335 vo_osd_changed (OSDTYPE_DVDNAV);
4336 } else {
4337 osd_set_nav_box(0, 0, 0, 0);
4338 vo_osd_changed(OSDTYPE_DVDNAV);
4339 vo_osd_changed(OSDTYPE_SPU);
4342 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4343 double ar = -1.0;
4344 if (mpctx->sh_video &&
4345 stream_control (mpctx->demuxer->stream,
4346 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4347 != STREAM_UNSUPPORTED)
4348 mpctx->sh_video->stream_aspect = ar;
4351 #endif
4353 //================= Keyboard events, SEEKing ====================
4355 current_module="key_events";
4358 while (1) {
4359 mp_cmd_t* cmd;
4360 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4361 run_command(mpctx, cmd);
4362 mp_cmd_free(cmd);
4363 if (mpctx->stop_play)
4364 break;
4365 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4366 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4367 /* Allow seek commands to be combined, but execute the real seek
4368 * before processing other commands */
4369 if (!cmd || cmd->id != MP_CMD_SEEK)
4370 break;
4373 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4374 || mpctx->abs_seek_pos)
4375 break;
4376 if (mpctx->sh_video) {
4377 update_osd_msg(mpctx);
4378 int hack = vo_osd_changed(0);
4379 vo_osd_changed(hack);
4380 if (hack) {
4381 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4382 add_step_frame(mpctx);
4383 break;
4385 else
4386 vo_osd_changed(0);
4389 pause_loop(mpctx);
4393 // handle -sstep
4394 if (step_sec > 0 && !mpctx->paused) {
4395 mpctx->osd_function=OSD_FFW;
4396 mpctx->rel_seek_secs+=step_sec;
4399 edl_update(mpctx);
4401 /* Looping. */
4402 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4403 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4405 if(opts->loop_times>1) opts->loop_times--; else
4406 if(opts->loop_times==1) opts->loop_times=-1;
4407 play_n_frames=play_n_frames_mf;
4408 mpctx->stop_play=0;
4409 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4412 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4413 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4415 mpctx->rel_seek_secs=0;
4416 mpctx->abs_seek_pos=0;
4419 } // while(!mpctx->stop_play)
4421 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4423 #ifdef CONFIG_DVBIN
4424 if(mpctx->dvbin_reopen)
4426 mpctx->stop_play = 0;
4427 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4428 cache_uninit(mpctx->stream);
4429 mpctx->dvbin_reopen = 0;
4430 goto goto_enable_cache;
4432 #endif
4435 goto_next_file: // don't jump here after ao/vo/getch initialization!
4437 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4439 if(benchmark){
4440 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4441 double total_time_usage;
4442 total_time_usage_start=GetTimer()-total_time_usage_start;
4443 total_time_usage = (float)total_time_usage_start*0.000001;
4444 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4445 video_time_usage,vout_time_usage,audio_time_usage,
4446 total_time_usage-tot,total_time_usage);
4447 if(total_time_usage>0.0)
4448 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4449 100.0*video_time_usage/total_time_usage,
4450 100.0*vout_time_usage/total_time_usage,
4451 100.0*audio_time_usage/total_time_usage,
4452 100.0*(total_time_usage-tot)/total_time_usage,
4453 100.0);
4454 if(total_frame_cnt && frame_dropping)
4455 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4456 total_frame_cnt-drop_frame_cnt,
4457 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4458 drop_frame_cnt,
4459 100*drop_frame_cnt/total_frame_cnt,
4460 total_frame_cnt,
4461 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4464 // time to uninit all, except global stuff:
4465 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4467 if(mpctx->set_of_sub_size > 0) {
4468 current_module="sub_free";
4469 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4470 sub_free(mpctx->set_of_subtitles[i]);
4471 #ifdef CONFIG_ASS
4472 if(mpctx->set_of_ass_tracks[i])
4473 ass_free_track( mpctx->set_of_ass_tracks[i] );
4474 #endif
4476 mpctx->set_of_sub_size = 0;
4478 vo_sub_last = vo_sub=NULL;
4479 subdata=NULL;
4480 #ifdef CONFIG_ASS
4481 ass_track = NULL;
4482 if(ass_library)
4483 ass_clear_fonts(ass_library);
4484 #endif
4486 if (!mpctx->stop_play) // In case some goto jumped here...
4487 mpctx->stop_play = PT_NEXT_ENTRY;
4489 int playtree_direction = 1;
4491 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4492 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4493 play_tree_iter_free(mpctx->playtree_iter);
4494 mpctx->playtree_iter = NULL;
4496 mpctx->play_tree_step = 1;
4497 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4498 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4499 if(mpctx->playtree_iter) {
4500 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4501 play_tree_iter_free(mpctx->playtree_iter);
4502 mpctx->playtree_iter = NULL;
4505 } else if (mpctx->stop_play == PT_STOP) {
4506 play_tree_iter_free(mpctx->playtree_iter);
4507 mpctx->playtree_iter = NULL;
4508 } else { // NEXT PREV SRC
4509 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4512 while(mpctx->playtree_iter != NULL) {
4513 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4514 if(mpctx->filename == NULL) {
4515 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4516 play_tree_iter_free(mpctx->playtree_iter);
4517 mpctx->playtree_iter = NULL;
4519 } else
4520 break;
4523 if(mpctx->playtree_iter != NULL || player_idle_mode){
4524 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4525 mpctx->stop_play = 0;
4526 goto play_next_file;
4530 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4532 return 1;
4534 #endif /* DISABLE_MAIN */