codecs.conf: remove yuv422 format from VDPAU section
[mplayer/glamo.git] / mplayer.c
blob15fef2fe1b6e1c53f5e746fea7a0e8ba814b994e
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 extern int cache_fill_status;
325 float stream_cache_min_percent=20.0;
326 float stream_cache_seek_min_percent=50.0;
327 #else
328 #define cache_fill_status 0
329 #endif
331 // dump:
332 static char *stream_dump_name="stream.dump";
333 int stream_dump_type=0;
335 // A-V sync:
336 static float default_max_pts_correction=-1;//0.01f;
337 float audio_delay=0;
338 static int ignore_start=0;
340 static int softsleep=0;
342 double force_fps=0;
343 static int force_srate=0;
344 static int audio_output_format=-1; // AF_FORMAT_UNKNOWN
345 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
346 static int play_n_frames=-1;
347 static int play_n_frames_mf=-1;
349 // sub:
350 char *font_name=NULL;
351 char *sub_font_name=NULL;
352 extern int font_fontconfig;
353 float font_factor=0.75;
354 char **sub_name=NULL;
355 float sub_delay=0;
356 float sub_fps=0;
357 int sub_auto = 1;
358 char *vobsub_name=NULL;
359 /*DSP!!char *dsp=NULL;*/
360 int subcc_enabled=0;
361 int suboverlap_enabled = 1;
363 #include "ass_mp.h"
365 char* current_module=NULL; // for debugging
368 // ---
370 #ifdef CONFIG_MENU
371 #include "m_struct.h"
372 #include "libmenu/menu.h"
373 extern vf_info_t vf_info_menu;
374 static const vf_info_t* const libmenu_vfs[] = {
375 &vf_info_menu,
376 NULL
378 static vf_instance_t* vf_menu = NULL;
379 int use_menu = 0;
380 static char* menu_cfg = NULL;
381 static char* menu_root = "main";
382 #endif
385 #ifdef HAVE_RTC
386 static int nortc = 1;
387 static char* rtc_device;
388 #endif
390 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
391 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
392 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
393 int use_filedir_conf;
394 int use_filename_title;
396 #include "mpcommon.h"
397 #include "command.h"
399 #include "metadata.h"
401 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
403 const void *mpctx_get_video_out(MPContext *mpctx)
405 return mpctx->video_out;
408 const void *mpctx_get_audio_out(MPContext *mpctx)
410 return mpctx->audio_out;
413 void *mpctx_get_demuxer(MPContext *mpctx)
415 return mpctx->demuxer;
418 void *mpctx_get_playtree_iter(MPContext *mpctx)
420 return mpctx->playtree_iter;
423 void *mpctx_get_mixer(MPContext *mpctx)
425 return &mpctx->mixer;
428 int mpctx_get_global_sub_size(MPContext *mpctx)
430 return mpctx->global_sub_size;
433 int mpctx_get_osd_function(MPContext *mpctx)
435 return mpctx->osd_function;
438 static float get_relative_time(struct MPContext *mpctx)
440 unsigned int new_time = GetTimer();
441 unsigned int delta = new_time - mpctx->last_time;
442 mpctx->last_time = new_time;
443 return delta * 0.000001;
446 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
447 switch (type)
449 /* check for valid video stream */
450 case META_VIDEO_CODEC:
451 case META_VIDEO_BITRATE:
452 case META_VIDEO_RESOLUTION:
454 if (!mpctx->sh_video)
455 return 0;
456 break;
459 /* check for valid audio stream */
460 case META_AUDIO_CODEC:
461 case META_AUDIO_BITRATE:
462 case META_AUDIO_SAMPLES:
464 if (!mpctx->sh_audio)
465 return 0;
466 break;
469 /* check for valid demuxer */
470 case META_INFO_TITLE:
471 case META_INFO_ARTIST:
472 case META_INFO_ALBUM:
473 case META_INFO_YEAR:
474 case META_INFO_COMMENT:
475 case META_INFO_TRACK:
476 case META_INFO_GENRE:
478 if (!mpctx->demuxer)
479 return 0;
480 break;
483 default:
484 break;
487 return 1;
490 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
491 char **info = mpctx->demuxer->info;
492 int n;
494 if (!info || !tag)
495 return NULL;
497 for (n = 0; info[2*n] != NULL ; n++)
498 if (!strcasecmp (info[2*n], tag))
499 break;
501 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
504 char *get_metadata(struct MPContext *mpctx, metadata_t type)
506 char *meta = NULL;
507 sh_audio_t * const sh_audio = mpctx->sh_audio;
508 sh_video_t * const sh_video = mpctx->sh_video;
510 if (!is_valid_metadata_type(mpctx, type))
511 return NULL;
513 switch (type)
515 case META_NAME:
517 return strdup (mp_basename2 (mpctx->filename));
520 case META_VIDEO_CODEC:
522 if (sh_video->format == 0x10000001)
523 meta = strdup ("mpeg1");
524 else if (sh_video->format == 0x10000002)
525 meta = strdup ("mpeg2");
526 else if (sh_video->format == 0x10000004)
527 meta = strdup ("mpeg4");
528 else if (sh_video->format == 0x10000005)
529 meta = strdup ("h264");
530 else if (sh_video->format >= 0x20202020)
532 meta = malloc (8);
533 sprintf (meta, "%.4s", (char *) &sh_video->format);
535 else
537 meta = malloc (8);
538 sprintf (meta, "0x%08X", sh_video->format);
540 return meta;
543 case META_VIDEO_BITRATE:
545 meta = malloc (16);
546 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
547 return meta;
550 case META_VIDEO_RESOLUTION:
552 meta = malloc (16);
553 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
554 return meta;
557 case META_AUDIO_CODEC:
559 if (sh_audio->codec && sh_audio->codec->name)
560 meta = strdup (sh_audio->codec->name);
561 return meta;
564 case META_AUDIO_BITRATE:
566 meta = malloc (16);
567 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
568 return meta;
571 case META_AUDIO_SAMPLES:
573 meta = malloc (16);
574 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
575 return meta;
578 /* check for valid demuxer */
579 case META_INFO_TITLE:
580 return get_demuxer_info(mpctx, "Title");
582 case META_INFO_ARTIST:
583 return get_demuxer_info(mpctx, "Artist");
585 case META_INFO_ALBUM:
586 return get_demuxer_info(mpctx, "Album");
588 case META_INFO_YEAR:
589 return get_demuxer_info(mpctx, "Year");
591 case META_INFO_COMMENT:
592 return get_demuxer_info(mpctx, "Comment");
594 case META_INFO_TRACK:
595 return get_demuxer_info(mpctx, "Track");
597 case META_INFO_GENRE:
598 return get_demuxer_info(mpctx, "Genre");
600 default:
601 break;
604 return meta;
607 static void print_file_properties(const MPContext *mpctx, const char *filename)
609 double start_pts = MP_NOPTS_VALUE;
610 double video_start_pts = MP_NOPTS_VALUE;
611 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
612 filename_recode(filename));
613 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
614 if (mpctx->sh_video) {
615 /* Assume FOURCC if all bytes >= 0x20 (' ') */
616 if (mpctx->sh_video->format >= 0x20202020)
617 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
618 else
619 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
620 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
621 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
622 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
623 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
624 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
625 video_start_pts = ds_get_next_pts(mpctx->d_video);
627 if (mpctx->sh_audio) {
628 /* Assume FOURCC if all bytes >= 0x20 (' ') */
629 if (mpctx->sh_audio->format >= 0x20202020)
630 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
631 else
632 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
633 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
634 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
635 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
636 start_pts = ds_get_next_pts(mpctx->d_audio);
638 if (video_start_pts != MP_NOPTS_VALUE) {
639 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
640 (mpctx->sh_video && video_start_pts < start_pts))
641 start_pts = video_start_pts;
643 if (start_pts != MP_NOPTS_VALUE)
644 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
645 else
646 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
647 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", mpctx->timeline ?
648 mpctx->timeline[mpctx->num_timeline_parts].start :
649 demuxer_get_time_length(mpctx->demuxer));
650 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
651 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
652 if (mpctx->demuxer) {
653 if (mpctx->demuxer->num_chapters == 0)
654 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
655 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
659 /// step size of mixer changes
660 int volstep = 3;
662 #ifdef CONFIG_DVDNAV
663 static void mp_dvdnav_context_free(MPContext *ctx){
664 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
665 ctx->nav_smpi = NULL;
666 if (ctx->nav_buffer) free(ctx->nav_buffer);
667 ctx->nav_buffer = NULL;
668 ctx->nav_start = NULL;
669 ctx->nav_in_size = 0;
671 #endif
673 void uninit_player(struct MPContext *mpctx, unsigned int mask){
674 mask &= mpctx->initialized_flags;
676 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
678 if(mask&INITIALIZED_ACODEC){
679 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
680 current_module="uninit_acodec";
681 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
682 mpctx->sh_audio=NULL;
683 mpctx->mixer.afilter = NULL;
686 if(mask&INITIALIZED_VCODEC){
687 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
688 current_module="uninit_vcodec";
689 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
690 mpctx->sh_video=NULL;
691 #ifdef CONFIG_MENU
692 vf_menu=NULL;
693 #endif
696 if(mask&INITIALIZED_DEMUXER){
697 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
698 current_module="free_demuxer";
699 if (mpctx->num_sources) {
700 mpctx->demuxer = mpctx->sources[0].demuxer;
701 for (int i = 1; i < mpctx->num_sources; i++) {
702 free_stream(mpctx->sources[i].stream);
703 free_demuxer(mpctx->sources[i].demuxer);
706 talloc_free(mpctx->sources);
707 mpctx->sources = NULL;
708 mpctx->num_sources = 0;
709 talloc_free(mpctx->timeline);
710 mpctx->timeline = NULL;
711 mpctx->num_timeline_parts = 0;
712 talloc_free(mpctx->chapters);
713 mpctx->chapters = NULL;
714 mpctx->num_chapters = 0;
715 mpctx->video_offset = 0;
716 if(mpctx->demuxer){
717 mpctx->stream=mpctx->demuxer->stream;
718 free_demuxer(mpctx->demuxer);
720 mpctx->demuxer=NULL;
723 // kill the cache process:
724 if(mask&INITIALIZED_STREAM){
725 mpctx->initialized_flags&=~INITIALIZED_STREAM;
726 current_module="uninit_stream";
727 if(mpctx->stream) free_stream(mpctx->stream);
728 mpctx->stream=NULL;
731 if(mask&INITIALIZED_VO){
732 mpctx->initialized_flags&=~INITIALIZED_VO;
733 current_module="uninit_vo";
734 vo_destroy(mpctx->video_out);
735 mpctx->video_out=NULL;
736 #ifdef CONFIG_DVDNAV
737 mp_dvdnav_context_free(mpctx);
738 #endif
741 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
742 if(mask&INITIALIZED_GETCH2){
743 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
744 current_module="uninit_getch2";
745 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
746 // restore terminal:
747 getch2_disable();
750 if(mask&INITIALIZED_VOBSUB){
751 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
752 current_module="uninit_vobsub";
753 if(vo_vobsub) vobsub_close(vo_vobsub);
754 vo_vobsub=NULL;
757 if (mask&INITIALIZED_SPUDEC){
758 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
759 current_module="uninit_spudec";
760 spudec_free(vo_spudec);
761 vo_spudec=NULL;
764 if(mask&INITIALIZED_AO){
765 mpctx->initialized_flags&=~INITIALIZED_AO;
766 current_module="uninit_ao";
767 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
768 if (mpctx->audio_out)
769 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
770 mpctx->audio_out=NULL;
773 current_module=NULL;
776 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
778 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
779 uninit_player(mpctx, INITIALIZED_ALL);
780 #if defined(__MINGW32__) || defined(__CYGWIN__)
781 timeEndPeriod(1);
782 #endif
783 #ifdef CONFIG_X11
784 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
785 #endif
787 current_module="uninit_input";
788 mp_input_uninit(mpctx->input);
789 #ifdef CONFIG_MENU
790 if (use_menu)
791 menu_uninit();
792 #endif
794 #ifdef CONFIG_FREETYPE
795 current_module="uninit_font";
796 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
797 free_font_desc(mpctx->osd->sub_font);
798 free_font_desc(vo_font);
799 vo_font = NULL;
800 done_freetype();
801 #endif
802 osd_free(mpctx->osd);
804 #ifdef CONFIG_ASS
805 ass_library_done(ass_library);
806 ass_library = NULL;
807 #endif
809 current_module="exit_player";
811 // free mplayer config
812 if(mpctx->mconfig)
813 m_config_free(mpctx->mconfig);
814 mpctx->mconfig = NULL;
816 if(mpctx->playtree_iter)
817 play_tree_iter_free(mpctx->playtree_iter);
818 mpctx->playtree_iter = NULL;
819 if(mpctx->playtree)
820 play_tree_free(mpctx->playtree, 1);
821 mpctx->playtree = NULL;
823 talloc_free(mpctx->key_fifo);
825 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
826 edl_records = NULL;
827 switch(how) {
828 case EXIT_QUIT:
829 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
830 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
831 break;
832 case EXIT_EOF:
833 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
834 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
835 break;
836 case EXIT_ERROR:
837 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
838 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
839 break;
840 default:
841 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
843 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
845 exit(rc);
848 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
850 exit_player_with_rc(mpctx, how, 1);
853 #ifndef __MINGW32__
854 static void child_sighandler(int x){
855 pid_t pid;
856 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
858 #endif
860 #ifdef CONFIG_CRASH_DEBUG
861 static char *prog_path;
862 static int crash_debug = 0;
863 #endif
865 static void exit_sighandler(int x){
866 static int sig_count=0;
867 #ifdef CONFIG_CRASH_DEBUG
868 if (!crash_debug || x != SIGTRAP)
869 #endif
870 ++sig_count;
871 if(sig_count==5)
873 /* We're crashing bad and can't uninit cleanly :(
874 * by popular request, we make one last (dirty)
875 * effort to restore the user's
876 * terminal. */
877 getch2_disable();
878 exit(1);
880 if(sig_count==6) exit(1);
881 if(sig_count>6){
882 // can't stop :(
883 #ifndef __MINGW32__
884 kill(getpid(),SIGKILL);
885 #endif
887 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
888 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
889 "\nMPlayer interrupted by signal %d in module: %s\n", x,
890 current_module ? current_module : "unknown");
891 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
892 if(sig_count<=1)
893 switch(x){
894 case SIGINT:
895 case SIGQUIT:
896 case SIGTERM:
897 case SIGKILL:
898 async_quit_request = 1;
899 return; // killed from keyboard (^C) or killed [-9]
900 case SIGILL:
901 #if CONFIG_RUNTIME_CPUDETECT
902 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
903 #else
904 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
905 #endif
906 case SIGFPE:
907 case SIGSEGV:
908 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
909 default:
910 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
911 #ifdef CONFIG_CRASH_DEBUG
912 if (crash_debug) {
913 int gdb_pid;
914 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
915 gdb_pid = fork();
916 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
917 if (gdb_pid == 0) { // We are the child
918 char spid[20];
919 snprintf(spid, sizeof(spid), "%i", getppid());
920 getch2_disable(); // allow terminal to work properly with gdb
921 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
922 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
923 } else if (gdb_pid < 0)
924 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
925 else {
926 waitpid(gdb_pid, NULL, 0);
928 if (x == SIGTRAP) return;
930 #endif
932 getch2_disable();
933 exit(1);
936 #include "cfg-mplayer.h"
938 static int cfg_include(m_option_t *conf, char *filename)
940 return m_config_parse_config_file(conf->priv, filename);
943 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
945 char *conffile;
946 int conffile_fd;
947 if (!disable_system_conf &&
948 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
949 exit_player(mpctx, EXIT_NONE);
950 if ((conffile = get_path("")) == NULL) {
951 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
952 } else {
953 #ifdef __MINGW32__
954 mkdir(conffile);
955 #else
956 mkdir(conffile, 0777);
957 #endif
958 free(conffile);
959 if ((conffile = get_path("config")) == NULL) {
960 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
961 } else {
962 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
963 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
964 write(conffile_fd, default_config, strlen(default_config));
965 close(conffile_fd);
967 if (!disable_user_conf &&
968 m_config_parse_config_file(conf, conffile) < 0)
969 exit_player(mpctx, EXIT_NONE);
970 free(conffile);
975 #define PROFILE_CFG_PROTOCOL "protocol."
977 static void load_per_protocol_config (m_config_t* conf, const char *const file)
979 char *str;
980 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
981 m_profile_t *p;
983 /* does filename actually uses a protocol ? */
984 str = strstr (file, "://");
985 if (!str)
986 return;
988 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
989 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
990 p = m_config_get_profile (conf, protocol);
991 if (p)
993 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
994 m_config_set_profile(conf,p);
998 #define PROFILE_CFG_EXTENSION "extension."
1000 static void load_per_extension_config (m_config_t* conf, const char *const file)
1002 char *str;
1003 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
1004 m_profile_t *p;
1006 /* does filename actually have an extension ? */
1007 str = strrchr (file, '.');
1008 if (!str)
1009 return;
1011 sprintf (extension, PROFILE_CFG_EXTENSION);
1012 strncat (extension, ++str, 7);
1013 p = m_config_get_profile (conf, extension);
1014 if (p)
1016 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
1017 m_config_set_profile(conf,p);
1021 #define PROFILE_CFG_VO "vo."
1022 #define PROFILE_CFG_AO "ao."
1024 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
1026 char profile[strlen (cfg) + strlen (out) + 1];
1027 m_profile_t *p;
1029 sprintf (profile, "%s%s", cfg, out);
1030 p = m_config_get_profile (conf, profile);
1031 if (p)
1033 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
1034 m_config_set_profile(conf,p);
1039 * Tries to load a config file
1040 * @return 0 if file was not found, 1 otherwise
1042 static int try_load_config(m_config_t *conf, const char *file)
1044 struct stat st;
1045 if (stat(file, &st))
1046 return 0;
1047 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1048 m_config_parse_config_file (conf, file);
1049 return 1;
1052 static void load_per_file_config (m_config_t* conf, const char *const file)
1054 char *confpath;
1055 char cfg[PATH_MAX];
1056 char *name;
1058 if (strlen(file) > PATH_MAX - 14) {
1059 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1060 return;
1062 sprintf (cfg, "%s.conf", file);
1064 name = strrchr(cfg, '/');
1065 if (HAVE_DOS_PATHS) {
1066 char *tmp = strrchr(cfg, '\\');
1067 if (!name || tmp > name)
1068 name = tmp;
1069 tmp = strrchr(cfg, ':');
1070 if (!name || tmp > name)
1071 name = tmp;
1073 if (!name)
1074 name = cfg;
1075 else
1076 name++;
1078 if (use_filedir_conf) {
1079 char dircfg[PATH_MAX];
1080 strcpy(dircfg, cfg);
1081 strcpy(dircfg + (name - cfg), "mplayer.conf");
1082 try_load_config(conf, dircfg);
1084 if (try_load_config(conf, cfg))
1085 return;
1088 if ((confpath = get_path (name)) != NULL)
1090 try_load_config(conf, confpath);
1092 free (confpath);
1096 /* When libmpdemux performs a blocking operation (network connection or
1097 * cache filling) if the operation fails we use this function to check
1098 * if it was interrupted by the user.
1099 * The function returns a new value for eof. */
1100 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1102 mp_cmd_t* cmd;
1103 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1104 switch(cmd->id) {
1105 case MP_CMD_QUIT:
1106 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1107 case MP_CMD_PLAY_TREE_STEP: {
1108 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1109 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1110 } break;
1111 case MP_CMD_PLAY_TREE_UP_STEP: {
1112 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1113 } break;
1114 case MP_CMD_PLAY_ALT_SRC_STEP: {
1115 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1116 } break;
1118 mp_cmd_free(cmd);
1120 return stop_play;
1123 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1125 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1127 play_tree_add_bpf(entry,mpctx->filename);
1130 if(!entry) {
1131 entry = mpctx->playtree_iter->tree;
1132 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1133 return PT_NEXT_ENTRY;
1135 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1136 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1137 return PT_NEXT_ENTRY;
1140 play_tree_remove(entry,1,1);
1141 return PT_NEXT_SRC;
1143 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1144 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1145 entry = mpctx->playtree_iter->tree;
1146 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1147 return PT_NEXT_ENTRY;
1149 play_tree_remove(entry,1,1);
1151 return PT_NEXT_SRC;
1154 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1156 struct MPOpts *opts = &mpctx->opts;
1157 sub_data *subd = NULL;
1158 struct ass_track *asst = NULL;
1160 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1161 return;
1164 #ifdef CONFIG_ASS
1165 if (opts->ass_enabled) {
1166 #ifdef CONFIG_ICONV
1167 asst = ass_read_stream(ass_library, filename, sub_cp);
1168 #else
1169 asst = ass_read_stream(ass_library, filename, 0);
1170 #endif
1171 if (!asst) {
1172 subd = sub_read_file(filename, fps);
1173 if (subd) {
1174 asst = ass_read_subdata(ass_library, subd, fps);
1175 if (asst) {
1176 sub_free(subd);
1177 subd = NULL;
1181 } else
1182 #endif
1183 subd = sub_read_file(filename, fps);
1186 if (!asst && !subd) {
1187 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1188 "Cannot load subtitles: %s\n", filename_recode(filename));
1189 return;
1192 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1193 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1194 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1195 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1196 filename_recode(filename));
1197 ++mpctx->set_of_sub_size;
1198 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1199 filename_recode(filename));
1202 void init_vo_spudec(struct MPContext *mpctx)
1204 if (vo_spudec)
1205 spudec_free(vo_spudec);
1206 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1207 vo_spudec = NULL;
1209 // we currently can't work without video stream
1210 if (!mpctx->sh_video)
1211 return;
1213 if (spudec_ifo) {
1214 unsigned int palette[16], width, height;
1215 current_module="spudec_init_vobsub";
1216 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1217 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1220 #ifdef CONFIG_DVDREAD
1221 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1222 current_module="spudec_init_dvdread";
1223 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1224 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1225 NULL, 0);
1227 #endif
1229 #ifdef CONFIG_DVDNAV
1230 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1231 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1232 current_module="spudec_init_dvdnav";
1233 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1235 #endif
1237 if (vo_spudec==NULL) {
1238 sh_sub_t *sh = (sh_sub_t *)mpctx->d_sub->sh;
1239 current_module="spudec_init_normal";
1240 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1241 spudec_set_font_factor(vo_spudec,font_factor);
1244 if (vo_spudec!=NULL) {
1245 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1246 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1251 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1252 * make it all work is to use the builtin SDL-bootstrap code, which
1253 * will be done automatically by replacing our main() if we include SDL.h.
1255 #if defined(__APPLE__) && defined(CONFIG_SDL)
1256 #ifdef CONFIG_SDL_SDL_H
1257 #include <SDL/SDL.h>
1258 #else
1259 #include <SDL.h>
1260 #endif
1261 #endif
1264 * \brief append a formatted string
1265 * \param buf buffer to print into
1266 * \param pos position of terminating 0 in buf
1267 * \param len maximum number of characters in buf, not including terminating 0
1268 * \param format printf format string
1270 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1272 va_list va;
1273 va_start(va, format);
1274 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1275 va_end(va);
1276 if (*pos >= len ) {
1277 buf[len] = 0;
1278 *pos = len;
1283 * \brief append time in the hh:mm:ss.f format
1284 * \param buf buffer to print into
1285 * \param pos position of terminating 0 in buf
1286 * \param len maximum number of characters in buf, not including terminating 0
1287 * \param time time value to convert/append
1289 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1290 int64_t tenths = 10 * time;
1291 int f1 = tenths % 10;
1292 int ss = (tenths / 10) % 60;
1293 int mm = (tenths / 600) % 60;
1294 int hh = tenths / 36000;
1295 if (time <= 0) {
1296 saddf(buf, pos, len, "unknown");
1297 return;
1299 if (hh > 0)
1300 saddf(buf, pos, len, "%2d:", hh);
1301 if (hh > 0 || mm > 0)
1302 saddf(buf, pos, len, "%02d:", mm);
1303 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1306 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1308 struct MPOpts *opts = &mpctx->opts;
1309 sh_video_t * const sh_video = mpctx->sh_video;
1311 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1312 a_pos = playing_audio_pts(mpctx);
1313 if (mpctx->sh_audio && sh_video && at_frame) {
1314 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1315 if (mpctx->time_frame > 0)
1316 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1317 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1318 && !mpctx->drop_message_shown) {
1319 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1320 mpctx->drop_message_shown = true;
1323 if (quiet)
1324 return;
1327 int width;
1328 char *line;
1329 unsigned pos = 0;
1330 get_screen_size();
1331 if (screen_width > 0)
1332 width = screen_width;
1333 else
1334 width = 80;
1335 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1336 /* Windows command line is broken (MinGW's rxvt works, but we
1337 * should not depend on that). */
1338 width--;
1339 #endif
1340 line = malloc(width + 1); // one additional char for the terminating null
1342 // Audio time
1343 if (mpctx->sh_audio) {
1344 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1345 if (!sh_video) {
1346 float len = demuxer_get_time_length(mpctx->demuxer);
1347 saddf(line, &pos, width, "(");
1348 sadd_hhmmssf(line, &pos, width, a_pos);
1349 saddf(line, &pos, width, ") of %.1f (", len);
1350 sadd_hhmmssf(line, &pos, width, len);
1351 saddf(line, &pos, width, ") ");
1355 // Video time
1356 if (sh_video)
1357 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1359 // A-V sync
1360 if (mpctx->sh_audio && sh_video)
1361 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1362 mpctx->last_av_difference, mpctx->total_avsync_change);
1364 // Video stats
1365 if (sh_video)
1366 saddf(line, &pos, width, "%3d/%3d ",
1367 (int)sh_video->num_frames,
1368 (int)sh_video->num_frames_decoded);
1370 // CPU usage
1371 if (sh_video) {
1372 if (sh_video->timer > 0.5)
1373 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1374 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1375 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1376 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1377 else
1378 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1379 } else if (mpctx->sh_audio) {
1380 if (mpctx->delay > 0.5)
1381 saddf(line, &pos, width, "%4.1f%% ",
1382 100.0*audio_time_usage/(double)mpctx->delay);
1383 else
1384 saddf(line, &pos, width, "??,?%% ");
1387 // VO stats
1388 if (sh_video)
1389 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1391 #ifdef CONFIG_STREAM_CACHE
1392 // cache stats
1393 if (stream_cache_size > 0)
1394 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1395 #endif
1397 // other
1398 if (opts->playback_speed != 1)
1399 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1401 // end
1402 if (erase_to_end_of_line) {
1403 line[pos] = 0;
1404 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1405 } else {
1406 memset(&line[pos], ' ', width - pos);
1407 line[width] = 0;
1408 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1410 free(line);
1414 * \brief build a chain of audio filters that converts the input format
1415 * to the ao's format, taking into account the current playback_speed.
1416 * \param sh_audio describes the requested input format of the chain.
1417 * \param ao_data describes the requested output format of the chain.
1419 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1421 struct MPOpts *opts = &mpctx->opts;
1422 int new_srate;
1423 int result;
1424 if (!sh_audio)
1426 mpctx->mixer.afilter = NULL;
1427 return 0;
1429 if(af_control_any_rev(sh_audio->afilter,
1430 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1431 &opts->playback_speed)) {
1432 new_srate = sh_audio->samplerate;
1433 } else {
1434 new_srate = sh_audio->samplerate * opts->playback_speed;
1435 if (new_srate != ao_data->samplerate) {
1436 // limits are taken from libaf/af_resample.c
1437 if (new_srate < 8000)
1438 new_srate = 8000;
1439 if (new_srate > 192000)
1440 new_srate = 192000;
1441 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1444 result = init_audio_filters(sh_audio, new_srate,
1445 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1446 mpctx->mixer.afilter = sh_audio->afilter;
1447 return result;
1451 typedef struct mp_osd_msg mp_osd_msg_t;
1452 struct mp_osd_msg {
1453 /// Previous message on the stack.
1454 mp_osd_msg_t* prev;
1455 /// Message text.
1456 char msg[128];
1457 int id,level,started;
1458 /// Display duration in ms.
1459 unsigned time;
1462 /// OSD message stack.
1463 static mp_osd_msg_t* osd_msg_stack = NULL;
1466 * \brief Add a message on the OSD message stack
1468 * If a message with the same id is already present in the stack
1469 * it is pulled on top of the stack, otherwise a new message is created.
1472 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1473 va_list ap)
1475 mp_osd_msg_t *msg,*last=NULL;
1476 int r;
1478 // look if the id is already in the stack
1479 for(msg = osd_msg_stack ; msg && msg->id != id ;
1480 last = msg, msg = msg->prev);
1481 // not found: alloc it
1482 if(!msg) {
1483 msg = calloc(1,sizeof(mp_osd_msg_t));
1484 msg->prev = osd_msg_stack;
1485 osd_msg_stack = msg;
1486 } else if(last) { // found, but it's not on top of the stack
1487 last->prev = msg->prev;
1488 msg->prev = osd_msg_stack;
1489 osd_msg_stack = msg;
1491 // write the msg
1492 r = vsnprintf(msg->msg, 128, fmt, ap);
1493 if(r >= 128) msg->msg[127] = 0;
1494 // set id and time
1495 msg->id = id;
1496 msg->level = level;
1497 msg->time = time;
1501 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1503 va_list ap;
1504 va_start(ap, fmt);
1505 set_osd_msg_va(id, level, time, fmt, ap);
1506 va_end(ap);
1509 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1511 va_list ap;
1512 va_start(ap, fmt);
1513 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1514 va_end(ap);
1519 * \brief Remove a message from the OSD stack
1521 * This function can be used to get rid of a message right away.
1525 void rm_osd_msg(int id) {
1526 mp_osd_msg_t *msg,*last=NULL;
1528 // Search for the msg
1529 for(msg = osd_msg_stack ; msg && msg->id != id ;
1530 last = msg, msg = msg->prev);
1531 if(!msg) return;
1533 // Detach it from the stack and free it
1534 if(last)
1535 last->prev = msg->prev;
1536 else
1537 osd_msg_stack = msg->prev;
1538 free(msg);
1542 * \brief Remove all messages from the OSD stack
1546 static void clear_osd_msgs(void) {
1547 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1548 while(msg) {
1549 prev = msg->prev;
1550 free(msg);
1551 msg = prev;
1553 osd_msg_stack = NULL;
1557 * \brief Get the current message from the OSD stack.
1559 * This function decrements the message timer and destroys the old ones.
1560 * The message that should be displayed is returned (if any).
1564 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1566 struct MPOpts *opts = &mpctx->opts;
1567 mp_osd_msg_t *msg,*prev,*last = NULL;
1568 static unsigned last_update = 0;
1569 unsigned now = GetTimerMS();
1570 unsigned diff;
1571 char hidden_dec_done = 0;
1573 if (mpctx->osd_visible) {
1574 // 36000000 means max timed visibility is 1 hour into the future, if
1575 // the difference is greater assume it's wrapped around from below 0
1576 if (mpctx->osd_visible - now > 36000000) {
1577 mpctx->osd_visible = 0;
1578 vo_osd_progbar_type = -1; // disable
1579 vo_osd_changed(OSDTYPE_PROGBAR);
1580 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1583 if (mpctx->osd_show_percentage_until - now > 36000000)
1584 mpctx->osd_show_percentage_until = 0;
1586 if(!last_update) last_update = now;
1587 diff = now >= last_update ? now - last_update : 0;
1589 last_update = now;
1591 // Look for the first message in the stack with high enough level.
1592 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1593 prev = msg->prev;
1594 if (msg->level > opts->osd_level && hidden_dec_done)
1595 continue;
1596 // The message has a high enough level or it is the first hidden one
1597 // in both cases we decrement the timer or kill it.
1598 if(!msg->started || msg->time > diff) {
1599 if(msg->started) msg->time -= diff;
1600 else msg->started = 1;
1601 // display it
1602 if (msg->level <= opts->osd_level)
1603 return msg;
1604 hidden_dec_done = 1;
1605 continue;
1607 // kill the message
1608 free(msg);
1609 if(last) {
1610 last->prev = prev;
1611 msg = last;
1612 } else {
1613 osd_msg_stack = prev;
1614 msg = NULL;
1617 // Nothing found
1618 return NULL;
1622 * \brief Display the OSD bar.
1624 * Display the OSD bar or fall back on a simple message.
1628 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1629 struct MPOpts *opts = &mpctx->opts;
1630 if (opts->osd_level < 1)
1631 return;
1633 if(mpctx->sh_video) {
1634 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1635 vo_osd_progbar_type = type;
1636 vo_osd_progbar_value = 256*(val-min)/(max-min);
1637 vo_osd_changed(OSDTYPE_PROGBAR);
1638 return;
1641 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1642 name, ROUND(100*(val-min)/(max-min)));
1646 * \brief Display text subtitles on the OSD
1648 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1650 int i;
1651 vo_sub = subs;
1652 vo_osd_changed(OSDTYPE_SUBTITLE);
1653 if (!mpctx->sh_video) {
1654 // reverse order, since newest set_osd_msg is displayed first
1655 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1656 if (!subs || i >= subs->lines || !subs->text[i])
1657 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1658 else {
1659 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1660 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1661 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1668 * \brief Update the OSD message line.
1670 * This function displays the current message on the vo OSD or on the term.
1671 * If the stack is empty and the OSD level is high enough the timer
1672 * is displayed (only on the vo OSD).
1676 static void update_osd_msg(struct MPContext *mpctx)
1678 struct MPOpts *opts = &mpctx->opts;
1679 mp_osd_msg_t *msg;
1680 struct osd_state *osd = mpctx->osd;
1681 char osd_text_timer[128];
1683 if (mpctx->add_osd_seek_info) {
1684 double percentage;
1685 if (mpctx->timeline && mpctx->sh_video)
1686 percentage = mpctx->sh_video->pts * 100 /
1687 mpctx->timeline[mpctx->num_timeline_parts].start;
1688 else
1689 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1690 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1691 if (mpctx->sh_video)
1692 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1693 mpctx->add_osd_seek_info = false;
1696 // Look if we have a msg
1697 if((msg = get_osd_msg(mpctx))) {
1698 if (strcmp(osd->osd_text, msg->msg)) {
1699 strncpy(osd->osd_text, msg->msg, 127);
1700 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1701 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1703 return;
1706 if(mpctx->sh_video) {
1707 // fallback on the timer
1708 if (opts->osd_level >= 2) {
1709 int len;
1710 if (mpctx->timeline)
1711 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1712 else
1713 len = demuxer_get_time_length(mpctx->demuxer);
1714 int percentage = -1;
1715 char percentage_text[10];
1716 int pts = demuxer_get_current_time(mpctx->demuxer);
1718 if (mpctx->osd_show_percentage_until) {
1719 if (mpctx->timeline)
1720 percentage = mpctx->sh_video->pts * 100 /
1721 mpctx->timeline[mpctx->num_timeline_parts].start;
1722 else
1723 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1726 if (percentage >= 0)
1727 snprintf(percentage_text, 9, " (%d%%)", percentage);
1728 else
1729 percentage_text[0] = 0;
1731 if (opts->osd_level == 3)
1732 snprintf(osd_text_timer, 63,
1733 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1734 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1735 len/3600,(len/60)%60,len%60,percentage_text);
1736 else
1737 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1738 mpctx->osd_function,pts/3600,(pts/60)%60,
1739 pts%60,percentage_text);
1740 } else
1741 osd_text_timer[0]=0;
1743 if (strcmp(osd->osd_text, osd_text_timer)) {
1744 strncpy(osd->osd_text, osd_text_timer, 63);
1745 vo_osd_changed(OSDTYPE_OSD);
1747 return;
1750 // Clear the term osd line
1751 if (term_osd && osd->osd_text[0]) {
1752 osd->osd_text[0] = 0;
1753 printf("%s\n",term_osd_esc);
1757 ///@}
1758 // OSDMsgStack
1761 void reinit_audio_chain(struct MPContext *mpctx)
1763 struct MPOpts *opts = &mpctx->opts;
1764 if (!mpctx->sh_audio)
1765 return;
1766 current_module="init_audio_codec";
1767 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1768 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1769 goto init_error;
1771 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1772 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1775 current_module="af_preinit";
1776 ao_data.samplerate=force_srate;
1777 ao_data.channels=0;
1778 ao_data.format=audio_output_format;
1779 // first init to detect best values
1780 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1781 // input:
1782 mpctx->sh_audio->samplerate,
1783 // output:
1784 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1785 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1786 "pre-init!\n");
1787 exit_player(mpctx, EXIT_ERROR);
1789 current_module="ao2_init";
1790 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1791 0, // plugin flag
1792 ao_data.samplerate,
1793 ao_data.channels,
1794 ao_data.format, 0);
1795 if(!mpctx->audio_out){
1796 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1797 goto init_error;
1799 mpctx->initialized_flags|=INITIALIZED_AO;
1800 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1801 mpctx->audio_out->info->short_name,
1802 ao_data.samplerate, ao_data.channels,
1803 af_fmt2str_short(ao_data.format),
1804 af_fmt2bits(ao_data.format)/8 );
1805 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1806 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1807 if(strlen(mpctx->audio_out->info->comment) > 0)
1808 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 void select_subtitle(MPContext *mpctx)
1953 struct MPOpts *opts = &mpctx->opts;
1954 // find the best sub to use
1955 int vobsub_index_id = vobsub_get_index_by_id(vo_vobsub, vobsub_id);
1956 mpctx->global_sub_pos = -1; // no subs by default
1957 if (vobsub_index_id >= 0) {
1958 // if user asks for a vobsub id, use that first.
1959 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] + vobsub_index_id;
1960 } else if (opts->sub_id >= 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
1961 // if user asks for a dvd sub id, use that next.
1962 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
1963 } else if (mpctx->global_sub_indices[SUB_SOURCE_SUBS] >= 0) {
1964 // if there are text subs to use, use those. (autosubs come last here)
1965 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_SUBS];
1966 } else if (opts->sub_id == -1 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
1967 // finally select subs by language and container hints
1968 if (opts->sub_id == -1 && opts->sub_lang)
1969 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, opts->sub_lang);
1970 if (opts->sub_id == -1)
1971 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
1972 if (opts->sub_id >= 0)
1973 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
1975 // rather than duplicate code, use the SUB_SELECT handler to init the right one.
1976 mpctx->global_sub_pos--;
1977 mp_property_do("sub",M_PROPERTY_STEP_UP,NULL, mpctx);
1980 #ifdef CONFIG_DVDNAV
1981 #ifndef FF_B_TYPE
1982 #define FF_B_TYPE 3
1983 #endif
1984 /// store decoded video image
1985 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1986 mp_image_t *from_mpi) {
1987 mp_image_t *mpi;
1989 /// Do not store B-frames
1990 if (from_mpi->pict_type == FF_B_TYPE)
1991 return to_mpi;
1993 if (to_mpi &&
1994 to_mpi->w == from_mpi->w &&
1995 to_mpi->h == from_mpi->h &&
1996 to_mpi->imgfmt == from_mpi->imgfmt)
1997 mpi = to_mpi;
1998 else {
1999 if (to_mpi)
2000 free_mp_image(to_mpi);
2001 if (from_mpi->w == 0 || from_mpi->h == 0)
2002 return NULL;
2003 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2006 copy_mpi(mpi,from_mpi);
2007 return mpi;
2010 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2011 struct MPOpts *opts = &ctx->opts;
2012 if (ctx->sh_video) {
2013 /// clear video pts
2014 ctx->d_video->pts = 0.0f;
2015 ctx->sh_video->pts = 0.0f;
2016 ctx->sh_video->i_pts = 0.0f;
2017 ctx->sh_video->last_pts = 0.0f;
2018 ctx->sh_video->num_buffered_pts = 0;
2019 ctx->sh_video->num_frames = 0;
2020 ctx->sh_video->num_frames_decoded = 0;
2021 ctx->sh_video->timer = 0.0f;
2022 ctx->sh_video->stream_delay = 0.0f;
2023 ctx->sh_video->timer = 0;
2024 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2027 if (ctx->sh_audio) {
2028 /// free audio packets and reset
2029 ds_free_packs(ctx->d_audio);
2030 audio_delay -= ctx->sh_audio->stream_delay;
2031 ctx->delay =- audio_delay;
2032 ctx->audio_out->reset();
2033 resync_audio_stream(ctx->sh_audio);
2036 audio_delay = 0.0f;
2037 ctx->global_sub_size = ctx->global_sub_indices[SUB_SOURCE_DEMUX] + mp_dvdnav_number_of_subs(ctx->stream);
2038 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2039 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2040 if (dvdsub_lang_id != opts->sub_id) {
2041 opts->sub_id = dvdsub_lang_id;
2042 select_subtitle(ctx);
2046 /// clear all EOF related flags
2047 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2050 /// Restore last decoded DVDNAV (still frame)
2051 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2052 int *in_size,
2053 unsigned char **start,
2054 mp_image_t *decoded_frame)
2056 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2057 return decoded_frame;
2059 /// a change occured in dvdnav stream
2060 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2061 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2062 mp_dvdnav_context_free(mpctx);
2063 mp_dvdnav_reset_stream(mpctx);
2064 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2065 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2068 if (*in_size < 0) {
2069 float len;
2071 /// Display still frame, if any
2072 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2073 decoded_frame = mpctx->nav_smpi;
2075 /// increment video frame : continue playing after still frame
2076 len = demuxer_get_time_length(mpctx->demuxer);
2077 if (mpctx->sh_video->pts >= len &&
2078 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2079 mp_dvdnav_skip_still(mpctx->stream);
2080 mp_dvdnav_skip_wait(mpctx->stream);
2082 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2084 if (mpctx->nav_buffer) {
2085 *start = mpctx->nav_start;
2086 *in_size = mpctx->nav_in_size;
2087 if (mpctx->nav_start)
2088 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2092 return decoded_frame;
2095 /// Save last decoded DVDNAV (still frame)
2096 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2097 unsigned char *start,
2098 mp_image_t *decoded_frame)
2100 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2101 return;
2103 if (mpctx->nav_buffer)
2104 free(mpctx->nav_buffer);
2106 mpctx->nav_buffer = malloc(in_size);
2107 mpctx->nav_start = start;
2108 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2109 if (mpctx->nav_buffer)
2110 memcpy(mpctx->nav_buffer,start,in_size);
2112 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2113 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2115 #endif /* CONFIG_DVDNAV */
2117 /* Modify video timing to match the audio timeline. There are two main
2118 * reasons this is needed. First, video and audio can start from different
2119 * positions at beginning of file or after a seek (MPlayer starts both
2120 * immediately even if they have different pts). Second, the file can have
2121 * audio timestamps that are inconsistent with the duration of the audio
2122 * packets, for example two consecutive timestamp values differing by
2123 * one second but only a packet with enough samples for half a second
2124 * of playback between them.
2126 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2128 current_module = "av_sync";
2130 if (!mpctx->sh_audio)
2131 return;
2133 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2134 double v_pts = mpctx->sh_video->pts;
2135 double av_delay = a_pts - v_pts;
2136 // Try to sync vo_flip() so it will *finish* at given time
2137 av_delay += mpctx->last_vo_flip_duration;
2138 av_delay -= audio_delay; // This much pts difference is desired
2140 double change = av_delay * 0.1;
2141 double max_change = default_max_pts_correction >= 0 ?
2142 default_max_pts_correction : frame_time * 0.1;
2143 if (change < -max_change)
2144 change = -max_change;
2145 else if (change > max_change)
2146 change = max_change;
2147 mpctx->delay += change;
2148 mpctx->total_avsync_change += change;
2151 static int fill_audio_out_buffers(struct MPContext *mpctx)
2153 struct MPOpts *opts = &mpctx->opts;
2154 unsigned int t;
2155 double tt;
2156 int playsize;
2157 int playflags=0;
2158 int audio_eof=0;
2159 sh_audio_t * const sh_audio = mpctx->sh_audio;
2161 current_module="play_audio";
2163 while (1) {
2164 int sleep_time;
2165 // all the current uses of ao_data.pts seem to be in aos that handle
2166 // sync completely wrong; there should be no need to use ao_data.pts
2167 // in get_space()
2168 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2169 playsize = mpctx->audio_out->get_space();
2170 if (mpctx->sh_video || playsize >= ao_data.outburst)
2171 break;
2173 // handle audio-only case:
2174 // this is where mplayer sleeps during audio-only playback
2175 // to avoid 100% CPU use
2176 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2177 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2178 usec_sleep(sleep_time * 1000);
2181 // Fill buffer if needed:
2182 current_module="decode_audio";
2183 t = GetTimer();
2184 if (decode_audio(sh_audio, playsize) < 0) // EOF or error
2185 if (mpctx->d_audio->eof) {
2186 audio_eof = 1;
2187 if (sh_audio->a_out_buffer_len == 0)
2188 return 0;
2190 t = GetTimer() - t;
2191 tt = t*0.000001f; audio_time_usage+=tt;
2192 if (playsize > sh_audio->a_out_buffer_len) {
2193 playsize = sh_audio->a_out_buffer_len;
2194 if (audio_eof)
2195 playflags |= AOPLAY_FINAL_CHUNK;
2197 if (!playsize)
2198 return 1;
2200 // play audio:
2201 current_module="play_audio";
2203 // Is this pts value actually useful for the aos that access it?
2204 // They're obviously badly broken in the way they handle av sync;
2205 // would not having access to this make them more broken?
2206 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2207 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2209 if (playsize > 0) {
2210 sh_audio->a_out_buffer_len -= playsize;
2211 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2212 sh_audio->a_out_buffer_len);
2213 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2215 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2216 // Sanity check to avoid hanging in case current ao doesn't output
2217 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2218 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2219 sh_audio->a_out_buffer_len = 0;
2222 return 1;
2225 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2226 float *aq_sleep_time)
2228 struct MPOpts *opts = &mpctx->opts;
2229 int frame_time_remaining = 0;
2230 current_module="calc_sleep_time";
2232 *time_frame -= get_relative_time(mpctx); // reset timer
2234 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2235 float delay = mpctx->audio_out->get_delay();
2236 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2238 if (autosync) {
2240 * Adjust this raw delay value by calculating the expected
2241 * delay for this frame and generating a new value which is
2242 * weighted between the two. The higher autosync is, the
2243 * closer to the delay value gets to that which "-nosound"
2244 * would have used, and the longer it will take for A/V
2245 * sync to settle at the right value (but it eventually will.)
2246 * This settling time is very short for values below 100.
2248 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2249 float difference = delay - predicted;
2250 delay = predicted + difference / (float)autosync;
2253 *time_frame = delay - mpctx->delay / opts->playback_speed;
2254 *time_frame -= mpctx->video_out->flip_queue_offset;
2256 // delay = amount of audio buffered in soundcard/driver
2257 if (delay > 0.25) delay=0.25; else
2258 if (delay < 0.10) delay=0.10;
2260 if (*time_frame > delay*0.6) {
2261 // sleep time too big - may cause audio drops (buffer underrun)
2262 frame_time_remaining = 1;
2263 *time_frame = delay*0.5;
2265 } else {
2266 // If we're lagging more than 200 ms behind the right playback rate,
2267 // don't try to "catch up".
2268 // If benchmark is set always output frames as fast as possible
2269 // without sleeping.
2270 if (*time_frame < -0.2 || benchmark)
2271 *time_frame = 0;
2272 *time_frame -= mpctx->video_out->flip_queue_offset;
2275 *aq_sleep_time += *time_frame;
2278 //============================== SLEEP: ===================================
2280 // flag 256 means: libvo driver does its timing (dvb card)
2281 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2282 *time_frame = timing_sleep(mpctx, *time_frame);
2283 *time_frame += mpctx->video_out->flip_queue_offset;
2284 return frame_time_remaining;
2287 int reinit_video_chain(struct MPContext *mpctx)
2289 struct MPOpts *opts = &mpctx->opts;
2290 sh_video_t * const sh_video = mpctx->sh_video;
2291 double ar=-1.0;
2292 //================== Init VIDEO (codec & libvo) ==========================
2293 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2294 current_module="preinit_libvo";
2296 //shouldn't we set dvideo->id=-2 when we fail?
2297 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2298 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2299 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2300 goto err_out;
2302 mpctx->initialized_flags|=INITIALIZED_VO;
2305 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2306 mpctx->sh_video->stream_aspect = ar;
2307 current_module="init_video_filters";
2309 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2310 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2312 #ifdef CONFIG_MENU
2313 if(use_menu) {
2314 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2315 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2316 if(!vf_menu) {
2317 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2318 use_menu = 0;
2321 if(vf_menu)
2322 sh_video->vfilter = vf_menu;
2323 #endif
2325 #ifdef CONFIG_ASS
2326 if(opts->ass_enabled) {
2327 int i;
2328 int insert = 1;
2329 if (opts->vf_settings)
2330 for (i = 0; opts->vf_settings[i].name; ++i)
2331 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2332 insert = 0;
2333 break;
2335 if (insert) {
2336 extern vf_info_t vf_info_ass;
2337 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2338 char* vf_arg[] = {"auto", "1", NULL};
2339 int retcode = 0;
2340 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2341 sh_video->vfilter,
2342 "ass", vf_arg,
2343 &retcode);
2344 if (vf_ass)
2345 sh_video->vfilter = vf_ass;
2346 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2347 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2348 else
2349 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2352 #endif
2354 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2356 #ifdef CONFIG_ASS
2357 if (opts->ass_enabled)
2358 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2359 #endif
2361 current_module="init_video_codec";
2363 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2364 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2365 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2367 if(!sh_video->initialized){
2368 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2369 goto err_out;
2372 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2374 if (sh_video->codec)
2375 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2377 sh_video->last_pts = MP_NOPTS_VALUE;
2378 sh_video->num_buffered_pts = 0;
2379 sh_video->next_frame_time = 0;
2381 if(auto_quality>0){
2382 // Auto quality option enabled
2383 output_quality=get_video_quality_max(sh_video);
2384 if(auto_quality>output_quality) auto_quality=output_quality;
2385 else output_quality=auto_quality;
2386 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2387 set_video_quality(sh_video,output_quality);
2390 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2392 current_module="init_vo";
2394 return 1;
2396 err_out:
2397 mpctx->sh_video = mpctx->d_video->sh = NULL;
2398 return 0;
2401 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2403 struct sh_video *sh_video = mpctx->sh_video;
2404 double frame_time = 0;
2405 struct vo *video_out = mpctx->video_out;
2406 while (!video_out->frame_loaded) {
2407 current_module = "filter_video";
2408 // In nocorrect-pts mode there is no way to properly time these frames
2409 if (vo_get_buffered_frame(video_out, 0) >= 0)
2410 break;
2411 if (vf_output_queued_frame(sh_video->vfilter))
2412 continue;
2413 unsigned char *packet = NULL;
2414 frame_time = sh_video->next_frame_time;
2415 if (mpctx->update_video_immediately)
2416 frame_time = 0;
2417 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2418 &packet, force_fps);
2419 if (in_size < 0) {
2420 #ifdef CONFIG_DVDNAV
2421 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2422 if (mp_dvdnav_is_eof(mpctx->stream))
2423 return -1;
2424 if (mpctx->d_video)
2425 mpctx->d_video->eof = 0;
2426 if (mpctx->d_audio)
2427 mpctx->d_audio->eof = 0;
2428 mpctx->stream->eof = 0;
2429 } else
2430 #endif
2431 return -1;
2433 if (in_size > max_framesize)
2434 max_framesize = in_size;
2435 sh_video->timer += frame_time;
2436 if (mpctx->sh_audio)
2437 mpctx->delay -= frame_time;
2438 // video_read_frame can change fps (e.g. for ASF video)
2439 vo_fps = sh_video->fps;
2440 int framedrop_type = check_framedrop(mpctx, frame_time);
2441 current_module = "decode video";
2443 void *decoded_frame;
2444 #ifdef CONFIG_DVDNAV
2445 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2446 if (in_size >= 0 && !decoded_frame)
2447 #endif
2448 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2449 sh_video->pts);
2450 #ifdef CONFIG_DVDNAV
2451 // Save last still frame for future display
2452 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2453 #endif
2454 if (decoded_frame) {
2455 current_module = "filter video";
2456 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2457 if (!video_out->config_ok)
2458 break;
2461 return frame_time;
2464 static void determine_frame_pts(struct MPContext *mpctx)
2466 struct sh_video *sh_video = mpctx->sh_video;
2467 struct MPOpts *opts = &mpctx->opts;
2469 if (opts->user_pts_assoc_mode) {
2470 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2471 } else if (sh_video->pts_assoc_mode == 0) {
2472 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2473 sh_video->pts_assoc_mode = 1;
2474 else
2475 sh_video->pts_assoc_mode = 2;
2476 } else {
2477 int probcount1 = sh_video->num_reordered_pts_problems;
2478 int probcount2 = sh_video->num_sorted_pts_problems;
2479 if (sh_video->pts_assoc_mode == 2) {
2480 int tmp = probcount1;
2481 probcount1 = probcount2;
2482 probcount2 = tmp;
2484 if (probcount1 >= probcount2 * 1.5 + 2) {
2485 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2486 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2487 "%d.\n", sh_video->pts_assoc_mode);
2490 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2491 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2494 static double update_video(struct MPContext *mpctx)
2496 struct sh_video *sh_video = mpctx->sh_video;
2497 struct vo *video_out = mpctx->video_out;
2498 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2499 mpctx->osd); // hack for vf_expand
2500 if (!mpctx->opts.correct_pts)
2501 return update_video_nocorrect_pts(mpctx);
2503 double pts;
2505 bool hit_eof = false;
2506 while (!video_out->frame_loaded) {
2507 current_module = "filter_video";
2508 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2509 break;
2510 // XXX Time used in this call is not counted in any performance
2511 // timer now, OSD time is not updated correctly for filter-added frames
2512 if (vf_output_queued_frame(sh_video->vfilter))
2513 continue;
2514 if (hit_eof)
2515 return -1;
2516 unsigned char *packet = NULL;
2517 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2518 if (pts != MP_NOPTS_VALUE)
2519 pts += mpctx->video_offset;
2520 if (in_size < 0) {
2521 // try to extract last frames in case of decoder lag
2522 in_size = 0;
2523 pts = MP_NOPTS_VALUE;
2524 hit_eof = true;
2526 if (in_size > max_framesize)
2527 max_framesize = in_size;
2528 current_module = "decode video";
2529 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2530 void *decoded_frame = decode_video(sh_video, packet, in_size,
2531 framedrop_type, pts);
2532 if (decoded_frame) {
2533 determine_frame_pts(mpctx);
2534 current_module = "filter video";
2535 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2536 if (!video_out->config_ok)
2537 break; // We'd likely hang in this loop otherwise
2541 pts = video_out->next_pts;
2542 if (pts == MP_NOPTS_VALUE) {
2543 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2544 // Try to use decoder pts from before filters
2545 pts = sh_video->pts;
2546 if (pts == MP_NOPTS_VALUE)
2547 pts = sh_video->last_pts;
2549 sh_video->pts = pts;
2550 if (sh_video->last_pts == MP_NOPTS_VALUE)
2551 sh_video->last_pts = sh_video->pts;
2552 else if (sh_video->last_pts > sh_video->pts) {
2553 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2554 sh_video->pts, sh_video->last_pts);
2555 /* If the difference in pts is small treat it as jitter around the
2556 * right value (possibly caused by incorrect timestamp ordering) and
2557 * just show this frame immediately after the last one.
2558 * Treat bigger differences as timestamp resets and start counting
2559 * timing of later frames from the position of this one. */
2560 if (sh_video->last_pts - sh_video->pts > 0.5)
2561 sh_video->last_pts = sh_video->pts;
2562 else
2563 sh_video->pts = sh_video->last_pts;
2565 double frame_time = sh_video->pts - sh_video->last_pts;
2566 sh_video->last_pts = sh_video->pts;
2567 sh_video->timer += frame_time;
2568 if (mpctx->sh_audio)
2569 mpctx->delay -= frame_time;
2570 return frame_time;
2573 void pause_player(struct MPContext *mpctx)
2575 if (mpctx->paused)
2576 return;
2577 mpctx->paused = 1;
2578 mpctx->step_frames = 0;
2579 mpctx->time_frame -= get_relative_time(mpctx);
2581 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2582 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2584 if (mpctx->audio_out && mpctx->sh_audio)
2585 mpctx->audio_out->pause(); // pause audio, keep data if possible
2588 void unpause_player(struct MPContext *mpctx)
2590 if (!mpctx->paused)
2591 return;
2592 mpctx->paused = 0;
2594 if (mpctx->audio_out && mpctx->sh_audio)
2595 mpctx->audio_out->resume(); // resume audio
2596 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2597 && !mpctx->step_frames)
2598 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2599 (void)get_relative_time(mpctx); // ignore time that passed during pause
2602 void add_step_frame(struct MPContext *mpctx)
2604 mpctx->step_frames++;
2605 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2606 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2607 unpause_player(mpctx);
2610 static void pause_loop(struct MPContext *mpctx)
2612 mp_cmd_t* cmd;
2613 if (!quiet) {
2614 // Small hack to display the pause message on the OSD line.
2615 // The pause string is: "\n == PAUSE == \r" so we need to
2616 // take the first and the last char out
2617 if (term_osd && !mpctx->sh_video) {
2618 char msg[128] = _("\n ===== PAUSE =====\r");
2619 int mlen = strlen(msg);
2620 msg[mlen-1] = '\0';
2621 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2622 update_osd_msg(mpctx);
2623 } else
2624 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2625 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2628 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2629 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2630 if (cmd) {
2631 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2632 run_command(mpctx, cmd);
2633 mp_cmd_free(cmd);
2634 continue;
2636 if (mpctx->sh_video && mpctx->video_out)
2637 vo_check_events(mpctx->video_out);
2638 #ifdef CONFIG_MENU
2639 if (vf_menu)
2640 vf_menu_pause_update(vf_menu);
2641 #endif
2642 usec_sleep(20000);
2643 update_osd_msg(mpctx);
2644 int hack = vo_osd_changed(0);
2645 vo_osd_changed(hack);
2646 if (hack)
2647 break;
2652 // Find the right mute status and record position for new file position
2653 static void edl_seek_reset(MPContext *mpctx)
2655 mpctx->edl_muted = 0;
2656 next_edl_record = edl_records;
2658 while (next_edl_record) {
2659 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2660 break;
2662 if (next_edl_record->action == EDL_MUTE)
2663 mpctx->edl_muted = !mpctx->edl_muted;
2664 next_edl_record = next_edl_record->next;
2666 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2667 mixer_mute(&mpctx->mixer);
2671 // Execute EDL command for the current position if one exists
2672 static void edl_update(MPContext *mpctx)
2674 if (!next_edl_record)
2675 return;
2677 if (!mpctx->sh_video) {
2678 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2679 free_edl(edl_records);
2680 next_edl_record = NULL;
2681 edl_records = NULL;
2682 return;
2685 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2686 if (next_edl_record->action == EDL_SKIP) {
2687 mpctx->osd_function = OSD_FFW;
2688 mpctx->abs_seek_pos = 0;
2689 mpctx->rel_seek_secs = next_edl_record->length_sec;
2690 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2691 "[%f], length [%f]\n", next_edl_record->start_sec,
2692 next_edl_record->stop_sec, next_edl_record->length_sec);
2694 else if (next_edl_record->action == EDL_MUTE) {
2695 mpctx->edl_muted = !mpctx->edl_muted;
2696 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2697 mixer_mute(&mpctx->mixer);
2698 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2699 next_edl_record->start_sec );
2701 next_edl_record = next_edl_record->next;
2705 static void reinit_decoders(struct MPContext *mpctx)
2707 reinit_video_chain(mpctx);
2708 reinit_audio_chain(mpctx);
2709 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2712 static void seek_reset(struct MPContext *mpctx)
2714 if (mpctx->sh_video) {
2715 current_module = "seek_video_reset";
2716 resync_video_stream(mpctx->sh_video);
2717 mpctx->sh_video->timer = 0;
2718 vo_seek_reset(mpctx->video_out);
2719 mpctx->sh_video->timer = 0;
2720 mpctx->sh_video->num_buffered_pts = 0;
2721 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2722 mpctx->delay = 0;
2723 mpctx->time_frame = 0;
2724 mpctx->update_video_immediately = true;
2725 // Not all demuxers set d_video->pts during seek, so this value
2726 // (which is used by at least vobsub and edl code below) may
2727 // be completely wrong (probably 0).
2728 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2729 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2730 mpctx->sh_video->pts, mpctx->video_offset,
2731 mpctx->d_sub, 1);
2732 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2735 if (mpctx->sh_audio) {
2736 current_module = "seek_audio_reset";
2737 resync_audio_stream(mpctx->sh_audio);
2738 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2739 mpctx->sh_audio->a_buffer_len = 0;
2740 mpctx->sh_audio->a_out_buffer_len = 0;
2741 if (!mpctx->sh_video)
2742 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2743 mpctx->video_offset, mpctx->d_sub, 1);
2746 if (vo_vobsub && mpctx->sh_video) {
2747 current_module = "seek_vobsub_reset";
2748 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2751 edl_seek_reset(mpctx);
2753 mpctx->total_avsync_change = 0;
2754 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2755 drop_frame_cnt = 0;
2757 current_module = NULL;
2760 static bool timeline_set_part(struct MPContext *mpctx, int i)
2762 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2763 struct timeline_part *n = mpctx->timeline + i;
2764 mpctx->timeline_part = i;
2765 mpctx->video_offset = n->start - n->source_start;
2766 if (n->source == p->source)
2767 return false;
2768 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2769 mpctx->demuxer = n->source->demuxer;
2770 mpctx->d_video = mpctx->demuxer->video;
2771 mpctx->d_audio = mpctx->demuxer->audio;
2772 mpctx->d_sub = mpctx->demuxer->sub;
2773 mpctx->sh_video = mpctx->d_video->sh;
2774 mpctx->sh_audio = mpctx->d_audio->sh;
2775 return true;
2778 // Given pts, switch playback to the corresponding part.
2779 // Return offset within that part.
2780 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2781 bool *need_reset)
2783 if (pts < 0)
2784 pts = 0;
2785 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2786 struct timeline_part *p = mpctx->timeline + i;
2787 if (pts < (p+1)->start) {
2788 *need_reset = timeline_set_part(mpctx, i);
2789 return pts - p->start + p->source_start;
2792 return -1;
2796 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2797 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2798 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2799 static int seek(MPContext *mpctx, double amount, int style)
2801 current_module = "seek";
2802 if (mpctx->stop_play == AT_END_OF_FILE)
2803 mpctx->stop_play = KEEP_PLAYING;
2804 if (style & SEEK_FACTOR
2805 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2806 || amount < 0)
2807 mpctx->last_chapter_seek = -1;
2808 if (mpctx->timeline && style & SEEK_FACTOR) {
2809 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2810 style &= ~SEEK_FACTOR;
2812 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2813 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2814 style |= SEEK_ABSOLUTE;
2815 if (amount > 0)
2816 style |= SEEK_FORWARD;
2817 else
2818 style |= SEEK_BACKWARD;
2819 amount += mpctx->sh_video->pts;
2822 /* At least the liba52 decoder wants to read from the input stream
2823 * during initialization, so reinit must be done after the demux_seek()
2824 * call that clears possible stream EOF. */
2825 bool need_reset = false;
2826 if (mpctx->timeline) {
2827 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2828 if (amount == -1) {
2829 mpctx->stop_play = AT_END_OF_FILE;
2830 // Clear audio from current position
2831 if (mpctx->sh_audio) {
2832 mpctx->audio_out->reset();
2833 mpctx->sh_audio->a_buffer_len = 0;
2834 mpctx->sh_audio->a_out_buffer_len = 0;
2836 return -1;
2839 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2840 if (need_reset)
2841 reinit_decoders(mpctx);
2842 if (seekresult == 0)
2843 return -1;
2845 seek_reset(mpctx);
2846 return 0;
2849 // -2 is no chapters, -1 is before first chapter
2850 int get_current_chapter(struct MPContext *mpctx)
2852 if (!mpctx->chapters || !mpctx->sh_video)
2853 return FFMAX(mpctx->last_chapter_seek,
2854 demuxer_get_current_chapter(mpctx->demuxer));
2856 int i;
2857 double current_pts = mpctx->sh_video->pts;
2858 for (i = 1; i < mpctx->num_chapters; i++)
2859 if (current_pts < mpctx->chapters[i].start)
2860 break;
2861 return FFMAX(mpctx->last_chapter_seek, i - 1);
2864 // currently returns a string allocated with malloc, not talloc
2865 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2867 if (!mpctx->chapters || !mpctx->sh_video)
2868 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2869 return strdup(mpctx->chapters[chapter].name);
2872 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2873 char **chapter_name)
2875 mpctx->last_chapter_seek = -1;
2876 if (!mpctx->chapters || !mpctx->sh_video) {
2877 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2878 chapter_name);
2879 if (res >= 0) {
2880 if (*seek_pts == -1)
2881 seek_reset(mpctx);
2882 else {
2883 mpctx->last_chapter_seek = res;
2884 mpctx->last_chapter_pts = *seek_pts;
2887 return res;
2890 if (chapter >= mpctx->num_chapters)
2891 return -1;
2892 if (chapter < 0)
2893 chapter = 0;
2894 *seek_pts = mpctx->chapters[chapter].start;
2895 mpctx->last_chapter_seek = chapter;
2896 mpctx->last_chapter_pts = *seek_pts;
2897 if (chapter_name)
2898 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2899 return chapter;
2902 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2903 struct content_source *sources,
2904 int num_sources,
2905 unsigned char uid_map[][16])
2907 int num_filenames = 0;
2908 char **filenames = NULL;
2909 if (num_sources > 1) {
2910 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2911 "other sources.\n");
2912 if (mpctx->stream->type != STREAMTYPE_FILE) {
2913 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2914 "normal disk file. Will not search for related files.\n");
2915 } else {
2916 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2917 "same directory to find referenced sources.\n");
2918 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2919 &num_filenames);
2923 int num_left = num_sources - 1;
2924 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2925 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2926 filename_recode(filenames[i]));
2927 int format;
2928 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2929 if (!s)
2930 continue;
2931 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2932 mpctx->opts.audio_id,
2933 mpctx->opts.video_id,
2934 mpctx->opts.sub_id, filenames[i]);
2935 if (!d) {
2936 free_stream(s);
2937 continue;
2939 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2940 for (int i = 1; i < num_sources; i++) {
2941 if (sources[i].demuxer)
2942 continue;
2943 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2944 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2945 i, filename_recode(d->filename));
2946 sources[i].stream = s;
2947 sources[i].demuxer = d;
2948 num_left--;
2949 goto match;
2953 free_demuxer(d);
2954 free_stream(s);
2955 continue;
2956 match:
2959 talloc_free(filenames);
2960 if (num_left) {
2961 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2962 "There will be parts MISSING from the video!\n");
2963 for (int i = 1, j = 1; i < num_sources; i++)
2964 if (sources[i].demuxer) {
2965 sources[j] = sources[i];
2966 memcpy(uid_map[j], uid_map[i], 16);
2967 j++;
2970 return num_sources - num_left;
2973 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2975 if (!mpctx->opts.ordered_chapters) {
2976 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
2977 "you have disabled support for them. Ignoring.\n");
2978 return;
2981 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
2982 "edit timeline.\n");
2984 struct demuxer *demuxer = mpctx->demuxer;
2985 struct matroska_data *m = &demuxer->matroska_data;
2987 // +1 because sources/uid_map[0] is original file even if all chapters
2988 // actually use other sources and need separate entries
2989 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
2990 m->num_ordered_chapters+1);
2991 sources[0].stream = mpctx->stream;
2992 sources[0].demuxer = mpctx->demuxer;
2993 unsigned char uid_map[m->num_ordered_chapters+1][16];
2994 int num_sources = 1;
2995 memcpy(uid_map[0], m->segment_uid, 16);
2997 for (int i = 0; i < m->num_ordered_chapters; i++) {
2998 struct matroska_chapter *c = m->ordered_chapters + i;
2999 if (!c->has_segment_uid)
3000 memcpy(c->segment_uid, m->segment_uid, 16);
3002 for (int j = 0; j < num_sources; j++)
3003 if (!memcmp(c->segment_uid, uid_map[j], 16))
3004 goto found1;
3005 memcpy(uid_map[num_sources], c->segment_uid, 16);
3006 sources[num_sources] = (struct content_source){};
3007 num_sources++;
3008 found1:
3012 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3013 uid_map);
3016 // +1 for terminating chapter with start time marking end of last real one
3017 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3018 m->num_ordered_chapters + 1);
3019 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3020 m->num_ordered_chapters);
3021 uint64_t starttime = 0;
3022 uint64_t missing_time = 0;
3023 int part_count = 0;
3024 int num_chapters = 0;
3025 uint64_t prev_part_offset = 0;
3026 for (int i = 0; i < m->num_ordered_chapters; i++) {
3027 struct matroska_chapter *c = m->ordered_chapters + i;
3029 int j;
3030 for (j = 0; j < num_sources; j++) {
3031 if (!memcmp(c->segment_uid, uid_map[j], 16))
3032 goto found2;
3034 missing_time += c->end - c->start;
3035 continue;
3036 found2:;
3037 chapters[num_chapters].start = starttime / 1000.;
3038 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3039 /* Only add a separate part if the time or file actually changes.
3040 * Matroska files have chapter divisions that are redundant from
3041 * timeline point of view because the same chapter structure is used
3042 * both to specify the timeline and for normal chapter information.
3043 * Removing a missing inserted external chapter can also cause this. */
3044 if (part_count == 0 || c->start != starttime + prev_part_offset
3045 || sources + j != timeline[part_count - 1].source) {
3046 timeline[part_count].source = sources + j;
3047 timeline[part_count].start = chapters[num_chapters].start;
3048 timeline[part_count].source_start = c->start / 1000.;
3049 prev_part_offset = c->start - starttime;
3050 part_count++;
3052 starttime += c->end - c->start;
3053 num_chapters++;
3055 timeline[part_count].start = starttime / 1000.;
3057 if (!part_count) {
3058 // None of the parts come from the file itself???
3059 talloc_free(sources);
3060 talloc_free(timeline);
3061 talloc_free(chapters);
3062 return;
3065 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3066 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3067 timeline[part_count].start);
3068 if (missing_time)
3069 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3070 "from the timeline!\n", missing_time / 1000.);
3071 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3072 for (int i = 0; i < num_sources; i++)
3073 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3074 filename_recode(sources[i].demuxer->filename));
3075 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3076 "source_start, source):\n");
3077 for (int i = 0; i < part_count; i++) {
3078 struct timeline_part *p = timeline + i;
3079 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3080 p->source_start, p->source - sources);
3082 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3083 mpctx->sources = sources;
3084 mpctx->num_sources = num_sources;
3085 mpctx->timeline = timeline;
3086 mpctx->num_timeline_parts = part_count;
3087 mpctx->num_chapters = num_chapters;
3088 mpctx->chapters = chapters;
3090 mpctx->timeline_part = 0;
3091 mpctx->demuxer = timeline[0].source->demuxer;
3095 static int read_keys(void *ctx, int fd)
3097 getch2(ctx);
3098 return mplayer_get_key(ctx, 0);
3102 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3103 * file for some tools to link against. */
3104 #ifndef DISABLE_MAIN
3105 int main(int argc,char* argv[]){
3108 char * mem_ptr;
3110 // movie info:
3112 /* Flag indicating whether MPlayer should exit without playing anything. */
3113 int opt_exit = 0;
3115 //float a_frame=0; // Audio
3117 int i;
3119 struct MPContext *mpctx = &(struct MPContext){
3120 .osd_function = OSD_PLAY,
3121 .begin_skip = MP_NOPTS_VALUE,
3122 .play_tree_step = 1,
3123 .global_sub_pos = -1,
3124 .set_of_sub_pos = -1,
3125 .file_format = DEMUXER_TYPE_UNKNOWN,
3126 .last_dvb_step = 1,
3129 InitTimer();
3130 srand(GetTimerMS());
3132 mp_msg_init();
3133 set_av_log_callback();
3135 #ifdef CONFIG_X11
3136 mpctx->x11_state = vo_x11_init_state();
3137 #endif
3138 struct MPOpts *opts = &mpctx->opts;
3139 set_default_mplayer_options(opts);
3140 // Create the config context and register the options
3141 mpctx->mconfig = m_config_new(opts, cfg_include);
3142 m_config_register_options(mpctx->mconfig,mplayer_opts);
3143 mp_input_register_options(mpctx->mconfig);
3145 // Preparse the command line
3146 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3148 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3149 set_path_env();
3150 #endif
3152 #ifdef CONFIG_TV
3153 stream_tv_defaults.immediate = 1;
3154 #endif
3156 parse_cfgfiles(mpctx, mpctx->mconfig);
3158 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3159 if(mpctx->playtree == NULL)
3160 opt_exit = 1;
3161 else {
3162 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3163 if(mpctx->playtree) {
3164 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3165 if(mpctx->playtree_iter) {
3166 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3167 play_tree_iter_free(mpctx->playtree_iter);
3168 mpctx->playtree_iter = NULL;
3170 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3174 mpctx->key_fifo = mp_fifo_create(opts);
3176 print_version("MPlayer");
3178 #if defined(__MINGW32__) || defined(__CYGWIN__)
3180 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3181 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3182 if (kernel32)
3183 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3184 if (setDEP) setDEP(3);
3186 // stop Windows from showing all kinds of annoying error dialogs
3187 SetErrorMode(0x8003);
3188 // request 1ms timer resolution
3189 timeBeginPeriod(1);
3190 #endif
3192 #ifdef CONFIG_PRIORITY
3193 set_priority();
3194 #endif
3196 if (codec_path)
3197 set_codec_path(codec_path);
3199 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3200 list_video_out();
3201 opt_exit = 1;
3204 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3205 list_audio_out();
3206 opt_exit = 1;
3209 /* Check codecs.conf. */
3210 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3211 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3212 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3213 if(!parse_codec_cfg(NULL)){
3214 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3216 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3219 free( mem_ptr ); // release the buffer created by get_path()
3222 #if 0
3223 if(video_codec_list){
3224 int i;
3225 video_codec=video_codec_list[0];
3226 for(i=0;video_codec_list[i];i++)
3227 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
3229 #endif
3230 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3231 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3232 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3233 list_codecs(1);
3234 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3235 opt_exit = 1;
3237 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3238 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3239 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3240 list_codecs(0);
3241 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3242 opt_exit = 1;
3244 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3245 vfm_help();
3246 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3247 opt_exit = 1;
3249 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3250 afm_help();
3251 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3252 opt_exit = 1;
3254 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3255 af_help();
3256 printf("\n");
3257 opt_exit = 1;
3259 #ifdef CONFIG_X11
3260 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3261 fstype_help();
3262 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3263 opt_exit = 1;
3265 #endif
3266 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3267 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3268 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3269 demuxer_help();
3270 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3271 opt_exit = 1;
3273 if(list_properties) {
3274 property_print_help();
3275 opt_exit = 1;
3278 if(opt_exit)
3279 exit_player(mpctx, EXIT_NONE);
3281 if(!mpctx->filename && !player_idle_mode){
3282 // no file/vcd/dvd -> show HELP:
3283 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3284 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3287 /* Display what configure line was used */
3288 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3290 // Many users forget to include command line in bugreports...
3291 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3292 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3293 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3294 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3297 //------ load global data first ------
3299 mpctx->osd = osd_create();
3301 // check font
3302 #ifdef CONFIG_FREETYPE
3303 init_freetype();
3304 #endif
3305 #ifdef CONFIG_FONTCONFIG
3306 if(font_fontconfig <= 0)
3308 #endif
3309 #ifdef CONFIG_BITMAP_FONT
3310 if(font_name){
3311 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3312 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3313 filename_recode(font_name));
3314 } else {
3315 // try default:
3316 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3317 free(mem_ptr); // release the buffer created by get_path()
3318 if(!vo_font)
3319 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3321 if (sub_font_name)
3322 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3323 else
3324 mpctx->osd->sub_font = vo_font;
3325 #endif
3326 #ifdef CONFIG_FONTCONFIG
3328 #endif
3330 #ifdef CONFIG_ASS
3331 ass_library = ass_init();
3332 #endif
3334 #ifdef HAVE_RTC
3335 if(!nortc)
3337 // seteuid(0); /* Can't hurt to try to get root here */
3338 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3339 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3340 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3341 else {
3342 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3344 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3345 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3346 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3347 close (rtc_fd);
3348 rtc_fd = -1;
3349 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3350 /* variable only by the root */
3351 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3352 close (rtc_fd);
3353 rtc_fd = -1;
3354 } else
3355 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3358 if(rtc_fd<0)
3359 #endif /* HAVE_RTC */
3360 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3361 softsleep?"software":timer_name);
3363 #ifdef HAVE_TERMCAP
3364 load_termcap(NULL); // load key-codes
3365 #endif
3367 // ========== Init keyboard FIFO (connection to libvo) ============
3369 // Init input system
3370 current_module = "init_input";
3371 mpctx->input = mp_input_init(&opts->input);
3372 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3373 if(slave_mode)
3374 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3375 else if(!noconsolecontrols)
3376 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3377 // Set the libstream interrupt callback
3378 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3380 #ifdef CONFIG_MENU
3381 if(use_menu) {
3382 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3383 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3384 else {
3385 menu_cfg = get_path("menu.conf");
3386 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3387 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3388 else {
3389 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3390 MPLAYER_CONFDIR "/menu.conf"))
3391 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3392 else {
3393 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3394 use_menu = 0;
3399 #endif
3401 current_module = NULL;
3403 /// Catch signals
3404 #ifndef __MINGW32__
3405 signal(SIGCHLD,child_sighandler);
3406 #endif
3408 #ifdef CONFIG_CRASH_DEBUG
3409 prog_path = argv[0];
3410 #endif
3411 //========= Catch terminate signals: ================
3412 // terminate requests:
3413 signal(SIGTERM,exit_sighandler); // kill
3414 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3416 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3418 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3419 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3420 #ifdef CONFIG_SIGHANDLER
3421 // fatal errors:
3422 signal(SIGBUS,exit_sighandler); // bus error
3423 signal(SIGSEGV,exit_sighandler); // segfault
3424 signal(SIGILL,exit_sighandler); // illegal instruction
3425 signal(SIGFPE,exit_sighandler); // floating point exc.
3426 signal(SIGABRT,exit_sighandler); // abort()
3427 #ifdef CONFIG_CRASH_DEBUG
3428 if (crash_debug)
3429 signal(SIGTRAP,exit_sighandler);
3430 #endif
3431 #endif
3433 // ******************* Now, let's see the per-file stuff ********************
3435 play_next_file:
3437 // init global sub numbers
3438 mpctx->global_sub_size = 0;
3439 { int i; for (i = 0; i < SUB_SOURCES; i++) mpctx->global_sub_indices[i] = -1; }
3441 if (mpctx->filename) {
3442 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3443 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3444 load_per_file_config (mpctx->mconfig, mpctx->filename);
3447 if (opts->video_driver_list)
3448 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3449 if (opts->audio_driver_list)
3450 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3452 // We must enable getch2 here to be able to interrupt network connection
3453 // or cache filling
3454 if(!noconsolecontrols && !slave_mode){
3455 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3456 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3457 else
3458 getch2_enable(); // prepare stdin for hotkeys...
3459 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3460 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3463 // =================== GUI idle loop (STOP state) ===========================
3464 while (player_idle_mode && !mpctx->filename) {
3465 play_tree_t * entry = NULL;
3466 mp_cmd_t * cmd;
3467 if (mpctx->video_out && mpctx->video_out->config_ok)
3468 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3469 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3470 if (mpctx->video_out)
3471 vo_check_events(mpctx->video_out);
3472 usec_sleep(20000);
3474 switch (cmd->id) {
3475 case MP_CMD_LOADFILE:
3476 // prepare a tree entry with the new filename
3477 entry = play_tree_new();
3478 play_tree_add_file(entry, cmd->args[0].v.s);
3479 // The entry is added to the main playtree after the switch().
3480 break;
3481 case MP_CMD_LOADLIST:
3482 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3483 break;
3484 case MP_CMD_QUIT:
3485 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3486 break;
3487 case MP_CMD_GET_PROPERTY:
3488 case MP_CMD_SET_PROPERTY:
3489 case MP_CMD_STEP_PROPERTY:
3490 run_command(mpctx, cmd);
3491 break;
3494 mp_cmd_free(cmd);
3496 if (entry) { // user entered a command that gave a valid entry
3497 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3498 play_tree_free_list(mpctx->playtree->child, 1);
3499 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3501 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3503 play_tree_set_child(mpctx->playtree, entry);
3505 /* Make iterator start at the top the of tree. */
3506 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3507 if (!mpctx->playtree_iter) continue;
3509 // find the first real item in the tree
3510 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3511 // no items!
3512 play_tree_iter_free(mpctx->playtree_iter);
3513 mpctx->playtree_iter = NULL;
3514 continue; // wait for next command
3516 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3519 //---------------------------------------------------------------------------
3521 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3522 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3524 if (mpctx->filename) {
3525 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3526 filename_recode(mpctx->filename));
3527 if(use_filename_title && vo_wintitle == NULL)
3528 vo_wintitle = strdup(mp_basename2(mpctx->filename));
3531 if (edl_filename) {
3532 if (edl_records) free_edl(edl_records);
3533 next_edl_record = edl_records = edl_parse_file();
3535 if (edl_output_filename) {
3536 if (edl_fd) fclose(edl_fd);
3537 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3539 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3540 filename_recode(edl_output_filename));
3544 //==================== Open VOB-Sub ============================
3546 current_module="vobsub";
3547 if (vobsub_name){
3548 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3549 if(vo_vobsub==NULL)
3550 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3551 filename_recode(vobsub_name));
3552 } else if (sub_auto && mpctx->filename){
3553 /* try to autodetect vobsub from movie filename ::atmos */
3554 char *buf = strdup(mpctx->filename), *psub;
3555 char *pdot = strrchr(buf, '.');
3556 char *pslash = strrchr(buf, '/');
3557 #if defined(__MINGW32__) || defined(__CYGWIN__)
3558 if (!pslash) pslash = strrchr(buf, '\\');
3559 #endif
3560 if (pdot && (!pslash || pdot > pslash))
3561 *pdot = '\0';
3562 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3563 /* try from ~/.mplayer/sub */
3564 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3565 char *bname;
3566 int l;
3567 bname = strrchr(buf,'/');
3568 #if defined(__MINGW32__) || defined(__CYGWIN__)
3569 if(!bname) bname = strrchr(buf,'\\');
3570 #endif
3571 if(bname) bname++;
3572 else bname = buf;
3573 l = strlen(psub) + strlen(bname) + 1;
3574 psub = realloc(psub,l);
3575 strcat(psub,bname);
3576 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3577 free(psub);
3579 free(buf);
3581 if(vo_vobsub){
3582 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3583 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3584 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3586 // setup global sub numbering
3587 mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] = mpctx->global_sub_size; // the global # of the first vobsub.
3588 mpctx->global_sub_size += vobsub_get_indexes_count(vo_vobsub);
3591 //============ Open & Sync STREAM --- fork cache2 ====================
3593 mpctx->stream=NULL;
3594 mpctx->demuxer=NULL;
3595 if (mpctx->d_audio) {
3596 //free_demuxer_stream(mpctx->d_audio);
3597 mpctx->d_audio=NULL;
3599 if (mpctx->d_video) {
3600 //free_demuxer_stream(d_video);
3601 mpctx->d_video=NULL;
3603 mpctx->sh_audio=NULL;
3604 mpctx->sh_video=NULL;
3606 current_module="open_stream";
3607 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3608 if(!mpctx->stream) { // error...
3609 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3610 goto goto_next_file;
3612 mpctx->initialized_flags|=INITIALIZED_STREAM;
3614 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3615 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3616 "playlist support will not be used automatically.\n"
3617 "MPlayer's playlist code is unsafe and should only be used with "
3618 "trusted sources.\nPlayback will probably fail.\n\n");
3619 #if 0
3620 play_tree_t* entry;
3621 // Handle playlist
3622 current_module="handle_playlist";
3623 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3624 filename_recode(mpctx->filename));
3625 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3626 mpctx->eof=playtree_add_playlist(mpctx, entry);
3627 goto goto_next_file;
3628 #endif
3630 mpctx->stream->start_pos+=seek_to_byte;
3632 if(stream_dump_type==5){
3633 unsigned char buf[4096];
3634 int len;
3635 FILE *f;
3636 current_module="dumpstream";
3637 stream_reset(mpctx->stream);
3638 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3639 f=fopen(stream_dump_name,"wb");
3640 if(!f){
3641 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3642 exit_player(mpctx, EXIT_ERROR);
3644 if (opts->chapterrange[0] > 1) {
3645 int chapter = opts->chapterrange[0] - 1;
3646 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3648 while(!mpctx->stream->eof && !async_quit_request){
3649 len=stream_read(mpctx->stream,buf,4096);
3650 if(len>0) {
3651 if(fwrite(buf,len,1,f) != 1) {
3652 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3653 exit_player(mpctx, EXIT_ERROR);
3656 if (opts->chapterrange[1] > 0) {
3657 int chapter = -1;
3658 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3659 &chapter) == STREAM_OK
3660 && chapter + 1 > opts->chapterrange[1])
3661 break;
3664 if(fclose(f)) {
3665 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3666 exit_player(mpctx, EXIT_ERROR);
3668 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3669 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3672 #ifdef CONFIG_DVDREAD
3673 if(mpctx->stream->type==STREAMTYPE_DVD){
3674 current_module="dvd lang->id";
3675 if(opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3676 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3677 // setup global sub numbering
3678 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3679 mpctx->global_sub_size += dvd_number_of_subs(mpctx->stream);
3680 current_module=NULL;
3682 #endif
3684 #ifdef CONFIG_DVDNAV
3685 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3686 current_module="dvdnav lang->id";
3687 if(opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3688 dvdsub_lang_id = -3;
3689 if(opts->sub_lang && opts->sub_id==-1)
3690 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3691 // setup global sub numbering
3692 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3693 mpctx->global_sub_size += mp_dvdnav_number_of_subs(mpctx->stream);
3694 current_module=NULL;
3696 #endif
3698 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3699 goto_enable_cache:
3700 if(stream_cache_size>0){
3701 int res;
3702 current_module="enable_cache";
3703 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3704 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3705 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3706 if(res == 0)
3707 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3710 //============ Open DEMUXERS --- DETECT file type =======================
3711 current_module="demux_open";
3713 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3715 // HACK to get MOV Reference Files working
3717 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3719 unsigned char* playlist_entry;
3720 play_tree_t *list = NULL, *entry = NULL;
3722 current_module="handle_demux_playlist";
3723 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3725 char *temp, *bname;
3727 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3728 filename_recode(playlist_entry));
3730 bname=mp_basename(playlist_entry);
3731 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3732 continue;
3734 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3735 continue;
3737 entry = play_tree_new();
3739 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3741 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3742 if (temp)
3744 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3745 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3746 strcat(temp, playlist_entry);
3747 if (!strcmp(temp, mpctx->filename)) {
3748 free(temp);
3749 continue;
3751 play_tree_add_file(entry,temp);
3752 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3753 free(temp);
3756 else
3757 play_tree_add_file(entry,playlist_entry);
3759 if(!list)
3760 list = entry;
3761 else
3762 play_tree_append_entry(list,entry);
3764 free_demuxer(mpctx->demuxer);
3765 mpctx->demuxer = NULL;
3767 if (list)
3769 entry = play_tree_new();
3770 play_tree_set_child(entry,list);
3771 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3772 goto goto_next_file;
3776 if(!mpctx->demuxer)
3777 goto goto_next_file;
3779 if (mpctx->demuxer->matroska_data.ordered_chapters)
3780 build_ordered_chapter_timeline(mpctx);
3782 if (!mpctx->sources) {
3783 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3784 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3785 .demuxer = mpctx->demuxer};
3786 mpctx->num_sources = 1;
3789 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3791 if (mpctx->stream->type != STREAMTYPE_DVD && mpctx->stream->type != STREAMTYPE_DVDNAV) {
3792 int i;
3793 int maxid = -1;
3794 // setup global sub numbering
3795 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3796 for (i = 0; i < MAX_S_STREAMS; i++)
3797 if (mpctx->demuxer->s_streams[i])
3798 maxid = FFMAX(maxid, mpctx->demuxer->s_streams[i]->sid);
3799 mpctx->global_sub_size += maxid + 1;
3801 // Make opts->sub_id always selectable if set.
3802 if (mpctx->global_sub_size <= mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id)
3803 mpctx->global_sub_size = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id + 1;
3805 #ifdef CONFIG_ASS
3806 if (opts->ass_enabled && ass_library) {
3807 for (int j = 0; j < mpctx->num_sources; j++) {
3808 struct demuxer *d = mpctx->sources[j].demuxer;
3809 for (int i = 0; i < d->num_attachments; i++) {
3810 struct demux_attachment *att = d->attachments + i;
3811 if (use_embedded_fonts && attachment_is_font(att))
3812 ass_add_font(ass_library, att->name, att->data, att->data_size);
3816 #endif
3818 current_module="demux_open2";
3820 //file_format=demuxer->file_format;
3822 mpctx->d_audio=mpctx->demuxer->audio;
3823 mpctx->d_video=mpctx->demuxer->video;
3824 mpctx->d_sub=mpctx->demuxer->sub;
3826 if (ts_prog) {
3827 int tmp = ts_prog;
3828 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3830 // select audio stream
3831 if (mpctx->num_sources)
3832 for (int i = 0; i < mpctx->num_sources; i++)
3833 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3834 opts->audio_lang);
3835 else
3836 select_audio(mpctx->demuxer, opts->audio_id, opts->audio_lang);
3838 // DUMP STREAMS:
3839 if((stream_dump_type)&&(stream_dump_type<4)){
3840 FILE *f;
3841 demux_stream_t *ds=NULL;
3842 current_module="dump";
3843 // select stream to dump
3844 switch(stream_dump_type){
3845 case 1: ds=mpctx->d_audio;break;
3846 case 2: ds=mpctx->d_video;break;
3847 case 3: ds=mpctx->d_sub;break;
3849 if(!ds){
3850 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3851 exit_player(mpctx, EXIT_ERROR);
3853 // disable other streams:
3854 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3855 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3856 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3857 // let's dump it!
3858 f=fopen(stream_dump_name,"wb");
3859 if(!f){
3860 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3861 exit_player(mpctx, EXIT_ERROR);
3863 while(!ds->eof){
3864 unsigned char* start;
3865 int in_size=ds_get_packet(ds,&start);
3866 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3867 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3868 if(in_size>0) fwrite(start,in_size,1,f);
3869 if (opts->chapterrange[1] > 0) {
3870 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3871 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3872 break;
3875 fclose(f);
3876 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3877 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3880 mpctx->sh_audio=mpctx->d_audio->sh;
3881 mpctx->sh_video=mpctx->d_video->sh;
3883 if(mpctx->sh_video){
3885 current_module="video_read_properties";
3886 if(!video_read_properties(mpctx->sh_video)) {
3887 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3888 mpctx->sh_video=mpctx->d_video->sh=NULL;
3889 } else {
3890 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3891 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3892 mpctx->sh_video->fps,mpctx->sh_video->frametime
3895 /* need to set fps here for output encoders to pick it up in their init */
3896 if(force_fps){
3897 mpctx->sh_video->fps=force_fps;
3898 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3900 vo_fps = mpctx->sh_video->fps;
3902 if(!mpctx->sh_video->fps && !force_fps){
3903 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3904 mpctx->opts.correct_pts = 1;
3910 if(!mpctx->sh_video && !mpctx->sh_audio){
3911 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3912 #ifdef CONFIG_DVBIN
3913 if(mpctx->stream->type == STREAMTYPE_DVB)
3915 int dir;
3916 int v = mpctx->last_dvb_step;
3917 if(v > 0)
3918 dir = DVB_CHANNEL_HIGHER;
3919 else
3920 dir = DVB_CHANNEL_LOWER;
3922 if(dvb_step_channel(mpctx->stream, dir)) {
3923 mpctx->stop_play = PT_NEXT_ENTRY;
3924 mpctx->dvbin_reopen = 1;
3927 #endif
3928 goto goto_next_file; // exit_player(_("Fatal error"));
3931 /* display clip info */
3932 demux_info_print(mpctx->demuxer);
3934 //================== Read SUBTITLES (DVD & TEXT) ==========================
3935 if(vo_spudec==NULL &&
3936 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3937 init_vo_spudec(mpctx);
3940 // after reading video params we should load subtitles because
3941 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3942 // check .sub
3943 current_module="read_subtitles_file";
3944 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3945 if(sub_name){
3946 for (i = 0; sub_name[i] != NULL; ++i)
3947 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3949 if(sub_auto) { // auto load sub file ...
3950 char *psub = get_path( "sub/" );
3951 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3952 int i = 0;
3953 free(psub); // release the buffer created by get_path() above
3954 while (tmp[i]) {
3955 add_subtitles(mpctx, tmp[i], sub_fps, 1);
3956 free(tmp[i++]);
3958 free(tmp);
3960 if (mpctx->set_of_sub_size > 0) {
3961 // setup global sub numbering
3962 mpctx->global_sub_indices[SUB_SOURCE_SUBS] = mpctx->global_sub_size; // the global # of the first sub.
3963 mpctx->global_sub_size += mpctx->set_of_sub_size;
3967 if (mpctx->global_sub_size) {
3968 select_subtitle(mpctx);
3969 if(subdata)
3970 switch (stream_dump_type) {
3971 case 3: list_sub_file(subdata); break;
3972 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3973 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3974 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3975 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3976 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3980 print_file_properties(mpctx, mpctx->filename);
3982 if(!mpctx->sh_video) goto main; // audio-only
3984 if(!reinit_video_chain(mpctx)) {
3985 if(!mpctx->sh_video){
3986 if(!mpctx->sh_audio) goto goto_next_file;
3987 goto main; // exit_player(_("Fatal error"));
3991 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
3992 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3994 #ifdef CONFIG_FREETYPE
3995 force_load_font = 1;
3996 #endif
3998 //================== MAIN: ==========================
3999 main:
4000 current_module="main";
4002 if(playing_msg) {
4003 char* msg = property_expand_string(mpctx, playing_msg);
4004 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4005 free(msg);
4009 // Disable the term OSD in verbose mode
4010 if(verbose) term_osd = 0;
4013 //int frame_corr_num=0; //
4014 //float v_frame=0; // Video
4015 //float num_frames=0; // number of frames played
4017 int frame_time_remaining=0; // flag
4018 int blit_frame=0;
4020 // Make sure old OSD does not stay around,
4021 // e.g. with -fixed-vo and same-resolution files
4022 clear_osd_msgs();
4023 update_osd_msg(mpctx);
4025 //================ SETUP AUDIO ==========================
4027 if(mpctx->sh_audio){
4028 reinit_audio_chain(mpctx);
4029 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4030 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4033 current_module="av_init";
4035 if(mpctx->sh_video){
4036 mpctx->sh_video->timer=0;
4037 if (! ignore_start)
4038 audio_delay += mpctx->sh_video->stream_delay;
4040 if(mpctx->sh_audio){
4041 if (start_volume >= 0)
4042 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4043 if (! ignore_start)
4044 audio_delay -= mpctx->sh_audio->stream_delay;
4045 mpctx->delay=-audio_delay;
4048 if(!mpctx->sh_audio){
4049 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4050 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4051 ds_free_packs(mpctx->d_audio); // free buffered chunks
4052 //mpctx->d_audio->id=-2; // do not read audio chunks
4053 //uninit_player(mpctx, INITIALIZED_AO); // close device
4055 if(!mpctx->sh_video){
4056 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4057 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4058 ds_free_packs(mpctx->d_video);
4059 mpctx->d_video->id=-2;
4060 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4063 if (!mpctx->sh_video && !mpctx->sh_audio)
4064 goto goto_next_file;
4066 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4067 if(force_fps && mpctx->sh_video){
4068 vo_fps = mpctx->sh_video->fps=force_fps;
4069 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4070 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4073 mp_input_set_section(mpctx->input, NULL);
4074 //TODO: add desired (stream-based) sections here
4075 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4076 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4078 //==================== START PLAYING =======================
4080 if(opts->loop_times>1) opts->loop_times--; else
4081 if(opts->loop_times==1) opts->loop_times = -1;
4083 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4085 total_time_usage_start=GetTimer();
4086 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4087 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4088 play_n_frames=play_n_frames_mf;
4090 if(play_n_frames==0){
4091 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4094 // If there's a timeline force an absolute seek to initialize state
4095 if (seek_to_sec || mpctx->timeline) {
4096 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4097 end_at.pos += seek_to_sec;
4099 if (opts->chapterrange[0] > 0) {
4100 double pts;
4101 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4102 && pts > -1.0)
4103 seek(mpctx, pts, SEEK_ABSOLUTE);
4106 if (end_at.type == END_AT_SIZE) {
4107 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4108 end_at.type = END_AT_NONE;
4111 #ifdef CONFIG_DVDNAV
4112 mp_dvdnav_context_free(mpctx);
4113 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4114 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4115 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4117 #endif
4119 get_relative_time(mpctx); // reset current delta
4120 mpctx->time_frame = 0;
4121 mpctx->drop_message_shown = 0;
4122 mpctx->update_video_immediately = true;
4123 mpctx->total_avsync_change = 0;
4124 mpctx->last_chapter_seek = -1;
4125 // Make sure VO knows current pause state
4126 if (mpctx->sh_video)
4127 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4128 NULL);
4130 while(!mpctx->stop_play){
4131 float aq_sleep_time=0;
4133 if (opts->chapterrange[1] > 0) {
4134 int cur_chapter = get_current_chapter(mpctx);
4135 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4136 goto goto_next_file;
4139 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4140 mpctx->sh_audio = mpctx->d_audio->sh;
4141 mpctx->sh_audio->ds = mpctx->d_audio;
4142 reinit_audio_chain(mpctx);
4145 /*========================== PLAY AUDIO ============================*/
4147 if (mpctx->sh_audio && !mpctx->paused)
4148 if (!fill_audio_out_buffers(mpctx))
4149 // at eof, all audio at least written to ao
4150 if (!mpctx->sh_video)
4151 mpctx->stop_play = AT_END_OF_FILE;
4154 if(!mpctx->sh_video) {
4155 // handle audio-only case:
4156 double a_pos=0;
4157 // sh_audio can be NULL due to video stream switching
4158 // TODO: handle this better
4159 if (mpctx->sh_audio)
4160 a_pos = playing_audio_pts(mpctx);
4162 print_status(mpctx, a_pos, false);
4164 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4165 mpctx->stop_play = PT_NEXT_ENTRY;
4166 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4167 mpctx->d_sub, 0);
4168 update_osd_msg(mpctx);
4170 } else {
4172 /*========================== PLAY VIDEO ============================*/
4174 vo_pts=mpctx->sh_video->timer*90000.0;
4175 vo_fps=mpctx->sh_video->fps;
4177 blit_frame = mpctx->video_out->frame_loaded;
4178 if (!blit_frame) {
4179 double frame_time = update_video(mpctx);
4180 blit_frame = mpctx->video_out->frame_loaded;
4181 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4182 if (mpctx->sh_video->vf_initialized < 0) {
4183 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4184 mpctx->stop_play = PT_NEXT_ENTRY;
4185 goto goto_next_file;
4187 if (blit_frame) {
4188 struct sh_video *sh_video = mpctx->sh_video;
4189 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4190 mpctx->video_offset, mpctx->d_sub, 0);
4191 update_teletext(sh_video, mpctx->demuxer, 0);
4192 update_osd_msg(mpctx);
4193 struct vf_instance *vf = mpctx->sh_video->vfilter;
4194 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4195 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4196 vo_osd_changed(0);
4198 if (frame_time < 0)
4199 mpctx->stop_play = AT_END_OF_FILE;
4200 else {
4201 if (mpctx->update_video_immediately) {
4202 // Show this frame immediately, rest normally
4203 mpctx->update_video_immediately = false;
4204 } else {
4205 mpctx->time_frame += frame_time / opts->playback_speed;
4206 adjust_sync(mpctx, frame_time);
4210 if (mpctx->timeline) {
4211 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4212 if (mpctx->sh_video->pts >= next->start
4213 || mpctx->stop_play == AT_END_OF_FILE
4214 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4215 seek(mpctx, next->start, SEEK_ABSOLUTE);
4216 continue;
4220 // ==========================================================================
4222 // current_module="draw_osd";
4223 // if(vo_config_count) mpctx->video_out->draw_osd();
4225 current_module="vo_check_events";
4226 vo_check_events(mpctx->video_out);
4228 #ifdef CONFIG_X11
4229 if (stop_xscreensaver) {
4230 current_module = "stop_xscreensaver";
4231 xscreensaver_heartbeat(mpctx->x11_state);
4233 #endif
4234 if (heartbeat_cmd) {
4235 static unsigned last_heartbeat;
4236 unsigned now = GetTimerMS();
4237 if (now - last_heartbeat > 30000) {
4238 last_heartbeat = now;
4239 system(heartbeat_cmd);
4243 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4245 //====================== FLIP PAGE (VIDEO BLT): =========================
4247 current_module="flip_page";
4248 if (!frame_time_remaining && blit_frame) {
4249 unsigned int t2=GetTimer();
4250 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4251 int duration = -1;
4252 double pts2 = mpctx->video_out->next_pts2;
4253 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4254 // expected A/V sync correction is ignored
4255 double diff = (pts2 - mpctx->sh_video->pts);
4256 diff /= opts->playback_speed;
4257 if (mpctx->time_frame < 0)
4258 diff += mpctx->time_frame;
4259 if (diff < 0)
4260 diff = 0;
4261 if (diff > 10)
4262 diff = 10;
4263 duration = diff * 1e6;
4265 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4267 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4268 vout_time_usage += mpctx->last_vo_flip_duration;
4269 if (mpctx->video_out->driver->flip_page_timed) {
4270 // No need to adjust sync based on flip speed
4271 mpctx->last_vo_flip_duration = 0;
4272 // For print_status - VO call finishing early is OK for sync
4273 mpctx->time_frame -= get_relative_time(mpctx);
4275 print_status(mpctx, MP_NOPTS_VALUE, true);
4277 else
4278 print_status(mpctx, MP_NOPTS_VALUE, false);
4280 //============================ Auto QUALITY ============================
4282 /*Output quality adjustments:*/
4283 if(auto_quality>0){
4284 current_module="autoq";
4285 // float total=0.000001f * (GetTimer()-aq_total_time);
4286 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4287 if(output_quality<auto_quality && aq_sleep_time>0)
4288 ++output_quality;
4289 else
4290 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4291 if(output_quality>1 && aq_sleep_time<0)
4292 --output_quality;
4293 else
4294 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4295 output_quality=0;
4296 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4297 set_video_quality(mpctx->sh_video,output_quality);
4300 if (!frame_time_remaining && blit_frame) {
4301 if (play_n_frames >= 0) {
4302 --play_n_frames;
4303 if (play_n_frames <= 0)
4304 mpctx->stop_play = PT_NEXT_ENTRY;
4306 if (mpctx->step_frames > 0) {
4307 mpctx->step_frames--;
4308 if (mpctx->step_frames == 0)
4309 pause_player(mpctx);
4314 // FIXME: add size based support for -endpos
4315 if (end_at.type == END_AT_TIME &&
4316 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4317 mpctx->stop_play = PT_NEXT_ENTRY;
4319 } // end if(mpctx->sh_video)
4321 #ifdef CONFIG_DVDNAV
4322 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4323 nav_highlight_t hl;
4324 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4325 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4326 vo_osd_changed (OSDTYPE_DVDNAV);
4328 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4329 double ar = -1.0;
4330 if (mpctx->sh_video &&
4331 stream_control (mpctx->demuxer->stream,
4332 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4333 != STREAM_UNSUPPORTED)
4334 mpctx->sh_video->stream_aspect = ar;
4337 #endif
4339 //================= Keyboard events, SEEKing ====================
4341 current_module="key_events";
4344 while (1) {
4345 mp_cmd_t* cmd;
4346 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4347 run_command(mpctx, cmd);
4348 mp_cmd_free(cmd);
4349 if (mpctx->stop_play)
4350 break;
4351 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4352 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4353 /* Allow seek commands to be combined, but execute the real seek
4354 * before processing other commands */
4355 if (!cmd || cmd->id != MP_CMD_SEEK)
4356 break;
4359 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4360 || mpctx->abs_seek_pos)
4361 break;
4362 if (mpctx->sh_video) {
4363 update_osd_msg(mpctx);
4364 int hack = vo_osd_changed(0);
4365 vo_osd_changed(hack);
4366 if (hack) {
4367 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4368 add_step_frame(mpctx);
4369 break;
4371 else
4372 vo_osd_changed(0);
4375 pause_loop(mpctx);
4379 // handle -sstep
4380 if (step_sec > 0 && !mpctx->paused) {
4381 mpctx->osd_function=OSD_FFW;
4382 mpctx->rel_seek_secs+=step_sec;
4385 edl_update(mpctx);
4387 /* Looping. */
4388 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4389 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4391 if(opts->loop_times>1) opts->loop_times--; else
4392 if(opts->loop_times==1) opts->loop_times=-1;
4393 play_n_frames=play_n_frames_mf;
4394 mpctx->stop_play=0;
4395 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4398 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4399 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4401 mpctx->rel_seek_secs=0;
4402 mpctx->abs_seek_pos=0;
4405 } // while(!mpctx->stop_play)
4407 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4409 #ifdef CONFIG_DVBIN
4410 if(mpctx->dvbin_reopen)
4412 mpctx->stop_play = 0;
4413 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4414 cache_uninit(mpctx->stream);
4415 mpctx->dvbin_reopen = 0;
4416 goto goto_enable_cache;
4418 #endif
4421 goto_next_file: // don't jump here after ao/vo/getch initialization!
4423 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4425 if(benchmark){
4426 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4427 double total_time_usage;
4428 total_time_usage_start=GetTimer()-total_time_usage_start;
4429 total_time_usage = (float)total_time_usage_start*0.000001;
4430 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4431 video_time_usage,vout_time_usage,audio_time_usage,
4432 total_time_usage-tot,total_time_usage);
4433 if(total_time_usage>0.0)
4434 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4435 100.0*video_time_usage/total_time_usage,
4436 100.0*vout_time_usage/total_time_usage,
4437 100.0*audio_time_usage/total_time_usage,
4438 100.0*(total_time_usage-tot)/total_time_usage,
4439 100.0);
4440 if(total_frame_cnt && frame_dropping)
4441 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4442 total_frame_cnt-drop_frame_cnt,
4443 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4444 drop_frame_cnt,
4445 100*drop_frame_cnt/total_frame_cnt,
4446 total_frame_cnt,
4447 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4450 // time to uninit all, except global stuff:
4451 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4453 if(mpctx->set_of_sub_size > 0) {
4454 current_module="sub_free";
4455 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4456 sub_free(mpctx->set_of_subtitles[i]);
4457 #ifdef CONFIG_ASS
4458 if(mpctx->set_of_ass_tracks[i])
4459 ass_free_track( mpctx->set_of_ass_tracks[i] );
4460 #endif
4462 mpctx->set_of_sub_size = 0;
4464 vo_sub_last = vo_sub=NULL;
4465 subdata=NULL;
4466 #ifdef CONFIG_ASS
4467 ass_track = NULL;
4468 if(ass_library)
4469 ass_clear_fonts(ass_library);
4470 #endif
4472 if (!mpctx->stop_play) // In case some goto jumped here...
4473 mpctx->stop_play = PT_NEXT_ENTRY;
4475 int playtree_direction = 1;
4477 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4478 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4479 play_tree_iter_free(mpctx->playtree_iter);
4480 mpctx->playtree_iter = NULL;
4482 mpctx->play_tree_step = 1;
4483 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4484 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4485 if(mpctx->playtree_iter) {
4486 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4487 play_tree_iter_free(mpctx->playtree_iter);
4488 mpctx->playtree_iter = NULL;
4491 } else if (mpctx->stop_play == PT_STOP) {
4492 play_tree_iter_free(mpctx->playtree_iter);
4493 mpctx->playtree_iter = NULL;
4494 } else { // NEXT PREV SRC
4495 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4498 while(mpctx->playtree_iter != NULL) {
4499 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4500 if(mpctx->filename == NULL) {
4501 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4502 play_tree_iter_free(mpctx->playtree_iter);
4503 mpctx->playtree_iter = NULL;
4505 } else
4506 break;
4509 if(mpctx->playtree_iter != NULL || player_idle_mode){
4510 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4511 mpctx->stop_play = 0;
4512 goto play_next_file;
4516 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4518 return 1;
4520 #endif /* DISABLE_MAIN */