vf_fixpts: Mark vf_info_t declaration const
[mplayer.git] / mplayer.c
blobd4a624c69626e7343d262d2a45b2f801b28803ca
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 static const vf_info_t* const libmenu_vfs[] = {
374 &vf_info_menu,
375 NULL
377 static vf_instance_t* vf_menu = NULL;
378 int use_menu = 0;
379 static char* menu_cfg = NULL;
380 static char* menu_root = "main";
381 #endif
384 #ifdef HAVE_RTC
385 static int nortc = 1;
386 static char* rtc_device;
387 #endif
389 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
390 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
391 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
392 int use_filedir_conf;
393 int use_filename_title;
395 #include "mpcommon.h"
396 #include "command.h"
398 #include "metadata.h"
400 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
402 const void *mpctx_get_video_out(MPContext *mpctx)
404 return mpctx->video_out;
407 const void *mpctx_get_audio_out(MPContext *mpctx)
409 return mpctx->audio_out;
412 void *mpctx_get_demuxer(MPContext *mpctx)
414 return mpctx->demuxer;
417 void *mpctx_get_playtree_iter(MPContext *mpctx)
419 return mpctx->playtree_iter;
422 void *mpctx_get_mixer(MPContext *mpctx)
424 return &mpctx->mixer;
427 int mpctx_get_global_sub_size(MPContext *mpctx)
429 return mpctx->global_sub_size;
432 int mpctx_get_osd_function(MPContext *mpctx)
434 return mpctx->osd_function;
437 static float get_relative_time(struct MPContext *mpctx)
439 unsigned int new_time = GetTimer();
440 unsigned int delta = new_time - mpctx->last_time;
441 mpctx->last_time = new_time;
442 return delta * 0.000001;
445 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
446 switch (type)
448 /* check for valid video stream */
449 case META_VIDEO_CODEC:
450 case META_VIDEO_BITRATE:
451 case META_VIDEO_RESOLUTION:
453 if (!mpctx->sh_video)
454 return 0;
455 break;
458 /* check for valid audio stream */
459 case META_AUDIO_CODEC:
460 case META_AUDIO_BITRATE:
461 case META_AUDIO_SAMPLES:
463 if (!mpctx->sh_audio)
464 return 0;
465 break;
468 /* check for valid demuxer */
469 case META_INFO_TITLE:
470 case META_INFO_ARTIST:
471 case META_INFO_ALBUM:
472 case META_INFO_YEAR:
473 case META_INFO_COMMENT:
474 case META_INFO_TRACK:
475 case META_INFO_GENRE:
477 if (!mpctx->demuxer)
478 return 0;
479 break;
482 default:
483 break;
486 return 1;
489 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
490 char **info = mpctx->demuxer->info;
491 int n;
493 if (!info || !tag)
494 return NULL;
496 for (n = 0; info[2*n] != NULL ; n++)
497 if (!strcasecmp (info[2*n], tag))
498 break;
500 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
503 char *get_metadata(struct MPContext *mpctx, metadata_t type)
505 char *meta = NULL;
506 sh_audio_t * const sh_audio = mpctx->sh_audio;
507 sh_video_t * const sh_video = mpctx->sh_video;
509 if (!is_valid_metadata_type(mpctx, type))
510 return NULL;
512 switch (type)
514 case META_NAME:
516 return strdup (mp_basename2 (mpctx->filename));
519 case META_VIDEO_CODEC:
521 if (sh_video->format == 0x10000001)
522 meta = strdup ("mpeg1");
523 else if (sh_video->format == 0x10000002)
524 meta = strdup ("mpeg2");
525 else if (sh_video->format == 0x10000004)
526 meta = strdup ("mpeg4");
527 else if (sh_video->format == 0x10000005)
528 meta = strdup ("h264");
529 else if (sh_video->format >= 0x20202020)
531 meta = malloc (8);
532 sprintf (meta, "%.4s", (char *) &sh_video->format);
534 else
536 meta = malloc (8);
537 sprintf (meta, "0x%08X", sh_video->format);
539 return meta;
542 case META_VIDEO_BITRATE:
544 meta = malloc (16);
545 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
546 return meta;
549 case META_VIDEO_RESOLUTION:
551 meta = malloc (16);
552 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
553 return meta;
556 case META_AUDIO_CODEC:
558 if (sh_audio->codec && sh_audio->codec->name)
559 meta = strdup (sh_audio->codec->name);
560 return meta;
563 case META_AUDIO_BITRATE:
565 meta = malloc (16);
566 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
567 return meta;
570 case META_AUDIO_SAMPLES:
572 meta = malloc (16);
573 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
574 return meta;
577 /* check for valid demuxer */
578 case META_INFO_TITLE:
579 return get_demuxer_info(mpctx, "Title");
581 case META_INFO_ARTIST:
582 return get_demuxer_info(mpctx, "Artist");
584 case META_INFO_ALBUM:
585 return get_demuxer_info(mpctx, "Album");
587 case META_INFO_YEAR:
588 return get_demuxer_info(mpctx, "Year");
590 case META_INFO_COMMENT:
591 return get_demuxer_info(mpctx, "Comment");
593 case META_INFO_TRACK:
594 return get_demuxer_info(mpctx, "Track");
596 case META_INFO_GENRE:
597 return get_demuxer_info(mpctx, "Genre");
599 default:
600 break;
603 return meta;
606 static void print_file_properties(const MPContext *mpctx, const char *filename)
608 double start_pts = MP_NOPTS_VALUE;
609 double video_start_pts = MP_NOPTS_VALUE;
610 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
611 filename_recode(filename));
612 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
613 if (mpctx->sh_video) {
614 /* Assume FOURCC if all bytes >= 0x20 (' ') */
615 if (mpctx->sh_video->format >= 0x20202020)
616 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
617 else
618 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
619 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
620 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
621 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
622 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
623 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
624 video_start_pts = ds_get_next_pts(mpctx->d_video);
626 if (mpctx->sh_audio) {
627 /* Assume FOURCC if all bytes >= 0x20 (' ') */
628 if (mpctx->sh_audio->format >= 0x20202020)
629 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
630 else
631 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
632 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
633 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
634 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
635 start_pts = ds_get_next_pts(mpctx->d_audio);
637 if (video_start_pts != MP_NOPTS_VALUE) {
638 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
639 (mpctx->sh_video && video_start_pts < start_pts))
640 start_pts = video_start_pts;
642 if (start_pts != MP_NOPTS_VALUE)
643 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
644 else
645 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
646 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", mpctx->timeline ?
647 mpctx->timeline[mpctx->num_timeline_parts].start :
648 demuxer_get_time_length(mpctx->demuxer));
649 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
650 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
651 if (mpctx->demuxer) {
652 if (mpctx->demuxer->num_chapters == 0)
653 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
654 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
658 /// step size of mixer changes
659 int volstep = 3;
661 #ifdef CONFIG_DVDNAV
662 static void mp_dvdnav_context_free(MPContext *ctx){
663 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
664 ctx->nav_smpi = NULL;
665 if (ctx->nav_buffer) free(ctx->nav_buffer);
666 ctx->nav_buffer = NULL;
667 ctx->nav_start = NULL;
668 ctx->nav_in_size = 0;
670 #endif
672 void uninit_player(struct MPContext *mpctx, unsigned int mask){
673 mask &= mpctx->initialized_flags;
675 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
677 if(mask&INITIALIZED_ACODEC){
678 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
679 current_module="uninit_acodec";
680 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
681 mpctx->sh_audio=NULL;
682 mpctx->mixer.afilter = NULL;
685 if(mask&INITIALIZED_VCODEC){
686 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
687 current_module="uninit_vcodec";
688 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
689 mpctx->sh_video=NULL;
690 #ifdef CONFIG_MENU
691 vf_menu=NULL;
692 #endif
695 if(mask&INITIALIZED_DEMUXER){
696 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
697 current_module="free_demuxer";
698 if (mpctx->num_sources) {
699 mpctx->demuxer = mpctx->sources[0].demuxer;
700 for (int i = 1; i < mpctx->num_sources; i++) {
701 free_stream(mpctx->sources[i].stream);
702 free_demuxer(mpctx->sources[i].demuxer);
705 talloc_free(mpctx->sources);
706 mpctx->sources = NULL;
707 mpctx->num_sources = 0;
708 talloc_free(mpctx->timeline);
709 mpctx->timeline = NULL;
710 mpctx->num_timeline_parts = 0;
711 talloc_free(mpctx->chapters);
712 mpctx->chapters = NULL;
713 mpctx->num_chapters = 0;
714 mpctx->video_offset = 0;
715 if(mpctx->demuxer){
716 mpctx->stream=mpctx->demuxer->stream;
717 free_demuxer(mpctx->demuxer);
719 mpctx->demuxer=NULL;
722 // kill the cache process:
723 if(mask&INITIALIZED_STREAM){
724 mpctx->initialized_flags&=~INITIALIZED_STREAM;
725 current_module="uninit_stream";
726 if(mpctx->stream) free_stream(mpctx->stream);
727 mpctx->stream=NULL;
730 if(mask&INITIALIZED_VO){
731 mpctx->initialized_flags&=~INITIALIZED_VO;
732 current_module="uninit_vo";
733 vo_destroy(mpctx->video_out);
734 mpctx->video_out=NULL;
735 #ifdef CONFIG_DVDNAV
736 mp_dvdnav_context_free(mpctx);
737 #endif
740 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
741 if(mask&INITIALIZED_GETCH2){
742 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
743 current_module="uninit_getch2";
744 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
745 // restore terminal:
746 getch2_disable();
749 if(mask&INITIALIZED_VOBSUB){
750 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
751 current_module="uninit_vobsub";
752 if(vo_vobsub) vobsub_close(vo_vobsub);
753 vo_vobsub=NULL;
756 if (mask&INITIALIZED_SPUDEC){
757 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
758 current_module="uninit_spudec";
759 spudec_free(vo_spudec);
760 vo_spudec=NULL;
763 if(mask&INITIALIZED_AO){
764 mpctx->initialized_flags&=~INITIALIZED_AO;
765 current_module="uninit_ao";
766 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
767 if (mpctx->audio_out)
768 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
769 mpctx->audio_out=NULL;
772 current_module=NULL;
775 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
777 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
778 uninit_player(mpctx, INITIALIZED_ALL);
779 #if defined(__MINGW32__) || defined(__CYGWIN__)
780 timeEndPeriod(1);
781 #endif
782 #ifdef CONFIG_X11
783 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
784 #endif
786 current_module="uninit_input";
787 mp_input_uninit(mpctx->input);
788 #ifdef CONFIG_MENU
789 if (use_menu)
790 menu_uninit();
791 #endif
793 #ifdef CONFIG_FREETYPE
794 current_module="uninit_font";
795 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
796 free_font_desc(mpctx->osd->sub_font);
797 free_font_desc(vo_font);
798 vo_font = NULL;
799 done_freetype();
800 #endif
801 osd_free(mpctx->osd);
803 #ifdef CONFIG_ASS
804 ass_library_done(ass_library);
805 ass_library = NULL;
806 #endif
808 current_module="exit_player";
810 // free mplayer config
811 if(mpctx->mconfig)
812 m_config_free(mpctx->mconfig);
813 mpctx->mconfig = NULL;
815 if(mpctx->playtree_iter)
816 play_tree_iter_free(mpctx->playtree_iter);
817 mpctx->playtree_iter = NULL;
818 if(mpctx->playtree)
819 play_tree_free(mpctx->playtree, 1);
820 mpctx->playtree = NULL;
822 talloc_free(mpctx->key_fifo);
824 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
825 edl_records = NULL;
826 switch(how) {
827 case EXIT_QUIT:
828 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
829 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
830 break;
831 case EXIT_EOF:
832 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
833 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
834 break;
835 case EXIT_ERROR:
836 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
837 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
838 break;
839 default:
840 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
842 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
844 exit(rc);
847 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
849 exit_player_with_rc(mpctx, how, 1);
852 #ifndef __MINGW32__
853 static void child_sighandler(int x){
854 pid_t pid;
855 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
857 #endif
859 #ifdef CONFIG_CRASH_DEBUG
860 static char *prog_path;
861 static int crash_debug = 0;
862 #endif
864 static void exit_sighandler(int x){
865 static int sig_count=0;
866 #ifdef CONFIG_CRASH_DEBUG
867 if (!crash_debug || x != SIGTRAP)
868 #endif
869 ++sig_count;
870 if(sig_count==5)
872 /* We're crashing bad and can't uninit cleanly :(
873 * by popular request, we make one last (dirty)
874 * effort to restore the user's
875 * terminal. */
876 getch2_disable();
877 exit(1);
879 if(sig_count==6) exit(1);
880 if(sig_count>6){
881 // can't stop :(
882 #ifndef __MINGW32__
883 kill(getpid(),SIGKILL);
884 #endif
886 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
887 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
888 "\nMPlayer interrupted by signal %d in module: %s\n", x,
889 current_module ? current_module : "unknown");
890 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
891 if(sig_count<=1)
892 switch(x){
893 case SIGINT:
894 case SIGPIPE:
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 = 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 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1767 current_module="init_audio_codec";
1768 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1769 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1770 goto init_error;
1772 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1773 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1777 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1778 current_module="af_preinit";
1779 ao_data.samplerate=force_srate;
1780 ao_data.channels=0;
1781 ao_data.format=audio_output_format;
1782 // first init to detect best values
1783 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1784 // input:
1785 mpctx->sh_audio->samplerate,
1786 // output:
1787 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1788 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1789 "pre-init!\n");
1790 exit_player(mpctx, EXIT_ERROR);
1792 current_module="ao2_init";
1793 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1794 0, // plugin flag
1795 ao_data.samplerate,
1796 ao_data.channels,
1797 ao_data.format, 0);
1798 if(!mpctx->audio_out){
1799 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1800 goto init_error;
1802 mpctx->initialized_flags|=INITIALIZED_AO;
1803 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1804 mpctx->audio_out->info->short_name,
1805 ao_data.samplerate, ao_data.channels,
1806 af_fmt2str_short(ao_data.format),
1807 af_fmt2bits(ao_data.format)/8 );
1808 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1809 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1810 if(strlen(mpctx->audio_out->info->comment) > 0)
1811 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1814 // init audio filters:
1815 current_module="af_init";
1816 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1817 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1818 goto init_error;
1820 mpctx->mixer.audio_out = mpctx->audio_out;
1821 mpctx->mixer.volstep = volstep;
1822 return;
1824 init_error:
1825 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1826 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1827 mpctx->d_audio->id = -2;
1831 ///@}
1832 // Command2Property
1835 // Return pts value corresponding to the end point of audio written to the
1836 // ao so far.
1837 static double written_audio_pts(struct MPContext *mpctx)
1839 sh_audio_t *sh_audio = mpctx->sh_audio;
1840 demux_stream_t *d_audio = mpctx->d_audio;
1841 double buffered_output;
1842 // first calculate the end pts of audio that has been output by decoder
1843 double a_pts = sh_audio->pts;
1844 if (a_pts != MP_NOPTS_VALUE)
1845 // Good, decoder supports new way of calculating audio pts.
1846 // sh_audio->pts is the timestamp of the latest input packet with
1847 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1848 // the amount of bytes the decoder has written after that timestamp.
1849 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1850 else {
1851 // Decoder doesn't support new way of calculating pts (or we're
1852 // being called before it has decoded anything with known timestamp).
1853 // Use the old method of audio pts calculation: take the timestamp
1854 // of last packet with known pts the decoder has read data from,
1855 // and add amount of bytes read after the beginning of that packet
1856 // divided by input bps. This will be inaccurate if the input/output
1857 // ratio is not constant for every audio packet or if it is constant
1858 // but not accurately known in sh_audio->i_bps.
1860 a_pts = d_audio->pts;
1861 // ds_tell_pts returns bytes read after last timestamp from
1862 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1863 // it has read but not decoded
1864 if (sh_audio->i_bps)
1865 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1866 (double)sh_audio->i_bps;
1868 // Now a_pts hopefully holds the pts for end of audio from decoder.
1869 // Substract data in buffers between decoder and audio out.
1871 // Decoded but not filtered
1872 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1874 // Data buffered in audio filters, measured in bytes of "missing" output
1875 buffered_output = af_calc_delay(sh_audio->afilter);
1877 // Data that was ready for ao but was buffered because ao didn't fully
1878 // accept everything to internal buffers yet
1879 buffered_output += sh_audio->a_out_buffer_len;
1881 // Filters divide audio length by playback_speed, so multiply by it
1882 // to get the length in original units without speedup or slowdown
1883 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1885 return a_pts + mpctx->video_offset;
1888 // Return pts value corresponding to currently playing audio.
1889 double playing_audio_pts(struct MPContext *mpctx)
1891 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1892 mpctx->audio_out->get_delay();
1895 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1896 struct MPOpts *opts = &mpctx->opts;
1897 // check for frame-drop:
1898 current_module = "check_framedrop";
1899 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1900 static int dropped_frames;
1901 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1902 float d = delay-mpctx->delay;
1903 ++total_frame_cnt;
1904 // we should avoid dropping too many frames in sequence unless we
1905 // are too late. and we allow 100ms A-V delay here:
1906 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1907 && !mpctx->update_video_immediately) {
1908 ++drop_frame_cnt;
1909 ++dropped_frames;
1910 return frame_dropping;
1911 } else
1912 dropped_frames = 0;
1914 return 0;
1918 #ifdef HAVE_RTC
1919 int rtc_fd = -1;
1920 #endif
1922 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1924 #ifdef HAVE_RTC
1925 if (rtc_fd >= 0){
1926 // -------- RTC -----------
1927 current_module="sleep_rtc";
1928 while (time_frame > 0.000) {
1929 unsigned long rtc_ts;
1930 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1931 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1932 time_frame -= get_relative_time(mpctx);
1934 } else
1935 #endif
1937 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1938 // unnecessarily high CPU usage
1939 float margin = softsleep ? 0.011 : 0;
1940 current_module = "sleep_timer";
1941 while (time_frame > margin) {
1942 usec_sleep(1000000 * (time_frame - margin));
1943 time_frame -= get_relative_time(mpctx);
1945 if (softsleep){
1946 current_module = "sleep_soft";
1947 if (time_frame < 0)
1948 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1949 while (time_frame > 0)
1950 time_frame -= get_relative_time(mpctx); // burn the CPU
1953 return time_frame;
1956 static int select_subtitle(MPContext *mpctx)
1958 struct MPOpts *opts = &mpctx->opts;
1959 // find the best sub to use
1960 int id;
1961 int found = 0;
1962 mpctx->global_sub_pos = -1; // no subs by default
1963 if (vobsub_id >= 0) {
1964 // if user asks for a vobsub id, use that first.
1965 id = vobsub_id;
1966 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1969 if (!found && opts->sub_id >= 0) {
1970 // if user asks for a dvd sub id, use that next.
1971 id = opts->sub_id;
1972 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1975 if (!found) {
1976 // if there are text subs to use, use those. (autosubs come last here)
1977 id = 0;
1978 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1981 if (!found && opts->sub_id == -1) {
1982 // finally select subs by language and container hints
1983 if (opts->sub_id == -1 && opts->sub_lang)
1984 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, opts->sub_lang);
1985 if (opts->sub_id == -1)
1986 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
1987 if (opts->sub_id >= 0) {
1988 id = opts->sub_id;
1989 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1992 return found;
1995 #ifdef CONFIG_DVDNAV
1996 #ifndef FF_B_TYPE
1997 #define FF_B_TYPE 3
1998 #endif
1999 /// store decoded video image
2000 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2001 mp_image_t *from_mpi) {
2002 mp_image_t *mpi;
2004 /// Do not store B-frames
2005 if (from_mpi->pict_type == FF_B_TYPE)
2006 return to_mpi;
2008 if (to_mpi &&
2009 to_mpi->w == from_mpi->w &&
2010 to_mpi->h == from_mpi->h &&
2011 to_mpi->imgfmt == from_mpi->imgfmt)
2012 mpi = to_mpi;
2013 else {
2014 if (to_mpi)
2015 free_mp_image(to_mpi);
2016 if (from_mpi->w == 0 || from_mpi->h == 0)
2017 return NULL;
2018 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2021 copy_mpi(mpi,from_mpi);
2022 return mpi;
2025 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2026 struct MPOpts *opts = &ctx->opts;
2027 if (ctx->sh_video) {
2028 /// clear video pts
2029 ctx->d_video->pts = 0.0f;
2030 ctx->sh_video->pts = 0.0f;
2031 ctx->sh_video->i_pts = 0.0f;
2032 ctx->sh_video->last_pts = 0.0f;
2033 ctx->sh_video->num_buffered_pts = 0;
2034 ctx->sh_video->num_frames = 0;
2035 ctx->sh_video->num_frames_decoded = 0;
2036 ctx->sh_video->timer = 0.0f;
2037 ctx->sh_video->stream_delay = 0.0f;
2038 ctx->sh_video->timer = 0;
2039 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2042 if (ctx->sh_audio) {
2043 /// free audio packets and reset
2044 ds_free_packs(ctx->d_audio);
2045 audio_delay -= ctx->sh_audio->stream_delay;
2046 ctx->delay =- audio_delay;
2047 ctx->audio_out->reset();
2048 resync_audio_stream(ctx->sh_audio);
2051 audio_delay = 0.0f;
2052 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2053 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2054 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2055 if (dvdsub_lang_id != opts->sub_id) {
2056 opts->sub_id = dvdsub_lang_id;
2057 select_subtitle(ctx);
2061 /// clear all EOF related flags
2062 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2065 /// Restore last decoded DVDNAV (still frame)
2066 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2067 int *in_size,
2068 unsigned char **start,
2069 mp_image_t *decoded_frame)
2071 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2072 return decoded_frame;
2074 /// a change occured in dvdnav stream
2075 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2076 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2077 mp_dvdnav_context_free(mpctx);
2078 mp_dvdnav_reset_stream(mpctx);
2079 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2080 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2083 if (*in_size < 0) {
2084 float len;
2086 /// Display still frame, if any
2087 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2088 decoded_frame = mpctx->nav_smpi;
2090 /// increment video frame : continue playing after still frame
2091 len = demuxer_get_time_length(mpctx->demuxer);
2092 if (mpctx->sh_video->pts >= len &&
2093 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2094 mp_dvdnav_skip_still(mpctx->stream);
2095 mp_dvdnav_skip_wait(mpctx->stream);
2097 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2099 if (mpctx->nav_buffer) {
2100 *start = mpctx->nav_start;
2101 *in_size = mpctx->nav_in_size;
2102 if (mpctx->nav_start)
2103 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2107 return decoded_frame;
2110 /// Save last decoded DVDNAV (still frame)
2111 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2112 unsigned char *start,
2113 mp_image_t *decoded_frame)
2115 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2116 return;
2118 if (mpctx->nav_buffer)
2119 free(mpctx->nav_buffer);
2121 mpctx->nav_buffer = malloc(in_size);
2122 mpctx->nav_start = start;
2123 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2124 if (mpctx->nav_buffer)
2125 memcpy(mpctx->nav_buffer,start,in_size);
2127 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2128 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2130 #endif /* CONFIG_DVDNAV */
2132 /* Modify video timing to match the audio timeline. There are two main
2133 * reasons this is needed. First, video and audio can start from different
2134 * positions at beginning of file or after a seek (MPlayer starts both
2135 * immediately even if they have different pts). Second, the file can have
2136 * audio timestamps that are inconsistent with the duration of the audio
2137 * packets, for example two consecutive timestamp values differing by
2138 * one second but only a packet with enough samples for half a second
2139 * of playback between them.
2141 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2143 current_module = "av_sync";
2145 if (!mpctx->sh_audio)
2146 return;
2148 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2149 double v_pts = mpctx->sh_video->pts;
2150 double av_delay = a_pts - v_pts;
2151 // Try to sync vo_flip() so it will *finish* at given time
2152 av_delay += mpctx->last_vo_flip_duration;
2153 av_delay -= audio_delay; // This much pts difference is desired
2155 double change = av_delay * 0.1;
2156 double max_change = default_max_pts_correction >= 0 ?
2157 default_max_pts_correction : frame_time * 0.1;
2158 if (change < -max_change)
2159 change = -max_change;
2160 else if (change > max_change)
2161 change = max_change;
2162 mpctx->delay += change;
2163 mpctx->total_avsync_change += change;
2166 static int fill_audio_out_buffers(struct MPContext *mpctx)
2168 struct MPOpts *opts = &mpctx->opts;
2169 unsigned int t;
2170 double tt;
2171 int playsize;
2172 int playflags=0;
2173 int audio_eof=0;
2174 bool format_change = false;
2175 sh_audio_t * const sh_audio = mpctx->sh_audio;
2177 current_module="play_audio";
2179 while (1) {
2180 int sleep_time;
2181 // all the current uses of ao_data.pts seem to be in aos that handle
2182 // sync completely wrong; there should be no need to use ao_data.pts
2183 // in get_space()
2184 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2185 playsize = mpctx->audio_out->get_space();
2186 if (mpctx->sh_video || playsize >= ao_data.outburst)
2187 break;
2189 // handle audio-only case:
2190 // this is where mplayer sleeps during audio-only playback
2191 // to avoid 100% CPU use
2192 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2193 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2194 usec_sleep(sleep_time * 1000);
2197 // Fill buffer if needed:
2198 current_module="decode_audio";
2199 t = GetTimer();
2200 int res = decode_audio(sh_audio, playsize);
2201 if (res < 0) { // EOF, error or format change
2202 if (res == -2)
2203 format_change = true;
2204 else if (mpctx->d_audio->eof) {
2205 audio_eof = 1;
2206 if (sh_audio->a_out_buffer_len == 0)
2207 return 0;
2210 t = GetTimer() - t;
2211 tt = t*0.000001f; audio_time_usage+=tt;
2212 if (playsize > sh_audio->a_out_buffer_len) {
2213 playsize = sh_audio->a_out_buffer_len;
2214 if (audio_eof)
2215 playflags |= AOPLAY_FINAL_CHUNK;
2217 if (!playsize)
2218 return 1;
2220 // play audio:
2221 current_module="play_audio";
2223 // Is this pts value actually useful for the aos that access it?
2224 // They're obviously badly broken in the way they handle av sync;
2225 // would not having access to this make them more broken?
2226 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2227 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2229 if (playsize > 0) {
2230 sh_audio->a_out_buffer_len -= playsize;
2231 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2232 sh_audio->a_out_buffer_len);
2233 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2235 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2236 // Sanity check to avoid hanging in case current ao doesn't output
2237 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2238 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2239 sh_audio->a_out_buffer_len = 0;
2242 /* The format change isn't handled too gracefully. A more precise
2243 * implementation would require draining buffered old-format audio
2244 * while displaying video, then doing the output format switch.
2246 if (format_change) {
2247 uninit_player(mpctx, INITIALIZED_AO);
2248 reinit_audio_chain(mpctx);
2251 return 1;
2254 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2255 float *aq_sleep_time)
2257 struct MPOpts *opts = &mpctx->opts;
2258 int frame_time_remaining = 0;
2259 current_module="calc_sleep_time";
2261 *time_frame -= get_relative_time(mpctx); // reset timer
2263 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2264 float delay = mpctx->audio_out->get_delay();
2265 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2267 if (autosync) {
2269 * Adjust this raw delay value by calculating the expected
2270 * delay for this frame and generating a new value which is
2271 * weighted between the two. The higher autosync is, the
2272 * closer to the delay value gets to that which "-nosound"
2273 * would have used, and the longer it will take for A/V
2274 * sync to settle at the right value (but it eventually will.)
2275 * This settling time is very short for values below 100.
2277 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2278 float difference = delay - predicted;
2279 delay = predicted + difference / (float)autosync;
2282 *time_frame = delay - mpctx->delay / opts->playback_speed;
2283 *time_frame -= mpctx->video_out->flip_queue_offset;
2285 // delay = amount of audio buffered in soundcard/driver
2286 if (delay > 0.25) delay=0.25; else
2287 if (delay < 0.10) delay=0.10;
2289 if (*time_frame > delay*0.6) {
2290 // sleep time too big - may cause audio drops (buffer underrun)
2291 frame_time_remaining = 1;
2292 *time_frame = delay*0.5;
2294 } else {
2295 // If we're lagging more than 200 ms behind the right playback rate,
2296 // don't try to "catch up".
2297 // If benchmark is set always output frames as fast as possible
2298 // without sleeping.
2299 if (*time_frame < -0.2 || benchmark)
2300 *time_frame = 0;
2301 *time_frame -= mpctx->video_out->flip_queue_offset;
2304 *aq_sleep_time += *time_frame;
2307 //============================== SLEEP: ===================================
2309 // flag 256 means: libvo driver does its timing (dvb card)
2310 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2311 *time_frame = timing_sleep(mpctx, *time_frame);
2312 *time_frame += mpctx->video_out->flip_queue_offset;
2313 return frame_time_remaining;
2316 int reinit_video_chain(struct MPContext *mpctx)
2318 struct MPOpts *opts = &mpctx->opts;
2319 sh_video_t * const sh_video = mpctx->sh_video;
2320 double ar=-1.0;
2321 //================== Init VIDEO (codec & libvo) ==========================
2322 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2323 current_module="preinit_libvo";
2325 //shouldn't we set dvideo->id=-2 when we fail?
2326 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2327 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2328 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2329 goto err_out;
2331 mpctx->initialized_flags|=INITIALIZED_VO;
2334 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2335 mpctx->sh_video->stream_aspect = ar;
2336 current_module="init_video_filters";
2338 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2339 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2341 #ifdef CONFIG_MENU
2342 if(use_menu) {
2343 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2344 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2345 if(!vf_menu) {
2346 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2347 use_menu = 0;
2350 if(vf_menu)
2351 sh_video->vfilter = vf_menu;
2352 #endif
2354 #ifdef CONFIG_ASS
2355 if(opts->ass_enabled) {
2356 int i;
2357 int insert = 1;
2358 if (opts->vf_settings)
2359 for (i = 0; opts->vf_settings[i].name; ++i)
2360 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2361 insert = 0;
2362 break;
2364 if (insert) {
2365 extern vf_info_t vf_info_ass;
2366 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2367 char* vf_arg[] = {"auto", "1", NULL};
2368 int retcode = 0;
2369 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2370 sh_video->vfilter,
2371 "ass", vf_arg,
2372 &retcode);
2373 if (vf_ass)
2374 sh_video->vfilter = vf_ass;
2375 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2376 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2377 else
2378 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2381 #endif
2383 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2385 #ifdef CONFIG_ASS
2386 if (opts->ass_enabled)
2387 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2388 #endif
2390 current_module="init_video_codec";
2392 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2393 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2394 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2396 if(!sh_video->initialized){
2397 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2398 goto err_out;
2401 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2403 if (sh_video->codec)
2404 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2406 sh_video->last_pts = MP_NOPTS_VALUE;
2407 sh_video->num_buffered_pts = 0;
2408 sh_video->next_frame_time = 0;
2410 if(auto_quality>0){
2411 // Auto quality option enabled
2412 output_quality=get_video_quality_max(sh_video);
2413 if(auto_quality>output_quality) auto_quality=output_quality;
2414 else output_quality=auto_quality;
2415 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2416 set_video_quality(sh_video,output_quality);
2419 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2421 current_module="init_vo";
2423 return 1;
2425 err_out:
2426 mpctx->sh_video = mpctx->d_video->sh = NULL;
2427 return 0;
2430 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2432 struct sh_video *sh_video = mpctx->sh_video;
2433 double frame_time = 0;
2434 struct vo *video_out = mpctx->video_out;
2435 while (!video_out->frame_loaded) {
2436 current_module = "filter_video";
2437 // In nocorrect-pts mode there is no way to properly time these frames
2438 if (vo_get_buffered_frame(video_out, 0) >= 0)
2439 break;
2440 if (vf_output_queued_frame(sh_video->vfilter))
2441 continue;
2442 unsigned char *packet = NULL;
2443 frame_time = sh_video->next_frame_time;
2444 if (mpctx->update_video_immediately)
2445 frame_time = 0;
2446 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2447 &packet, force_fps);
2448 if (in_size < 0) {
2449 #ifdef CONFIG_DVDNAV
2450 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2451 if (mp_dvdnav_is_eof(mpctx->stream))
2452 return -1;
2453 if (mpctx->d_video)
2454 mpctx->d_video->eof = 0;
2455 if (mpctx->d_audio)
2456 mpctx->d_audio->eof = 0;
2457 mpctx->stream->eof = 0;
2458 } else
2459 #endif
2460 return -1;
2462 if (in_size > max_framesize)
2463 max_framesize = in_size;
2464 sh_video->timer += frame_time;
2465 if (mpctx->sh_audio)
2466 mpctx->delay -= frame_time;
2467 // video_read_frame can change fps (e.g. for ASF video)
2468 vo_fps = sh_video->fps;
2469 int framedrop_type = check_framedrop(mpctx, frame_time);
2470 current_module = "decode video";
2472 void *decoded_frame;
2473 #ifdef CONFIG_DVDNAV
2474 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2475 if (in_size >= 0 && !decoded_frame)
2476 #endif
2477 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2478 sh_video->pts);
2479 #ifdef CONFIG_DVDNAV
2480 // Save last still frame for future display
2481 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2482 #endif
2483 if (decoded_frame) {
2484 current_module = "filter video";
2485 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2486 if (!video_out->config_ok)
2487 break;
2490 return frame_time;
2493 static void determine_frame_pts(struct MPContext *mpctx)
2495 struct sh_video *sh_video = mpctx->sh_video;
2496 struct MPOpts *opts = &mpctx->opts;
2498 if (opts->user_pts_assoc_mode) {
2499 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2500 } else if (sh_video->pts_assoc_mode == 0) {
2501 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2502 sh_video->pts_assoc_mode = 1;
2503 else
2504 sh_video->pts_assoc_mode = 2;
2505 } else {
2506 int probcount1 = sh_video->num_reordered_pts_problems;
2507 int probcount2 = sh_video->num_sorted_pts_problems;
2508 if (sh_video->pts_assoc_mode == 2) {
2509 int tmp = probcount1;
2510 probcount1 = probcount2;
2511 probcount2 = tmp;
2513 if (probcount1 >= probcount2 * 1.5 + 2) {
2514 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2515 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2516 "%d.\n", sh_video->pts_assoc_mode);
2519 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2520 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2523 static double update_video(struct MPContext *mpctx)
2525 struct sh_video *sh_video = mpctx->sh_video;
2526 struct vo *video_out = mpctx->video_out;
2527 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2528 mpctx->osd); // hack for vf_expand
2529 if (!mpctx->opts.correct_pts)
2530 return update_video_nocorrect_pts(mpctx);
2532 double pts;
2534 bool hit_eof = false;
2535 while (!video_out->frame_loaded) {
2536 current_module = "filter_video";
2537 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2538 break;
2539 // XXX Time used in this call is not counted in any performance
2540 // timer now, OSD time is not updated correctly for filter-added frames
2541 if (vf_output_queued_frame(sh_video->vfilter))
2542 continue;
2543 if (hit_eof)
2544 return -1;
2545 unsigned char *packet = NULL;
2546 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2547 if (pts != MP_NOPTS_VALUE)
2548 pts += mpctx->video_offset;
2549 if (in_size < 0) {
2550 // try to extract last frames in case of decoder lag
2551 in_size = 0;
2552 pts = MP_NOPTS_VALUE;
2553 hit_eof = true;
2555 if (in_size > max_framesize)
2556 max_framesize = in_size;
2557 current_module = "decode video";
2558 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2559 void *decoded_frame = decode_video(sh_video, packet, in_size,
2560 framedrop_type, pts);
2561 if (decoded_frame) {
2562 determine_frame_pts(mpctx);
2563 current_module = "filter video";
2564 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2565 if (!video_out->config_ok)
2566 break; // We'd likely hang in this loop otherwise
2570 pts = video_out->next_pts;
2571 if (pts == MP_NOPTS_VALUE) {
2572 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2573 // Try to use decoder pts from before filters
2574 pts = sh_video->pts;
2575 if (pts == MP_NOPTS_VALUE)
2576 pts = sh_video->last_pts;
2578 sh_video->pts = pts;
2579 if (sh_video->last_pts == MP_NOPTS_VALUE)
2580 sh_video->last_pts = sh_video->pts;
2581 else if (sh_video->last_pts > sh_video->pts) {
2582 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2583 sh_video->pts, sh_video->last_pts);
2584 /* If the difference in pts is small treat it as jitter around the
2585 * right value (possibly caused by incorrect timestamp ordering) and
2586 * just show this frame immediately after the last one.
2587 * Treat bigger differences as timestamp resets and start counting
2588 * timing of later frames from the position of this one. */
2589 if (sh_video->last_pts - sh_video->pts > 0.5)
2590 sh_video->last_pts = sh_video->pts;
2591 else
2592 sh_video->pts = sh_video->last_pts;
2594 double frame_time = sh_video->pts - sh_video->last_pts;
2595 sh_video->last_pts = sh_video->pts;
2596 sh_video->timer += frame_time;
2597 if (mpctx->sh_audio)
2598 mpctx->delay -= frame_time;
2599 return frame_time;
2602 void pause_player(struct MPContext *mpctx)
2604 if (mpctx->paused)
2605 return;
2606 mpctx->paused = 1;
2607 mpctx->step_frames = 0;
2608 mpctx->time_frame -= get_relative_time(mpctx);
2610 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2611 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2613 if (mpctx->audio_out && mpctx->sh_audio)
2614 mpctx->audio_out->pause(); // pause audio, keep data if possible
2617 void unpause_player(struct MPContext *mpctx)
2619 if (!mpctx->paused)
2620 return;
2621 mpctx->paused = 0;
2623 if (mpctx->audio_out && mpctx->sh_audio)
2624 mpctx->audio_out->resume(); // resume audio
2625 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2626 && !mpctx->step_frames)
2627 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2628 (void)get_relative_time(mpctx); // ignore time that passed during pause
2631 void add_step_frame(struct MPContext *mpctx)
2633 mpctx->step_frames++;
2634 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2635 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2636 unpause_player(mpctx);
2639 static void pause_loop(struct MPContext *mpctx)
2641 mp_cmd_t* cmd;
2642 if (!quiet) {
2643 // Small hack to display the pause message on the OSD line.
2644 // The pause string is: "\n == PAUSE == \r" so we need to
2645 // take the first and the last char out
2646 if (term_osd && !mpctx->sh_video) {
2647 char msg[128] = _("\n ===== PAUSE =====\r");
2648 int mlen = strlen(msg);
2649 msg[mlen-1] = '\0';
2650 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2651 update_osd_msg(mpctx);
2652 } else
2653 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2654 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2657 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2658 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2659 if (cmd) {
2660 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2661 run_command(mpctx, cmd);
2662 mp_cmd_free(cmd);
2663 continue;
2665 if (mpctx->sh_video && mpctx->video_out)
2666 vo_check_events(mpctx->video_out);
2667 #ifdef CONFIG_MENU
2668 if (vf_menu)
2669 vf_menu_pause_update(vf_menu);
2670 #endif
2671 usec_sleep(20000);
2672 update_osd_msg(mpctx);
2673 int hack = vo_osd_changed(0);
2674 vo_osd_changed(hack);
2675 if (hack)
2676 break;
2681 // Find the right mute status and record position for new file position
2682 static void edl_seek_reset(MPContext *mpctx)
2684 mpctx->edl_muted = 0;
2685 next_edl_record = edl_records;
2687 while (next_edl_record) {
2688 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2689 break;
2691 if (next_edl_record->action == EDL_MUTE)
2692 mpctx->edl_muted = !mpctx->edl_muted;
2693 next_edl_record = next_edl_record->next;
2695 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2696 mixer_mute(&mpctx->mixer);
2700 // Execute EDL command for the current position if one exists
2701 static void edl_update(MPContext *mpctx)
2703 if (!next_edl_record)
2704 return;
2706 if (!mpctx->sh_video) {
2707 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2708 free_edl(edl_records);
2709 next_edl_record = NULL;
2710 edl_records = NULL;
2711 return;
2714 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2715 if (next_edl_record->action == EDL_SKIP) {
2716 mpctx->osd_function = OSD_FFW;
2717 mpctx->abs_seek_pos = 0;
2718 mpctx->rel_seek_secs = next_edl_record->length_sec;
2719 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2720 "[%f], length [%f]\n", next_edl_record->start_sec,
2721 next_edl_record->stop_sec, next_edl_record->length_sec);
2723 else if (next_edl_record->action == EDL_MUTE) {
2724 mpctx->edl_muted = !mpctx->edl_muted;
2725 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2726 mixer_mute(&mpctx->mixer);
2727 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2728 next_edl_record->start_sec );
2730 next_edl_record = next_edl_record->next;
2734 static void reinit_decoders(struct MPContext *mpctx)
2736 reinit_video_chain(mpctx);
2737 reinit_audio_chain(mpctx);
2738 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2741 static void seek_reset(struct MPContext *mpctx)
2743 if (mpctx->sh_video) {
2744 current_module = "seek_video_reset";
2745 resync_video_stream(mpctx->sh_video);
2746 mpctx->sh_video->timer = 0;
2747 vo_seek_reset(mpctx->video_out);
2748 mpctx->sh_video->timer = 0;
2749 mpctx->sh_video->num_buffered_pts = 0;
2750 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2751 mpctx->delay = 0;
2752 mpctx->time_frame = 0;
2753 mpctx->update_video_immediately = true;
2754 // Not all demuxers set d_video->pts during seek, so this value
2755 // (which is used by at least vobsub and edl code below) may
2756 // be completely wrong (probably 0).
2757 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2758 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2759 mpctx->sh_video->pts, mpctx->video_offset,
2760 mpctx->d_sub, 1);
2761 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2764 if (mpctx->sh_audio) {
2765 current_module = "seek_audio_reset";
2766 resync_audio_stream(mpctx->sh_audio);
2767 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2768 mpctx->sh_audio->a_buffer_len = 0;
2769 mpctx->sh_audio->a_out_buffer_len = 0;
2770 if (!mpctx->sh_video)
2771 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2772 mpctx->video_offset, mpctx->d_sub, 1);
2775 if (vo_vobsub && mpctx->sh_video) {
2776 current_module = "seek_vobsub_reset";
2777 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2780 edl_seek_reset(mpctx);
2782 mpctx->total_avsync_change = 0;
2783 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2784 drop_frame_cnt = 0;
2786 current_module = NULL;
2789 static bool timeline_set_part(struct MPContext *mpctx, int i)
2791 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2792 struct timeline_part *n = mpctx->timeline + i;
2793 mpctx->timeline_part = i;
2794 mpctx->video_offset = n->start - n->source_start;
2795 if (n->source == p->source)
2796 return false;
2797 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2798 mpctx->demuxer = n->source->demuxer;
2799 mpctx->d_video = mpctx->demuxer->video;
2800 mpctx->d_audio = mpctx->demuxer->audio;
2801 mpctx->d_sub = mpctx->demuxer->sub;
2802 mpctx->sh_video = mpctx->d_video->sh;
2803 mpctx->sh_audio = mpctx->d_audio->sh;
2804 return true;
2807 // Given pts, switch playback to the corresponding part.
2808 // Return offset within that part.
2809 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2810 bool *need_reset)
2812 if (pts < 0)
2813 pts = 0;
2814 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2815 struct timeline_part *p = mpctx->timeline + i;
2816 if (pts < (p+1)->start) {
2817 *need_reset = timeline_set_part(mpctx, i);
2818 return pts - p->start + p->source_start;
2821 return -1;
2825 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2826 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2827 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2828 static int seek(MPContext *mpctx, double amount, int style)
2830 current_module = "seek";
2831 if (mpctx->stop_play == AT_END_OF_FILE)
2832 mpctx->stop_play = KEEP_PLAYING;
2833 if (style & SEEK_FACTOR
2834 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2835 || amount < 0)
2836 mpctx->last_chapter_seek = -1;
2837 if (mpctx->timeline && style & SEEK_FACTOR) {
2838 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2839 style &= ~SEEK_FACTOR;
2841 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2842 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2843 style |= SEEK_ABSOLUTE;
2844 if (amount > 0)
2845 style |= SEEK_FORWARD;
2846 else
2847 style |= SEEK_BACKWARD;
2848 amount += mpctx->sh_video->pts;
2851 /* At least the liba52 decoder wants to read from the input stream
2852 * during initialization, so reinit must be done after the demux_seek()
2853 * call that clears possible stream EOF. */
2854 bool need_reset = false;
2855 if (mpctx->timeline) {
2856 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2857 if (amount == -1) {
2858 mpctx->stop_play = AT_END_OF_FILE;
2859 // Clear audio from current position
2860 if (mpctx->sh_audio) {
2861 mpctx->audio_out->reset();
2862 mpctx->sh_audio->a_buffer_len = 0;
2863 mpctx->sh_audio->a_out_buffer_len = 0;
2865 return -1;
2868 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2869 if (need_reset)
2870 reinit_decoders(mpctx);
2871 if (seekresult == 0)
2872 return -1;
2874 seek_reset(mpctx);
2875 return 0;
2878 // -2 is no chapters, -1 is before first chapter
2879 int get_current_chapter(struct MPContext *mpctx)
2881 if (!mpctx->chapters || !mpctx->sh_video)
2882 return FFMAX(mpctx->last_chapter_seek,
2883 demuxer_get_current_chapter(mpctx->demuxer));
2885 int i;
2886 double current_pts = mpctx->sh_video->pts;
2887 for (i = 1; i < mpctx->num_chapters; i++)
2888 if (current_pts < mpctx->chapters[i].start)
2889 break;
2890 return FFMAX(mpctx->last_chapter_seek, i - 1);
2893 // currently returns a string allocated with malloc, not talloc
2894 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2896 if (!mpctx->chapters || !mpctx->sh_video)
2897 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2898 return strdup(mpctx->chapters[chapter].name);
2901 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2902 char **chapter_name)
2904 mpctx->last_chapter_seek = -1;
2905 if (!mpctx->chapters || !mpctx->sh_video) {
2906 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2907 chapter_name);
2908 if (res >= 0) {
2909 if (*seek_pts == -1)
2910 seek_reset(mpctx);
2911 else {
2912 mpctx->last_chapter_seek = res;
2913 mpctx->last_chapter_pts = *seek_pts;
2916 return res;
2919 if (chapter >= mpctx->num_chapters)
2920 return -1;
2921 if (chapter < 0)
2922 chapter = 0;
2923 *seek_pts = mpctx->chapters[chapter].start;
2924 mpctx->last_chapter_seek = chapter;
2925 mpctx->last_chapter_pts = *seek_pts;
2926 if (chapter_name)
2927 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2928 return chapter;
2931 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2932 struct content_source *sources,
2933 int num_sources,
2934 unsigned char uid_map[][16])
2936 int num_filenames = 0;
2937 char **filenames = NULL;
2938 if (num_sources > 1) {
2939 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2940 "other sources.\n");
2941 if (mpctx->stream->type != STREAMTYPE_FILE) {
2942 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2943 "normal disk file. Will not search for related files.\n");
2944 } else {
2945 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2946 "same directory to find referenced sources.\n");
2947 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2948 &num_filenames);
2952 int num_left = num_sources - 1;
2953 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2954 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2955 filename_recode(filenames[i]));
2956 int format;
2957 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2958 if (!s)
2959 continue;
2960 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2961 mpctx->opts.audio_id,
2962 mpctx->opts.video_id,
2963 mpctx->opts.sub_id, filenames[i]);
2964 if (!d) {
2965 free_stream(s);
2966 continue;
2968 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2969 for (int i = 1; i < num_sources; i++) {
2970 if (sources[i].demuxer)
2971 continue;
2972 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2973 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2974 i, filename_recode(d->filename));
2975 sources[i].stream = s;
2976 sources[i].demuxer = d;
2977 num_left--;
2978 goto match;
2982 free_demuxer(d);
2983 free_stream(s);
2984 continue;
2985 match:
2988 talloc_free(filenames);
2989 if (num_left) {
2990 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2991 "There will be parts MISSING from the video!\n");
2992 for (int i = 1, j = 1; i < num_sources; i++)
2993 if (sources[i].demuxer) {
2994 sources[j] = sources[i];
2995 memcpy(uid_map[j], uid_map[i], 16);
2996 j++;
2999 return num_sources - num_left;
3002 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3004 if (!mpctx->opts.ordered_chapters) {
3005 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3006 "you have disabled support for them. Ignoring.\n");
3007 return;
3010 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3011 "edit timeline.\n");
3013 struct demuxer *demuxer = mpctx->demuxer;
3014 struct matroska_data *m = &demuxer->matroska_data;
3016 // +1 because sources/uid_map[0] is original file even if all chapters
3017 // actually use other sources and need separate entries
3018 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3019 m->num_ordered_chapters+1);
3020 sources[0].stream = mpctx->stream;
3021 sources[0].demuxer = mpctx->demuxer;
3022 unsigned char uid_map[m->num_ordered_chapters+1][16];
3023 int num_sources = 1;
3024 memcpy(uid_map[0], m->segment_uid, 16);
3026 for (int i = 0; i < m->num_ordered_chapters; i++) {
3027 struct matroska_chapter *c = m->ordered_chapters + i;
3028 if (!c->has_segment_uid)
3029 memcpy(c->segment_uid, m->segment_uid, 16);
3031 for (int j = 0; j < num_sources; j++)
3032 if (!memcmp(c->segment_uid, uid_map[j], 16))
3033 goto found1;
3034 memcpy(uid_map[num_sources], c->segment_uid, 16);
3035 sources[num_sources] = (struct content_source){};
3036 num_sources++;
3037 found1:
3041 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3042 uid_map);
3045 // +1 for terminating chapter with start time marking end of last real one
3046 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3047 m->num_ordered_chapters + 1);
3048 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3049 m->num_ordered_chapters);
3050 uint64_t starttime = 0;
3051 uint64_t missing_time = 0;
3052 int part_count = 0;
3053 int num_chapters = 0;
3054 uint64_t prev_part_offset = 0;
3055 for (int i = 0; i < m->num_ordered_chapters; i++) {
3056 struct matroska_chapter *c = m->ordered_chapters + i;
3058 int j;
3059 for (j = 0; j < num_sources; j++) {
3060 if (!memcmp(c->segment_uid, uid_map[j], 16))
3061 goto found2;
3063 missing_time += c->end - c->start;
3064 continue;
3065 found2:;
3066 chapters[num_chapters].start = starttime / 1000.;
3067 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3068 /* Only add a separate part if the time or file actually changes.
3069 * Matroska files have chapter divisions that are redundant from
3070 * timeline point of view because the same chapter structure is used
3071 * both to specify the timeline and for normal chapter information.
3072 * Removing a missing inserted external chapter can also cause this. */
3073 if (part_count == 0 || c->start != starttime + prev_part_offset
3074 || sources + j != timeline[part_count - 1].source) {
3075 timeline[part_count].source = sources + j;
3076 timeline[part_count].start = chapters[num_chapters].start;
3077 timeline[part_count].source_start = c->start / 1000.;
3078 prev_part_offset = c->start - starttime;
3079 part_count++;
3081 starttime += c->end - c->start;
3082 num_chapters++;
3084 timeline[part_count].start = starttime / 1000.;
3086 if (!part_count) {
3087 // None of the parts come from the file itself???
3088 talloc_free(sources);
3089 talloc_free(timeline);
3090 talloc_free(chapters);
3091 return;
3094 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3095 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3096 timeline[part_count].start);
3097 if (missing_time)
3098 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3099 "from the timeline!\n", missing_time / 1000.);
3100 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3101 for (int i = 0; i < num_sources; i++)
3102 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3103 filename_recode(sources[i].demuxer->filename));
3104 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3105 "source_start, source):\n");
3106 for (int i = 0; i < part_count; i++) {
3107 struct timeline_part *p = timeline + i;
3108 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3109 p->source_start, p->source - sources);
3111 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3112 mpctx->sources = sources;
3113 mpctx->num_sources = num_sources;
3114 mpctx->timeline = timeline;
3115 mpctx->num_timeline_parts = part_count;
3116 mpctx->num_chapters = num_chapters;
3117 mpctx->chapters = chapters;
3119 mpctx->timeline_part = 0;
3120 mpctx->demuxer = timeline[0].source->demuxer;
3124 static int read_keys(void *ctx, int fd)
3126 getch2(ctx);
3127 return mplayer_get_key(ctx, 0);
3131 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3132 * file for some tools to link against. */
3133 #ifndef DISABLE_MAIN
3134 int main(int argc,char* argv[]){
3137 char * mem_ptr;
3139 // movie info:
3141 /* Flag indicating whether MPlayer should exit without playing anything. */
3142 int opt_exit = 0;
3144 //float a_frame=0; // Audio
3146 int i;
3148 struct MPContext *mpctx = &(struct MPContext){
3149 .osd_function = OSD_PLAY,
3150 .begin_skip = MP_NOPTS_VALUE,
3151 .play_tree_step = 1,
3152 .global_sub_pos = -1,
3153 .set_of_sub_pos = -1,
3154 .file_format = DEMUXER_TYPE_UNKNOWN,
3155 .last_dvb_step = 1,
3158 InitTimer();
3159 srand(GetTimerMS());
3161 mp_msg_init();
3162 set_av_log_callback();
3164 #ifdef CONFIG_X11
3165 mpctx->x11_state = vo_x11_init_state();
3166 #endif
3167 struct MPOpts *opts = &mpctx->opts;
3168 set_default_mplayer_options(opts);
3169 // Create the config context and register the options
3170 mpctx->mconfig = m_config_new(opts, cfg_include);
3171 m_config_register_options(mpctx->mconfig,mplayer_opts);
3172 m_config_register_options(mpctx->mconfig, common_opts);
3173 mp_input_register_options(mpctx->mconfig);
3175 // Preparse the command line
3176 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3178 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3179 set_path_env();
3180 #endif
3182 #ifdef CONFIG_TV
3183 stream_tv_defaults.immediate = 1;
3184 #endif
3186 parse_cfgfiles(mpctx, mpctx->mconfig);
3188 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3189 if(mpctx->playtree == NULL)
3190 opt_exit = 1;
3191 else {
3192 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3193 if(mpctx->playtree) {
3194 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3195 if(mpctx->playtree_iter) {
3196 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3197 play_tree_iter_free(mpctx->playtree_iter);
3198 mpctx->playtree_iter = NULL;
3200 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3204 mpctx->key_fifo = mp_fifo_create(opts);
3206 print_version("MPlayer");
3208 #if defined(__MINGW32__) || defined(__CYGWIN__)
3210 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3211 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3212 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3213 if (kernel32) {
3214 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3215 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3217 if (setDEP) setDEP(3);
3218 if (setDllDir) setDllDir("");
3220 // stop Windows from showing all kinds of annoying error dialogs
3221 SetErrorMode(0x8003);
3222 // request 1ms timer resolution
3223 timeBeginPeriod(1);
3224 #endif
3226 #ifdef CONFIG_PRIORITY
3227 set_priority();
3228 #endif
3230 if (codec_path)
3231 set_codec_path(codec_path);
3233 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3234 list_video_out();
3235 opt_exit = 1;
3238 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3239 list_audio_out();
3240 opt_exit = 1;
3243 /* Check codecs.conf. */
3244 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3245 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3246 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3247 if(!parse_codec_cfg(NULL)){
3248 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3250 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3253 free( mem_ptr ); // release the buffer created by get_path()
3256 #if 0
3257 if(video_codec_list){
3258 int i;
3259 video_codec=video_codec_list[0];
3260 for(i=0;video_codec_list[i];i++)
3261 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
3263 #endif
3264 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3265 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3266 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3267 list_codecs(1);
3268 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3269 opt_exit = 1;
3271 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3272 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3273 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3274 list_codecs(0);
3275 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3276 opt_exit = 1;
3278 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3279 vfm_help();
3280 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3281 opt_exit = 1;
3283 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3284 afm_help();
3285 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3286 opt_exit = 1;
3288 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3289 af_help();
3290 printf("\n");
3291 opt_exit = 1;
3293 #ifdef CONFIG_X11
3294 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3295 fstype_help();
3296 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3297 opt_exit = 1;
3299 #endif
3300 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3301 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3302 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3303 demuxer_help();
3304 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3305 opt_exit = 1;
3307 if(list_properties) {
3308 property_print_help();
3309 opt_exit = 1;
3312 if(opt_exit)
3313 exit_player(mpctx, EXIT_NONE);
3315 if(!mpctx->filename && !player_idle_mode){
3316 // no file/vcd/dvd -> show HELP:
3317 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3318 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3321 /* Display what configure line was used */
3322 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3324 // Many users forget to include command line in bugreports...
3325 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3326 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3327 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3328 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3331 //------ load global data first ------
3333 mpctx->osd = osd_create();
3335 // check font
3336 #ifdef CONFIG_FREETYPE
3337 init_freetype();
3338 #endif
3339 #ifdef CONFIG_FONTCONFIG
3340 if(font_fontconfig <= 0)
3342 #endif
3343 #ifdef CONFIG_BITMAP_FONT
3344 if(font_name){
3345 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3346 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3347 filename_recode(font_name));
3348 } else {
3349 // try default:
3350 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3351 free(mem_ptr); // release the buffer created by get_path()
3352 if(!vo_font)
3353 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3355 if (sub_font_name)
3356 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3357 else
3358 mpctx->osd->sub_font = vo_font;
3359 #endif
3360 #ifdef CONFIG_FONTCONFIG
3362 #endif
3364 #ifdef CONFIG_ASS
3365 ass_library = ass_init();
3366 #endif
3368 #ifdef HAVE_RTC
3369 if(!nortc)
3371 // seteuid(0); /* Can't hurt to try to get root here */
3372 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3373 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3374 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3375 else {
3376 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3378 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3379 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3380 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3381 close (rtc_fd);
3382 rtc_fd = -1;
3383 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3384 /* variable only by the root */
3385 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3386 close (rtc_fd);
3387 rtc_fd = -1;
3388 } else
3389 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3392 if(rtc_fd<0)
3393 #endif /* HAVE_RTC */
3394 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3395 softsleep?"software":timer_name);
3397 #ifdef HAVE_TERMCAP
3398 load_termcap(NULL); // load key-codes
3399 #endif
3401 // ========== Init keyboard FIFO (connection to libvo) ============
3403 // Init input system
3404 current_module = "init_input";
3405 mpctx->input = mp_input_init(&opts->input);
3406 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3407 if(slave_mode)
3408 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3409 else if(!noconsolecontrols)
3410 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3411 // Set the libstream interrupt callback
3412 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3414 #ifdef CONFIG_MENU
3415 if(use_menu) {
3416 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3417 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3418 else {
3419 menu_cfg = get_path("menu.conf");
3420 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3421 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3422 else {
3423 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3424 MPLAYER_CONFDIR "/menu.conf"))
3425 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3426 else {
3427 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3428 use_menu = 0;
3433 #endif
3435 current_module = NULL;
3437 /// Catch signals
3438 #ifndef __MINGW32__
3439 signal(SIGCHLD,child_sighandler);
3440 #endif
3442 #ifdef CONFIG_CRASH_DEBUG
3443 prog_path = argv[0];
3444 #endif
3445 //========= Catch terminate signals: ================
3446 // terminate requests:
3447 signal(SIGTERM,exit_sighandler); // kill
3448 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3450 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3452 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3453 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3454 #ifdef CONFIG_SIGHANDLER
3455 // fatal errors:
3456 signal(SIGBUS,exit_sighandler); // bus error
3457 signal(SIGSEGV,exit_sighandler); // segfault
3458 signal(SIGILL,exit_sighandler); // illegal instruction
3459 signal(SIGFPE,exit_sighandler); // floating point exc.
3460 signal(SIGABRT,exit_sighandler); // abort()
3461 #ifdef CONFIG_CRASH_DEBUG
3462 if (crash_debug)
3463 signal(SIGTRAP,exit_sighandler);
3464 #endif
3465 #endif
3467 // ******************* Now, let's see the per-file stuff ********************
3469 play_next_file:
3471 // init global sub numbers
3472 mpctx->global_sub_size = 0;
3473 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3475 if (mpctx->filename) {
3476 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3477 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3478 load_per_file_config (mpctx->mconfig, mpctx->filename);
3481 if (opts->video_driver_list)
3482 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3483 if (opts->audio_driver_list)
3484 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3486 // We must enable getch2 here to be able to interrupt network connection
3487 // or cache filling
3488 if(!noconsolecontrols && !slave_mode){
3489 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3490 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3491 else
3492 getch2_enable(); // prepare stdin for hotkeys...
3493 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3494 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3497 // =================== GUI idle loop (STOP state) ===========================
3498 while (player_idle_mode && !mpctx->filename) {
3499 play_tree_t * entry = NULL;
3500 mp_cmd_t * cmd;
3501 if (mpctx->video_out && mpctx->video_out->config_ok)
3502 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3503 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3504 if (mpctx->video_out)
3505 vo_check_events(mpctx->video_out);
3506 usec_sleep(20000);
3508 switch (cmd->id) {
3509 case MP_CMD_LOADFILE:
3510 // prepare a tree entry with the new filename
3511 entry = play_tree_new();
3512 play_tree_add_file(entry, cmd->args[0].v.s);
3513 // The entry is added to the main playtree after the switch().
3514 break;
3515 case MP_CMD_LOADLIST:
3516 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3517 break;
3518 case MP_CMD_QUIT:
3519 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3520 break;
3521 case MP_CMD_VO_FULLSCREEN:
3522 case MP_CMD_GET_PROPERTY:
3523 case MP_CMD_SET_PROPERTY:
3524 case MP_CMD_STEP_PROPERTY:
3525 run_command(mpctx, cmd);
3526 break;
3529 mp_cmd_free(cmd);
3531 if (entry) { // user entered a command that gave a valid entry
3532 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3533 play_tree_free_list(mpctx->playtree->child, 1);
3534 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3536 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3538 play_tree_set_child(mpctx->playtree, entry);
3540 /* Make iterator start at the top the of tree. */
3541 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3542 if (!mpctx->playtree_iter) continue;
3544 // find the first real item in the tree
3545 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3546 // no items!
3547 play_tree_iter_free(mpctx->playtree_iter);
3548 mpctx->playtree_iter = NULL;
3549 continue; // wait for next command
3551 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3554 //---------------------------------------------------------------------------
3556 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3557 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3559 if (mpctx->filename) {
3560 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3561 filename_recode(mpctx->filename));
3562 if(use_filename_title && vo_wintitle == NULL)
3563 vo_wintitle = strdup(mp_basename2(mpctx->filename));
3566 if (edl_filename) {
3567 if (edl_records) free_edl(edl_records);
3568 next_edl_record = edl_records = edl_parse_file();
3570 if (edl_output_filename) {
3571 if (edl_fd) fclose(edl_fd);
3572 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3574 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3575 filename_recode(edl_output_filename));
3579 //==================== Open VOB-Sub ============================
3581 current_module="vobsub";
3582 if (vobsub_name){
3583 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3584 if(vo_vobsub==NULL)
3585 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3586 filename_recode(vobsub_name));
3587 } else if (sub_auto && mpctx->filename){
3588 /* try to autodetect vobsub from movie filename ::atmos */
3589 char *buf = strdup(mpctx->filename), *psub;
3590 char *pdot = strrchr(buf, '.');
3591 char *pslash = strrchr(buf, '/');
3592 #if defined(__MINGW32__) || defined(__CYGWIN__)
3593 if (!pslash) pslash = strrchr(buf, '\\');
3594 #endif
3595 if (pdot && (!pslash || pdot > pslash))
3596 *pdot = '\0';
3597 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3598 /* try from ~/.mplayer/sub */
3599 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3600 char *bname;
3601 int l;
3602 bname = strrchr(buf,'/');
3603 #if defined(__MINGW32__) || defined(__CYGWIN__)
3604 if(!bname) bname = strrchr(buf,'\\');
3605 #endif
3606 if(bname) bname++;
3607 else bname = buf;
3608 l = strlen(psub) + strlen(bname) + 1;
3609 psub = realloc(psub,l);
3610 strcat(psub,bname);
3611 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3612 free(psub);
3614 free(buf);
3616 if(vo_vobsub){
3617 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3618 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3619 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3621 // setup global sub numbering
3622 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3625 //============ Open & Sync STREAM --- fork cache2 ====================
3627 mpctx->stream=NULL;
3628 mpctx->demuxer=NULL;
3629 if (mpctx->d_audio) {
3630 //free_demuxer_stream(mpctx->d_audio);
3631 mpctx->d_audio=NULL;
3633 if (mpctx->d_video) {
3634 //free_demuxer_stream(d_video);
3635 mpctx->d_video=NULL;
3637 mpctx->sh_audio=NULL;
3638 mpctx->sh_video=NULL;
3640 current_module="open_stream";
3641 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3642 if(!mpctx->stream) { // error...
3643 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3644 goto goto_next_file;
3646 mpctx->initialized_flags|=INITIALIZED_STREAM;
3648 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3649 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3650 "playlist support will not be used automatically.\n"
3651 "MPlayer's playlist code is unsafe and should only be used with "
3652 "trusted sources.\nPlayback will probably fail.\n\n");
3653 #if 0
3654 play_tree_t* entry;
3655 // Handle playlist
3656 current_module="handle_playlist";
3657 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3658 filename_recode(mpctx->filename));
3659 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3660 mpctx->eof=playtree_add_playlist(mpctx, entry);
3661 goto goto_next_file;
3662 #endif
3664 mpctx->stream->start_pos+=seek_to_byte;
3666 if(stream_dump_type==5){
3667 unsigned char buf[4096];
3668 int len;
3669 FILE *f;
3670 current_module="dumpstream";
3671 stream_reset(mpctx->stream);
3672 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3673 f=fopen(stream_dump_name,"wb");
3674 if(!f){
3675 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3676 exit_player(mpctx, EXIT_ERROR);
3678 if (opts->chapterrange[0] > 1) {
3679 int chapter = opts->chapterrange[0] - 1;
3680 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3682 while(!mpctx->stream->eof && !async_quit_request){
3683 len=stream_read(mpctx->stream,buf,4096);
3684 if(len>0) {
3685 if(fwrite(buf,len,1,f) != 1) {
3686 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3687 exit_player(mpctx, EXIT_ERROR);
3690 if (opts->chapterrange[1] > 0) {
3691 int chapter = -1;
3692 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3693 &chapter) == STREAM_OK
3694 && chapter + 1 > opts->chapterrange[1])
3695 break;
3698 if(fclose(f)) {
3699 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3700 exit_player(mpctx, EXIT_ERROR);
3702 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3703 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3706 #ifdef CONFIG_DVDREAD
3707 if(mpctx->stream->type==STREAMTYPE_DVD){
3708 current_module="dvd lang->id";
3709 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3710 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3711 // setup global sub numbering
3712 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3713 current_module=NULL;
3715 #endif
3717 #ifdef CONFIG_DVDNAV
3718 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3719 current_module="dvdnav lang->id";
3720 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3721 dvdsub_lang_id = -3;
3722 if(opts->sub_lang && opts->sub_id==-1)
3723 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3724 // setup global sub numbering
3725 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3726 current_module=NULL;
3728 #endif
3730 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3731 goto_enable_cache:
3732 if(stream_cache_size>0){
3733 int res;
3734 current_module="enable_cache";
3735 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3736 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3737 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3738 if(res == 0)
3739 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3742 //============ Open DEMUXERS --- DETECT file type =======================
3743 current_module="demux_open";
3745 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3747 // HACK to get MOV Reference Files working
3749 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3751 unsigned char* playlist_entry;
3752 play_tree_t *list = NULL, *entry = NULL;
3754 current_module="handle_demux_playlist";
3755 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3757 char *temp, *bname;
3759 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3760 filename_recode(playlist_entry));
3762 bname=mp_basename(playlist_entry);
3763 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3764 continue;
3766 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3767 continue;
3769 entry = play_tree_new();
3771 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3773 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3774 if (temp)
3776 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3777 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3778 strcat(temp, playlist_entry);
3779 if (!strcmp(temp, mpctx->filename)) {
3780 free(temp);
3781 continue;
3783 play_tree_add_file(entry,temp);
3784 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3785 free(temp);
3788 else
3789 play_tree_add_file(entry,playlist_entry);
3791 if(!list)
3792 list = entry;
3793 else
3794 play_tree_append_entry(list,entry);
3796 free_demuxer(mpctx->demuxer);
3797 mpctx->demuxer = NULL;
3799 if (list)
3801 entry = play_tree_new();
3802 play_tree_set_child(entry,list);
3803 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3804 goto goto_next_file;
3808 if(!mpctx->demuxer)
3809 goto goto_next_file;
3811 if (mpctx->demuxer->matroska_data.ordered_chapters)
3812 build_ordered_chapter_timeline(mpctx);
3814 if (!mpctx->sources) {
3815 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3816 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3817 .demuxer = mpctx->demuxer};
3818 mpctx->num_sources = 1;
3821 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3823 #ifdef CONFIG_ASS
3824 if (opts->ass_enabled && ass_library) {
3825 for (int j = 0; j < mpctx->num_sources; j++) {
3826 struct demuxer *d = mpctx->sources[j].demuxer;
3827 for (int i = 0; i < d->num_attachments; i++) {
3828 struct demux_attachment *att = d->attachments + i;
3829 if (use_embedded_fonts && attachment_is_font(att))
3830 ass_add_font(ass_library, att->name, att->data, att->data_size);
3834 #endif
3836 current_module="demux_open2";
3838 //file_format=demuxer->file_format;
3840 mpctx->d_audio=mpctx->demuxer->audio;
3841 mpctx->d_video=mpctx->demuxer->video;
3842 mpctx->d_sub=mpctx->demuxer->sub;
3844 if (ts_prog) {
3845 int tmp = ts_prog;
3846 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3848 // select audio stream
3849 if (mpctx->num_sources)
3850 for (int i = 0; i < mpctx->num_sources; i++)
3851 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3852 opts->audio_lang);
3853 else
3854 select_audio(mpctx->demuxer, opts->audio_id, opts->audio_lang);
3856 // DUMP STREAMS:
3857 if((stream_dump_type)&&(stream_dump_type<4)){
3858 FILE *f;
3859 demux_stream_t *ds=NULL;
3860 current_module="dump";
3861 // select stream to dump
3862 switch(stream_dump_type){
3863 case 1: ds=mpctx->d_audio;break;
3864 case 2: ds=mpctx->d_video;break;
3865 case 3: ds=mpctx->d_sub;break;
3867 if(!ds){
3868 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3869 exit_player(mpctx, EXIT_ERROR);
3871 // disable other streams:
3872 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3873 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3874 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3875 // let's dump it!
3876 f=fopen(stream_dump_name,"wb");
3877 if(!f){
3878 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3879 exit_player(mpctx, EXIT_ERROR);
3881 while(!ds->eof){
3882 unsigned char* start;
3883 int in_size=ds_get_packet(ds,&start);
3884 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3885 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3886 if(in_size>0) fwrite(start,in_size,1,f);
3887 if (opts->chapterrange[1] > 0) {
3888 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3889 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3890 break;
3893 fclose(f);
3894 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3895 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3898 mpctx->sh_audio=mpctx->d_audio->sh;
3899 mpctx->sh_video=mpctx->d_video->sh;
3901 if(mpctx->sh_video){
3903 current_module="video_read_properties";
3904 if(!video_read_properties(mpctx->sh_video)) {
3905 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3906 mpctx->sh_video=mpctx->d_video->sh=NULL;
3907 } else {
3908 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3909 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3910 mpctx->sh_video->fps,mpctx->sh_video->frametime
3913 /* need to set fps here for output encoders to pick it up in their init */
3914 if(force_fps){
3915 mpctx->sh_video->fps=force_fps;
3916 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3918 vo_fps = mpctx->sh_video->fps;
3920 if(!mpctx->sh_video->fps && !force_fps){
3921 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3922 mpctx->opts.correct_pts = 1;
3928 if(!mpctx->sh_video && !mpctx->sh_audio){
3929 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3930 #ifdef CONFIG_DVBIN
3931 if(mpctx->stream->type == STREAMTYPE_DVB)
3933 int dir;
3934 int v = mpctx->last_dvb_step;
3935 if(v > 0)
3936 dir = DVB_CHANNEL_HIGHER;
3937 else
3938 dir = DVB_CHANNEL_LOWER;
3940 if(dvb_step_channel(mpctx->stream, dir)) {
3941 mpctx->stop_play = PT_NEXT_ENTRY;
3942 mpctx->dvbin_reopen = 1;
3945 #endif
3946 goto goto_next_file; // exit_player(_("Fatal error"));
3949 /* display clip info */
3950 demux_info_print(mpctx->demuxer);
3952 //================== Read SUBTITLES (DVD & TEXT) ==========================
3953 if(vo_spudec==NULL &&
3954 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3955 init_vo_spudec(mpctx);
3958 // after reading video params we should load subtitles because
3959 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3960 // check .sub
3961 current_module="read_subtitles_file";
3962 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3963 if(sub_name){
3964 for (i = 0; sub_name[i] != NULL; ++i)
3965 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3967 if(sub_auto) { // auto load sub file ...
3968 char *psub = get_path( "sub/" );
3969 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3970 int i = 0;
3971 free(psub); // release the buffer created by get_path() above
3972 while (tmp[i]) {
3973 add_subtitles(mpctx, tmp[i], sub_fps, 1);
3974 free(tmp[i++]);
3976 free(tmp);
3978 if (mpctx->set_of_sub_size > 0)
3979 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
3981 if (select_subtitle(mpctx)) {
3982 if(subdata)
3983 switch (stream_dump_type) {
3984 case 3: list_sub_file(subdata); break;
3985 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3986 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3987 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3988 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3989 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3993 print_file_properties(mpctx, mpctx->filename);
3995 if(!mpctx->sh_video) goto main; // audio-only
3997 if(!reinit_video_chain(mpctx)) {
3998 if(!mpctx->sh_video){
3999 if(!mpctx->sh_audio) goto goto_next_file;
4000 goto main; // exit_player(_("Fatal error"));
4004 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4005 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4007 #ifdef CONFIG_FREETYPE
4008 force_load_font = 1;
4009 #endif
4011 //================== MAIN: ==========================
4012 main:
4013 current_module="main";
4015 if(playing_msg) {
4016 char* msg = property_expand_string(mpctx, playing_msg);
4017 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4018 free(msg);
4022 // Disable the term OSD in verbose mode
4023 if(verbose) term_osd = 0;
4026 //int frame_corr_num=0; //
4027 //float v_frame=0; // Video
4028 //float num_frames=0; // number of frames played
4030 int frame_time_remaining=0; // flag
4031 int blit_frame=0;
4033 // Make sure old OSD does not stay around,
4034 // e.g. with -fixed-vo and same-resolution files
4035 clear_osd_msgs();
4036 update_osd_msg(mpctx);
4038 //================ SETUP AUDIO ==========================
4040 if(mpctx->sh_audio){
4041 reinit_audio_chain(mpctx);
4042 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4043 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4046 current_module="av_init";
4048 if(mpctx->sh_video){
4049 mpctx->sh_video->timer=0;
4050 if (! ignore_start)
4051 audio_delay += mpctx->sh_video->stream_delay;
4053 if(mpctx->sh_audio){
4054 if (start_volume >= 0)
4055 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4056 if (! ignore_start)
4057 audio_delay -= mpctx->sh_audio->stream_delay;
4058 mpctx->delay=-audio_delay;
4061 if(!mpctx->sh_audio){
4062 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4063 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4064 ds_free_packs(mpctx->d_audio); // free buffered chunks
4065 //mpctx->d_audio->id=-2; // do not read audio chunks
4066 //uninit_player(mpctx, INITIALIZED_AO); // close device
4068 if(!mpctx->sh_video){
4069 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4070 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4071 ds_free_packs(mpctx->d_video);
4072 mpctx->d_video->id=-2;
4073 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4076 if (!mpctx->sh_video && !mpctx->sh_audio)
4077 goto goto_next_file;
4079 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4080 if(force_fps && mpctx->sh_video){
4081 vo_fps = mpctx->sh_video->fps=force_fps;
4082 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4083 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4086 mp_input_set_section(mpctx->input, NULL);
4087 //TODO: add desired (stream-based) sections here
4088 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4089 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4091 //==================== START PLAYING =======================
4093 if(opts->loop_times>1) opts->loop_times--; else
4094 if(opts->loop_times==1) opts->loop_times = -1;
4096 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4098 total_time_usage_start=GetTimer();
4099 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4100 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4101 play_n_frames=play_n_frames_mf;
4103 if(play_n_frames==0){
4104 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4107 // If there's a timeline force an absolute seek to initialize state
4108 if (seek_to_sec || mpctx->timeline) {
4109 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4110 end_at.pos += seek_to_sec;
4112 if (opts->chapterrange[0] > 0) {
4113 double pts;
4114 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4115 && pts > -1.0)
4116 seek(mpctx, pts, SEEK_ABSOLUTE);
4119 if (end_at.type == END_AT_SIZE) {
4120 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4121 end_at.type = END_AT_NONE;
4124 #ifdef CONFIG_DVDNAV
4125 mp_dvdnav_context_free(mpctx);
4126 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4127 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4128 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4130 #endif
4132 get_relative_time(mpctx); // reset current delta
4133 mpctx->time_frame = 0;
4134 mpctx->drop_message_shown = 0;
4135 mpctx->update_video_immediately = true;
4136 mpctx->total_avsync_change = 0;
4137 mpctx->last_chapter_seek = -1;
4138 // Make sure VO knows current pause state
4139 if (mpctx->sh_video)
4140 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4141 NULL);
4143 while(!mpctx->stop_play){
4144 float aq_sleep_time=0;
4146 if (opts->chapterrange[1] > 0) {
4147 int cur_chapter = get_current_chapter(mpctx);
4148 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4149 goto goto_next_file;
4152 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4153 mpctx->sh_audio = mpctx->d_audio->sh;
4154 mpctx->sh_audio->ds = mpctx->d_audio;
4155 reinit_audio_chain(mpctx);
4158 /*========================== PLAY AUDIO ============================*/
4160 if (mpctx->sh_audio && !mpctx->paused)
4161 if (!fill_audio_out_buffers(mpctx))
4162 // at eof, all audio at least written to ao
4163 if (!mpctx->sh_video)
4164 mpctx->stop_play = AT_END_OF_FILE;
4167 if(!mpctx->sh_video) {
4168 // handle audio-only case:
4169 double a_pos=0;
4170 // sh_audio can be NULL due to video stream switching
4171 // TODO: handle this better
4172 if (mpctx->sh_audio)
4173 a_pos = playing_audio_pts(mpctx);
4175 print_status(mpctx, a_pos, false);
4177 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4178 mpctx->stop_play = PT_NEXT_ENTRY;
4179 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4180 mpctx->d_sub, 0);
4181 update_osd_msg(mpctx);
4183 } else {
4185 /*========================== PLAY VIDEO ============================*/
4187 vo_pts=mpctx->sh_video->timer*90000.0;
4188 vo_fps=mpctx->sh_video->fps;
4190 blit_frame = mpctx->video_out->frame_loaded;
4191 if (!blit_frame) {
4192 double frame_time = update_video(mpctx);
4193 blit_frame = mpctx->video_out->frame_loaded;
4194 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4195 if (mpctx->sh_video->vf_initialized < 0) {
4196 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4197 mpctx->stop_play = PT_NEXT_ENTRY;
4198 goto goto_next_file;
4200 if (blit_frame) {
4201 struct sh_video *sh_video = mpctx->sh_video;
4202 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4203 mpctx->video_offset, mpctx->d_sub, 0);
4204 update_teletext(sh_video, mpctx->demuxer, 0);
4205 update_osd_msg(mpctx);
4206 struct vf_instance *vf = mpctx->sh_video->vfilter;
4207 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4208 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4209 vo_osd_changed(0);
4211 if (frame_time < 0)
4212 mpctx->stop_play = AT_END_OF_FILE;
4213 else {
4214 if (mpctx->update_video_immediately) {
4215 // Show this frame immediately, rest normally
4216 mpctx->update_video_immediately = false;
4217 } else {
4218 mpctx->time_frame += frame_time / opts->playback_speed;
4219 adjust_sync(mpctx, frame_time);
4223 if (mpctx->timeline) {
4224 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4225 if (mpctx->sh_video->pts >= next->start
4226 || mpctx->stop_play == AT_END_OF_FILE
4227 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4228 seek(mpctx, next->start, SEEK_ABSOLUTE);
4229 continue;
4233 // ==========================================================================
4235 // current_module="draw_osd";
4236 // if(vo_config_count) mpctx->video_out->draw_osd();
4238 current_module="vo_check_events";
4239 vo_check_events(mpctx->video_out);
4241 #ifdef CONFIG_X11
4242 if (stop_xscreensaver) {
4243 current_module = "stop_xscreensaver";
4244 xscreensaver_heartbeat(mpctx->x11_state);
4246 #endif
4247 if (heartbeat_cmd) {
4248 static unsigned last_heartbeat;
4249 unsigned now = GetTimerMS();
4250 if (now - last_heartbeat > 30000) {
4251 last_heartbeat = now;
4252 system(heartbeat_cmd);
4256 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4258 //====================== FLIP PAGE (VIDEO BLT): =========================
4260 current_module="flip_page";
4261 if (!frame_time_remaining && blit_frame) {
4262 unsigned int t2=GetTimer();
4263 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4264 int duration = -1;
4265 double pts2 = mpctx->video_out->next_pts2;
4266 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4267 // expected A/V sync correction is ignored
4268 double diff = (pts2 - mpctx->sh_video->pts);
4269 diff /= opts->playback_speed;
4270 if (mpctx->time_frame < 0)
4271 diff += mpctx->time_frame;
4272 if (diff < 0)
4273 diff = 0;
4274 if (diff > 10)
4275 diff = 10;
4276 duration = diff * 1e6;
4278 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4280 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4281 vout_time_usage += mpctx->last_vo_flip_duration;
4282 if (mpctx->video_out->driver->flip_page_timed) {
4283 // No need to adjust sync based on flip speed
4284 mpctx->last_vo_flip_duration = 0;
4285 // For print_status - VO call finishing early is OK for sync
4286 mpctx->time_frame -= get_relative_time(mpctx);
4288 print_status(mpctx, MP_NOPTS_VALUE, true);
4290 else
4291 print_status(mpctx, MP_NOPTS_VALUE, false);
4293 //============================ Auto QUALITY ============================
4295 /*Output quality adjustments:*/
4296 if(auto_quality>0){
4297 current_module="autoq";
4298 // float total=0.000001f * (GetTimer()-aq_total_time);
4299 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4300 if(output_quality<auto_quality && aq_sleep_time>0)
4301 ++output_quality;
4302 else
4303 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4304 if(output_quality>1 && aq_sleep_time<0)
4305 --output_quality;
4306 else
4307 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4308 output_quality=0;
4309 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4310 set_video_quality(mpctx->sh_video,output_quality);
4313 if (!frame_time_remaining && blit_frame) {
4314 if (play_n_frames >= 0) {
4315 --play_n_frames;
4316 if (play_n_frames <= 0)
4317 mpctx->stop_play = PT_NEXT_ENTRY;
4319 if (mpctx->step_frames > 0) {
4320 mpctx->step_frames--;
4321 if (mpctx->step_frames == 0)
4322 pause_player(mpctx);
4327 // FIXME: add size based support for -endpos
4328 if (end_at.type == END_AT_TIME &&
4329 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4330 mpctx->stop_play = PT_NEXT_ENTRY;
4332 } // end if(mpctx->sh_video)
4334 #ifdef CONFIG_DVDNAV
4335 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4336 nav_highlight_t hl;
4337 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4338 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4339 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4340 vo_osd_changed (OSDTYPE_DVDNAV);
4341 } else {
4342 osd_set_nav_box(0, 0, 0, 0);
4343 vo_osd_changed(OSDTYPE_DVDNAV);
4344 vo_osd_changed(OSDTYPE_SPU);
4347 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4348 double ar = -1.0;
4349 if (mpctx->sh_video &&
4350 stream_control (mpctx->demuxer->stream,
4351 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4352 != STREAM_UNSUPPORTED)
4353 mpctx->sh_video->stream_aspect = ar;
4356 #endif
4358 //================= Keyboard events, SEEKing ====================
4360 current_module="key_events";
4363 while (1) {
4364 mp_cmd_t* cmd;
4365 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4366 run_command(mpctx, cmd);
4367 mp_cmd_free(cmd);
4368 if (mpctx->stop_play)
4369 break;
4370 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4371 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4372 /* Allow seek commands to be combined, but execute the real seek
4373 * before processing other commands */
4374 if (!cmd || cmd->id != MP_CMD_SEEK)
4375 break;
4378 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4379 || mpctx->abs_seek_pos)
4380 break;
4381 if (mpctx->sh_video) {
4382 update_osd_msg(mpctx);
4383 int hack = vo_osd_changed(0);
4384 vo_osd_changed(hack);
4385 if (hack) {
4386 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4387 add_step_frame(mpctx);
4388 break;
4390 else
4391 vo_osd_changed(0);
4394 pause_loop(mpctx);
4398 // handle -sstep
4399 if (step_sec > 0 && !mpctx->paused) {
4400 mpctx->osd_function=OSD_FFW;
4401 mpctx->rel_seek_secs+=step_sec;
4404 edl_update(mpctx);
4406 /* Looping. */
4407 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4408 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4410 if(opts->loop_times>1) opts->loop_times--; else
4411 if(opts->loop_times==1) opts->loop_times=-1;
4412 play_n_frames=play_n_frames_mf;
4413 mpctx->stop_play=0;
4414 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4417 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4418 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4420 mpctx->rel_seek_secs=0;
4421 mpctx->abs_seek_pos=0;
4424 } // while(!mpctx->stop_play)
4426 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4428 #ifdef CONFIG_DVBIN
4429 if(mpctx->dvbin_reopen)
4431 mpctx->stop_play = 0;
4432 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4433 cache_uninit(mpctx->stream);
4434 mpctx->dvbin_reopen = 0;
4435 goto goto_enable_cache;
4437 #endif
4440 goto_next_file: // don't jump here after ao/vo/getch initialization!
4442 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4444 if(benchmark){
4445 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4446 double total_time_usage;
4447 total_time_usage_start=GetTimer()-total_time_usage_start;
4448 total_time_usage = (float)total_time_usage_start*0.000001;
4449 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4450 video_time_usage,vout_time_usage,audio_time_usage,
4451 total_time_usage-tot,total_time_usage);
4452 if(total_time_usage>0.0)
4453 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4454 100.0*video_time_usage/total_time_usage,
4455 100.0*vout_time_usage/total_time_usage,
4456 100.0*audio_time_usage/total_time_usage,
4457 100.0*(total_time_usage-tot)/total_time_usage,
4458 100.0);
4459 if(total_frame_cnt && frame_dropping)
4460 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4461 total_frame_cnt-drop_frame_cnt,
4462 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4463 drop_frame_cnt,
4464 100*drop_frame_cnt/total_frame_cnt,
4465 total_frame_cnt,
4466 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4469 // time to uninit all, except global stuff:
4470 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4472 if(mpctx->set_of_sub_size > 0) {
4473 current_module="sub_free";
4474 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4475 sub_free(mpctx->set_of_subtitles[i]);
4476 #ifdef CONFIG_ASS
4477 if(mpctx->set_of_ass_tracks[i])
4478 ass_free_track( mpctx->set_of_ass_tracks[i] );
4479 #endif
4481 mpctx->set_of_sub_size = 0;
4483 vo_sub_last = vo_sub=NULL;
4484 subdata=NULL;
4485 #ifdef CONFIG_ASS
4486 ass_track = NULL;
4487 if(ass_library)
4488 ass_clear_fonts(ass_library);
4489 #endif
4491 if (!mpctx->stop_play) // In case some goto jumped here...
4492 mpctx->stop_play = PT_NEXT_ENTRY;
4494 int playtree_direction = 1;
4496 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4497 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4498 play_tree_iter_free(mpctx->playtree_iter);
4499 mpctx->playtree_iter = NULL;
4501 mpctx->play_tree_step = 1;
4502 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4503 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4504 if(mpctx->playtree_iter) {
4505 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4506 play_tree_iter_free(mpctx->playtree_iter);
4507 mpctx->playtree_iter = NULL;
4510 } else if (mpctx->stop_play == PT_STOP) {
4511 play_tree_iter_free(mpctx->playtree_iter);
4512 mpctx->playtree_iter = NULL;
4513 } else { // NEXT PREV SRC
4514 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4517 while(mpctx->playtree_iter != NULL) {
4518 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4519 if(mpctx->filename == NULL) {
4520 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4521 play_tree_iter_free(mpctx->playtree_iter);
4522 mpctx->playtree_iter = NULL;
4524 } else
4525 break;
4528 if(mpctx->playtree_iter != NULL || player_idle_mode){
4529 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4530 mpctx->stop_play = 0;
4531 goto play_next_file;
4535 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4537 return 1;
4539 #endif /* DISABLE_MAIN */