cosmetics: mplayer.c: Remove obsolete declarations
[mplayer/greg.git] / mplayer.c
blob36537964aabe2f30acc88a0afa095e8a0c983268
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 /// \file
20 /// \ingroup Properties Command2Property OSDMsgStack
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdbool.h>
25 #include "config.h"
26 #include "talloc.h"
28 #if defined(__MINGW32__) || defined(__CYGWIN__)
29 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
30 #include <windows.h>
31 #endif
32 #include <string.h>
33 #include <unistd.h>
35 // #include <sys/mman.h>
36 #include <sys/types.h>
37 #ifndef __MINGW32__
38 #include <sys/ioctl.h>
39 #include <sys/wait.h>
40 #else
41 #define SIGHUP 1 /* hangup */
42 #define SIGQUIT 3 /* quit */
43 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
44 #define SIGBUS 10 /* bus error */
45 #define SIGPIPE 13 /* broken pipe */
46 #endif
48 #include <sys/time.h>
49 #include <sys/stat.h>
51 #include <signal.h>
52 #include <time.h>
53 #include <fcntl.h>
54 #include <limits.h>
56 #include <errno.h>
58 #include "mp_msg.h"
59 #include "av_log.h"
62 #include "m_option.h"
63 #include "m_config.h"
64 #include "mplayer.h"
65 #include "access_mpcontext.h"
66 #include "m_property.h"
68 #include "cfg-mplayer-def.h"
70 #include "libavutil/avstring.h"
72 #include "subreader.h"
74 #include "mp_osd.h"
75 #include "libvo/video_out.h"
77 #include "libvo/font_load.h"
78 #include "libvo/sub.h"
80 #ifdef CONFIG_X11
81 #include "libvo/x11_common.h"
82 #endif
84 #include "libao2/audio_out.h"
86 #include "codec-cfg.h"
88 #include "edl.h"
90 #include "spudec.h"
91 #include "vobsub.h"
93 #include "osdep/getch2.h"
94 #include "osdep/timer.h"
95 #include "osdep/findfiles.h"
97 #include "input/input.h"
99 const int under_mencoder = 0;
100 int slave_mode=0;
101 int player_idle_mode=0;
102 int quiet=0;
103 int enable_mouse_movements=0;
104 float start_volume = -1;
106 #include "osdep/priority.h"
108 char *heartbeat_cmd;
110 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
112 #ifdef HAVE_RTC
113 #ifdef __linux__
114 #include <linux/rtc.h>
115 #else
116 #include <rtc.h>
117 #define RTC_IRQP_SET RTCIO_IRQP_SET
118 #define RTC_PIE_ON RTCIO_PIE_ON
119 #endif /* __linux__ */
120 #endif /* HAVE_RTC */
122 #include "stream/tv.h"
123 #include "stream/stream_radio.h"
124 #ifdef CONFIG_DVBIN
125 #include "stream/dvbin.h"
126 #endif
127 #include "stream/cache2.h"
129 //**************************************************************************//
130 // Playtree
131 //**************************************************************************//
132 #include "playtree.h"
133 #include "playtreeparser.h"
135 //**************************************************************************//
136 // Config
137 //**************************************************************************//
138 #include "parser-cfg.h"
139 #include "parser-mpcmd.h"
141 //**************************************************************************//
142 // Config file
143 //**************************************************************************//
145 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
147 #include "path.h"
149 //**************************************************************************//
150 //**************************************************************************//
151 // Input media streaming & demultiplexer:
152 //**************************************************************************//
154 static int max_framesize=0;
156 #include "stream/stream.h"
157 #include "libmpdemux/demuxer.h"
158 #include "libmpdemux/stheader.h"
160 #ifdef CONFIG_DVDREAD
161 #include "stream/stream_dvd.h"
162 #endif
163 #include "stream/stream_dvdnav.h"
165 #include "libmpcodecs/dec_audio.h"
166 #include "libmpcodecs/dec_video.h"
167 #include "libmpcodecs/mp_image.h"
168 #include "libmpcodecs/vf.h"
169 #include "libmpcodecs/vd.h"
171 #include "mixer.h"
173 #include "mp_core.h"
174 #include "options.h"
175 #include "defaultopts.h"
177 static const char help_text[]=_(
178 "Usage: mplayer [options] [url|path/]filename\n"
179 "\n"
180 "Basic options: (complete list in the man page)\n"
181 " -vo <drv> select video output driver ('-vo help' for a list)\n"
182 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
183 #ifdef CONFIG_VCD
184 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
185 #endif
186 #ifdef CONFIG_DVDREAD
187 " dvd://<titleno> play DVD title from device instead of plain file\n"
188 #endif
189 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
190 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
191 " -nosound do not play sound\n"
192 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
193 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
194 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
195 " -playlist <file> specify playlist file\n"
196 " -vid x -aid y select video (x) and audio (y) stream to play\n"
197 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
198 " -pp <quality> enable postprocessing filter (details in the man page)\n"
199 " -framedrop enable frame dropping (for slow machines)\n"
200 "\n"
201 "Basic keys: (complete list in the man page, also check input.conf)\n"
202 " <- or -> seek backward/forward 10 seconds\n"
203 " down or up seek backward/forward 1 minute\n"
204 " pgdown or pgup seek backward/forward 10 minutes\n"
205 " < or > step backward/forward in playlist\n"
206 " p or SPACE pause movie (press any key to continue)\n"
207 " q or ESC stop playing and quit program\n"
208 " + or - adjust audio delay by +/- 0.1 second\n"
209 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
210 " * or / increase or decrease PCM volume\n"
211 " x or z adjust subtitle delay by +/- 0.1 second\n"
212 " r or t adjust subtitle position up/down, also see -vf expand\n"
213 "\n"
214 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
215 "\n");
218 #define Exit_SIGILL_RTCpuSel _(\
219 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
220 " It may be a bug in our new runtime CPU-detection code...\n"\
221 " Please read DOCS/HTML/en/bugreports.html.\n")
223 #define Exit_SIGILL _(\
224 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
225 " It usually happens when you run it on a CPU different than the one it was\n"\
226 " compiled/optimized for.\n"\
227 " Verify this!\n")
229 #define Exit_SIGSEGV_SIGFPE _(\
230 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
231 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
232 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
234 #define Exit_SIGCRASH _(\
235 "- MPlayer crashed. This shouldn't happen.\n"\
236 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
237 " gcc version. If you think it's MPlayer's fault, please read\n"\
238 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
239 " won't help unless you provide this information when reporting a possible bug.\n")
241 #define SystemTooSlow _("\n\n"\
242 " ************************************************\n"\
243 " **** Your system is too SLOW to play this! ****\n"\
244 " ************************************************\n\n"\
245 "Possible reasons, problems, workarounds:\n"\
246 "- Most common: broken/buggy _audio_ driver\n"\
247 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
248 " - Experiment with different values for -autosync, 30 is a good start.\n"\
249 "- Slow video output\n"\
250 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
251 "- Slow CPU\n"\
252 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
253 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
254 "- Broken file\n"\
255 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
256 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
257 " - Try -cache 8192.\n"\
258 "- Are you using -cache to play a non-interleaved AVI file?\n"\
259 " - Try -nocache.\n"\
260 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
261 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
264 //**************************************************************************//
265 //**************************************************************************//
267 // Common FIFO functions, and keyboard/event FIFO code
268 #include "mp_fifo.h"
269 int noconsolecontrols=0;
270 //**************************************************************************//
272 // benchmark:
273 double video_time_usage=0;
274 double vout_time_usage=0;
275 static double audio_time_usage=0;
276 static int total_time_usage_start=0;
277 static int total_frame_cnt=0;
278 static int drop_frame_cnt=0; // total number of dropped frames
279 int benchmark=0;
281 // options:
282 int auto_quality=0;
283 static int output_quality=0;
285 static int list_properties = 0;
287 int term_osd = 1;
288 static char* term_osd_esc = "\x1b[A\r\x1b[K";
289 static char* playing_msg = NULL;
290 // seek:
291 static double seek_to_sec;
292 static off_t seek_to_byte=0;
293 static off_t step_sec=0;
295 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
297 // A/V sync:
298 int autosync=0; // 30 might be a good default value.
300 // codecs:
301 char **audio_codec_list=NULL; // override audio codec
302 char **video_codec_list=NULL; // override video codec
303 char **audio_fm_list=NULL; // override audio codec family
304 char **video_fm_list=NULL; // override video codec family
306 // demuxer:
307 extern char *demuxer_name; // override demuxer
308 extern char *audio_demuxer_name; // override audio demuxer
309 extern char *sub_demuxer_name; // override sub demuxer
311 // this dvdsub_id was selected via slang
312 // use this to allow dvdnav to follow -slang across stream resets,
313 // in particular the subtitle ID for a language changes
314 int dvdsub_lang_id;
315 int vobsub_id=-1;
316 static char* spudec_ifo=NULL;
317 int forced_subs_only=0;
318 int file_filter=1;
320 // cache2:
321 int stream_cache_size=-1;
322 #ifdef CONFIG_STREAM_CACHE
323 float stream_cache_min_percent=20.0;
324 float stream_cache_seek_min_percent=50.0;
325 #else
326 #define cache_fill_status 0
327 #endif
329 // dump:
330 static char *stream_dump_name="stream.dump";
331 int stream_dump_type=0;
333 // A-V sync:
334 static float default_max_pts_correction=-1;//0.01f;
335 float audio_delay=0;
336 static int ignore_start=0;
338 static int softsleep=0;
340 double force_fps=0;
341 static int force_srate=0;
342 static int audio_output_format=-1; // AF_FORMAT_UNKNOWN
343 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
344 static int play_n_frames=-1;
345 static int play_n_frames_mf=-1;
347 // sub:
348 char *font_name=NULL;
349 char *sub_font_name=NULL;
350 extern int font_fontconfig;
351 float font_factor=0.75;
352 char **sub_name=NULL;
353 float sub_delay=0;
354 float sub_fps=0;
355 int sub_auto = 1;
356 char *vobsub_name=NULL;
357 /*DSP!!char *dsp=NULL;*/
358 int subcc_enabled=0;
359 int suboverlap_enabled = 1;
361 #include "ass_mp.h"
363 char* current_module=NULL; // for debugging
366 // ---
368 #ifdef CONFIG_MENU
369 #include "m_struct.h"
370 #include "libmenu/menu.h"
371 static const vf_info_t* const libmenu_vfs[] = {
372 &vf_info_menu,
373 NULL
375 static vf_instance_t* vf_menu = NULL;
376 int use_menu = 0;
377 static char* menu_cfg = NULL;
378 static char* menu_root = "main";
379 #endif
382 #ifdef HAVE_RTC
383 static int nortc = 1;
384 static char* rtc_device;
385 #endif
387 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
388 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
389 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
390 int use_filedir_conf;
391 int use_filename_title;
393 #include "mpcommon.h"
394 #include "command.h"
396 #include "metadata.h"
398 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
400 const void *mpctx_get_video_out(MPContext *mpctx)
402 return mpctx->video_out;
405 const void *mpctx_get_audio_out(MPContext *mpctx)
407 return mpctx->audio_out;
410 void *mpctx_get_demuxer(MPContext *mpctx)
412 return mpctx->demuxer;
415 void *mpctx_get_playtree_iter(MPContext *mpctx)
417 return mpctx->playtree_iter;
420 void *mpctx_get_mixer(MPContext *mpctx)
422 return &mpctx->mixer;
425 int mpctx_get_global_sub_size(MPContext *mpctx)
427 return mpctx->global_sub_size;
430 int mpctx_get_osd_function(MPContext *mpctx)
432 return mpctx->osd_function;
435 static float get_relative_time(struct MPContext *mpctx)
437 unsigned int new_time = GetTimer();
438 unsigned int delta = new_time - mpctx->last_time;
439 mpctx->last_time = new_time;
440 return delta * 0.000001;
443 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
444 switch (type)
446 /* check for valid video stream */
447 case META_VIDEO_CODEC:
448 case META_VIDEO_BITRATE:
449 case META_VIDEO_RESOLUTION:
451 if (!mpctx->sh_video)
452 return 0;
453 break;
456 /* check for valid audio stream */
457 case META_AUDIO_CODEC:
458 case META_AUDIO_BITRATE:
459 case META_AUDIO_SAMPLES:
461 if (!mpctx->sh_audio)
462 return 0;
463 break;
466 /* check for valid demuxer */
467 case META_INFO_TITLE:
468 case META_INFO_ARTIST:
469 case META_INFO_ALBUM:
470 case META_INFO_YEAR:
471 case META_INFO_COMMENT:
472 case META_INFO_TRACK:
473 case META_INFO_GENRE:
475 if (!mpctx->demuxer)
476 return 0;
477 break;
480 default:
481 break;
484 return 1;
487 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
488 char **info = mpctx->demuxer->info;
489 int n;
491 if (!info || !tag)
492 return NULL;
494 for (n = 0; info[2*n] != NULL ; n++)
495 if (!strcasecmp (info[2*n], tag))
496 break;
498 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
501 char *get_metadata(struct MPContext *mpctx, metadata_t type)
503 char *meta = NULL;
504 sh_audio_t * const sh_audio = mpctx->sh_audio;
505 sh_video_t * const sh_video = mpctx->sh_video;
507 if (!is_valid_metadata_type(mpctx, type))
508 return NULL;
510 switch (type)
512 case META_NAME:
514 return strdup (mp_basename2 (mpctx->filename));
517 case META_VIDEO_CODEC:
519 if (sh_video->format == 0x10000001)
520 meta = strdup ("mpeg1");
521 else if (sh_video->format == 0x10000002)
522 meta = strdup ("mpeg2");
523 else if (sh_video->format == 0x10000004)
524 meta = strdup ("mpeg4");
525 else if (sh_video->format == 0x10000005)
526 meta = strdup ("h264");
527 else if (sh_video->format >= 0x20202020)
529 meta = malloc (8);
530 sprintf (meta, "%.4s", (char *) &sh_video->format);
532 else
534 meta = malloc (8);
535 sprintf (meta, "0x%08X", sh_video->format);
537 return meta;
540 case META_VIDEO_BITRATE:
542 meta = malloc (16);
543 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
544 return meta;
547 case META_VIDEO_RESOLUTION:
549 meta = malloc (16);
550 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
551 return meta;
554 case META_AUDIO_CODEC:
556 if (sh_audio->codec && sh_audio->codec->name)
557 meta = strdup (sh_audio->codec->name);
558 return meta;
561 case META_AUDIO_BITRATE:
563 meta = malloc (16);
564 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
565 return meta;
568 case META_AUDIO_SAMPLES:
570 meta = malloc (16);
571 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
572 return meta;
575 /* check for valid demuxer */
576 case META_INFO_TITLE:
577 return get_demuxer_info(mpctx, "Title");
579 case META_INFO_ARTIST:
580 return get_demuxer_info(mpctx, "Artist");
582 case META_INFO_ALBUM:
583 return get_demuxer_info(mpctx, "Album");
585 case META_INFO_YEAR:
586 return get_demuxer_info(mpctx, "Year");
588 case META_INFO_COMMENT:
589 return get_demuxer_info(mpctx, "Comment");
591 case META_INFO_TRACK:
592 return get_demuxer_info(mpctx, "Track");
594 case META_INFO_GENRE:
595 return get_demuxer_info(mpctx, "Genre");
597 default:
598 break;
601 return meta;
604 static void print_file_properties(const MPContext *mpctx, const char *filename)
606 double start_pts = MP_NOPTS_VALUE;
607 double video_start_pts = MP_NOPTS_VALUE;
608 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
609 filename_recode(filename));
610 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
611 if (mpctx->sh_video) {
612 /* Assume FOURCC if all bytes >= 0x20 (' ') */
613 if (mpctx->sh_video->format >= 0x20202020)
614 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
615 else
616 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
617 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
618 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
619 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
620 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
621 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
622 video_start_pts = ds_get_next_pts(mpctx->d_video);
624 if (mpctx->sh_audio) {
625 /* Assume FOURCC if all bytes >= 0x20 (' ') */
626 if (mpctx->sh_audio->format >= 0x20202020)
627 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
628 else
629 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
630 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
631 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
632 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
633 start_pts = ds_get_next_pts(mpctx->d_audio);
635 if (video_start_pts != MP_NOPTS_VALUE) {
636 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
637 (mpctx->sh_video && video_start_pts < start_pts))
638 start_pts = video_start_pts;
640 if (start_pts != MP_NOPTS_VALUE)
641 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
642 else
643 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
644 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", mpctx->timeline ?
645 mpctx->timeline[mpctx->num_timeline_parts].start :
646 demuxer_get_time_length(mpctx->demuxer));
647 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
648 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
649 if (mpctx->demuxer) {
650 if (mpctx->demuxer->num_chapters == 0)
651 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
652 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
656 /// step size of mixer changes
657 int volstep = 3;
659 #ifdef CONFIG_DVDNAV
660 static void mp_dvdnav_context_free(MPContext *ctx){
661 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
662 ctx->nav_smpi = NULL;
663 if (ctx->nav_buffer) free(ctx->nav_buffer);
664 ctx->nav_buffer = NULL;
665 ctx->nav_start = NULL;
666 ctx->nav_in_size = 0;
668 #endif
670 void uninit_player(struct MPContext *mpctx, unsigned int mask){
671 mask &= mpctx->initialized_flags;
673 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
675 if(mask&INITIALIZED_ACODEC){
676 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
677 current_module="uninit_acodec";
678 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
679 mpctx->sh_audio=NULL;
680 mpctx->mixer.afilter = NULL;
683 if(mask&INITIALIZED_VCODEC){
684 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
685 current_module="uninit_vcodec";
686 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
687 mpctx->sh_video=NULL;
688 #ifdef CONFIG_MENU
689 vf_menu=NULL;
690 #endif
693 if(mask&INITIALIZED_DEMUXER){
694 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
695 current_module="free_demuxer";
696 if (mpctx->num_sources) {
697 mpctx->demuxer = mpctx->sources[0].demuxer;
698 for (int i = 1; i < mpctx->num_sources; i++) {
699 free_stream(mpctx->sources[i].stream);
700 free_demuxer(mpctx->sources[i].demuxer);
703 talloc_free(mpctx->sources);
704 mpctx->sources = NULL;
705 mpctx->num_sources = 0;
706 talloc_free(mpctx->timeline);
707 mpctx->timeline = NULL;
708 mpctx->num_timeline_parts = 0;
709 talloc_free(mpctx->chapters);
710 mpctx->chapters = NULL;
711 mpctx->num_chapters = 0;
712 mpctx->video_offset = 0;
713 if(mpctx->demuxer){
714 mpctx->stream=mpctx->demuxer->stream;
715 free_demuxer(mpctx->demuxer);
717 mpctx->demuxer=NULL;
720 // kill the cache process:
721 if(mask&INITIALIZED_STREAM){
722 mpctx->initialized_flags&=~INITIALIZED_STREAM;
723 current_module="uninit_stream";
724 if(mpctx->stream) free_stream(mpctx->stream);
725 mpctx->stream=NULL;
728 if(mask&INITIALIZED_VO){
729 mpctx->initialized_flags&=~INITIALIZED_VO;
730 current_module="uninit_vo";
731 vo_destroy(mpctx->video_out);
732 mpctx->video_out=NULL;
733 #ifdef CONFIG_DVDNAV
734 mp_dvdnav_context_free(mpctx);
735 #endif
738 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
739 if(mask&INITIALIZED_GETCH2){
740 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
741 current_module="uninit_getch2";
742 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
743 // restore terminal:
744 getch2_disable();
747 if(mask&INITIALIZED_VOBSUB){
748 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
749 current_module="uninit_vobsub";
750 if(vo_vobsub) vobsub_close(vo_vobsub);
751 vo_vobsub=NULL;
754 if (mask&INITIALIZED_SPUDEC){
755 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
756 current_module="uninit_spudec";
757 spudec_free(vo_spudec);
758 vo_spudec=NULL;
761 if(mask&INITIALIZED_AO){
762 mpctx->initialized_flags&=~INITIALIZED_AO;
763 current_module="uninit_ao";
764 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
765 if (mpctx->audio_out)
766 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
767 mpctx->audio_out=NULL;
770 current_module=NULL;
773 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
775 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
776 uninit_player(mpctx, INITIALIZED_ALL);
777 #if defined(__MINGW32__) || defined(__CYGWIN__)
778 timeEndPeriod(1);
779 #endif
780 #ifdef CONFIG_X11
781 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
782 #endif
784 current_module="uninit_input";
785 mp_input_uninit(mpctx->input);
786 #ifdef CONFIG_MENU
787 if (use_menu)
788 menu_uninit();
789 #endif
791 #ifdef CONFIG_FREETYPE
792 current_module="uninit_font";
793 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
794 free_font_desc(mpctx->osd->sub_font);
795 free_font_desc(vo_font);
796 vo_font = NULL;
797 done_freetype();
798 #endif
799 osd_free(mpctx->osd);
801 #ifdef CONFIG_ASS
802 ass_library_done(ass_library);
803 ass_library = NULL;
804 #endif
806 current_module="exit_player";
808 // free mplayer config
809 if(mpctx->mconfig)
810 m_config_free(mpctx->mconfig);
811 mpctx->mconfig = NULL;
813 if(mpctx->playtree_iter)
814 play_tree_iter_free(mpctx->playtree_iter);
815 mpctx->playtree_iter = NULL;
816 if(mpctx->playtree)
817 play_tree_free(mpctx->playtree, 1);
818 mpctx->playtree = NULL;
820 talloc_free(mpctx->key_fifo);
822 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
823 edl_records = NULL;
824 switch(how) {
825 case EXIT_QUIT:
826 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
827 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
828 break;
829 case EXIT_EOF:
830 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
831 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
832 break;
833 case EXIT_ERROR:
834 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
835 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
836 break;
837 default:
838 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
840 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
842 exit(rc);
845 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
847 exit_player_with_rc(mpctx, how, 1);
850 #ifndef __MINGW32__
851 static void child_sighandler(int x){
852 pid_t pid;
853 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
855 #endif
857 #ifdef CONFIG_CRASH_DEBUG
858 static char *prog_path;
859 static int crash_debug = 0;
860 #endif
862 static void exit_sighandler(int x){
863 static int sig_count=0;
864 #ifdef CONFIG_CRASH_DEBUG
865 if (!crash_debug || x != SIGTRAP)
866 #endif
867 ++sig_count;
868 if(sig_count==5)
870 /* We're crashing bad and can't uninit cleanly :(
871 * by popular request, we make one last (dirty)
872 * effort to restore the user's
873 * terminal. */
874 getch2_disable();
875 exit(1);
877 if(sig_count==6) exit(1);
878 if(sig_count>6){
879 // can't stop :(
880 #ifndef __MINGW32__
881 kill(getpid(),SIGKILL);
882 #endif
884 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
885 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
886 "\nMPlayer interrupted by signal %d in module: %s\n", x,
887 current_module ? current_module : "unknown");
888 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
889 if(sig_count<=1)
890 switch(x){
891 case SIGINT:
892 case SIGPIPE:
893 case SIGQUIT:
894 case SIGTERM:
895 case SIGKILL:
896 async_quit_request = 1;
897 return; // killed from keyboard (^C) or killed [-9]
898 case SIGILL:
899 #if CONFIG_RUNTIME_CPUDETECT
900 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
901 #else
902 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
903 #endif
904 case SIGFPE:
905 case SIGSEGV:
906 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
907 default:
908 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
909 #ifdef CONFIG_CRASH_DEBUG
910 if (crash_debug) {
911 int gdb_pid;
912 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
913 gdb_pid = fork();
914 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
915 if (gdb_pid == 0) { // We are the child
916 char spid[20];
917 snprintf(spid, sizeof(spid), "%i", getppid());
918 getch2_disable(); // allow terminal to work properly with gdb
919 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
920 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
921 } else if (gdb_pid < 0)
922 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
923 else {
924 waitpid(gdb_pid, NULL, 0);
926 if (x == SIGTRAP) return;
928 #endif
930 getch2_disable();
931 exit(1);
934 #include "cfg-mplayer.h"
936 static int cfg_include(m_option_t *conf, char *filename)
938 return m_config_parse_config_file(conf->priv, filename);
941 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
943 char *conffile;
944 int conffile_fd;
945 if (!disable_system_conf &&
946 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
947 exit_player(mpctx, EXIT_NONE);
948 if ((conffile = get_path("")) == NULL) {
949 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
950 } else {
951 #ifdef __MINGW32__
952 mkdir(conffile);
953 #else
954 mkdir(conffile, 0777);
955 #endif
956 free(conffile);
957 if ((conffile = get_path("config")) == NULL) {
958 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
959 } else {
960 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
961 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
962 write(conffile_fd, default_config, strlen(default_config));
963 close(conffile_fd);
965 if (!disable_user_conf &&
966 m_config_parse_config_file(conf, conffile) < 0)
967 exit_player(mpctx, EXIT_NONE);
968 free(conffile);
973 #define PROFILE_CFG_PROTOCOL "protocol."
975 static void load_per_protocol_config (m_config_t* conf, const char *const file)
977 char *str;
978 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
979 m_profile_t *p;
981 /* does filename actually uses a protocol ? */
982 str = strstr (file, "://");
983 if (!str)
984 return;
986 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
987 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
988 p = m_config_get_profile (conf, protocol);
989 if (p)
991 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
992 m_config_set_profile(conf,p);
996 #define PROFILE_CFG_EXTENSION "extension."
998 static void load_per_extension_config (m_config_t* conf, const char *const file)
1000 char *str;
1001 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
1002 m_profile_t *p;
1004 /* does filename actually have an extension ? */
1005 str = strrchr (file, '.');
1006 if (!str)
1007 return;
1009 sprintf (extension, PROFILE_CFG_EXTENSION);
1010 strncat (extension, ++str, 7);
1011 p = m_config_get_profile (conf, extension);
1012 if (p)
1014 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
1015 m_config_set_profile(conf,p);
1019 #define PROFILE_CFG_VO "vo."
1020 #define PROFILE_CFG_AO "ao."
1022 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
1024 char profile[strlen (cfg) + strlen (out) + 1];
1025 m_profile_t *p;
1027 sprintf (profile, "%s%s", cfg, out);
1028 p = m_config_get_profile (conf, profile);
1029 if (p)
1031 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
1032 m_config_set_profile(conf,p);
1037 * Tries to load a config file
1038 * @return 0 if file was not found, 1 otherwise
1040 static int try_load_config(m_config_t *conf, const char *file)
1042 struct stat st;
1043 if (stat(file, &st))
1044 return 0;
1045 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1046 m_config_parse_config_file (conf, file);
1047 return 1;
1050 static void load_per_file_config (m_config_t* conf, const char *const file)
1052 char *confpath;
1053 char cfg[PATH_MAX];
1054 char *name;
1056 if (strlen(file) > PATH_MAX - 14) {
1057 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1058 return;
1060 sprintf (cfg, "%s.conf", file);
1062 name = strrchr(cfg, '/');
1063 if (HAVE_DOS_PATHS) {
1064 char *tmp = strrchr(cfg, '\\');
1065 if (!name || tmp > name)
1066 name = tmp;
1067 tmp = strrchr(cfg, ':');
1068 if (!name || tmp > name)
1069 name = tmp;
1071 if (!name)
1072 name = cfg;
1073 else
1074 name++;
1076 if (use_filedir_conf) {
1077 char dircfg[PATH_MAX];
1078 strcpy(dircfg, cfg);
1079 strcpy(dircfg + (name - cfg), "mplayer.conf");
1080 try_load_config(conf, dircfg);
1082 if (try_load_config(conf, cfg))
1083 return;
1086 if ((confpath = get_path (name)) != NULL)
1088 try_load_config(conf, confpath);
1090 free (confpath);
1094 /* When libmpdemux performs a blocking operation (network connection or
1095 * cache filling) if the operation fails we use this function to check
1096 * if it was interrupted by the user.
1097 * The function returns a new value for eof. */
1098 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1100 mp_cmd_t* cmd;
1101 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1102 switch(cmd->id) {
1103 case MP_CMD_QUIT:
1104 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1105 case MP_CMD_PLAY_TREE_STEP: {
1106 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1107 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1108 } break;
1109 case MP_CMD_PLAY_TREE_UP_STEP: {
1110 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1111 } break;
1112 case MP_CMD_PLAY_ALT_SRC_STEP: {
1113 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1114 } break;
1116 mp_cmd_free(cmd);
1118 return stop_play;
1121 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1123 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1125 play_tree_add_bpf(entry,mpctx->filename);
1128 if(!entry) {
1129 entry = mpctx->playtree_iter->tree;
1130 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1131 return PT_NEXT_ENTRY;
1133 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1134 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1135 return PT_NEXT_ENTRY;
1138 play_tree_remove(entry,1,1);
1139 return PT_NEXT_SRC;
1141 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1142 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1143 entry = mpctx->playtree_iter->tree;
1144 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1145 return PT_NEXT_ENTRY;
1147 play_tree_remove(entry,1,1);
1149 return PT_NEXT_SRC;
1152 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1154 struct MPOpts *opts = &mpctx->opts;
1155 sub_data *subd = NULL;
1156 struct ass_track *asst = NULL;
1158 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1159 return;
1162 #ifdef CONFIG_ASS
1163 if (opts->ass_enabled) {
1164 #ifdef CONFIG_ICONV
1165 asst = ass_read_stream(ass_library, filename, sub_cp);
1166 #else
1167 asst = ass_read_stream(ass_library, filename, 0);
1168 #endif
1169 if (!asst) {
1170 subd = sub_read_file(filename, fps);
1171 if (subd) {
1172 asst = ass_read_subdata(ass_library, subd, fps);
1173 if (asst) {
1174 sub_free(subd);
1175 subd = NULL;
1179 } else
1180 #endif
1181 subd = sub_read_file(filename, fps);
1184 if (!asst && !subd) {
1185 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1186 "Cannot load subtitles: %s\n", filename_recode(filename));
1187 return;
1190 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1191 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1192 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1193 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1194 filename_recode(filename));
1195 ++mpctx->set_of_sub_size;
1196 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1197 filename_recode(filename));
1200 void init_vo_spudec(struct MPContext *mpctx)
1202 if (vo_spudec)
1203 spudec_free(vo_spudec);
1204 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1205 vo_spudec = NULL;
1207 // we currently can't work without video stream
1208 if (!mpctx->sh_video)
1209 return;
1211 if (spudec_ifo) {
1212 unsigned int palette[16], width, height;
1213 current_module="spudec_init_vobsub";
1214 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1215 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1218 #ifdef CONFIG_DVDREAD
1219 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1220 current_module="spudec_init_dvdread";
1221 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1222 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1223 NULL, 0);
1225 #endif
1227 #ifdef CONFIG_DVDNAV
1228 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1229 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1230 current_module="spudec_init_dvdnav";
1231 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1233 #endif
1235 if (vo_spudec==NULL) {
1236 sh_sub_t *sh = mpctx->d_sub->sh;
1237 current_module="spudec_init_normal";
1238 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1239 spudec_set_font_factor(vo_spudec,font_factor);
1242 if (vo_spudec!=NULL) {
1243 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1244 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1249 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1250 * make it all work is to use the builtin SDL-bootstrap code, which
1251 * will be done automatically by replacing our main() if we include SDL.h.
1253 #if defined(__APPLE__) && defined(CONFIG_SDL)
1254 #ifdef CONFIG_SDL_SDL_H
1255 #include <SDL/SDL.h>
1256 #else
1257 #include <SDL.h>
1258 #endif
1259 #endif
1262 * \brief append a formatted string
1263 * \param buf buffer to print into
1264 * \param pos position of terminating 0 in buf
1265 * \param len maximum number of characters in buf, not including terminating 0
1266 * \param format printf format string
1268 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1270 va_list va;
1271 va_start(va, format);
1272 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1273 va_end(va);
1274 if (*pos >= len ) {
1275 buf[len] = 0;
1276 *pos = len;
1281 * \brief append time in the hh:mm:ss.f format
1282 * \param buf buffer to print into
1283 * \param pos position of terminating 0 in buf
1284 * \param len maximum number of characters in buf, not including terminating 0
1285 * \param time time value to convert/append
1287 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1288 int64_t tenths = 10 * time;
1289 int f1 = tenths % 10;
1290 int ss = (tenths / 10) % 60;
1291 int mm = (tenths / 600) % 60;
1292 int hh = tenths / 36000;
1293 if (time <= 0) {
1294 saddf(buf, pos, len, "unknown");
1295 return;
1297 if (hh > 0)
1298 saddf(buf, pos, len, "%2d:", hh);
1299 if (hh > 0 || mm > 0)
1300 saddf(buf, pos, len, "%02d:", mm);
1301 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1304 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1306 struct MPOpts *opts = &mpctx->opts;
1307 sh_video_t * const sh_video = mpctx->sh_video;
1309 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1310 a_pos = playing_audio_pts(mpctx);
1311 if (mpctx->sh_audio && sh_video && at_frame) {
1312 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1313 if (mpctx->time_frame > 0)
1314 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1315 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1316 && !mpctx->drop_message_shown) {
1317 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1318 mpctx->drop_message_shown = true;
1321 if (quiet)
1322 return;
1325 int width;
1326 char *line;
1327 unsigned pos = 0;
1328 get_screen_size();
1329 if (screen_width > 0)
1330 width = screen_width;
1331 else
1332 width = 80;
1333 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1334 /* Windows command line is broken (MinGW's rxvt works, but we
1335 * should not depend on that). */
1336 width--;
1337 #endif
1338 line = malloc(width + 1); // one additional char for the terminating null
1340 // Audio time
1341 if (mpctx->sh_audio) {
1342 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1343 if (!sh_video) {
1344 float len = demuxer_get_time_length(mpctx->demuxer);
1345 saddf(line, &pos, width, "(");
1346 sadd_hhmmssf(line, &pos, width, a_pos);
1347 saddf(line, &pos, width, ") of %.1f (", len);
1348 sadd_hhmmssf(line, &pos, width, len);
1349 saddf(line, &pos, width, ") ");
1353 // Video time
1354 if (sh_video)
1355 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1357 // A-V sync
1358 if (mpctx->sh_audio && sh_video)
1359 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1360 mpctx->last_av_difference, mpctx->total_avsync_change);
1362 // Video stats
1363 if (sh_video)
1364 saddf(line, &pos, width, "%3d/%3d ",
1365 (int)sh_video->num_frames,
1366 (int)sh_video->num_frames_decoded);
1368 // CPU usage
1369 if (sh_video) {
1370 if (sh_video->timer > 0.5)
1371 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1372 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1373 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1374 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1375 else
1376 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1377 } else if (mpctx->sh_audio) {
1378 if (mpctx->delay > 0.5)
1379 saddf(line, &pos, width, "%4.1f%% ",
1380 100.0*audio_time_usage/(double)mpctx->delay);
1381 else
1382 saddf(line, &pos, width, "??,?%% ");
1385 // VO stats
1386 if (sh_video)
1387 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1389 #ifdef CONFIG_STREAM_CACHE
1390 // cache stats
1391 if (stream_cache_size > 0)
1392 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1393 #endif
1395 // other
1396 if (opts->playback_speed != 1)
1397 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1399 // end
1400 if (erase_to_end_of_line) {
1401 line[pos] = 0;
1402 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1403 } else {
1404 memset(&line[pos], ' ', width - pos);
1405 line[width] = 0;
1406 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1408 free(line);
1412 * \brief build a chain of audio filters that converts the input format
1413 * to the ao's format, taking into account the current playback_speed.
1414 * \param sh_audio describes the requested input format of the chain.
1415 * \param ao_data describes the requested output format of the chain.
1417 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1419 struct MPOpts *opts = &mpctx->opts;
1420 int new_srate;
1421 int result;
1422 if (!sh_audio)
1424 mpctx->mixer.afilter = NULL;
1425 return 0;
1427 if(af_control_any_rev(sh_audio->afilter,
1428 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1429 &opts->playback_speed)) {
1430 new_srate = sh_audio->samplerate;
1431 } else {
1432 new_srate = sh_audio->samplerate * opts->playback_speed;
1433 if (new_srate != ao_data->samplerate) {
1434 // limits are taken from libaf/af_resample.c
1435 if (new_srate < 8000)
1436 new_srate = 8000;
1437 if (new_srate > 192000)
1438 new_srate = 192000;
1439 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1442 result = init_audio_filters(sh_audio, new_srate,
1443 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1444 mpctx->mixer.afilter = sh_audio->afilter;
1445 return result;
1449 typedef struct mp_osd_msg mp_osd_msg_t;
1450 struct mp_osd_msg {
1451 /// Previous message on the stack.
1452 mp_osd_msg_t* prev;
1453 /// Message text.
1454 char msg[128];
1455 int id,level,started;
1456 /// Display duration in ms.
1457 unsigned time;
1460 /// OSD message stack.
1461 static mp_osd_msg_t* osd_msg_stack = NULL;
1464 * \brief Add a message on the OSD message stack
1466 * If a message with the same id is already present in the stack
1467 * it is pulled on top of the stack, otherwise a new message is created.
1470 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1471 va_list ap)
1473 mp_osd_msg_t *msg,*last=NULL;
1474 int r;
1476 // look if the id is already in the stack
1477 for(msg = osd_msg_stack ; msg && msg->id != id ;
1478 last = msg, msg = msg->prev);
1479 // not found: alloc it
1480 if(!msg) {
1481 msg = calloc(1,sizeof(mp_osd_msg_t));
1482 msg->prev = osd_msg_stack;
1483 osd_msg_stack = msg;
1484 } else if(last) { // found, but it's not on top of the stack
1485 last->prev = msg->prev;
1486 msg->prev = osd_msg_stack;
1487 osd_msg_stack = msg;
1489 // write the msg
1490 r = vsnprintf(msg->msg, 128, fmt, ap);
1491 if(r >= 128) msg->msg[127] = 0;
1492 // set id and time
1493 msg->id = id;
1494 msg->level = level;
1495 msg->time = time;
1499 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1501 va_list ap;
1502 va_start(ap, fmt);
1503 set_osd_msg_va(id, level, time, fmt, ap);
1504 va_end(ap);
1507 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1509 va_list ap;
1510 va_start(ap, fmt);
1511 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1512 va_end(ap);
1517 * \brief Remove a message from the OSD stack
1519 * This function can be used to get rid of a message right away.
1523 void rm_osd_msg(int id) {
1524 mp_osd_msg_t *msg,*last=NULL;
1526 // Search for the msg
1527 for(msg = osd_msg_stack ; msg && msg->id != id ;
1528 last = msg, msg = msg->prev);
1529 if(!msg) return;
1531 // Detach it from the stack and free it
1532 if(last)
1533 last->prev = msg->prev;
1534 else
1535 osd_msg_stack = msg->prev;
1536 free(msg);
1540 * \brief Remove all messages from the OSD stack
1544 static void clear_osd_msgs(void) {
1545 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1546 while(msg) {
1547 prev = msg->prev;
1548 free(msg);
1549 msg = prev;
1551 osd_msg_stack = NULL;
1555 * \brief Get the current message from the OSD stack.
1557 * This function decrements the message timer and destroys the old ones.
1558 * The message that should be displayed is returned (if any).
1562 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1564 struct MPOpts *opts = &mpctx->opts;
1565 mp_osd_msg_t *msg,*prev,*last = NULL;
1566 static unsigned last_update = 0;
1567 unsigned now = GetTimerMS();
1568 unsigned diff;
1569 char hidden_dec_done = 0;
1571 if (mpctx->osd_visible) {
1572 // 36000000 means max timed visibility is 1 hour into the future, if
1573 // the difference is greater assume it's wrapped around from below 0
1574 if (mpctx->osd_visible - now > 36000000) {
1575 mpctx->osd_visible = 0;
1576 vo_osd_progbar_type = -1; // disable
1577 vo_osd_changed(OSDTYPE_PROGBAR);
1578 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1581 if (mpctx->osd_show_percentage_until - now > 36000000)
1582 mpctx->osd_show_percentage_until = 0;
1584 if(!last_update) last_update = now;
1585 diff = now >= last_update ? now - last_update : 0;
1587 last_update = now;
1589 // Look for the first message in the stack with high enough level.
1590 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1591 prev = msg->prev;
1592 if (msg->level > opts->osd_level && hidden_dec_done)
1593 continue;
1594 // The message has a high enough level or it is the first hidden one
1595 // in both cases we decrement the timer or kill it.
1596 if(!msg->started || msg->time > diff) {
1597 if(msg->started) msg->time -= diff;
1598 else msg->started = 1;
1599 // display it
1600 if (msg->level <= opts->osd_level)
1601 return msg;
1602 hidden_dec_done = 1;
1603 continue;
1605 // kill the message
1606 free(msg);
1607 if(last) {
1608 last->prev = prev;
1609 msg = last;
1610 } else {
1611 osd_msg_stack = prev;
1612 msg = NULL;
1615 // Nothing found
1616 return NULL;
1620 * \brief Display the OSD bar.
1622 * Display the OSD bar or fall back on a simple message.
1626 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1627 struct MPOpts *opts = &mpctx->opts;
1628 if (opts->osd_level < 1)
1629 return;
1631 if(mpctx->sh_video) {
1632 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1633 vo_osd_progbar_type = type;
1634 vo_osd_progbar_value = 256*(val-min)/(max-min);
1635 vo_osd_changed(OSDTYPE_PROGBAR);
1636 return;
1639 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1640 name, ROUND(100*(val-min)/(max-min)));
1644 * \brief Display text subtitles on the OSD
1646 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1648 int i;
1649 vo_sub = subs;
1650 vo_osd_changed(OSDTYPE_SUBTITLE);
1651 if (!mpctx->sh_video) {
1652 // reverse order, since newest set_osd_msg is displayed first
1653 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1654 if (!subs || i >= subs->lines || !subs->text[i])
1655 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1656 else {
1657 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1658 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1659 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1666 * \brief Update the OSD message line.
1668 * This function displays the current message on the vo OSD or on the term.
1669 * If the stack is empty and the OSD level is high enough the timer
1670 * is displayed (only on the vo OSD).
1674 static void update_osd_msg(struct MPContext *mpctx)
1676 struct MPOpts *opts = &mpctx->opts;
1677 mp_osd_msg_t *msg;
1678 struct osd_state *osd = mpctx->osd;
1679 char osd_text_timer[128];
1681 if (mpctx->add_osd_seek_info) {
1682 double percentage;
1683 if (mpctx->timeline && mpctx->sh_video)
1684 percentage = mpctx->sh_video->pts * 100 /
1685 mpctx->timeline[mpctx->num_timeline_parts].start;
1686 else
1687 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1688 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1689 if (mpctx->sh_video)
1690 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1691 mpctx->add_osd_seek_info = false;
1694 // Look if we have a msg
1695 if((msg = get_osd_msg(mpctx))) {
1696 if (strcmp(osd->osd_text, msg->msg)) {
1697 strncpy(osd->osd_text, msg->msg, 127);
1698 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1699 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1701 return;
1704 if(mpctx->sh_video) {
1705 // fallback on the timer
1706 if (opts->osd_level >= 2) {
1707 int len;
1708 if (mpctx->timeline)
1709 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1710 else
1711 len = demuxer_get_time_length(mpctx->demuxer);
1712 int percentage = -1;
1713 char percentage_text[10];
1714 int pts = demuxer_get_current_time(mpctx->demuxer);
1716 if (mpctx->osd_show_percentage_until) {
1717 if (mpctx->timeline)
1718 percentage = mpctx->sh_video->pts * 100 /
1719 mpctx->timeline[mpctx->num_timeline_parts].start;
1720 else
1721 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1724 if (percentage >= 0)
1725 snprintf(percentage_text, 9, " (%d%%)", percentage);
1726 else
1727 percentage_text[0] = 0;
1729 if (opts->osd_level == 3)
1730 snprintf(osd_text_timer, 63,
1731 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1732 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1733 len/3600,(len/60)%60,len%60,percentage_text);
1734 else
1735 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1736 mpctx->osd_function,pts/3600,(pts/60)%60,
1737 pts%60,percentage_text);
1738 } else
1739 osd_text_timer[0]=0;
1741 if (strcmp(osd->osd_text, osd_text_timer)) {
1742 strncpy(osd->osd_text, osd_text_timer, 63);
1743 vo_osd_changed(OSDTYPE_OSD);
1745 return;
1748 // Clear the term osd line
1749 if (term_osd && osd->osd_text[0]) {
1750 osd->osd_text[0] = 0;
1751 printf("%s\n",term_osd_esc);
1755 ///@}
1756 // OSDMsgStack
1759 void reinit_audio_chain(struct MPContext *mpctx)
1761 struct MPOpts *opts = &mpctx->opts;
1762 if (!mpctx->sh_audio)
1763 return;
1764 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1765 current_module="init_audio_codec";
1766 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1767 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1768 goto init_error;
1770 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1771 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1775 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1776 current_module="af_preinit";
1777 ao_data.samplerate=force_srate;
1778 ao_data.channels=0;
1779 ao_data.format=audio_output_format;
1780 // first init to detect best values
1781 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1782 // input:
1783 mpctx->sh_audio->samplerate,
1784 // output:
1785 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1786 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1787 "pre-init!\n");
1788 exit_player(mpctx, EXIT_ERROR);
1790 current_module="ao2_init";
1791 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1792 0, // plugin flag
1793 ao_data.samplerate,
1794 ao_data.channels,
1795 ao_data.format, 0);
1796 if(!mpctx->audio_out){
1797 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1798 goto init_error;
1800 mpctx->initialized_flags|=INITIALIZED_AO;
1801 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1802 mpctx->audio_out->info->short_name,
1803 ao_data.samplerate, ao_data.channels,
1804 af_fmt2str_short(ao_data.format),
1805 af_fmt2bits(ao_data.format)/8 );
1806 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1807 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1808 if(strlen(mpctx->audio_out->info->comment) > 0)
1809 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1812 // init audio filters:
1813 current_module="af_init";
1814 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1815 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1816 goto init_error;
1818 mpctx->mixer.audio_out = mpctx->audio_out;
1819 mpctx->mixer.volstep = volstep;
1820 return;
1822 init_error:
1823 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1824 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1825 mpctx->d_audio->id = -2;
1829 ///@}
1830 // Command2Property
1833 // Return pts value corresponding to the end point of audio written to the
1834 // ao so far.
1835 static double written_audio_pts(struct MPContext *mpctx)
1837 sh_audio_t *sh_audio = mpctx->sh_audio;
1838 demux_stream_t *d_audio = mpctx->d_audio;
1839 double buffered_output;
1840 // first calculate the end pts of audio that has been output by decoder
1841 double a_pts = sh_audio->pts;
1842 if (a_pts != MP_NOPTS_VALUE)
1843 // Good, decoder supports new way of calculating audio pts.
1844 // sh_audio->pts is the timestamp of the latest input packet with
1845 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1846 // the amount of bytes the decoder has written after that timestamp.
1847 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1848 else {
1849 // Decoder doesn't support new way of calculating pts (or we're
1850 // being called before it has decoded anything with known timestamp).
1851 // Use the old method of audio pts calculation: take the timestamp
1852 // of last packet with known pts the decoder has read data from,
1853 // and add amount of bytes read after the beginning of that packet
1854 // divided by input bps. This will be inaccurate if the input/output
1855 // ratio is not constant for every audio packet or if it is constant
1856 // but not accurately known in sh_audio->i_bps.
1858 a_pts = d_audio->pts;
1859 // ds_tell_pts returns bytes read after last timestamp from
1860 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1861 // it has read but not decoded
1862 if (sh_audio->i_bps)
1863 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1864 (double)sh_audio->i_bps;
1866 // Now a_pts hopefully holds the pts for end of audio from decoder.
1867 // Substract data in buffers between decoder and audio out.
1869 // Decoded but not filtered
1870 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1872 // Data buffered in audio filters, measured in bytes of "missing" output
1873 buffered_output = af_calc_delay(sh_audio->afilter);
1875 // Data that was ready for ao but was buffered because ao didn't fully
1876 // accept everything to internal buffers yet
1877 buffered_output += sh_audio->a_out_buffer_len;
1879 // Filters divide audio length by playback_speed, so multiply by it
1880 // to get the length in original units without speedup or slowdown
1881 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1883 return a_pts + mpctx->video_offset;
1886 // Return pts value corresponding to currently playing audio.
1887 double playing_audio_pts(struct MPContext *mpctx)
1889 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1890 mpctx->audio_out->get_delay();
1893 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1894 struct MPOpts *opts = &mpctx->opts;
1895 // check for frame-drop:
1896 current_module = "check_framedrop";
1897 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1898 static int dropped_frames;
1899 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1900 float d = delay-mpctx->delay;
1901 ++total_frame_cnt;
1902 // we should avoid dropping too many frames in sequence unless we
1903 // are too late. and we allow 100ms A-V delay here:
1904 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1905 && !mpctx->update_video_immediately) {
1906 ++drop_frame_cnt;
1907 ++dropped_frames;
1908 return frame_dropping;
1909 } else
1910 dropped_frames = 0;
1912 return 0;
1916 #ifdef HAVE_RTC
1917 int rtc_fd = -1;
1918 #endif
1920 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1922 #ifdef HAVE_RTC
1923 if (rtc_fd >= 0){
1924 // -------- RTC -----------
1925 current_module="sleep_rtc";
1926 while (time_frame > 0.000) {
1927 unsigned long rtc_ts;
1928 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1929 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1930 time_frame -= get_relative_time(mpctx);
1932 } else
1933 #endif
1935 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1936 // unnecessarily high CPU usage
1937 float margin = softsleep ? 0.011 : 0;
1938 current_module = "sleep_timer";
1939 while (time_frame > margin) {
1940 usec_sleep(1000000 * (time_frame - margin));
1941 time_frame -= get_relative_time(mpctx);
1943 if (softsleep){
1944 current_module = "sleep_soft";
1945 if (time_frame < 0)
1946 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1947 while (time_frame > 0)
1948 time_frame -= get_relative_time(mpctx); // burn the CPU
1951 return time_frame;
1954 static int select_subtitle(MPContext *mpctx)
1956 struct MPOpts *opts = &mpctx->opts;
1957 // find the best sub to use
1958 int id;
1959 int found = 0;
1960 mpctx->global_sub_pos = -1; // no subs by default
1961 if (vobsub_id >= 0) {
1962 // if user asks for a vobsub id, use that first.
1963 id = vobsub_id;
1964 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1967 if (!found && opts->sub_id >= 0) {
1968 // if user asks for a dvd sub id, use that next.
1969 id = opts->sub_id;
1970 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1973 if (!found) {
1974 // if there are text subs to use, use those. (autosubs come last here)
1975 id = 0;
1976 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1979 if (!found && opts->sub_id == -1) {
1980 // finally select subs by language and container hints
1981 if (opts->sub_id == -1 && opts->sub_lang)
1982 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, opts->sub_lang);
1983 if (opts->sub_id == -1)
1984 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
1985 if (opts->sub_id >= 0) {
1986 id = opts->sub_id;
1987 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1990 return found;
1993 #ifdef CONFIG_DVDNAV
1994 #ifndef FF_B_TYPE
1995 #define FF_B_TYPE 3
1996 #endif
1997 /// store decoded video image
1998 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1999 mp_image_t *from_mpi) {
2000 mp_image_t *mpi;
2002 /// Do not store B-frames
2003 if (from_mpi->pict_type == FF_B_TYPE)
2004 return to_mpi;
2006 if (to_mpi &&
2007 to_mpi->w == from_mpi->w &&
2008 to_mpi->h == from_mpi->h &&
2009 to_mpi->imgfmt == from_mpi->imgfmt)
2010 mpi = to_mpi;
2011 else {
2012 if (to_mpi)
2013 free_mp_image(to_mpi);
2014 if (from_mpi->w == 0 || from_mpi->h == 0)
2015 return NULL;
2016 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2019 copy_mpi(mpi,from_mpi);
2020 return mpi;
2023 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2024 struct MPOpts *opts = &ctx->opts;
2025 if (ctx->sh_video) {
2026 /// clear video pts
2027 ctx->d_video->pts = 0.0f;
2028 ctx->sh_video->pts = 0.0f;
2029 ctx->sh_video->i_pts = 0.0f;
2030 ctx->sh_video->last_pts = 0.0f;
2031 ctx->sh_video->num_buffered_pts = 0;
2032 ctx->sh_video->num_frames = 0;
2033 ctx->sh_video->num_frames_decoded = 0;
2034 ctx->sh_video->timer = 0.0f;
2035 ctx->sh_video->stream_delay = 0.0f;
2036 ctx->sh_video->timer = 0;
2037 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2040 if (ctx->sh_audio) {
2041 /// free audio packets and reset
2042 ds_free_packs(ctx->d_audio);
2043 audio_delay -= ctx->sh_audio->stream_delay;
2044 ctx->delay =- audio_delay;
2045 ctx->audio_out->reset();
2046 resync_audio_stream(ctx->sh_audio);
2049 audio_delay = 0.0f;
2050 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2051 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2052 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2053 if (dvdsub_lang_id != opts->sub_id) {
2054 opts->sub_id = dvdsub_lang_id;
2055 select_subtitle(ctx);
2059 /// clear all EOF related flags
2060 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2063 /// Restore last decoded DVDNAV (still frame)
2064 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2065 int *in_size,
2066 unsigned char **start,
2067 mp_image_t *decoded_frame)
2069 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2070 return decoded_frame;
2072 /// a change occured in dvdnav stream
2073 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2074 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2075 mp_dvdnav_context_free(mpctx);
2076 mp_dvdnav_reset_stream(mpctx);
2077 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2078 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2081 if (*in_size < 0) {
2082 float len;
2084 /// Display still frame, if any
2085 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2086 decoded_frame = mpctx->nav_smpi;
2088 /// increment video frame : continue playing after still frame
2089 len = demuxer_get_time_length(mpctx->demuxer);
2090 if (mpctx->sh_video->pts >= len &&
2091 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2092 mp_dvdnav_skip_still(mpctx->stream);
2093 mp_dvdnav_skip_wait(mpctx->stream);
2095 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2097 if (mpctx->nav_buffer) {
2098 *start = mpctx->nav_start;
2099 *in_size = mpctx->nav_in_size;
2100 if (mpctx->nav_start)
2101 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2105 return decoded_frame;
2108 /// Save last decoded DVDNAV (still frame)
2109 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2110 unsigned char *start,
2111 mp_image_t *decoded_frame)
2113 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2114 return;
2116 if (mpctx->nav_buffer)
2117 free(mpctx->nav_buffer);
2119 mpctx->nav_buffer = malloc(in_size);
2120 mpctx->nav_start = start;
2121 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2122 if (mpctx->nav_buffer)
2123 memcpy(mpctx->nav_buffer,start,in_size);
2125 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2126 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2128 #endif /* CONFIG_DVDNAV */
2130 /* Modify video timing to match the audio timeline. There are two main
2131 * reasons this is needed. First, video and audio can start from different
2132 * positions at beginning of file or after a seek (MPlayer starts both
2133 * immediately even if they have different pts). Second, the file can have
2134 * audio timestamps that are inconsistent with the duration of the audio
2135 * packets, for example two consecutive timestamp values differing by
2136 * one second but only a packet with enough samples for half a second
2137 * of playback between them.
2139 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2141 current_module = "av_sync";
2143 if (!mpctx->sh_audio)
2144 return;
2146 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2147 double v_pts = mpctx->sh_video->pts;
2148 double av_delay = a_pts - v_pts;
2149 // Try to sync vo_flip() so it will *finish* at given time
2150 av_delay += mpctx->last_vo_flip_duration;
2151 av_delay -= audio_delay; // This much pts difference is desired
2153 double change = av_delay * 0.1;
2154 double max_change = default_max_pts_correction >= 0 ?
2155 default_max_pts_correction : frame_time * 0.1;
2156 if (change < -max_change)
2157 change = -max_change;
2158 else if (change > max_change)
2159 change = max_change;
2160 mpctx->delay += change;
2161 mpctx->total_avsync_change += change;
2164 static int fill_audio_out_buffers(struct MPContext *mpctx)
2166 struct MPOpts *opts = &mpctx->opts;
2167 unsigned int t;
2168 double tt;
2169 int playsize;
2170 int playflags=0;
2171 int audio_eof=0;
2172 bool format_change = false;
2173 sh_audio_t * const sh_audio = mpctx->sh_audio;
2175 current_module="play_audio";
2177 while (1) {
2178 int sleep_time;
2179 // all the current uses of ao_data.pts seem to be in aos that handle
2180 // sync completely wrong; there should be no need to use ao_data.pts
2181 // in get_space()
2182 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2183 playsize = mpctx->audio_out->get_space();
2184 if (mpctx->sh_video || playsize >= ao_data.outburst)
2185 break;
2187 // handle audio-only case:
2188 // this is where mplayer sleeps during audio-only playback
2189 // to avoid 100% CPU use
2190 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2191 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2192 usec_sleep(sleep_time * 1000);
2195 // Fill buffer if needed:
2196 current_module="decode_audio";
2197 t = GetTimer();
2198 int res = decode_audio(sh_audio, playsize);
2199 if (res < 0) { // EOF, error or format change
2200 if (res == -2)
2201 format_change = true;
2202 else if (mpctx->d_audio->eof) {
2203 audio_eof = 1;
2204 if (sh_audio->a_out_buffer_len == 0)
2205 return 0;
2208 t = GetTimer() - t;
2209 tt = t*0.000001f; audio_time_usage+=tt;
2210 if (playsize > sh_audio->a_out_buffer_len) {
2211 playsize = sh_audio->a_out_buffer_len;
2212 if (audio_eof)
2213 playflags |= AOPLAY_FINAL_CHUNK;
2215 if (!playsize)
2216 return 1;
2218 // play audio:
2219 current_module="play_audio";
2221 // Is this pts value actually useful for the aos that access it?
2222 // They're obviously badly broken in the way they handle av sync;
2223 // would not having access to this make them more broken?
2224 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2225 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2227 if (playsize > 0) {
2228 sh_audio->a_out_buffer_len -= playsize;
2229 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2230 sh_audio->a_out_buffer_len);
2231 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2233 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2234 // Sanity check to avoid hanging in case current ao doesn't output
2235 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2236 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2237 sh_audio->a_out_buffer_len = 0;
2240 /* The format change isn't handled too gracefully. A more precise
2241 * implementation would require draining buffered old-format audio
2242 * while displaying video, then doing the output format switch.
2244 if (format_change) {
2245 uninit_player(mpctx, INITIALIZED_AO);
2246 reinit_audio_chain(mpctx);
2249 return 1;
2252 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2253 float *aq_sleep_time)
2255 struct MPOpts *opts = &mpctx->opts;
2256 int frame_time_remaining = 0;
2257 current_module="calc_sleep_time";
2259 *time_frame -= get_relative_time(mpctx); // reset timer
2261 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2262 float delay = mpctx->audio_out->get_delay();
2263 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2265 if (autosync) {
2267 * Adjust this raw delay value by calculating the expected
2268 * delay for this frame and generating a new value which is
2269 * weighted between the two. The higher autosync is, the
2270 * closer to the delay value gets to that which "-nosound"
2271 * would have used, and the longer it will take for A/V
2272 * sync to settle at the right value (but it eventually will.)
2273 * This settling time is very short for values below 100.
2275 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2276 float difference = delay - predicted;
2277 delay = predicted + difference / (float)autosync;
2280 *time_frame = delay - mpctx->delay / opts->playback_speed;
2281 *time_frame -= mpctx->video_out->flip_queue_offset;
2283 // delay = amount of audio buffered in soundcard/driver
2284 if (delay > 0.25) delay=0.25; else
2285 if (delay < 0.10) delay=0.10;
2287 if (*time_frame > delay*0.6) {
2288 // sleep time too big - may cause audio drops (buffer underrun)
2289 frame_time_remaining = 1;
2290 *time_frame = delay*0.5;
2292 } else {
2293 // If we're lagging more than 200 ms behind the right playback rate,
2294 // don't try to "catch up".
2295 // If benchmark is set always output frames as fast as possible
2296 // without sleeping.
2297 if (*time_frame < -0.2 || benchmark)
2298 *time_frame = 0;
2299 *time_frame -= mpctx->video_out->flip_queue_offset;
2302 *aq_sleep_time += *time_frame;
2305 //============================== SLEEP: ===================================
2307 // flag 256 means: libvo driver does its timing (dvb card)
2308 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2309 *time_frame = timing_sleep(mpctx, *time_frame);
2310 *time_frame += mpctx->video_out->flip_queue_offset;
2311 return frame_time_remaining;
2314 int reinit_video_chain(struct MPContext *mpctx)
2316 struct MPOpts *opts = &mpctx->opts;
2317 sh_video_t * const sh_video = mpctx->sh_video;
2318 double ar=-1.0;
2319 //================== Init VIDEO (codec & libvo) ==========================
2320 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2321 current_module="preinit_libvo";
2323 //shouldn't we set dvideo->id=-2 when we fail?
2324 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2325 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2326 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2327 goto err_out;
2329 mpctx->initialized_flags|=INITIALIZED_VO;
2332 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2333 mpctx->sh_video->stream_aspect = ar;
2334 current_module="init_video_filters";
2336 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2337 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2339 #ifdef CONFIG_MENU
2340 if(use_menu) {
2341 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2342 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2343 if(!vf_menu) {
2344 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2345 use_menu = 0;
2348 if(vf_menu)
2349 sh_video->vfilter = vf_menu;
2350 #endif
2352 #ifdef CONFIG_ASS
2353 if(opts->ass_enabled) {
2354 int i;
2355 int insert = 1;
2356 if (opts->vf_settings)
2357 for (i = 0; opts->vf_settings[i].name; ++i)
2358 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2359 insert = 0;
2360 break;
2362 if (insert) {
2363 extern vf_info_t vf_info_ass;
2364 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2365 char* vf_arg[] = {"auto", "1", NULL};
2366 int retcode = 0;
2367 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2368 sh_video->vfilter,
2369 "ass", vf_arg,
2370 &retcode);
2371 if (vf_ass)
2372 sh_video->vfilter = vf_ass;
2373 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2374 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2375 else
2376 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2379 #endif
2381 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2383 #ifdef CONFIG_ASS
2384 if (opts->ass_enabled)
2385 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2386 #endif
2388 current_module="init_video_codec";
2390 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2391 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2392 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2394 if(!sh_video->initialized){
2395 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2396 goto err_out;
2399 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2401 if (sh_video->codec)
2402 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2404 sh_video->last_pts = MP_NOPTS_VALUE;
2405 sh_video->num_buffered_pts = 0;
2406 sh_video->next_frame_time = 0;
2408 if(auto_quality>0){
2409 // Auto quality option enabled
2410 output_quality=get_video_quality_max(sh_video);
2411 if(auto_quality>output_quality) auto_quality=output_quality;
2412 else output_quality=auto_quality;
2413 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2414 set_video_quality(sh_video,output_quality);
2417 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2419 current_module="init_vo";
2421 return 1;
2423 err_out:
2424 mpctx->sh_video = mpctx->d_video->sh = NULL;
2425 return 0;
2428 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2430 struct sh_video *sh_video = mpctx->sh_video;
2431 double frame_time = 0;
2432 struct vo *video_out = mpctx->video_out;
2433 while (!video_out->frame_loaded) {
2434 current_module = "filter_video";
2435 // In nocorrect-pts mode there is no way to properly time these frames
2436 if (vo_get_buffered_frame(video_out, 0) >= 0)
2437 break;
2438 if (vf_output_queued_frame(sh_video->vfilter))
2439 continue;
2440 unsigned char *packet = NULL;
2441 frame_time = sh_video->next_frame_time;
2442 if (mpctx->update_video_immediately)
2443 frame_time = 0;
2444 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2445 &packet, force_fps);
2446 if (in_size < 0) {
2447 #ifdef CONFIG_DVDNAV
2448 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2449 if (mp_dvdnav_is_eof(mpctx->stream))
2450 return -1;
2451 if (mpctx->d_video)
2452 mpctx->d_video->eof = 0;
2453 if (mpctx->d_audio)
2454 mpctx->d_audio->eof = 0;
2455 mpctx->stream->eof = 0;
2456 } else
2457 #endif
2458 return -1;
2460 if (in_size > max_framesize)
2461 max_framesize = in_size;
2462 sh_video->timer += frame_time;
2463 if (mpctx->sh_audio)
2464 mpctx->delay -= frame_time;
2465 // video_read_frame can change fps (e.g. for ASF video)
2466 vo_fps = sh_video->fps;
2467 int framedrop_type = check_framedrop(mpctx, frame_time);
2468 current_module = "decode video";
2470 void *decoded_frame;
2471 #ifdef CONFIG_DVDNAV
2472 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2473 if (in_size >= 0 && !decoded_frame)
2474 #endif
2475 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2476 sh_video->pts);
2477 #ifdef CONFIG_DVDNAV
2478 // Save last still frame for future display
2479 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2480 #endif
2481 if (decoded_frame) {
2482 current_module = "filter video";
2483 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2484 if (!video_out->config_ok)
2485 break;
2488 return frame_time;
2491 static void determine_frame_pts(struct MPContext *mpctx)
2493 struct sh_video *sh_video = mpctx->sh_video;
2494 struct MPOpts *opts = &mpctx->opts;
2496 if (opts->user_pts_assoc_mode) {
2497 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2498 } else if (sh_video->pts_assoc_mode == 0) {
2499 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2500 sh_video->pts_assoc_mode = 1;
2501 else
2502 sh_video->pts_assoc_mode = 2;
2503 } else {
2504 int probcount1 = sh_video->num_reordered_pts_problems;
2505 int probcount2 = sh_video->num_sorted_pts_problems;
2506 if (sh_video->pts_assoc_mode == 2) {
2507 int tmp = probcount1;
2508 probcount1 = probcount2;
2509 probcount2 = tmp;
2511 if (probcount1 >= probcount2 * 1.5 + 2) {
2512 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2513 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2514 "%d.\n", sh_video->pts_assoc_mode);
2517 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2518 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2521 static double update_video(struct MPContext *mpctx)
2523 struct sh_video *sh_video = mpctx->sh_video;
2524 struct vo *video_out = mpctx->video_out;
2525 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2526 mpctx->osd); // hack for vf_expand
2527 if (!mpctx->opts.correct_pts)
2528 return update_video_nocorrect_pts(mpctx);
2530 double pts;
2532 bool hit_eof = false;
2533 while (!video_out->frame_loaded) {
2534 current_module = "filter_video";
2535 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2536 break;
2537 // XXX Time used in this call is not counted in any performance
2538 // timer now, OSD time is not updated correctly for filter-added frames
2539 if (vf_output_queued_frame(sh_video->vfilter))
2540 continue;
2541 if (hit_eof)
2542 return -1;
2543 unsigned char *packet = NULL;
2544 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2545 if (pts != MP_NOPTS_VALUE)
2546 pts += mpctx->video_offset;
2547 if (in_size < 0) {
2548 // try to extract last frames in case of decoder lag
2549 in_size = 0;
2550 pts = MP_NOPTS_VALUE;
2551 hit_eof = true;
2553 if (in_size > max_framesize)
2554 max_framesize = in_size;
2555 current_module = "decode video";
2556 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2557 void *decoded_frame = decode_video(sh_video, packet, in_size,
2558 framedrop_type, pts);
2559 if (decoded_frame) {
2560 determine_frame_pts(mpctx);
2561 current_module = "filter video";
2562 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2563 if (!video_out->config_ok)
2564 break; // We'd likely hang in this loop otherwise
2568 pts = video_out->next_pts;
2569 if (pts == MP_NOPTS_VALUE) {
2570 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2571 // Try to use decoder pts from before filters
2572 pts = sh_video->pts;
2573 if (pts == MP_NOPTS_VALUE)
2574 pts = sh_video->last_pts;
2576 sh_video->pts = pts;
2577 if (sh_video->last_pts == MP_NOPTS_VALUE)
2578 sh_video->last_pts = sh_video->pts;
2579 else if (sh_video->last_pts > sh_video->pts) {
2580 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2581 sh_video->pts, sh_video->last_pts);
2582 /* If the difference in pts is small treat it as jitter around the
2583 * right value (possibly caused by incorrect timestamp ordering) and
2584 * just show this frame immediately after the last one.
2585 * Treat bigger differences as timestamp resets and start counting
2586 * timing of later frames from the position of this one. */
2587 if (sh_video->last_pts - sh_video->pts > 0.5)
2588 sh_video->last_pts = sh_video->pts;
2589 else
2590 sh_video->pts = sh_video->last_pts;
2592 double frame_time = sh_video->pts - sh_video->last_pts;
2593 sh_video->last_pts = sh_video->pts;
2594 sh_video->timer += frame_time;
2595 if (mpctx->sh_audio)
2596 mpctx->delay -= frame_time;
2597 return frame_time;
2600 void pause_player(struct MPContext *mpctx)
2602 if (mpctx->paused)
2603 return;
2604 mpctx->paused = 1;
2605 mpctx->step_frames = 0;
2606 mpctx->time_frame -= get_relative_time(mpctx);
2608 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2609 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2611 if (mpctx->audio_out && mpctx->sh_audio)
2612 mpctx->audio_out->pause(); // pause audio, keep data if possible
2615 void unpause_player(struct MPContext *mpctx)
2617 if (!mpctx->paused)
2618 return;
2619 mpctx->paused = 0;
2621 if (mpctx->audio_out && mpctx->sh_audio)
2622 mpctx->audio_out->resume(); // resume audio
2623 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2624 && !mpctx->step_frames)
2625 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2626 (void)get_relative_time(mpctx); // ignore time that passed during pause
2629 void add_step_frame(struct MPContext *mpctx)
2631 mpctx->step_frames++;
2632 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2633 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2634 unpause_player(mpctx);
2637 static void pause_loop(struct MPContext *mpctx)
2639 mp_cmd_t* cmd;
2640 if (!quiet) {
2641 // Small hack to display the pause message on the OSD line.
2642 // The pause string is: "\n == PAUSE == \r" so we need to
2643 // take the first and the last char out
2644 if (term_osd && !mpctx->sh_video) {
2645 char msg[128] = _("\n ===== PAUSE =====\r");
2646 int mlen = strlen(msg);
2647 msg[mlen-1] = '\0';
2648 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2649 update_osd_msg(mpctx);
2650 } else
2651 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2652 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2655 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2656 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2657 if (cmd) {
2658 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2659 run_command(mpctx, cmd);
2660 mp_cmd_free(cmd);
2661 continue;
2663 if (mpctx->sh_video && mpctx->video_out)
2664 vo_check_events(mpctx->video_out);
2665 #ifdef CONFIG_MENU
2666 if (vf_menu)
2667 vf_menu_pause_update(vf_menu);
2668 #endif
2669 usec_sleep(20000);
2670 update_osd_msg(mpctx);
2671 int hack = vo_osd_changed(0);
2672 vo_osd_changed(hack);
2673 if (hack)
2674 break;
2679 // Find the right mute status and record position for new file position
2680 static void edl_seek_reset(MPContext *mpctx)
2682 mpctx->edl_muted = 0;
2683 next_edl_record = edl_records;
2685 while (next_edl_record) {
2686 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2687 break;
2689 if (next_edl_record->action == EDL_MUTE)
2690 mpctx->edl_muted = !mpctx->edl_muted;
2691 next_edl_record = next_edl_record->next;
2693 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2694 mixer_mute(&mpctx->mixer);
2698 // Execute EDL command for the current position if one exists
2699 static void edl_update(MPContext *mpctx)
2701 if (!next_edl_record)
2702 return;
2704 if (!mpctx->sh_video) {
2705 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2706 free_edl(edl_records);
2707 next_edl_record = NULL;
2708 edl_records = NULL;
2709 return;
2712 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2713 if (next_edl_record->action == EDL_SKIP) {
2714 mpctx->osd_function = OSD_FFW;
2715 mpctx->abs_seek_pos = 0;
2716 mpctx->rel_seek_secs = next_edl_record->length_sec;
2717 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2718 "[%f], length [%f]\n", next_edl_record->start_sec,
2719 next_edl_record->stop_sec, next_edl_record->length_sec);
2721 else if (next_edl_record->action == EDL_MUTE) {
2722 mpctx->edl_muted = !mpctx->edl_muted;
2723 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2724 mixer_mute(&mpctx->mixer);
2725 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2726 next_edl_record->start_sec );
2728 next_edl_record = next_edl_record->next;
2732 static void reinit_decoders(struct MPContext *mpctx)
2734 reinit_video_chain(mpctx);
2735 reinit_audio_chain(mpctx);
2736 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2739 static void seek_reset(struct MPContext *mpctx)
2741 if (mpctx->sh_video) {
2742 current_module = "seek_video_reset";
2743 resync_video_stream(mpctx->sh_video);
2744 mpctx->sh_video->timer = 0;
2745 vo_seek_reset(mpctx->video_out);
2746 mpctx->sh_video->timer = 0;
2747 mpctx->sh_video->num_buffered_pts = 0;
2748 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2749 mpctx->delay = 0;
2750 mpctx->time_frame = 0;
2751 mpctx->update_video_immediately = true;
2752 // Not all demuxers set d_video->pts during seek, so this value
2753 // (which is used by at least vobsub and edl code below) may
2754 // be completely wrong (probably 0).
2755 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2756 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2757 mpctx->sh_video->pts, mpctx->video_offset,
2758 mpctx->d_sub, 1);
2759 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2762 if (mpctx->sh_audio) {
2763 current_module = "seek_audio_reset";
2764 resync_audio_stream(mpctx->sh_audio);
2765 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2766 mpctx->sh_audio->a_buffer_len = 0;
2767 mpctx->sh_audio->a_out_buffer_len = 0;
2768 if (!mpctx->sh_video)
2769 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2770 mpctx->video_offset, mpctx->d_sub, 1);
2773 if (vo_vobsub && mpctx->sh_video) {
2774 current_module = "seek_vobsub_reset";
2775 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2778 edl_seek_reset(mpctx);
2780 mpctx->total_avsync_change = 0;
2781 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2782 drop_frame_cnt = 0;
2784 current_module = NULL;
2787 static bool timeline_set_part(struct MPContext *mpctx, int i)
2789 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2790 struct timeline_part *n = mpctx->timeline + i;
2791 mpctx->timeline_part = i;
2792 mpctx->video_offset = n->start - n->source_start;
2793 if (n->source == p->source)
2794 return false;
2795 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2796 mpctx->demuxer = n->source->demuxer;
2797 mpctx->d_video = mpctx->demuxer->video;
2798 mpctx->d_audio = mpctx->demuxer->audio;
2799 mpctx->d_sub = mpctx->demuxer->sub;
2800 mpctx->sh_video = mpctx->d_video->sh;
2801 mpctx->sh_audio = mpctx->d_audio->sh;
2802 return true;
2805 // Given pts, switch playback to the corresponding part.
2806 // Return offset within that part.
2807 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2808 bool *need_reset)
2810 if (pts < 0)
2811 pts = 0;
2812 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2813 struct timeline_part *p = mpctx->timeline + i;
2814 if (pts < (p+1)->start) {
2815 *need_reset = timeline_set_part(mpctx, i);
2816 return pts - p->start + p->source_start;
2819 return -1;
2823 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2824 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2825 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2826 static int seek(MPContext *mpctx, double amount, int style)
2828 current_module = "seek";
2829 if (mpctx->stop_play == AT_END_OF_FILE)
2830 mpctx->stop_play = KEEP_PLAYING;
2831 if (style & SEEK_FACTOR
2832 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2833 || amount < 0)
2834 mpctx->last_chapter_seek = -1;
2835 if (mpctx->timeline && style & SEEK_FACTOR) {
2836 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2837 style &= ~SEEK_FACTOR;
2839 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2840 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2841 style |= SEEK_ABSOLUTE;
2842 if (amount > 0)
2843 style |= SEEK_FORWARD;
2844 else
2845 style |= SEEK_BACKWARD;
2846 amount += mpctx->sh_video->pts;
2849 /* At least the liba52 decoder wants to read from the input stream
2850 * during initialization, so reinit must be done after the demux_seek()
2851 * call that clears possible stream EOF. */
2852 bool need_reset = false;
2853 if (mpctx->timeline) {
2854 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2855 if (amount == -1) {
2856 mpctx->stop_play = AT_END_OF_FILE;
2857 // Clear audio from current position
2858 if (mpctx->sh_audio) {
2859 mpctx->audio_out->reset();
2860 mpctx->sh_audio->a_buffer_len = 0;
2861 mpctx->sh_audio->a_out_buffer_len = 0;
2863 return -1;
2866 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2867 if (need_reset)
2868 reinit_decoders(mpctx);
2869 if (seekresult == 0)
2870 return -1;
2872 seek_reset(mpctx);
2873 return 0;
2876 // -2 is no chapters, -1 is before first chapter
2877 int get_current_chapter(struct MPContext *mpctx)
2879 if (!mpctx->chapters || !mpctx->sh_video)
2880 return FFMAX(mpctx->last_chapter_seek,
2881 demuxer_get_current_chapter(mpctx->demuxer));
2883 int i;
2884 double current_pts = mpctx->sh_video->pts;
2885 for (i = 1; i < mpctx->num_chapters; i++)
2886 if (current_pts < mpctx->chapters[i].start)
2887 break;
2888 return FFMAX(mpctx->last_chapter_seek, i - 1);
2891 // currently returns a string allocated with malloc, not talloc
2892 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2894 if (!mpctx->chapters || !mpctx->sh_video)
2895 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2896 return strdup(mpctx->chapters[chapter].name);
2899 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2900 char **chapter_name)
2902 mpctx->last_chapter_seek = -1;
2903 if (!mpctx->chapters || !mpctx->sh_video) {
2904 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2905 chapter_name);
2906 if (res >= 0) {
2907 if (*seek_pts == -1)
2908 seek_reset(mpctx);
2909 else {
2910 mpctx->last_chapter_seek = res;
2911 mpctx->last_chapter_pts = *seek_pts;
2914 return res;
2917 if (chapter >= mpctx->num_chapters)
2918 return -1;
2919 if (chapter < 0)
2920 chapter = 0;
2921 *seek_pts = mpctx->chapters[chapter].start;
2922 mpctx->last_chapter_seek = chapter;
2923 mpctx->last_chapter_pts = *seek_pts;
2924 if (chapter_name)
2925 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2926 return chapter;
2929 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2930 struct content_source *sources,
2931 int num_sources,
2932 unsigned char uid_map[][16])
2934 int num_filenames = 0;
2935 char **filenames = NULL;
2936 if (num_sources > 1) {
2937 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2938 "other sources.\n");
2939 if (mpctx->stream->type != STREAMTYPE_FILE) {
2940 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2941 "normal disk file. Will not search for related files.\n");
2942 } else {
2943 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2944 "same directory to find referenced sources.\n");
2945 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2946 &num_filenames);
2950 int num_left = num_sources - 1;
2951 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2952 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2953 filename_recode(filenames[i]));
2954 int format;
2955 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2956 if (!s)
2957 continue;
2958 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2959 mpctx->opts.audio_id,
2960 mpctx->opts.video_id,
2961 mpctx->opts.sub_id, filenames[i]);
2962 if (!d) {
2963 free_stream(s);
2964 continue;
2966 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2967 for (int i = 1; i < num_sources; i++) {
2968 if (sources[i].demuxer)
2969 continue;
2970 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2971 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2972 i, filename_recode(d->filename));
2973 sources[i].stream = s;
2974 sources[i].demuxer = d;
2975 num_left--;
2976 goto match;
2980 free_demuxer(d);
2981 free_stream(s);
2982 continue;
2983 match:
2986 talloc_free(filenames);
2987 if (num_left) {
2988 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2989 "There will be parts MISSING from the video!\n");
2990 for (int i = 1, j = 1; i < num_sources; i++)
2991 if (sources[i].demuxer) {
2992 sources[j] = sources[i];
2993 memcpy(uid_map[j], uid_map[i], 16);
2994 j++;
2997 return num_sources - num_left;
3000 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3002 if (!mpctx->opts.ordered_chapters) {
3003 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3004 "you have disabled support for them. Ignoring.\n");
3005 return;
3008 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3009 "edit timeline.\n");
3011 struct demuxer *demuxer = mpctx->demuxer;
3012 struct matroska_data *m = &demuxer->matroska_data;
3014 // +1 because sources/uid_map[0] is original file even if all chapters
3015 // actually use other sources and need separate entries
3016 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3017 m->num_ordered_chapters+1);
3018 sources[0].stream = mpctx->stream;
3019 sources[0].demuxer = mpctx->demuxer;
3020 unsigned char uid_map[m->num_ordered_chapters+1][16];
3021 int num_sources = 1;
3022 memcpy(uid_map[0], m->segment_uid, 16);
3024 for (int i = 0; i < m->num_ordered_chapters; i++) {
3025 struct matroska_chapter *c = m->ordered_chapters + i;
3026 if (!c->has_segment_uid)
3027 memcpy(c->segment_uid, m->segment_uid, 16);
3029 for (int j = 0; j < num_sources; j++)
3030 if (!memcmp(c->segment_uid, uid_map[j], 16))
3031 goto found1;
3032 memcpy(uid_map[num_sources], c->segment_uid, 16);
3033 sources[num_sources] = (struct content_source){};
3034 num_sources++;
3035 found1:
3039 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3040 uid_map);
3043 // +1 for terminating chapter with start time marking end of last real one
3044 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3045 m->num_ordered_chapters + 1);
3046 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3047 m->num_ordered_chapters);
3048 uint64_t starttime = 0;
3049 uint64_t missing_time = 0;
3050 int part_count = 0;
3051 int num_chapters = 0;
3052 uint64_t prev_part_offset = 0;
3053 for (int i = 0; i < m->num_ordered_chapters; i++) {
3054 struct matroska_chapter *c = m->ordered_chapters + i;
3056 int j;
3057 for (j = 0; j < num_sources; j++) {
3058 if (!memcmp(c->segment_uid, uid_map[j], 16))
3059 goto found2;
3061 missing_time += c->end - c->start;
3062 continue;
3063 found2:;
3064 chapters[num_chapters].start = starttime / 1000.;
3065 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3066 /* Only add a separate part if the time or file actually changes.
3067 * Matroska files have chapter divisions that are redundant from
3068 * timeline point of view because the same chapter structure is used
3069 * both to specify the timeline and for normal chapter information.
3070 * Removing a missing inserted external chapter can also cause this. */
3071 if (part_count == 0 || c->start != starttime + prev_part_offset
3072 || sources + j != timeline[part_count - 1].source) {
3073 timeline[part_count].source = sources + j;
3074 timeline[part_count].start = chapters[num_chapters].start;
3075 timeline[part_count].source_start = c->start / 1000.;
3076 prev_part_offset = c->start - starttime;
3077 part_count++;
3079 starttime += c->end - c->start;
3080 num_chapters++;
3082 timeline[part_count].start = starttime / 1000.;
3084 if (!part_count) {
3085 // None of the parts come from the file itself???
3086 talloc_free(sources);
3087 talloc_free(timeline);
3088 talloc_free(chapters);
3089 return;
3092 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3093 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3094 timeline[part_count].start);
3095 if (missing_time)
3096 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3097 "from the timeline!\n", missing_time / 1000.);
3098 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3099 for (int i = 0; i < num_sources; i++)
3100 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3101 filename_recode(sources[i].demuxer->filename));
3102 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3103 "source_start, source):\n");
3104 for (int i = 0; i < part_count; i++) {
3105 struct timeline_part *p = timeline + i;
3106 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3107 p->source_start, p->source - sources);
3109 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3110 mpctx->sources = sources;
3111 mpctx->num_sources = num_sources;
3112 mpctx->timeline = timeline;
3113 mpctx->num_timeline_parts = part_count;
3114 mpctx->num_chapters = num_chapters;
3115 mpctx->chapters = chapters;
3117 mpctx->timeline_part = 0;
3118 mpctx->demuxer = timeline[0].source->demuxer;
3122 static int read_keys(void *ctx, int fd)
3124 getch2(ctx);
3125 return mplayer_get_key(ctx, 0);
3129 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3130 * file for some tools to link against. */
3131 #ifndef DISABLE_MAIN
3132 int main(int argc,char* argv[]){
3135 char * mem_ptr;
3137 // movie info:
3139 /* Flag indicating whether MPlayer should exit without playing anything. */
3140 int opt_exit = 0;
3142 //float a_frame=0; // Audio
3144 int i;
3146 struct MPContext *mpctx = &(struct MPContext){
3147 .osd_function = OSD_PLAY,
3148 .begin_skip = MP_NOPTS_VALUE,
3149 .play_tree_step = 1,
3150 .global_sub_pos = -1,
3151 .set_of_sub_pos = -1,
3152 .file_format = DEMUXER_TYPE_UNKNOWN,
3153 .last_dvb_step = 1,
3156 InitTimer();
3157 srand(GetTimerMS());
3159 mp_msg_init();
3160 set_av_log_callback();
3162 #ifdef CONFIG_X11
3163 mpctx->x11_state = vo_x11_init_state();
3164 #endif
3165 struct MPOpts *opts = &mpctx->opts;
3166 set_default_mplayer_options(opts);
3167 // Create the config context and register the options
3168 mpctx->mconfig = m_config_new(opts, cfg_include);
3169 m_config_register_options(mpctx->mconfig,mplayer_opts);
3170 m_config_register_options(mpctx->mconfig, common_opts);
3171 mp_input_register_options(mpctx->mconfig);
3173 // Preparse the command line
3174 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3176 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3177 set_path_env();
3178 #endif
3180 #ifdef CONFIG_TV
3181 stream_tv_defaults.immediate = 1;
3182 #endif
3184 parse_cfgfiles(mpctx, mpctx->mconfig);
3186 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3187 if(mpctx->playtree == NULL)
3188 opt_exit = 1;
3189 else {
3190 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3191 if(mpctx->playtree) {
3192 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3193 if(mpctx->playtree_iter) {
3194 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3195 play_tree_iter_free(mpctx->playtree_iter);
3196 mpctx->playtree_iter = NULL;
3198 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3202 mpctx->key_fifo = mp_fifo_create(opts);
3204 print_version("MPlayer");
3206 #if defined(__MINGW32__) || defined(__CYGWIN__)
3208 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3209 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3210 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3211 if (kernel32) {
3212 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3213 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3215 if (setDEP) setDEP(3);
3216 if (setDllDir) setDllDir("");
3218 // stop Windows from showing all kinds of annoying error dialogs
3219 SetErrorMode(0x8003);
3220 // request 1ms timer resolution
3221 timeBeginPeriod(1);
3222 #endif
3224 #ifdef CONFIG_PRIORITY
3225 set_priority();
3226 #endif
3228 if (codec_path)
3229 set_codec_path(codec_path);
3231 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3232 list_video_out();
3233 opt_exit = 1;
3236 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3237 list_audio_out();
3238 opt_exit = 1;
3241 /* Check codecs.conf. */
3242 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3243 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3244 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3245 if(!parse_codec_cfg(NULL)){
3246 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3248 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3251 free( mem_ptr ); // release the buffer created by get_path()
3254 #if 0
3255 if(video_codec_list){
3256 int i;
3257 video_codec=video_codec_list[0];
3258 for(i=0;video_codec_list[i];i++)
3259 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
3261 #endif
3262 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3263 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3264 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3265 list_codecs(1);
3266 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3267 opt_exit = 1;
3269 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3270 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3271 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3272 list_codecs(0);
3273 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3274 opt_exit = 1;
3276 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3277 vfm_help();
3278 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3279 opt_exit = 1;
3281 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3282 afm_help();
3283 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3284 opt_exit = 1;
3286 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3287 af_help();
3288 printf("\n");
3289 opt_exit = 1;
3291 #ifdef CONFIG_X11
3292 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3293 fstype_help();
3294 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3295 opt_exit = 1;
3297 #endif
3298 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3299 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3300 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3301 demuxer_help();
3302 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3303 opt_exit = 1;
3305 if(list_properties) {
3306 property_print_help();
3307 opt_exit = 1;
3310 if(opt_exit)
3311 exit_player(mpctx, EXIT_NONE);
3313 if(!mpctx->filename && !player_idle_mode){
3314 // no file/vcd/dvd -> show HELP:
3315 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3316 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3319 /* Display what configure line was used */
3320 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3322 // Many users forget to include command line in bugreports...
3323 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3324 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3325 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3326 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3329 //------ load global data first ------
3331 mpctx->osd = osd_create();
3333 // check font
3334 #ifdef CONFIG_FREETYPE
3335 init_freetype();
3336 #endif
3337 #ifdef CONFIG_FONTCONFIG
3338 if(font_fontconfig <= 0)
3340 #endif
3341 #ifdef CONFIG_BITMAP_FONT
3342 if(font_name){
3343 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3344 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3345 filename_recode(font_name));
3346 } else {
3347 // try default:
3348 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3349 free(mem_ptr); // release the buffer created by get_path()
3350 if(!vo_font)
3351 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3353 if (sub_font_name)
3354 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3355 else
3356 mpctx->osd->sub_font = vo_font;
3357 #endif
3358 #ifdef CONFIG_FONTCONFIG
3360 #endif
3362 #ifdef CONFIG_ASS
3363 ass_library = ass_init();
3364 #endif
3366 #ifdef HAVE_RTC
3367 if(!nortc)
3369 // seteuid(0); /* Can't hurt to try to get root here */
3370 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3371 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3372 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3373 else {
3374 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3376 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3377 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3378 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3379 close (rtc_fd);
3380 rtc_fd = -1;
3381 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3382 /* variable only by the root */
3383 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3384 close (rtc_fd);
3385 rtc_fd = -1;
3386 } else
3387 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3390 if(rtc_fd<0)
3391 #endif /* HAVE_RTC */
3392 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3393 softsleep?"software":timer_name);
3395 #ifdef HAVE_TERMCAP
3396 load_termcap(NULL); // load key-codes
3397 #endif
3399 // ========== Init keyboard FIFO (connection to libvo) ============
3401 // Init input system
3402 current_module = "init_input";
3403 mpctx->input = mp_input_init(&opts->input);
3404 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3405 if(slave_mode)
3406 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3407 else if(!noconsolecontrols)
3408 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3409 // Set the libstream interrupt callback
3410 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3412 #ifdef CONFIG_MENU
3413 if(use_menu) {
3414 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3415 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3416 else {
3417 menu_cfg = get_path("menu.conf");
3418 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3419 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3420 else {
3421 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3422 MPLAYER_CONFDIR "/menu.conf"))
3423 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3424 else {
3425 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3426 use_menu = 0;
3431 #endif
3433 current_module = NULL;
3435 /// Catch signals
3436 #ifndef __MINGW32__
3437 signal(SIGCHLD,child_sighandler);
3438 #endif
3440 #ifdef CONFIG_CRASH_DEBUG
3441 prog_path = argv[0];
3442 #endif
3443 //========= Catch terminate signals: ================
3444 // terminate requests:
3445 signal(SIGTERM,exit_sighandler); // kill
3446 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3448 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3450 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3451 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3452 #ifdef CONFIG_SIGHANDLER
3453 // fatal errors:
3454 signal(SIGBUS,exit_sighandler); // bus error
3455 signal(SIGSEGV,exit_sighandler); // segfault
3456 signal(SIGILL,exit_sighandler); // illegal instruction
3457 signal(SIGFPE,exit_sighandler); // floating point exc.
3458 signal(SIGABRT,exit_sighandler); // abort()
3459 #ifdef CONFIG_CRASH_DEBUG
3460 if (crash_debug)
3461 signal(SIGTRAP,exit_sighandler);
3462 #endif
3463 #endif
3465 // ******************* Now, let's see the per-file stuff ********************
3467 play_next_file:
3469 // init global sub numbers
3470 mpctx->global_sub_size = 0;
3471 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3473 if (mpctx->filename) {
3474 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3475 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3476 load_per_file_config (mpctx->mconfig, mpctx->filename);
3479 if (opts->video_driver_list)
3480 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3481 if (opts->audio_driver_list)
3482 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3484 // We must enable getch2 here to be able to interrupt network connection
3485 // or cache filling
3486 if(!noconsolecontrols && !slave_mode){
3487 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3488 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3489 else
3490 getch2_enable(); // prepare stdin for hotkeys...
3491 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3492 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3495 // =================== GUI idle loop (STOP state) ===========================
3496 while (player_idle_mode && !mpctx->filename) {
3497 play_tree_t * entry = NULL;
3498 mp_cmd_t * cmd;
3499 if (mpctx->video_out && mpctx->video_out->config_ok)
3500 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3501 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3502 if (mpctx->video_out)
3503 vo_check_events(mpctx->video_out);
3504 usec_sleep(20000);
3506 switch (cmd->id) {
3507 case MP_CMD_LOADFILE:
3508 // prepare a tree entry with the new filename
3509 entry = play_tree_new();
3510 play_tree_add_file(entry, cmd->args[0].v.s);
3511 // The entry is added to the main playtree after the switch().
3512 break;
3513 case MP_CMD_LOADLIST:
3514 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3515 break;
3516 case MP_CMD_QUIT:
3517 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3518 break;
3519 case MP_CMD_VO_FULLSCREEN:
3520 case MP_CMD_GET_PROPERTY:
3521 case MP_CMD_SET_PROPERTY:
3522 case MP_CMD_STEP_PROPERTY:
3523 run_command(mpctx, cmd);
3524 break;
3527 mp_cmd_free(cmd);
3529 if (entry) { // user entered a command that gave a valid entry
3530 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3531 play_tree_free_list(mpctx->playtree->child, 1);
3532 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3534 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3536 play_tree_set_child(mpctx->playtree, entry);
3538 /* Make iterator start at the top the of tree. */
3539 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3540 if (!mpctx->playtree_iter) continue;
3542 // find the first real item in the tree
3543 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3544 // no items!
3545 play_tree_iter_free(mpctx->playtree_iter);
3546 mpctx->playtree_iter = NULL;
3547 continue; // wait for next command
3549 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3552 //---------------------------------------------------------------------------
3554 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3555 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3557 if (mpctx->filename) {
3558 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3559 filename_recode(mpctx->filename));
3560 if(use_filename_title && vo_wintitle == NULL)
3561 vo_wintitle = strdup(mp_basename2(mpctx->filename));
3564 if (edl_filename) {
3565 if (edl_records) free_edl(edl_records);
3566 next_edl_record = edl_records = edl_parse_file();
3568 if (edl_output_filename) {
3569 if (edl_fd) fclose(edl_fd);
3570 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3572 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3573 filename_recode(edl_output_filename));
3577 //==================== Open VOB-Sub ============================
3579 current_module="vobsub";
3580 if (vobsub_name){
3581 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3582 if(vo_vobsub==NULL)
3583 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3584 filename_recode(vobsub_name));
3585 } else if (sub_auto && mpctx->filename){
3586 /* try to autodetect vobsub from movie filename ::atmos */
3587 char *buf = strdup(mpctx->filename), *psub;
3588 char *pdot = strrchr(buf, '.');
3589 char *pslash = strrchr(buf, '/');
3590 #if defined(__MINGW32__) || defined(__CYGWIN__)
3591 if (!pslash) pslash = strrchr(buf, '\\');
3592 #endif
3593 if (pdot && (!pslash || pdot > pslash))
3594 *pdot = '\0';
3595 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3596 /* try from ~/.mplayer/sub */
3597 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3598 char *bname;
3599 int l;
3600 bname = strrchr(buf,'/');
3601 #if defined(__MINGW32__) || defined(__CYGWIN__)
3602 if(!bname) bname = strrchr(buf,'\\');
3603 #endif
3604 if(bname) bname++;
3605 else bname = buf;
3606 l = strlen(psub) + strlen(bname) + 1;
3607 psub = realloc(psub,l);
3608 strcat(psub,bname);
3609 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3610 free(psub);
3612 free(buf);
3614 if(vo_vobsub){
3615 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3616 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3617 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3619 // setup global sub numbering
3620 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3623 //============ Open & Sync STREAM --- fork cache2 ====================
3625 mpctx->stream=NULL;
3626 mpctx->demuxer=NULL;
3627 if (mpctx->d_audio) {
3628 //free_demuxer_stream(mpctx->d_audio);
3629 mpctx->d_audio=NULL;
3631 if (mpctx->d_video) {
3632 //free_demuxer_stream(d_video);
3633 mpctx->d_video=NULL;
3635 mpctx->sh_audio=NULL;
3636 mpctx->sh_video=NULL;
3638 current_module="open_stream";
3639 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3640 if(!mpctx->stream) { // error...
3641 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3642 goto goto_next_file;
3644 mpctx->initialized_flags|=INITIALIZED_STREAM;
3646 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3647 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3648 "playlist support will not be used automatically.\n"
3649 "MPlayer's playlist code is unsafe and should only be used with "
3650 "trusted sources.\nPlayback will probably fail.\n\n");
3651 #if 0
3652 play_tree_t* entry;
3653 // Handle playlist
3654 current_module="handle_playlist";
3655 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3656 filename_recode(mpctx->filename));
3657 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3658 mpctx->eof=playtree_add_playlist(mpctx, entry);
3659 goto goto_next_file;
3660 #endif
3662 mpctx->stream->start_pos+=seek_to_byte;
3664 if(stream_dump_type==5){
3665 unsigned char buf[4096];
3666 int len;
3667 FILE *f;
3668 current_module="dumpstream";
3669 stream_reset(mpctx->stream);
3670 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3671 f=fopen(stream_dump_name,"wb");
3672 if(!f){
3673 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3674 exit_player(mpctx, EXIT_ERROR);
3676 if (opts->chapterrange[0] > 1) {
3677 int chapter = opts->chapterrange[0] - 1;
3678 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3680 while(!mpctx->stream->eof && !async_quit_request){
3681 len=stream_read(mpctx->stream,buf,4096);
3682 if(len>0) {
3683 if(fwrite(buf,len,1,f) != 1) {
3684 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3685 exit_player(mpctx, EXIT_ERROR);
3688 if (opts->chapterrange[1] > 0) {
3689 int chapter = -1;
3690 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3691 &chapter) == STREAM_OK
3692 && chapter + 1 > opts->chapterrange[1])
3693 break;
3696 if(fclose(f)) {
3697 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3698 exit_player(mpctx, EXIT_ERROR);
3700 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3701 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3704 #ifdef CONFIG_DVDREAD
3705 if(mpctx->stream->type==STREAMTYPE_DVD){
3706 current_module="dvd lang->id";
3707 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3708 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3709 // setup global sub numbering
3710 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3711 current_module=NULL;
3713 #endif
3715 #ifdef CONFIG_DVDNAV
3716 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3717 current_module="dvdnav lang->id";
3718 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3719 dvdsub_lang_id = -3;
3720 if(opts->sub_lang && opts->sub_id==-1)
3721 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3722 // setup global sub numbering
3723 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3724 current_module=NULL;
3726 #endif
3728 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3729 goto_enable_cache:
3730 if(stream_cache_size>0){
3731 int res;
3732 current_module="enable_cache";
3733 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3734 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3735 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3736 if(res == 0)
3737 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3740 //============ Open DEMUXERS --- DETECT file type =======================
3741 current_module="demux_open";
3743 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3745 // HACK to get MOV Reference Files working
3747 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3749 unsigned char* playlist_entry;
3750 play_tree_t *list = NULL, *entry = NULL;
3752 current_module="handle_demux_playlist";
3753 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3755 char *temp, *bname;
3757 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3758 filename_recode(playlist_entry));
3760 bname=mp_basename(playlist_entry);
3761 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3762 continue;
3764 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3765 continue;
3767 entry = play_tree_new();
3769 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3771 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3772 if (temp)
3774 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3775 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3776 strcat(temp, playlist_entry);
3777 if (!strcmp(temp, mpctx->filename)) {
3778 free(temp);
3779 continue;
3781 play_tree_add_file(entry,temp);
3782 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3783 free(temp);
3786 else
3787 play_tree_add_file(entry,playlist_entry);
3789 if(!list)
3790 list = entry;
3791 else
3792 play_tree_append_entry(list,entry);
3794 free_demuxer(mpctx->demuxer);
3795 mpctx->demuxer = NULL;
3797 if (list)
3799 entry = play_tree_new();
3800 play_tree_set_child(entry,list);
3801 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3802 goto goto_next_file;
3806 if(!mpctx->demuxer)
3807 goto goto_next_file;
3809 if (mpctx->demuxer->matroska_data.ordered_chapters)
3810 build_ordered_chapter_timeline(mpctx);
3812 if (!mpctx->sources) {
3813 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3814 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3815 .demuxer = mpctx->demuxer};
3816 mpctx->num_sources = 1;
3819 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3821 #ifdef CONFIG_ASS
3822 if (opts->ass_enabled && ass_library) {
3823 for (int j = 0; j < mpctx->num_sources; j++) {
3824 struct demuxer *d = mpctx->sources[j].demuxer;
3825 for (int i = 0; i < d->num_attachments; i++) {
3826 struct demux_attachment *att = d->attachments + i;
3827 if (use_embedded_fonts && attachment_is_font(att))
3828 ass_add_font(ass_library, att->name, att->data, att->data_size);
3832 #endif
3834 current_module="demux_open2";
3836 //file_format=demuxer->file_format;
3838 mpctx->d_audio=mpctx->demuxer->audio;
3839 mpctx->d_video=mpctx->demuxer->video;
3840 mpctx->d_sub=mpctx->demuxer->sub;
3842 if (ts_prog) {
3843 int tmp = ts_prog;
3844 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3846 // select audio stream
3847 if (mpctx->num_sources)
3848 for (int i = 0; i < mpctx->num_sources; i++)
3849 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3850 opts->audio_lang);
3851 else
3852 select_audio(mpctx->demuxer, opts->audio_id, opts->audio_lang);
3854 // DUMP STREAMS:
3855 if((stream_dump_type)&&(stream_dump_type<4)){
3856 FILE *f;
3857 demux_stream_t *ds=NULL;
3858 current_module="dump";
3859 // select stream to dump
3860 switch(stream_dump_type){
3861 case 1: ds=mpctx->d_audio;break;
3862 case 2: ds=mpctx->d_video;break;
3863 case 3: ds=mpctx->d_sub;break;
3865 if(!ds){
3866 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3867 exit_player(mpctx, EXIT_ERROR);
3869 // disable other streams:
3870 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3871 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3872 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3873 // let's dump it!
3874 f=fopen(stream_dump_name,"wb");
3875 if(!f){
3876 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3877 exit_player(mpctx, EXIT_ERROR);
3879 while(!ds->eof){
3880 unsigned char* start;
3881 int in_size=ds_get_packet(ds,&start);
3882 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3883 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3884 if(in_size>0) fwrite(start,in_size,1,f);
3885 if (opts->chapterrange[1] > 0) {
3886 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3887 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3888 break;
3891 fclose(f);
3892 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3893 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3896 mpctx->sh_audio=mpctx->d_audio->sh;
3897 mpctx->sh_video=mpctx->d_video->sh;
3899 if(mpctx->sh_video){
3901 current_module="video_read_properties";
3902 if(!video_read_properties(mpctx->sh_video)) {
3903 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3904 mpctx->sh_video=mpctx->d_video->sh=NULL;
3905 } else {
3906 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3907 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3908 mpctx->sh_video->fps,mpctx->sh_video->frametime
3911 /* need to set fps here for output encoders to pick it up in their init */
3912 if(force_fps){
3913 mpctx->sh_video->fps=force_fps;
3914 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3916 vo_fps = mpctx->sh_video->fps;
3918 if(!mpctx->sh_video->fps && !force_fps){
3919 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3920 mpctx->opts.correct_pts = 1;
3926 if(!mpctx->sh_video && !mpctx->sh_audio){
3927 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3928 #ifdef CONFIG_DVBIN
3929 if(mpctx->stream->type == STREAMTYPE_DVB)
3931 int dir;
3932 int v = mpctx->last_dvb_step;
3933 if(v > 0)
3934 dir = DVB_CHANNEL_HIGHER;
3935 else
3936 dir = DVB_CHANNEL_LOWER;
3938 if(dvb_step_channel(mpctx->stream, dir)) {
3939 mpctx->stop_play = PT_NEXT_ENTRY;
3940 mpctx->dvbin_reopen = 1;
3943 #endif
3944 goto goto_next_file; // exit_player(_("Fatal error"));
3947 /* display clip info */
3948 demux_info_print(mpctx->demuxer);
3950 //================== Read SUBTITLES (DVD & TEXT) ==========================
3951 if(vo_spudec==NULL &&
3952 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3953 init_vo_spudec(mpctx);
3956 // after reading video params we should load subtitles because
3957 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3958 // check .sub
3959 current_module="read_subtitles_file";
3960 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3961 if(sub_name){
3962 for (i = 0; sub_name[i] != NULL; ++i)
3963 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3965 if(sub_auto) { // auto load sub file ...
3966 char *psub = get_path( "sub/" );
3967 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3968 int i = 0;
3969 free(psub); // release the buffer created by get_path() above
3970 while (tmp[i]) {
3971 add_subtitles(mpctx, tmp[i], sub_fps, 1);
3972 free(tmp[i++]);
3974 free(tmp);
3976 if (mpctx->set_of_sub_size > 0)
3977 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
3979 if (select_subtitle(mpctx)) {
3980 if(subdata)
3981 switch (stream_dump_type) {
3982 case 3: list_sub_file(subdata); break;
3983 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3984 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3985 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3986 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3987 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3991 print_file_properties(mpctx, mpctx->filename);
3993 if(!mpctx->sh_video) goto main; // audio-only
3995 if(!reinit_video_chain(mpctx)) {
3996 if(!mpctx->sh_video){
3997 if(!mpctx->sh_audio) goto goto_next_file;
3998 goto main; // exit_player(_("Fatal error"));
4002 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4003 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4005 #ifdef CONFIG_FREETYPE
4006 force_load_font = 1;
4007 #endif
4009 //================== MAIN: ==========================
4010 main:
4011 current_module="main";
4013 if(playing_msg) {
4014 char* msg = property_expand_string(mpctx, playing_msg);
4015 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4016 free(msg);
4020 // Disable the term OSD in verbose mode
4021 if(verbose) term_osd = 0;
4024 //int frame_corr_num=0; //
4025 //float v_frame=0; // Video
4026 //float num_frames=0; // number of frames played
4028 int frame_time_remaining=0; // flag
4029 int blit_frame=0;
4031 // Make sure old OSD does not stay around,
4032 // e.g. with -fixed-vo and same-resolution files
4033 clear_osd_msgs();
4034 update_osd_msg(mpctx);
4036 //================ SETUP AUDIO ==========================
4038 if(mpctx->sh_audio){
4039 reinit_audio_chain(mpctx);
4040 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4041 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4044 current_module="av_init";
4046 if(mpctx->sh_video){
4047 mpctx->sh_video->timer=0;
4048 if (! ignore_start)
4049 audio_delay += mpctx->sh_video->stream_delay;
4051 if(mpctx->sh_audio){
4052 if (start_volume >= 0)
4053 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4054 if (! ignore_start)
4055 audio_delay -= mpctx->sh_audio->stream_delay;
4056 mpctx->delay=-audio_delay;
4059 if(!mpctx->sh_audio){
4060 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4061 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4062 ds_free_packs(mpctx->d_audio); // free buffered chunks
4063 //mpctx->d_audio->id=-2; // do not read audio chunks
4064 //uninit_player(mpctx, INITIALIZED_AO); // close device
4066 if(!mpctx->sh_video){
4067 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4068 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4069 ds_free_packs(mpctx->d_video);
4070 mpctx->d_video->id=-2;
4071 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4074 if (!mpctx->sh_video && !mpctx->sh_audio)
4075 goto goto_next_file;
4077 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4078 if(force_fps && mpctx->sh_video){
4079 vo_fps = mpctx->sh_video->fps=force_fps;
4080 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4081 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4084 mp_input_set_section(mpctx->input, NULL);
4085 //TODO: add desired (stream-based) sections here
4086 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4087 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4089 //==================== START PLAYING =======================
4091 if(opts->loop_times>1) opts->loop_times--; else
4092 if(opts->loop_times==1) opts->loop_times = -1;
4094 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4096 total_time_usage_start=GetTimer();
4097 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4098 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4099 play_n_frames=play_n_frames_mf;
4101 if(play_n_frames==0){
4102 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4105 // If there's a timeline force an absolute seek to initialize state
4106 if (seek_to_sec || mpctx->timeline) {
4107 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4108 end_at.pos += seek_to_sec;
4110 if (opts->chapterrange[0] > 0) {
4111 double pts;
4112 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4113 && pts > -1.0)
4114 seek(mpctx, pts, SEEK_ABSOLUTE);
4117 if (end_at.type == END_AT_SIZE) {
4118 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4119 end_at.type = END_AT_NONE;
4122 #ifdef CONFIG_DVDNAV
4123 mp_dvdnav_context_free(mpctx);
4124 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4125 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4126 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4128 #endif
4130 get_relative_time(mpctx); // reset current delta
4131 mpctx->time_frame = 0;
4132 mpctx->drop_message_shown = 0;
4133 mpctx->update_video_immediately = true;
4134 mpctx->total_avsync_change = 0;
4135 mpctx->last_chapter_seek = -1;
4136 // Make sure VO knows current pause state
4137 if (mpctx->sh_video)
4138 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4139 NULL);
4141 while(!mpctx->stop_play){
4142 float aq_sleep_time=0;
4144 if (opts->chapterrange[1] > 0) {
4145 int cur_chapter = get_current_chapter(mpctx);
4146 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4147 goto goto_next_file;
4150 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4151 mpctx->sh_audio = mpctx->d_audio->sh;
4152 mpctx->sh_audio->ds = mpctx->d_audio;
4153 reinit_audio_chain(mpctx);
4156 /*========================== PLAY AUDIO ============================*/
4158 if (mpctx->sh_audio && !mpctx->paused)
4159 if (!fill_audio_out_buffers(mpctx))
4160 // at eof, all audio at least written to ao
4161 if (!mpctx->sh_video)
4162 mpctx->stop_play = AT_END_OF_FILE;
4165 if(!mpctx->sh_video) {
4166 // handle audio-only case:
4167 double a_pos=0;
4168 // sh_audio can be NULL due to video stream switching
4169 // TODO: handle this better
4170 if (mpctx->sh_audio)
4171 a_pos = playing_audio_pts(mpctx);
4173 print_status(mpctx, a_pos, false);
4175 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4176 mpctx->stop_play = PT_NEXT_ENTRY;
4177 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4178 mpctx->d_sub, 0);
4179 update_osd_msg(mpctx);
4181 } else {
4183 /*========================== PLAY VIDEO ============================*/
4185 vo_pts=mpctx->sh_video->timer*90000.0;
4186 vo_fps=mpctx->sh_video->fps;
4188 blit_frame = mpctx->video_out->frame_loaded;
4189 if (!blit_frame) {
4190 double frame_time = update_video(mpctx);
4191 blit_frame = mpctx->video_out->frame_loaded;
4192 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4193 if (mpctx->sh_video->vf_initialized < 0) {
4194 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4195 mpctx->stop_play = PT_NEXT_ENTRY;
4196 goto goto_next_file;
4198 if (blit_frame) {
4199 struct sh_video *sh_video = mpctx->sh_video;
4200 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4201 mpctx->video_offset, mpctx->d_sub, 0);
4202 update_teletext(sh_video, mpctx->demuxer, 0);
4203 update_osd_msg(mpctx);
4204 struct vf_instance *vf = mpctx->sh_video->vfilter;
4205 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4206 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4207 vo_osd_changed(0);
4209 if (frame_time < 0)
4210 mpctx->stop_play = AT_END_OF_FILE;
4211 else {
4212 if (mpctx->update_video_immediately) {
4213 // Show this frame immediately, rest normally
4214 mpctx->update_video_immediately = false;
4215 } else {
4216 mpctx->time_frame += frame_time / opts->playback_speed;
4217 adjust_sync(mpctx, frame_time);
4221 if (mpctx->timeline) {
4222 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4223 if (mpctx->sh_video->pts >= next->start
4224 || mpctx->stop_play == AT_END_OF_FILE
4225 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4226 seek(mpctx, next->start, SEEK_ABSOLUTE);
4227 continue;
4231 // ==========================================================================
4233 // current_module="draw_osd";
4234 // if(vo_config_count) mpctx->video_out->draw_osd();
4236 current_module="vo_check_events";
4237 vo_check_events(mpctx->video_out);
4239 #ifdef CONFIG_X11
4240 if (stop_xscreensaver) {
4241 current_module = "stop_xscreensaver";
4242 xscreensaver_heartbeat(mpctx->x11_state);
4244 #endif
4245 if (heartbeat_cmd) {
4246 static unsigned last_heartbeat;
4247 unsigned now = GetTimerMS();
4248 if (now - last_heartbeat > 30000) {
4249 last_heartbeat = now;
4250 system(heartbeat_cmd);
4254 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4256 //====================== FLIP PAGE (VIDEO BLT): =========================
4258 current_module="flip_page";
4259 if (!frame_time_remaining && blit_frame) {
4260 unsigned int t2=GetTimer();
4261 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4262 int duration = -1;
4263 double pts2 = mpctx->video_out->next_pts2;
4264 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4265 // expected A/V sync correction is ignored
4266 double diff = (pts2 - mpctx->sh_video->pts);
4267 diff /= opts->playback_speed;
4268 if (mpctx->time_frame < 0)
4269 diff += mpctx->time_frame;
4270 if (diff < 0)
4271 diff = 0;
4272 if (diff > 10)
4273 diff = 10;
4274 duration = diff * 1e6;
4276 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4278 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4279 vout_time_usage += mpctx->last_vo_flip_duration;
4280 if (mpctx->video_out->driver->flip_page_timed) {
4281 // No need to adjust sync based on flip speed
4282 mpctx->last_vo_flip_duration = 0;
4283 // For print_status - VO call finishing early is OK for sync
4284 mpctx->time_frame -= get_relative_time(mpctx);
4286 print_status(mpctx, MP_NOPTS_VALUE, true);
4288 else
4289 print_status(mpctx, MP_NOPTS_VALUE, false);
4291 //============================ Auto QUALITY ============================
4293 /*Output quality adjustments:*/
4294 if(auto_quality>0){
4295 current_module="autoq";
4296 // float total=0.000001f * (GetTimer()-aq_total_time);
4297 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4298 if(output_quality<auto_quality && aq_sleep_time>0)
4299 ++output_quality;
4300 else
4301 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4302 if(output_quality>1 && aq_sleep_time<0)
4303 --output_quality;
4304 else
4305 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4306 output_quality=0;
4307 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4308 set_video_quality(mpctx->sh_video,output_quality);
4311 if (!frame_time_remaining && blit_frame) {
4312 if (play_n_frames >= 0) {
4313 --play_n_frames;
4314 if (play_n_frames <= 0)
4315 mpctx->stop_play = PT_NEXT_ENTRY;
4317 if (mpctx->step_frames > 0) {
4318 mpctx->step_frames--;
4319 if (mpctx->step_frames == 0)
4320 pause_player(mpctx);
4325 // FIXME: add size based support for -endpos
4326 if (end_at.type == END_AT_TIME &&
4327 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4328 mpctx->stop_play = PT_NEXT_ENTRY;
4330 } // end if(mpctx->sh_video)
4332 #ifdef CONFIG_DVDNAV
4333 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4334 nav_highlight_t hl;
4335 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4336 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4337 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4338 vo_osd_changed (OSDTYPE_DVDNAV);
4339 } else {
4340 osd_set_nav_box(0, 0, 0, 0);
4341 vo_osd_changed(OSDTYPE_DVDNAV);
4342 vo_osd_changed(OSDTYPE_SPU);
4345 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4346 double ar = -1.0;
4347 if (mpctx->sh_video &&
4348 stream_control (mpctx->demuxer->stream,
4349 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4350 != STREAM_UNSUPPORTED)
4351 mpctx->sh_video->stream_aspect = ar;
4354 #endif
4356 //================= Keyboard events, SEEKing ====================
4358 current_module="key_events";
4361 while (1) {
4362 mp_cmd_t* cmd;
4363 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4364 run_command(mpctx, cmd);
4365 mp_cmd_free(cmd);
4366 if (mpctx->stop_play)
4367 break;
4368 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4369 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4370 /* Allow seek commands to be combined, but execute the real seek
4371 * before processing other commands */
4372 if (!cmd || cmd->id != MP_CMD_SEEK)
4373 break;
4376 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4377 || mpctx->abs_seek_pos)
4378 break;
4379 if (mpctx->sh_video) {
4380 update_osd_msg(mpctx);
4381 int hack = vo_osd_changed(0);
4382 vo_osd_changed(hack);
4383 if (hack) {
4384 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4385 add_step_frame(mpctx);
4386 break;
4388 else
4389 vo_osd_changed(0);
4392 pause_loop(mpctx);
4396 // handle -sstep
4397 if (step_sec > 0 && !mpctx->paused) {
4398 mpctx->osd_function=OSD_FFW;
4399 mpctx->rel_seek_secs+=step_sec;
4402 edl_update(mpctx);
4404 /* Looping. */
4405 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4406 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4408 if(opts->loop_times>1) opts->loop_times--; else
4409 if(opts->loop_times==1) opts->loop_times=-1;
4410 play_n_frames=play_n_frames_mf;
4411 mpctx->stop_play=0;
4412 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4415 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4416 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4418 mpctx->rel_seek_secs=0;
4419 mpctx->abs_seek_pos=0;
4422 } // while(!mpctx->stop_play)
4424 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4426 #ifdef CONFIG_DVBIN
4427 if(mpctx->dvbin_reopen)
4429 mpctx->stop_play = 0;
4430 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4431 cache_uninit(mpctx->stream);
4432 mpctx->dvbin_reopen = 0;
4433 goto goto_enable_cache;
4435 #endif
4438 goto_next_file: // don't jump here after ao/vo/getch initialization!
4440 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4442 if(benchmark){
4443 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4444 double total_time_usage;
4445 total_time_usage_start=GetTimer()-total_time_usage_start;
4446 total_time_usage = (float)total_time_usage_start*0.000001;
4447 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4448 video_time_usage,vout_time_usage,audio_time_usage,
4449 total_time_usage-tot,total_time_usage);
4450 if(total_time_usage>0.0)
4451 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4452 100.0*video_time_usage/total_time_usage,
4453 100.0*vout_time_usage/total_time_usage,
4454 100.0*audio_time_usage/total_time_usage,
4455 100.0*(total_time_usage-tot)/total_time_usage,
4456 100.0);
4457 if(total_frame_cnt && frame_dropping)
4458 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4459 total_frame_cnt-drop_frame_cnt,
4460 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4461 drop_frame_cnt,
4462 100*drop_frame_cnt/total_frame_cnt,
4463 total_frame_cnt,
4464 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4467 // time to uninit all, except global stuff:
4468 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4470 if(mpctx->set_of_sub_size > 0) {
4471 current_module="sub_free";
4472 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4473 sub_free(mpctx->set_of_subtitles[i]);
4474 #ifdef CONFIG_ASS
4475 if(mpctx->set_of_ass_tracks[i])
4476 ass_free_track( mpctx->set_of_ass_tracks[i] );
4477 #endif
4479 mpctx->set_of_sub_size = 0;
4481 vo_sub_last = vo_sub=NULL;
4482 subdata=NULL;
4483 #ifdef CONFIG_ASS
4484 ass_track = NULL;
4485 if(ass_library)
4486 ass_clear_fonts(ass_library);
4487 #endif
4489 if (!mpctx->stop_play) // In case some goto jumped here...
4490 mpctx->stop_play = PT_NEXT_ENTRY;
4492 int playtree_direction = 1;
4494 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4495 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4496 play_tree_iter_free(mpctx->playtree_iter);
4497 mpctx->playtree_iter = NULL;
4499 mpctx->play_tree_step = 1;
4500 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4501 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4502 if(mpctx->playtree_iter) {
4503 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4504 play_tree_iter_free(mpctx->playtree_iter);
4505 mpctx->playtree_iter = NULL;
4508 } else if (mpctx->stop_play == PT_STOP) {
4509 play_tree_iter_free(mpctx->playtree_iter);
4510 mpctx->playtree_iter = NULL;
4511 } else { // NEXT PREV SRC
4512 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4515 while(mpctx->playtree_iter != NULL) {
4516 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4517 if(mpctx->filename == NULL) {
4518 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4519 play_tree_iter_free(mpctx->playtree_iter);
4520 mpctx->playtree_iter = NULL;
4522 } else
4523 break;
4526 if(mpctx->playtree_iter != NULL || player_idle_mode){
4527 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4528 mpctx->stop_play = 0;
4529 goto play_next_file;
4533 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4535 return 1;
4537 #endif /* DISABLE_MAIN */