options: move some demux options to option struct
[mplayer/greg.git] / mplayer.c
blob1c6bf14226769fbfc6f93895123524e5af697518
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 // this dvdsub_id was selected via slang
307 // use this to allow dvdnav to follow -slang across stream resets,
308 // in particular the subtitle ID for a language changes
309 int dvdsub_lang_id;
310 int vobsub_id=-1;
311 static char* spudec_ifo=NULL;
312 int forced_subs_only=0;
313 int file_filter=1;
315 // cache2:
316 int stream_cache_size=-1;
317 #ifdef CONFIG_STREAM_CACHE
318 float stream_cache_min_percent=20.0;
319 float stream_cache_seek_min_percent=50.0;
320 #endif
322 // dump:
323 int stream_dump_type=0;
325 // A-V sync:
326 static float default_max_pts_correction=-1;//0.01f;
327 float audio_delay=0;
328 static int ignore_start=0;
330 static int softsleep=0;
332 double force_fps=0;
333 static int force_srate=0;
334 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
335 static int play_n_frames=-1;
336 static int play_n_frames_mf=-1;
338 // sub:
339 char *font_name=NULL;
340 char *sub_font_name=NULL;
341 extern int font_fontconfig;
342 float font_factor=0.75;
343 char **sub_name=NULL;
344 float sub_delay=0;
345 float sub_fps=0;
346 int sub_auto = 1;
347 char *vobsub_name=NULL;
348 int subcc_enabled=0;
349 int suboverlap_enabled = 1;
351 #include "ass_mp.h"
353 char* current_module=NULL; // for debugging
356 // ---
358 #ifdef CONFIG_MENU
359 #include "m_struct.h"
360 #include "libmenu/menu.h"
361 static const vf_info_t* const libmenu_vfs[] = {
362 &vf_info_menu,
363 NULL
365 static vf_instance_t* vf_menu = NULL;
366 int use_menu = 0;
367 static char* menu_cfg = NULL;
368 static char* menu_root = "main";
369 #endif
372 #ifdef HAVE_RTC
373 static int nortc = 1;
374 static char* rtc_device;
375 #endif
377 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
378 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
379 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
380 int use_filedir_conf;
381 int use_filename_title;
383 #include "mpcommon.h"
384 #include "command.h"
386 #include "metadata.h"
388 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
390 const void *mpctx_get_video_out(MPContext *mpctx)
392 return mpctx->video_out;
395 const void *mpctx_get_audio_out(MPContext *mpctx)
397 return mpctx->audio_out;
400 void *mpctx_get_demuxer(MPContext *mpctx)
402 return mpctx->demuxer;
405 void *mpctx_get_playtree_iter(MPContext *mpctx)
407 return mpctx->playtree_iter;
410 void *mpctx_get_mixer(MPContext *mpctx)
412 return &mpctx->mixer;
415 int mpctx_get_global_sub_size(MPContext *mpctx)
417 return mpctx->global_sub_size;
420 int mpctx_get_osd_function(MPContext *mpctx)
422 return mpctx->osd_function;
425 static float get_relative_time(struct MPContext *mpctx)
427 unsigned int new_time = GetTimer();
428 unsigned int delta = new_time - mpctx->last_time;
429 mpctx->last_time = new_time;
430 return delta * 0.000001;
433 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
434 switch (type)
436 /* check for valid video stream */
437 case META_VIDEO_CODEC:
438 case META_VIDEO_BITRATE:
439 case META_VIDEO_RESOLUTION:
441 if (!mpctx->sh_video)
442 return 0;
443 break;
446 /* check for valid audio stream */
447 case META_AUDIO_CODEC:
448 case META_AUDIO_BITRATE:
449 case META_AUDIO_SAMPLES:
451 if (!mpctx->sh_audio)
452 return 0;
453 break;
456 /* check for valid demuxer */
457 case META_INFO_TITLE:
458 case META_INFO_ARTIST:
459 case META_INFO_ALBUM:
460 case META_INFO_YEAR:
461 case META_INFO_COMMENT:
462 case META_INFO_TRACK:
463 case META_INFO_GENRE:
465 if (!mpctx->demuxer)
466 return 0;
467 break;
470 default:
471 break;
474 return 1;
477 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
478 char **info = mpctx->demuxer->info;
479 int n;
481 if (!info || !tag)
482 return NULL;
484 for (n = 0; info[2*n] != NULL ; n++)
485 if (!strcasecmp (info[2*n], tag))
486 break;
488 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
491 char *get_metadata(struct MPContext *mpctx, metadata_t type)
493 char *meta = NULL;
494 sh_audio_t * const sh_audio = mpctx->sh_audio;
495 sh_video_t * const sh_video = mpctx->sh_video;
497 if (!is_valid_metadata_type(mpctx, type))
498 return NULL;
500 switch (type)
502 case META_NAME:
504 return strdup (mp_basename2 (mpctx->filename));
507 case META_VIDEO_CODEC:
509 if (sh_video->format == 0x10000001)
510 meta = strdup ("mpeg1");
511 else if (sh_video->format == 0x10000002)
512 meta = strdup ("mpeg2");
513 else if (sh_video->format == 0x10000004)
514 meta = strdup ("mpeg4");
515 else if (sh_video->format == 0x10000005)
516 meta = strdup ("h264");
517 else if (sh_video->format >= 0x20202020)
519 meta = malloc (8);
520 sprintf (meta, "%.4s", (char *) &sh_video->format);
522 else
524 meta = malloc (8);
525 sprintf (meta, "0x%08X", sh_video->format);
527 return meta;
530 case META_VIDEO_BITRATE:
532 meta = malloc (16);
533 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
534 return meta;
537 case META_VIDEO_RESOLUTION:
539 meta = malloc (16);
540 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
541 return meta;
544 case META_AUDIO_CODEC:
546 if (sh_audio->codec && sh_audio->codec->name)
547 meta = strdup (sh_audio->codec->name);
548 return meta;
551 case META_AUDIO_BITRATE:
553 meta = malloc (16);
554 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
555 return meta;
558 case META_AUDIO_SAMPLES:
560 meta = malloc (16);
561 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
562 return meta;
565 /* check for valid demuxer */
566 case META_INFO_TITLE:
567 return get_demuxer_info(mpctx, "Title");
569 case META_INFO_ARTIST:
570 return get_demuxer_info(mpctx, "Artist");
572 case META_INFO_ALBUM:
573 return get_demuxer_info(mpctx, "Album");
575 case META_INFO_YEAR:
576 return get_demuxer_info(mpctx, "Year");
578 case META_INFO_COMMENT:
579 return get_demuxer_info(mpctx, "Comment");
581 case META_INFO_TRACK:
582 return get_demuxer_info(mpctx, "Track");
584 case META_INFO_GENRE:
585 return get_demuxer_info(mpctx, "Genre");
587 default:
588 break;
591 return meta;
594 static void print_file_properties(struct MPContext *mpctx, const char *filename)
596 double start_pts = MP_NOPTS_VALUE;
597 double video_start_pts = MP_NOPTS_VALUE;
598 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
599 filename_recode(filename));
600 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
601 if (mpctx->sh_video) {
602 /* Assume FOURCC if all bytes >= 0x20 (' ') */
603 if (mpctx->sh_video->format >= 0x20202020)
604 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
605 else
606 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
607 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
608 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
609 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
610 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
611 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
612 video_start_pts = ds_get_next_pts(mpctx->d_video);
614 if (mpctx->sh_audio) {
615 /* Assume FOURCC if all bytes >= 0x20 (' ') */
616 if (mpctx->sh_audio->format >= 0x20202020)
617 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
618 else
619 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
620 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
621 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
622 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
623 start_pts = ds_get_next_pts(mpctx->d_audio);
625 if (video_start_pts != MP_NOPTS_VALUE) {
626 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
627 (mpctx->sh_video && video_start_pts < start_pts))
628 start_pts = video_start_pts;
630 if (start_pts != MP_NOPTS_VALUE)
631 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
632 else
633 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
634 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
635 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
636 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
637 if (mpctx->demuxer) {
638 if (mpctx->demuxer->num_chapters == 0)
639 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
640 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
644 /// step size of mixer changes
645 int volstep = 3;
647 #ifdef CONFIG_DVDNAV
648 static void mp_dvdnav_context_free(MPContext *ctx){
649 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
650 ctx->nav_smpi = NULL;
651 free(ctx->nav_buffer);
652 ctx->nav_buffer = NULL;
653 ctx->nav_start = NULL;
654 ctx->nav_in_size = 0;
656 #endif
658 void uninit_player(struct MPContext *mpctx, unsigned int mask){
659 mask &= mpctx->initialized_flags;
661 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
663 if(mask&INITIALIZED_ACODEC){
664 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
665 current_module="uninit_acodec";
666 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
667 mpctx->sh_audio=NULL;
668 mpctx->mixer.afilter = NULL;
671 if(mask&INITIALIZED_VCODEC){
672 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
673 current_module="uninit_vcodec";
674 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
675 mpctx->sh_video=NULL;
676 #ifdef CONFIG_MENU
677 vf_menu=NULL;
678 #endif
681 if(mask&INITIALIZED_DEMUXER){
682 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
683 current_module="free_demuxer";
684 if (mpctx->num_sources) {
685 mpctx->demuxer = mpctx->sources[0].demuxer;
686 for (int i = 1; i < mpctx->num_sources; i++) {
687 free_stream(mpctx->sources[i].stream);
688 free_demuxer(mpctx->sources[i].demuxer);
691 talloc_free(mpctx->sources);
692 mpctx->sources = NULL;
693 mpctx->num_sources = 0;
694 talloc_free(mpctx->timeline);
695 mpctx->timeline = NULL;
696 mpctx->num_timeline_parts = 0;
697 talloc_free(mpctx->chapters);
698 mpctx->chapters = NULL;
699 mpctx->num_chapters = 0;
700 mpctx->video_offset = 0;
701 if(mpctx->demuxer){
702 mpctx->stream=mpctx->demuxer->stream;
703 free_demuxer(mpctx->demuxer);
705 mpctx->demuxer=NULL;
708 // kill the cache process:
709 if(mask&INITIALIZED_STREAM){
710 mpctx->initialized_flags&=~INITIALIZED_STREAM;
711 current_module="uninit_stream";
712 if(mpctx->stream) free_stream(mpctx->stream);
713 mpctx->stream=NULL;
716 if(mask&INITIALIZED_VO){
717 mpctx->initialized_flags&=~INITIALIZED_VO;
718 current_module="uninit_vo";
719 vo_destroy(mpctx->video_out);
720 mpctx->video_out=NULL;
721 #ifdef CONFIG_DVDNAV
722 mp_dvdnav_context_free(mpctx);
723 #endif
726 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
727 if(mask&INITIALIZED_GETCH2){
728 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
729 current_module="uninit_getch2";
730 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
731 // restore terminal:
732 getch2_disable();
735 if(mask&INITIALIZED_VOBSUB){
736 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
737 current_module="uninit_vobsub";
738 if(vo_vobsub) vobsub_close(vo_vobsub);
739 vo_vobsub=NULL;
742 if (mask&INITIALIZED_SPUDEC){
743 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
744 current_module="uninit_spudec";
745 spudec_free(vo_spudec);
746 vo_spudec=NULL;
749 if(mask&INITIALIZED_AO){
750 mpctx->initialized_flags&=~INITIALIZED_AO;
751 current_module="uninit_ao";
752 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
753 if (mpctx->audio_out)
754 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
755 mpctx->audio_out=NULL;
758 current_module=NULL;
761 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
763 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
764 uninit_player(mpctx, INITIALIZED_ALL);
765 #if defined(__MINGW32__) || defined(__CYGWIN__)
766 timeEndPeriod(1);
767 #endif
768 #ifdef CONFIG_X11
769 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
770 #endif
772 current_module="uninit_input";
773 mp_input_uninit(mpctx->input);
774 #ifdef CONFIG_MENU
775 if (use_menu)
776 menu_uninit();
777 #endif
779 #ifdef CONFIG_FREETYPE
780 current_module="uninit_font";
781 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
782 free_font_desc(mpctx->osd->sub_font);
783 free_font_desc(vo_font);
784 vo_font = NULL;
785 done_freetype();
786 #endif
787 osd_free(mpctx->osd);
789 #ifdef CONFIG_ASS
790 ass_library_done(ass_library);
791 ass_library = NULL;
792 #endif
794 current_module="exit_player";
796 // free mplayer config
797 if(mpctx->mconfig)
798 m_config_free(mpctx->mconfig);
799 mpctx->mconfig = NULL;
801 if(mpctx->playtree_iter)
802 play_tree_iter_free(mpctx->playtree_iter);
803 mpctx->playtree_iter = NULL;
804 if(mpctx->playtree)
805 play_tree_free(mpctx->playtree, 1);
806 mpctx->playtree = NULL;
808 talloc_free(mpctx->key_fifo);
810 free(edl_records); // free mem allocated for EDL
811 edl_records = NULL;
812 switch(how) {
813 case EXIT_QUIT:
814 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
815 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
816 break;
817 case EXIT_EOF:
818 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
819 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
820 break;
821 case EXIT_ERROR:
822 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
823 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
824 break;
825 default:
826 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
828 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
830 exit(rc);
833 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
835 exit_player_with_rc(mpctx, how, 1);
838 #ifndef __MINGW32__
839 static void child_sighandler(int x){
840 pid_t pid;
841 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
843 #endif
845 #ifdef CONFIG_CRASH_DEBUG
846 static char *prog_path;
847 static int crash_debug = 0;
848 #endif
850 static void exit_sighandler(int x){
851 static int sig_count=0;
852 #ifdef CONFIG_CRASH_DEBUG
853 if (!crash_debug || x != SIGTRAP)
854 #endif
855 ++sig_count;
856 if(sig_count==5)
858 /* We're crashing bad and can't uninit cleanly :(
859 * by popular request, we make one last (dirty)
860 * effort to restore the user's
861 * terminal. */
862 getch2_disable();
863 exit(1);
865 if(sig_count==6) exit(1);
866 if(sig_count>6){
867 // can't stop :(
868 #ifndef __MINGW32__
869 kill(getpid(),SIGKILL);
870 #endif
872 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
873 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
874 "\nMPlayer interrupted by signal %d in module: %s\n", x,
875 current_module ? current_module : "unknown");
876 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
877 if(sig_count<=1)
878 switch(x){
879 case SIGINT:
880 case SIGPIPE:
881 case SIGQUIT:
882 case SIGTERM:
883 case SIGKILL:
884 async_quit_request = 1;
885 return; // killed from keyboard (^C) or killed [-9]
886 case SIGILL:
887 #if CONFIG_RUNTIME_CPUDETECT
888 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
889 #else
890 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
891 #endif
892 case SIGFPE:
893 case SIGSEGV:
894 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
895 default:
896 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
897 #ifdef CONFIG_CRASH_DEBUG
898 if (crash_debug) {
899 int gdb_pid;
900 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
901 gdb_pid = fork();
902 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
903 if (gdb_pid == 0) { // We are the child
904 char spid[20];
905 snprintf(spid, sizeof(spid), "%i", getppid());
906 getch2_disable(); // allow terminal to work properly with gdb
907 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
908 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
909 } else if (gdb_pid < 0)
910 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
911 else {
912 waitpid(gdb_pid, NULL, 0);
914 if (x == SIGTRAP) return;
916 #endif
918 getch2_disable();
919 exit(1);
922 #include "cfg-mplayer.h"
924 static int cfg_include(m_option_t *conf, char *filename)
926 return m_config_parse_config_file(conf->priv, filename);
929 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
931 char *conffile;
932 int conffile_fd;
933 if (!disable_system_conf &&
934 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
935 exit_player(mpctx, EXIT_NONE);
936 if ((conffile = get_path("")) == NULL) {
937 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
938 } else {
939 #ifdef __MINGW32__
940 mkdir(conffile);
941 #else
942 mkdir(conffile, 0777);
943 #endif
944 free(conffile);
945 if ((conffile = get_path("config")) == NULL) {
946 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
947 } else {
948 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
949 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
950 write(conffile_fd, default_config, strlen(default_config));
951 close(conffile_fd);
953 if (!disable_user_conf &&
954 m_config_parse_config_file(conf, conffile) < 0)
955 exit_player(mpctx, EXIT_NONE);
956 free(conffile);
961 #define PROFILE_CFG_PROTOCOL "protocol."
963 static void load_per_protocol_config (m_config_t* conf, const char *const file)
965 char *str;
966 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
967 m_profile_t *p;
969 /* does filename actually uses a protocol ? */
970 str = strstr (file, "://");
971 if (!str)
972 return;
974 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
975 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
976 p = m_config_get_profile (conf, protocol);
977 if (p)
979 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
980 m_config_set_profile(conf,p);
984 #define PROFILE_CFG_EXTENSION "extension."
986 static void load_per_extension_config (m_config_t* conf, const char *const file)
988 char *str;
989 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
990 m_profile_t *p;
992 /* does filename actually have an extension ? */
993 str = strrchr (file, '.');
994 if (!str)
995 return;
997 sprintf (extension, PROFILE_CFG_EXTENSION);
998 strncat (extension, ++str, 7);
999 p = m_config_get_profile (conf, extension);
1000 if (p)
1002 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
1003 m_config_set_profile(conf,p);
1007 #define PROFILE_CFG_VO "vo."
1008 #define PROFILE_CFG_AO "ao."
1010 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
1012 char profile[strlen (cfg) + strlen (out) + 1];
1013 m_profile_t *p;
1015 sprintf (profile, "%s%s", cfg, out);
1016 p = m_config_get_profile (conf, profile);
1017 if (p)
1019 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
1020 m_config_set_profile(conf,p);
1025 * Tries to load a config file
1026 * @return 0 if file was not found, 1 otherwise
1028 static int try_load_config(m_config_t *conf, const char *file)
1030 struct stat st;
1031 if (stat(file, &st))
1032 return 0;
1033 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1034 m_config_parse_config_file (conf, file);
1035 return 1;
1038 static void load_per_file_config (m_config_t* conf, const char *const file)
1040 char *confpath;
1041 char cfg[PATH_MAX];
1042 char *name;
1044 if (strlen(file) > PATH_MAX - 14) {
1045 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1046 return;
1048 sprintf (cfg, "%s.conf", file);
1050 name = strrchr(cfg, '/');
1051 if (HAVE_DOS_PATHS) {
1052 char *tmp = strrchr(cfg, '\\');
1053 if (!name || tmp > name)
1054 name = tmp;
1055 tmp = strrchr(cfg, ':');
1056 if (!name || tmp > name)
1057 name = tmp;
1059 if (!name)
1060 name = cfg;
1061 else
1062 name++;
1064 if (use_filedir_conf) {
1065 char dircfg[PATH_MAX];
1066 strcpy(dircfg, cfg);
1067 strcpy(dircfg + (name - cfg), "mplayer.conf");
1068 try_load_config(conf, dircfg);
1070 if (try_load_config(conf, cfg))
1071 return;
1074 if ((confpath = get_path (name)) != NULL)
1076 try_load_config(conf, confpath);
1078 free (confpath);
1082 /* When libmpdemux performs a blocking operation (network connection or
1083 * cache filling) if the operation fails we use this function to check
1084 * if it was interrupted by the user.
1085 * The function returns a new value for eof. */
1086 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1088 mp_cmd_t* cmd;
1089 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1090 switch(cmd->id) {
1091 case MP_CMD_QUIT:
1092 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1093 case MP_CMD_PLAY_TREE_STEP: {
1094 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1095 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1096 } break;
1097 case MP_CMD_PLAY_TREE_UP_STEP: {
1098 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1099 } break;
1100 case MP_CMD_PLAY_ALT_SRC_STEP: {
1101 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1102 } break;
1104 mp_cmd_free(cmd);
1106 return stop_play;
1109 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1111 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1113 play_tree_add_bpf(entry,mpctx->filename);
1116 if(!entry) {
1117 entry = mpctx->playtree_iter->tree;
1118 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1119 return PT_NEXT_ENTRY;
1121 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1122 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1123 return PT_NEXT_ENTRY;
1126 play_tree_remove(entry,1,1);
1127 return PT_NEXT_SRC;
1129 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1130 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1131 entry = mpctx->playtree_iter->tree;
1132 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1133 return PT_NEXT_ENTRY;
1135 play_tree_remove(entry,1,1);
1137 return PT_NEXT_SRC;
1140 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1142 struct MPOpts *opts = &mpctx->opts;
1143 sub_data *subd = NULL;
1144 struct ass_track *asst = NULL;
1146 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1147 return;
1150 #ifdef CONFIG_ASS
1151 if (opts->ass_enabled) {
1152 #ifdef CONFIG_ICONV
1153 asst = ass_read_stream(ass_library, filename, sub_cp);
1154 #else
1155 asst = ass_read_stream(ass_library, filename, 0);
1156 #endif
1157 if (!asst) {
1158 subd = sub_read_file(filename, fps);
1159 if (subd) {
1160 asst = ass_read_subdata(ass_library, subd, fps);
1161 if (asst) {
1162 sub_free(subd);
1163 subd = NULL;
1167 } else
1168 #endif
1169 subd = sub_read_file(filename, fps);
1172 if (!asst && !subd) {
1173 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1174 "Cannot load subtitles: %s\n", filename_recode(filename));
1175 return;
1178 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1179 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1180 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1181 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1182 filename_recode(filename));
1183 ++mpctx->set_of_sub_size;
1184 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1185 filename_recode(filename));
1188 void init_vo_spudec(struct MPContext *mpctx)
1190 if (vo_spudec)
1191 spudec_free(vo_spudec);
1192 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1193 vo_spudec = NULL;
1195 // we currently can't work without video stream
1196 if (!mpctx->sh_video)
1197 return;
1199 if (spudec_ifo) {
1200 unsigned int palette[16], width, height;
1201 current_module="spudec_init_vobsub";
1202 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1203 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1206 #ifdef CONFIG_DVDREAD
1207 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1208 current_module="spudec_init_dvdread";
1209 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1210 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1211 NULL, 0);
1213 #endif
1215 #ifdef CONFIG_DVDNAV
1216 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1217 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1218 current_module="spudec_init_dvdnav";
1219 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1221 #endif
1223 if (vo_spudec==NULL) {
1224 sh_sub_t *sh = mpctx->d_sub->sh;
1225 current_module="spudec_init_normal";
1226 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1227 spudec_set_font_factor(vo_spudec,font_factor);
1230 if (vo_spudec!=NULL) {
1231 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1232 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1237 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1238 * make it all work is to use the builtin SDL-bootstrap code, which
1239 * will be done automatically by replacing our main() if we include SDL.h.
1241 #if defined(__APPLE__) && defined(CONFIG_SDL)
1242 #ifdef CONFIG_SDL_SDL_H
1243 #include <SDL/SDL.h>
1244 #else
1245 #include <SDL.h>
1246 #endif
1247 #endif
1250 * \brief append a formatted string
1251 * \param buf buffer to print into
1252 * \param pos position of terminating 0 in buf
1253 * \param len maximum number of characters in buf, not including terminating 0
1254 * \param format printf format string
1256 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1258 va_list va;
1259 va_start(va, format);
1260 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1261 va_end(va);
1262 if (*pos >= len ) {
1263 buf[len] = 0;
1264 *pos = len;
1269 * \brief append time in the hh:mm:ss.f format
1270 * \param buf buffer to print into
1271 * \param pos position of terminating 0 in buf
1272 * \param len maximum number of characters in buf, not including terminating 0
1273 * \param time time value to convert/append
1275 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1276 int64_t tenths = 10 * time;
1277 int f1 = tenths % 10;
1278 int ss = (tenths / 10) % 60;
1279 int mm = (tenths / 600) % 60;
1280 int hh = tenths / 36000;
1281 if (time <= 0) {
1282 saddf(buf, pos, len, "unknown");
1283 return;
1285 if (hh > 0)
1286 saddf(buf, pos, len, "%2d:", hh);
1287 if (hh > 0 || mm > 0)
1288 saddf(buf, pos, len, "%02d:", mm);
1289 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1292 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1294 struct MPOpts *opts = &mpctx->opts;
1295 sh_video_t * const sh_video = mpctx->sh_video;
1297 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1298 a_pos = playing_audio_pts(mpctx);
1299 if (mpctx->sh_audio && sh_video && at_frame) {
1300 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1301 if (mpctx->time_frame > 0)
1302 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1303 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1304 && !mpctx->drop_message_shown) {
1305 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1306 mpctx->drop_message_shown = true;
1309 if (quiet)
1310 return;
1313 int width;
1314 char *line;
1315 unsigned pos = 0;
1316 get_screen_size();
1317 if (screen_width > 0)
1318 width = screen_width;
1319 else
1320 width = 80;
1321 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1322 /* Windows command line is broken (MinGW's rxvt works, but we
1323 * should not depend on that). */
1324 width--;
1325 #endif
1326 line = malloc(width + 1); // one additional char for the terminating null
1328 // Audio time
1329 if (mpctx->sh_audio) {
1330 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1331 if (!sh_video) {
1332 float len = get_time_length(mpctx);
1333 saddf(line, &pos, width, "(");
1334 sadd_hhmmssf(line, &pos, width, a_pos);
1335 saddf(line, &pos, width, ") of %.1f (", len);
1336 sadd_hhmmssf(line, &pos, width, len);
1337 saddf(line, &pos, width, ") ");
1341 // Video time
1342 if (sh_video)
1343 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1345 // A-V sync
1346 if (mpctx->sh_audio && sh_video)
1347 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1348 mpctx->last_av_difference, mpctx->total_avsync_change);
1350 // Video stats
1351 if (sh_video)
1352 saddf(line, &pos, width, "%3d/%3d ",
1353 (int)sh_video->num_frames,
1354 (int)sh_video->num_frames_decoded);
1356 // CPU usage
1357 if (sh_video) {
1358 if (sh_video->timer > 0.5)
1359 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1360 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1361 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1362 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1363 else
1364 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1365 } else if (mpctx->sh_audio) {
1366 if (mpctx->delay > 0.5)
1367 saddf(line, &pos, width, "%4.1f%% ",
1368 100.0*audio_time_usage/(double)mpctx->delay);
1369 else
1370 saddf(line, &pos, width, "??,?%% ");
1373 // VO stats
1374 if (sh_video)
1375 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1377 #ifdef CONFIG_STREAM_CACHE
1378 // cache stats
1379 if (stream_cache_size > 0)
1380 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1381 #endif
1383 // other
1384 if (opts->playback_speed != 1)
1385 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1387 // end
1388 if (erase_to_end_of_line) {
1389 line[pos] = 0;
1390 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1391 } else {
1392 memset(&line[pos], ' ', width - pos);
1393 line[width] = 0;
1394 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1396 free(line);
1400 * \brief build a chain of audio filters that converts the input format
1401 * to the ao's format, taking into account the current playback_speed.
1402 * \param sh_audio describes the requested input format of the chain.
1403 * \param ao_data describes the requested output format of the chain.
1405 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1407 struct MPOpts *opts = &mpctx->opts;
1408 int new_srate;
1409 int result;
1410 if (!sh_audio)
1412 mpctx->mixer.afilter = NULL;
1413 return 0;
1415 if(af_control_any_rev(sh_audio->afilter,
1416 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1417 &opts->playback_speed)) {
1418 new_srate = sh_audio->samplerate;
1419 } else {
1420 new_srate = sh_audio->samplerate * opts->playback_speed;
1421 if (new_srate != ao_data->samplerate) {
1422 // limits are taken from libaf/af_resample.c
1423 if (new_srate < 8000)
1424 new_srate = 8000;
1425 if (new_srate > 192000)
1426 new_srate = 192000;
1427 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1430 result = init_audio_filters(sh_audio, new_srate,
1431 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1432 mpctx->mixer.afilter = sh_audio->afilter;
1433 return result;
1437 typedef struct mp_osd_msg mp_osd_msg_t;
1438 struct mp_osd_msg {
1439 /// Previous message on the stack.
1440 mp_osd_msg_t* prev;
1441 /// Message text.
1442 char msg[128];
1443 int id,level,started;
1444 /// Display duration in ms.
1445 unsigned time;
1448 /// OSD message stack.
1449 static mp_osd_msg_t* osd_msg_stack = NULL;
1452 * \brief Add a message on the OSD message stack
1454 * If a message with the same id is already present in the stack
1455 * it is pulled on top of the stack, otherwise a new message is created.
1458 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1459 va_list ap)
1461 mp_osd_msg_t *msg,*last=NULL;
1462 int r;
1464 // look if the id is already in the stack
1465 for(msg = osd_msg_stack ; msg && msg->id != id ;
1466 last = msg, msg = msg->prev);
1467 // not found: alloc it
1468 if(!msg) {
1469 msg = calloc(1,sizeof(mp_osd_msg_t));
1470 msg->prev = osd_msg_stack;
1471 osd_msg_stack = msg;
1472 } else if(last) { // found, but it's not on top of the stack
1473 last->prev = msg->prev;
1474 msg->prev = osd_msg_stack;
1475 osd_msg_stack = msg;
1477 // write the msg
1478 r = vsnprintf(msg->msg, 128, fmt, ap);
1479 if(r >= 128) msg->msg[127] = 0;
1480 // set id and time
1481 msg->id = id;
1482 msg->level = level;
1483 msg->time = time;
1487 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1489 va_list ap;
1490 va_start(ap, fmt);
1491 set_osd_msg_va(id, level, time, fmt, ap);
1492 va_end(ap);
1495 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1497 va_list ap;
1498 va_start(ap, fmt);
1499 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1500 va_end(ap);
1505 * \brief Remove a message from the OSD stack
1507 * This function can be used to get rid of a message right away.
1511 void rm_osd_msg(int id) {
1512 mp_osd_msg_t *msg,*last=NULL;
1514 // Search for the msg
1515 for(msg = osd_msg_stack ; msg && msg->id != id ;
1516 last = msg, msg = msg->prev);
1517 if(!msg) return;
1519 // Detach it from the stack and free it
1520 if(last)
1521 last->prev = msg->prev;
1522 else
1523 osd_msg_stack = msg->prev;
1524 free(msg);
1528 * \brief Remove all messages from the OSD stack
1532 static void clear_osd_msgs(void) {
1533 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1534 while(msg) {
1535 prev = msg->prev;
1536 free(msg);
1537 msg = prev;
1539 osd_msg_stack = NULL;
1543 * \brief Get the current message from the OSD stack.
1545 * This function decrements the message timer and destroys the old ones.
1546 * The message that should be displayed is returned (if any).
1550 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1552 struct MPOpts *opts = &mpctx->opts;
1553 mp_osd_msg_t *msg,*prev,*last = NULL;
1554 static unsigned last_update = 0;
1555 unsigned now = GetTimerMS();
1556 unsigned diff;
1557 char hidden_dec_done = 0;
1559 if (mpctx->osd_visible) {
1560 // 36000000 means max timed visibility is 1 hour into the future, if
1561 // the difference is greater assume it's wrapped around from below 0
1562 if (mpctx->osd_visible - now > 36000000) {
1563 mpctx->osd_visible = 0;
1564 vo_osd_progbar_type = -1; // disable
1565 vo_osd_changed(OSDTYPE_PROGBAR);
1566 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1569 if (mpctx->osd_show_percentage_until - now > 36000000)
1570 mpctx->osd_show_percentage_until = 0;
1572 if(!last_update) last_update = now;
1573 diff = now >= last_update ? now - last_update : 0;
1575 last_update = now;
1577 // Look for the first message in the stack with high enough level.
1578 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1579 prev = msg->prev;
1580 if (msg->level > opts->osd_level && hidden_dec_done)
1581 continue;
1582 // The message has a high enough level or it is the first hidden one
1583 // in both cases we decrement the timer or kill it.
1584 if(!msg->started || msg->time > diff) {
1585 if(msg->started) msg->time -= diff;
1586 else msg->started = 1;
1587 // display it
1588 if (msg->level <= opts->osd_level)
1589 return msg;
1590 hidden_dec_done = 1;
1591 continue;
1593 // kill the message
1594 free(msg);
1595 if(last) {
1596 last->prev = prev;
1597 msg = last;
1598 } else {
1599 osd_msg_stack = prev;
1600 msg = NULL;
1603 // Nothing found
1604 return NULL;
1608 * \brief Display the OSD bar.
1610 * Display the OSD bar or fall back on a simple message.
1614 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1615 struct MPOpts *opts = &mpctx->opts;
1616 if (opts->osd_level < 1)
1617 return;
1619 if(mpctx->sh_video) {
1620 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1621 vo_osd_progbar_type = type;
1622 vo_osd_progbar_value = 256*(val-min)/(max-min);
1623 vo_osd_changed(OSDTYPE_PROGBAR);
1624 return;
1627 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1628 name, ROUND(100*(val-min)/(max-min)));
1632 * \brief Display text subtitles on the OSD
1634 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1636 int i;
1637 vo_sub = subs;
1638 vo_osd_changed(OSDTYPE_SUBTITLE);
1639 if (!mpctx->sh_video) {
1640 // reverse order, since newest set_osd_msg is displayed first
1641 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1642 if (!subs || i >= subs->lines || !subs->text[i])
1643 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1644 else {
1645 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1646 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1647 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1654 * \brief Update the OSD message line.
1656 * This function displays the current message on the vo OSD or on the term.
1657 * If the stack is empty and the OSD level is high enough the timer
1658 * is displayed (only on the vo OSD).
1662 static void update_osd_msg(struct MPContext *mpctx)
1664 struct MPOpts *opts = &mpctx->opts;
1665 mp_osd_msg_t *msg;
1666 struct osd_state *osd = mpctx->osd;
1667 char osd_text_timer[128];
1669 if (mpctx->add_osd_seek_info) {
1670 double percentage = get_percent_pos(mpctx);
1671 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1672 if (mpctx->sh_video)
1673 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1674 mpctx->add_osd_seek_info = false;
1677 // Look if we have a msg
1678 if((msg = get_osd_msg(mpctx))) {
1679 if (strcmp(osd->osd_text, msg->msg)) {
1680 strncpy(osd->osd_text, msg->msg, 127);
1681 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1682 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1684 return;
1687 if(mpctx->sh_video) {
1688 // fallback on the timer
1689 if (opts->osd_level >= 2) {
1690 int len = get_time_length(mpctx);
1691 int percentage = -1;
1692 char percentage_text[10];
1693 int pts = get_current_time(mpctx);
1695 if (mpctx->osd_show_percentage_until)
1696 percentage = get_percent_pos(mpctx);
1698 if (percentage >= 0)
1699 snprintf(percentage_text, 9, " (%d%%)", percentage);
1700 else
1701 percentage_text[0] = 0;
1703 if (opts->osd_level == 3)
1704 snprintf(osd_text_timer, 63,
1705 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1706 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1707 len/3600,(len/60)%60,len%60,percentage_text);
1708 else
1709 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1710 mpctx->osd_function,pts/3600,(pts/60)%60,
1711 pts%60,percentage_text);
1712 } else
1713 osd_text_timer[0]=0;
1715 if (strcmp(osd->osd_text, osd_text_timer)) {
1716 strncpy(osd->osd_text, osd_text_timer, 63);
1717 vo_osd_changed(OSDTYPE_OSD);
1719 return;
1722 // Clear the term osd line
1723 if (term_osd && osd->osd_text[0]) {
1724 osd->osd_text[0] = 0;
1725 printf("%s\n",term_osd_esc);
1729 ///@}
1730 // OSDMsgStack
1733 void reinit_audio_chain(struct MPContext *mpctx)
1735 struct MPOpts *opts = &mpctx->opts;
1736 if (!mpctx->sh_audio)
1737 return;
1738 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1739 current_module="init_audio_codec";
1740 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1741 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1742 goto init_error;
1744 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1745 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1749 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1750 current_module="af_preinit";
1751 ao_data.samplerate=force_srate;
1752 ao_data.channels=0;
1753 ao_data.format = opts->audio_output_format;
1754 // first init to detect best values
1755 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1756 // input:
1757 mpctx->sh_audio->samplerate,
1758 // output:
1759 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1760 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1761 "pre-init!\n");
1762 exit_player(mpctx, EXIT_ERROR);
1764 current_module="ao2_init";
1765 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1766 0, // plugin flag
1767 ao_data.samplerate,
1768 ao_data.channels,
1769 ao_data.format, 0);
1770 if(!mpctx->audio_out){
1771 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1772 goto init_error;
1774 mpctx->initialized_flags|=INITIALIZED_AO;
1775 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1776 mpctx->audio_out->info->short_name,
1777 ao_data.samplerate, ao_data.channels,
1778 af_fmt2str_short(ao_data.format),
1779 af_fmt2bits(ao_data.format)/8 );
1780 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1781 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1782 if(strlen(mpctx->audio_out->info->comment) > 0)
1783 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1786 // init audio filters:
1787 current_module="af_init";
1788 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1789 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1790 goto init_error;
1792 mpctx->mixer.audio_out = mpctx->audio_out;
1793 mpctx->mixer.volstep = volstep;
1794 return;
1796 init_error:
1797 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1798 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1799 mpctx->d_audio->id = -2;
1803 ///@}
1804 // Command2Property
1807 // Return pts value corresponding to the end point of audio written to the
1808 // ao so far.
1809 static double written_audio_pts(struct MPContext *mpctx)
1811 sh_audio_t *sh_audio = mpctx->sh_audio;
1812 demux_stream_t *d_audio = mpctx->d_audio;
1813 double buffered_output;
1814 // first calculate the end pts of audio that has been output by decoder
1815 double a_pts = sh_audio->pts;
1816 if (a_pts != MP_NOPTS_VALUE)
1817 // Good, decoder supports new way of calculating audio pts.
1818 // sh_audio->pts is the timestamp of the latest input packet with
1819 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1820 // the amount of bytes the decoder has written after that timestamp.
1821 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1822 else {
1823 // Decoder doesn't support new way of calculating pts (or we're
1824 // being called before it has decoded anything with known timestamp).
1825 // Use the old method of audio pts calculation: take the timestamp
1826 // of last packet with known pts the decoder has read data from,
1827 // and add amount of bytes read after the beginning of that packet
1828 // divided by input bps. This will be inaccurate if the input/output
1829 // ratio is not constant for every audio packet or if it is constant
1830 // but not accurately known in sh_audio->i_bps.
1832 a_pts = d_audio->pts;
1833 // ds_tell_pts returns bytes read after last timestamp from
1834 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1835 // it has read but not decoded
1836 if (sh_audio->i_bps)
1837 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1838 (double)sh_audio->i_bps;
1840 // Now a_pts hopefully holds the pts for end of audio from decoder.
1841 // Substract data in buffers between decoder and audio out.
1843 // Decoded but not filtered
1844 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1846 // Data buffered in audio filters, measured in bytes of "missing" output
1847 buffered_output = af_calc_delay(sh_audio->afilter);
1849 // Data that was ready for ao but was buffered because ao didn't fully
1850 // accept everything to internal buffers yet
1851 buffered_output += sh_audio->a_out_buffer_len;
1853 // Filters divide audio length by playback_speed, so multiply by it
1854 // to get the length in original units without speedup or slowdown
1855 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1857 return a_pts + mpctx->video_offset;
1860 // Return pts value corresponding to currently playing audio.
1861 double playing_audio_pts(struct MPContext *mpctx)
1863 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1864 mpctx->audio_out->get_delay();
1867 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1868 struct MPOpts *opts = &mpctx->opts;
1869 // check for frame-drop:
1870 current_module = "check_framedrop";
1871 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1872 static int dropped_frames;
1873 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1874 float d = delay-mpctx->delay;
1875 ++total_frame_cnt;
1876 // we should avoid dropping too many frames in sequence unless we
1877 // are too late. and we allow 100ms A-V delay here:
1878 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1879 && !mpctx->restart_playback) {
1880 ++drop_frame_cnt;
1881 ++dropped_frames;
1882 return frame_dropping;
1883 } else
1884 dropped_frames = 0;
1886 return 0;
1890 #ifdef HAVE_RTC
1891 int rtc_fd = -1;
1892 #endif
1894 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1896 #ifdef HAVE_RTC
1897 if (rtc_fd >= 0){
1898 // -------- RTC -----------
1899 current_module="sleep_rtc";
1900 while (time_frame > 0.000) {
1901 unsigned long rtc_ts;
1902 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1903 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1904 time_frame -= get_relative_time(mpctx);
1906 } else
1907 #endif
1909 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1910 // unnecessarily high CPU usage
1911 float margin = softsleep ? 0.011 : 0;
1912 current_module = "sleep_timer";
1913 while (time_frame > margin) {
1914 usec_sleep(1000000 * (time_frame - margin));
1915 time_frame -= get_relative_time(mpctx);
1917 if (softsleep){
1918 current_module = "sleep_soft";
1919 if (time_frame < 0)
1920 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1921 while (time_frame > 0)
1922 time_frame -= get_relative_time(mpctx); // burn the CPU
1925 return time_frame;
1928 static int select_subtitle(MPContext *mpctx)
1930 struct MPOpts *opts = &mpctx->opts;
1931 // find the best sub to use
1932 int id;
1933 int found = 0;
1934 mpctx->global_sub_pos = -1; // no subs by default
1935 if (vobsub_id >= 0) {
1936 // if user asks for a vobsub id, use that first.
1937 id = vobsub_id;
1938 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1941 if (!found && opts->sub_id >= 0) {
1942 // if user asks for a dvd sub id, use that next.
1943 id = opts->sub_id;
1944 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1947 if (!found) {
1948 // if there are text subs to use, use those. (autosubs come last here)
1949 id = 0;
1950 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1953 if (!found && opts->sub_id == -1) {
1954 // finally select subs by language and container hints
1955 if (opts->sub_id == -1)
1956 opts->sub_id =
1957 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
1958 opts->sub_lang);
1959 if (opts->sub_id >= 0) {
1960 id = opts->sub_id;
1961 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1964 return found;
1967 #ifdef CONFIG_DVDNAV
1968 #ifndef FF_B_TYPE
1969 #define FF_B_TYPE 3
1970 #endif
1971 /// store decoded video image
1972 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1973 mp_image_t *from_mpi) {
1974 mp_image_t *mpi;
1976 /// Do not store B-frames
1977 if (from_mpi->pict_type == FF_B_TYPE)
1978 return to_mpi;
1980 if (to_mpi &&
1981 to_mpi->w == from_mpi->w &&
1982 to_mpi->h == from_mpi->h &&
1983 to_mpi->imgfmt == from_mpi->imgfmt)
1984 mpi = to_mpi;
1985 else {
1986 if (to_mpi)
1987 free_mp_image(to_mpi);
1988 if (from_mpi->w == 0 || from_mpi->h == 0)
1989 return NULL;
1990 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1993 copy_mpi(mpi,from_mpi);
1994 return mpi;
1997 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1998 struct MPOpts *opts = &ctx->opts;
1999 if (ctx->sh_video) {
2000 /// clear video pts
2001 ctx->d_video->pts = 0.0f;
2002 ctx->sh_video->pts = 0.0f;
2003 ctx->sh_video->i_pts = 0.0f;
2004 ctx->sh_video->last_pts = 0.0f;
2005 ctx->sh_video->num_buffered_pts = 0;
2006 ctx->sh_video->num_frames = 0;
2007 ctx->sh_video->num_frames_decoded = 0;
2008 ctx->sh_video->timer = 0.0f;
2009 ctx->sh_video->stream_delay = 0.0f;
2010 ctx->sh_video->timer = 0;
2011 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2014 if (ctx->sh_audio) {
2015 /// free audio packets and reset
2016 ds_free_packs(ctx->d_audio);
2017 audio_delay -= ctx->sh_audio->stream_delay;
2018 ctx->delay =- audio_delay;
2019 ctx->audio_out->reset();
2020 resync_audio_stream(ctx->sh_audio);
2023 audio_delay = 0.0f;
2024 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2025 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2026 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2027 if (dvdsub_lang_id != opts->sub_id) {
2028 opts->sub_id = dvdsub_lang_id;
2029 select_subtitle(ctx);
2033 /// clear all EOF related flags
2034 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2037 /// Restore last decoded DVDNAV (still frame)
2038 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2039 int *in_size,
2040 unsigned char **start,
2041 mp_image_t *decoded_frame)
2043 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2044 return decoded_frame;
2046 /// a change occured in dvdnav stream
2047 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2048 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2049 mp_dvdnav_context_free(mpctx);
2050 mp_dvdnav_reset_stream(mpctx);
2051 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2052 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2055 if (*in_size < 0) {
2056 float len;
2058 /// Display still frame, if any
2059 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2060 decoded_frame = mpctx->nav_smpi;
2062 /// increment video frame : continue playing after still frame
2063 len = get_time_length(mpctx);
2064 if (mpctx->sh_video->pts >= len &&
2065 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2066 mp_dvdnav_skip_still(mpctx->stream);
2067 mp_dvdnav_skip_wait(mpctx->stream);
2069 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2071 if (mpctx->nav_buffer) {
2072 *start = mpctx->nav_start;
2073 *in_size = mpctx->nav_in_size;
2074 if (mpctx->nav_start)
2075 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2079 return decoded_frame;
2082 /// Save last decoded DVDNAV (still frame)
2083 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2084 unsigned char *start,
2085 mp_image_t *decoded_frame)
2087 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2088 return;
2090 free(mpctx->nav_buffer);
2092 mpctx->nav_buffer = malloc(in_size);
2093 mpctx->nav_start = start;
2094 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2095 if (mpctx->nav_buffer)
2096 memcpy(mpctx->nav_buffer,start,in_size);
2098 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2099 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2101 #endif /* CONFIG_DVDNAV */
2103 /* Modify video timing to match the audio timeline. There are two main
2104 * reasons this is needed. First, video and audio can start from different
2105 * positions at beginning of file or after a seek (MPlayer starts both
2106 * immediately even if they have different pts). Second, the file can have
2107 * audio timestamps that are inconsistent with the duration of the audio
2108 * packets, for example two consecutive timestamp values differing by
2109 * one second but only a packet with enough samples for half a second
2110 * of playback between them.
2112 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2114 current_module = "av_sync";
2116 if (!mpctx->sh_audio)
2117 return;
2119 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2120 double v_pts = mpctx->sh_video->pts;
2121 double av_delay = a_pts - v_pts;
2122 // Try to sync vo_flip() so it will *finish* at given time
2123 av_delay += mpctx->last_vo_flip_duration;
2124 av_delay -= audio_delay; // This much pts difference is desired
2126 double change = av_delay * 0.1;
2127 double max_change = default_max_pts_correction >= 0 ?
2128 default_max_pts_correction : frame_time * 0.1;
2129 if (change < -max_change)
2130 change = -max_change;
2131 else if (change > max_change)
2132 change = max_change;
2133 mpctx->delay += change;
2134 mpctx->total_avsync_change += change;
2137 static int fill_audio_out_buffers(struct MPContext *mpctx)
2139 struct MPOpts *opts = &mpctx->opts;
2140 unsigned int t;
2141 double tt;
2142 int playsize;
2143 int playflags=0;
2144 int audio_eof=0;
2145 bool format_change = false;
2146 sh_audio_t * const sh_audio = mpctx->sh_audio;
2148 current_module="play_audio";
2150 while (1) {
2151 int sleep_time;
2152 // all the current uses of ao_data.pts seem to be in aos that handle
2153 // sync completely wrong; there should be no need to use ao_data.pts
2154 // in get_space()
2155 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2156 playsize = mpctx->audio_out->get_space();
2157 if (mpctx->sh_video || playsize >= ao_data.outburst)
2158 break;
2160 // handle audio-only case:
2161 // this is where mplayer sleeps during audio-only playback
2162 // to avoid 100% CPU use
2163 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2164 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2165 usec_sleep(sleep_time * 1000);
2168 // Fill buffer if needed:
2169 current_module="decode_audio";
2170 t = GetTimer();
2171 int res = decode_audio(sh_audio, playsize);
2172 if (res < 0) { // EOF, error or format change
2173 if (res == -2)
2174 format_change = true;
2175 else if (mpctx->d_audio->eof) {
2176 audio_eof = 1;
2177 if (sh_audio->a_out_buffer_len == 0)
2178 return 0;
2181 t = GetTimer() - t;
2182 tt = t*0.000001f; audio_time_usage+=tt;
2183 if (playsize > sh_audio->a_out_buffer_len) {
2184 playsize = sh_audio->a_out_buffer_len;
2185 if (audio_eof)
2186 playflags |= AOPLAY_FINAL_CHUNK;
2188 if (!playsize)
2189 return 1;
2191 // play audio:
2192 current_module="play_audio";
2194 // Is this pts value actually useful for the aos that access it?
2195 // They're obviously badly broken in the way they handle av sync;
2196 // would not having access to this make them more broken?
2197 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2198 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2200 if (playsize > 0) {
2201 sh_audio->a_out_buffer_len -= playsize;
2202 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2203 sh_audio->a_out_buffer_len);
2204 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2206 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2207 // Sanity check to avoid hanging in case current ao doesn't output
2208 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2209 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2210 sh_audio->a_out_buffer_len = 0;
2213 /* The format change isn't handled too gracefully. A more precise
2214 * implementation would require draining buffered old-format audio
2215 * while displaying video, then doing the output format switch.
2217 if (format_change) {
2218 uninit_player(mpctx, INITIALIZED_AO);
2219 reinit_audio_chain(mpctx);
2222 return 1;
2225 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2226 float *aq_sleep_time)
2228 struct MPOpts *opts = &mpctx->opts;
2229 int frame_time_remaining = 0;
2230 current_module="calc_sleep_time";
2232 *time_frame -= get_relative_time(mpctx); // reset timer
2234 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2235 float delay = mpctx->audio_out->get_delay();
2236 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2238 if (autosync) {
2240 * Adjust this raw delay value by calculating the expected
2241 * delay for this frame and generating a new value which is
2242 * weighted between the two. The higher autosync is, the
2243 * closer to the delay value gets to that which "-nosound"
2244 * would have used, and the longer it will take for A/V
2245 * sync to settle at the right value (but it eventually will.)
2246 * This settling time is very short for values below 100.
2248 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2249 float difference = delay - predicted;
2250 delay = predicted + difference / (float)autosync;
2253 *time_frame = delay - mpctx->delay / opts->playback_speed;
2254 *time_frame -= mpctx->video_out->flip_queue_offset;
2256 // delay = amount of audio buffered in soundcard/driver
2257 if (delay > 0.25) delay=0.25; else
2258 if (delay < 0.10) delay=0.10;
2260 if (*time_frame > delay*0.6) {
2261 // sleep time too big - may cause audio drops (buffer underrun)
2262 frame_time_remaining = 1;
2263 *time_frame = delay*0.5;
2265 } else {
2266 // If we're lagging more than 200 ms behind the right playback rate,
2267 // don't try to "catch up".
2268 // If benchmark is set always output frames as fast as possible
2269 // without sleeping.
2270 if (*time_frame < -0.2 || benchmark)
2271 *time_frame = 0;
2272 *time_frame -= mpctx->video_out->flip_queue_offset;
2275 *aq_sleep_time += *time_frame;
2278 //============================== SLEEP: ===================================
2280 // flag 256 means: libvo driver does its timing (dvb card)
2281 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2282 *time_frame = timing_sleep(mpctx, *time_frame);
2283 *time_frame += mpctx->video_out->flip_queue_offset;
2284 return frame_time_remaining;
2287 int reinit_video_chain(struct MPContext *mpctx)
2289 struct MPOpts *opts = &mpctx->opts;
2290 sh_video_t * const sh_video = mpctx->sh_video;
2291 double ar=-1.0;
2292 //================== Init VIDEO (codec & libvo) ==========================
2293 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2294 current_module="preinit_libvo";
2296 //shouldn't we set dvideo->id=-2 when we fail?
2297 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2298 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2299 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2300 goto err_out;
2302 mpctx->initialized_flags|=INITIALIZED_VO;
2305 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2306 mpctx->sh_video->stream_aspect = ar;
2307 current_module="init_video_filters";
2309 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2310 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2312 #ifdef CONFIG_MENU
2313 if(use_menu) {
2314 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2315 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2316 if(!vf_menu) {
2317 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2318 use_menu = 0;
2321 if(vf_menu)
2322 sh_video->vfilter = vf_menu;
2323 #endif
2325 #ifdef CONFIG_ASS
2326 if(opts->ass_enabled) {
2327 int i;
2328 int insert = 1;
2329 if (opts->vf_settings)
2330 for (i = 0; opts->vf_settings[i].name; ++i)
2331 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2332 insert = 0;
2333 break;
2335 if (insert) {
2336 extern vf_info_t vf_info_ass;
2337 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2338 char* vf_arg[] = {"auto", "1", NULL};
2339 int retcode = 0;
2340 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2341 sh_video->vfilter,
2342 "ass", vf_arg,
2343 &retcode);
2344 if (vf_ass)
2345 sh_video->vfilter = vf_ass;
2346 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2347 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2348 else
2349 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2352 #endif
2354 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2356 #ifdef CONFIG_ASS
2357 if (opts->ass_enabled)
2358 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2359 #endif
2361 current_module="init_video_codec";
2363 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2364 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2365 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2367 if(!sh_video->initialized){
2368 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2369 goto err_out;
2372 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2374 if (sh_video->codec)
2375 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2377 sh_video->last_pts = MP_NOPTS_VALUE;
2378 sh_video->num_buffered_pts = 0;
2379 sh_video->next_frame_time = 0;
2381 if(auto_quality>0){
2382 // Auto quality option enabled
2383 output_quality=get_video_quality_max(sh_video);
2384 if(auto_quality>output_quality) auto_quality=output_quality;
2385 else output_quality=auto_quality;
2386 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2387 set_video_quality(sh_video,output_quality);
2390 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2392 current_module="init_vo";
2394 return 1;
2396 err_out:
2397 mpctx->sh_video = mpctx->d_video->sh = NULL;
2398 return 0;
2401 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2403 struct sh_video *sh_video = mpctx->sh_video;
2404 double frame_time = 0;
2405 struct vo *video_out = mpctx->video_out;
2406 while (!video_out->frame_loaded) {
2407 current_module = "filter_video";
2408 // In nocorrect-pts mode there is no way to properly time these frames
2409 if (vo_get_buffered_frame(video_out, 0) >= 0)
2410 break;
2411 if (vf_output_queued_frame(sh_video->vfilter))
2412 continue;
2413 unsigned char *packet = NULL;
2414 frame_time = sh_video->next_frame_time;
2415 if (mpctx->restart_playback)
2416 frame_time = 0;
2417 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2418 &packet, force_fps);
2419 if (in_size < 0) {
2420 #ifdef CONFIG_DVDNAV
2421 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2422 if (mp_dvdnav_is_eof(mpctx->stream))
2423 return -1;
2424 if (mpctx->d_video)
2425 mpctx->d_video->eof = 0;
2426 if (mpctx->d_audio)
2427 mpctx->d_audio->eof = 0;
2428 mpctx->stream->eof = 0;
2429 } else
2430 #endif
2431 return -1;
2433 if (in_size > max_framesize)
2434 max_framesize = in_size;
2435 sh_video->timer += frame_time;
2436 if (mpctx->sh_audio)
2437 mpctx->delay -= frame_time;
2438 // video_read_frame can change fps (e.g. for ASF video)
2439 vo_fps = sh_video->fps;
2440 int framedrop_type = check_framedrop(mpctx, frame_time);
2441 current_module = "decode video";
2443 void *decoded_frame;
2444 #ifdef CONFIG_DVDNAV
2445 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2446 if (in_size >= 0 && !decoded_frame)
2447 #endif
2448 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2449 sh_video->pts);
2450 #ifdef CONFIG_DVDNAV
2451 // Save last still frame for future display
2452 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2453 #endif
2454 if (decoded_frame) {
2455 current_module = "filter video";
2456 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2457 if (!video_out->config_ok)
2458 break;
2461 return frame_time;
2464 static void determine_frame_pts(struct MPContext *mpctx)
2466 struct sh_video *sh_video = mpctx->sh_video;
2467 struct MPOpts *opts = &mpctx->opts;
2469 if (opts->user_pts_assoc_mode) {
2470 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2471 } else if (sh_video->pts_assoc_mode == 0) {
2472 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2473 sh_video->pts_assoc_mode = 1;
2474 else
2475 sh_video->pts_assoc_mode = 2;
2476 } else {
2477 int probcount1 = sh_video->num_reordered_pts_problems;
2478 int probcount2 = sh_video->num_sorted_pts_problems;
2479 if (sh_video->pts_assoc_mode == 2) {
2480 int tmp = probcount1;
2481 probcount1 = probcount2;
2482 probcount2 = tmp;
2484 if (probcount1 >= probcount2 * 1.5 + 2) {
2485 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2486 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2487 "%d.\n", sh_video->pts_assoc_mode);
2490 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2491 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2494 static double update_video(struct MPContext *mpctx)
2496 struct sh_video *sh_video = mpctx->sh_video;
2497 struct vo *video_out = mpctx->video_out;
2498 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2499 mpctx->osd); // hack for vf_expand
2500 if (!mpctx->opts.correct_pts)
2501 return update_video_nocorrect_pts(mpctx);
2503 double pts;
2505 bool hit_eof = false;
2506 while (!video_out->frame_loaded) {
2507 current_module = "filter_video";
2508 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2509 break;
2510 // XXX Time used in this call is not counted in any performance
2511 // timer now, OSD time is not updated correctly for filter-added frames
2512 if (vf_output_queued_frame(sh_video->vfilter))
2513 continue;
2514 if (hit_eof)
2515 return -1;
2516 unsigned char *packet = NULL;
2517 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2518 if (pts != MP_NOPTS_VALUE)
2519 pts += mpctx->video_offset;
2520 if (in_size < 0) {
2521 // try to extract last frames in case of decoder lag
2522 in_size = 0;
2523 pts = MP_NOPTS_VALUE;
2524 hit_eof = true;
2526 if (in_size > max_framesize)
2527 max_framesize = in_size;
2528 current_module = "decode video";
2529 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2530 void *decoded_frame = decode_video(sh_video, packet, in_size,
2531 framedrop_type, pts);
2532 if (decoded_frame) {
2533 determine_frame_pts(mpctx);
2534 current_module = "filter video";
2535 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2536 if (!video_out->config_ok)
2537 break; // We'd likely hang in this loop otherwise
2541 pts = video_out->next_pts;
2542 if (pts == MP_NOPTS_VALUE) {
2543 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2544 // Try to use decoder pts from before filters
2545 pts = sh_video->pts;
2546 if (pts == MP_NOPTS_VALUE)
2547 pts = sh_video->last_pts;
2549 sh_video->pts = pts;
2550 if (sh_video->last_pts == MP_NOPTS_VALUE)
2551 sh_video->last_pts = sh_video->pts;
2552 else if (sh_video->last_pts > sh_video->pts) {
2553 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2554 sh_video->pts, sh_video->last_pts);
2555 /* If the difference in pts is small treat it as jitter around the
2556 * right value (possibly caused by incorrect timestamp ordering) and
2557 * just show this frame immediately after the last one.
2558 * Treat bigger differences as timestamp resets and start counting
2559 * timing of later frames from the position of this one. */
2560 if (sh_video->last_pts - sh_video->pts > 0.5)
2561 sh_video->last_pts = sh_video->pts;
2562 else
2563 sh_video->pts = sh_video->last_pts;
2565 double frame_time = sh_video->pts - sh_video->last_pts;
2566 sh_video->last_pts = sh_video->pts;
2567 sh_video->timer += frame_time;
2568 if (mpctx->sh_audio)
2569 mpctx->delay -= frame_time;
2570 return frame_time;
2573 void pause_player(struct MPContext *mpctx)
2575 if (mpctx->paused)
2576 return;
2577 mpctx->paused = 1;
2578 mpctx->step_frames = 0;
2579 mpctx->time_frame -= get_relative_time(mpctx);
2581 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2582 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2584 if (mpctx->audio_out && mpctx->sh_audio)
2585 mpctx->audio_out->pause(); // pause audio, keep data if possible
2588 void unpause_player(struct MPContext *mpctx)
2590 if (!mpctx->paused)
2591 return;
2592 mpctx->paused = 0;
2594 if (mpctx->audio_out && mpctx->sh_audio)
2595 mpctx->audio_out->resume(); // resume audio
2596 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2597 && !mpctx->step_frames)
2598 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2599 (void)get_relative_time(mpctx); // ignore time that passed during pause
2602 void add_step_frame(struct MPContext *mpctx)
2604 mpctx->step_frames++;
2605 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2606 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2607 unpause_player(mpctx);
2610 static void pause_loop(struct MPContext *mpctx)
2612 mp_cmd_t* cmd;
2613 if (!quiet) {
2614 // Small hack to display the pause message on the OSD line.
2615 // The pause string is: "\n == PAUSE == \r" so we need to
2616 // take the first and the last char out
2617 if (term_osd && !mpctx->sh_video) {
2618 char msg[128] = _("\n ===== PAUSE =====\r");
2619 int mlen = strlen(msg);
2620 msg[mlen-1] = '\0';
2621 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2622 update_osd_msg(mpctx);
2623 } else
2624 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2625 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2628 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2629 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2630 if (cmd) {
2631 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2632 run_command(mpctx, cmd);
2633 mp_cmd_free(cmd);
2634 continue;
2636 if (mpctx->sh_video && mpctx->video_out)
2637 vo_check_events(mpctx->video_out);
2638 #ifdef CONFIG_MENU
2639 if (vf_menu)
2640 vf_menu_pause_update(vf_menu);
2641 #endif
2642 usec_sleep(20000);
2643 update_osd_msg(mpctx);
2644 int hack = vo_osd_changed(0);
2645 vo_osd_changed(hack);
2646 if (hack)
2647 break;
2652 // Find the right mute status and record position for new file position
2653 static void edl_seek_reset(MPContext *mpctx)
2655 mpctx->edl_muted = 0;
2656 next_edl_record = edl_records;
2658 while (next_edl_record) {
2659 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2660 break;
2662 if (next_edl_record->action == EDL_MUTE)
2663 mpctx->edl_muted = !mpctx->edl_muted;
2664 next_edl_record = next_edl_record->next;
2666 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2667 mixer_mute(&mpctx->mixer);
2671 // Execute EDL command for the current position if one exists
2672 static void edl_update(MPContext *mpctx)
2674 if (!next_edl_record)
2675 return;
2677 if (!mpctx->sh_video) {
2678 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2679 free_edl(edl_records);
2680 next_edl_record = NULL;
2681 edl_records = NULL;
2682 return;
2685 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2686 if (next_edl_record->action == EDL_SKIP) {
2687 mpctx->osd_function = OSD_FFW;
2688 mpctx->abs_seek_pos = 0;
2689 mpctx->rel_seek_secs = next_edl_record->length_sec;
2690 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2691 "[%f], length [%f]\n", next_edl_record->start_sec,
2692 next_edl_record->stop_sec, next_edl_record->length_sec);
2694 else if (next_edl_record->action == EDL_MUTE) {
2695 mpctx->edl_muted = !mpctx->edl_muted;
2696 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2697 mixer_mute(&mpctx->mixer);
2698 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2699 next_edl_record->start_sec );
2701 next_edl_record = next_edl_record->next;
2705 static void reinit_decoders(struct MPContext *mpctx)
2707 reinit_video_chain(mpctx);
2708 reinit_audio_chain(mpctx);
2709 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2712 static void seek_reset(struct MPContext *mpctx)
2714 if (mpctx->sh_video) {
2715 current_module = "seek_video_reset";
2716 resync_video_stream(mpctx->sh_video);
2717 mpctx->sh_video->timer = 0;
2718 vo_seek_reset(mpctx->video_out);
2719 mpctx->sh_video->timer = 0;
2720 mpctx->sh_video->num_buffered_pts = 0;
2721 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2722 mpctx->delay = 0;
2723 mpctx->time_frame = 0;
2724 mpctx->restart_playback = true;
2725 // Not all demuxers set d_video->pts during seek, so this value
2726 // (which is used by at least vobsub and edl code below) may
2727 // be completely wrong (probably 0).
2728 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2729 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2730 mpctx->sh_video->pts, mpctx->video_offset,
2731 mpctx->d_sub, 1);
2732 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2735 if (mpctx->sh_audio) {
2736 current_module = "seek_audio_reset";
2737 resync_audio_stream(mpctx->sh_audio);
2738 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2739 mpctx->sh_audio->a_buffer_len = 0;
2740 mpctx->sh_audio->a_out_buffer_len = 0;
2741 if (!mpctx->sh_video)
2742 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2743 mpctx->video_offset, mpctx->d_sub, 1);
2746 if (vo_vobsub && mpctx->sh_video) {
2747 current_module = "seek_vobsub_reset";
2748 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2751 edl_seek_reset(mpctx);
2753 mpctx->total_avsync_change = 0;
2754 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2755 drop_frame_cnt = 0;
2757 current_module = NULL;
2760 static bool timeline_set_part(struct MPContext *mpctx, int i)
2762 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2763 struct timeline_part *n = mpctx->timeline + i;
2764 mpctx->timeline_part = i;
2765 mpctx->video_offset = n->start - n->source_start;
2766 if (n->source == p->source)
2767 return false;
2768 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2769 mpctx->demuxer = n->source->demuxer;
2770 mpctx->d_video = mpctx->demuxer->video;
2771 mpctx->d_audio = mpctx->demuxer->audio;
2772 mpctx->d_sub = mpctx->demuxer->sub;
2773 mpctx->sh_video = mpctx->d_video->sh;
2774 mpctx->sh_audio = mpctx->d_audio->sh;
2775 return true;
2778 // Given pts, switch playback to the corresponding part.
2779 // Return offset within that part.
2780 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2781 bool *need_reset)
2783 if (pts < 0)
2784 pts = 0;
2785 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2786 struct timeline_part *p = mpctx->timeline + i;
2787 if (pts < (p+1)->start) {
2788 *need_reset = timeline_set_part(mpctx, i);
2789 return pts - p->start + p->source_start;
2792 return -1;
2796 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2797 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2798 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2799 static int seek(MPContext *mpctx, double amount, int style)
2801 current_module = "seek";
2802 if (mpctx->stop_play == AT_END_OF_FILE)
2803 mpctx->stop_play = KEEP_PLAYING;
2804 if (style & SEEK_FACTOR
2805 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2806 || amount < 0)
2807 mpctx->last_chapter_seek = -1;
2808 if (mpctx->timeline && style & SEEK_FACTOR) {
2809 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2810 style &= ~SEEK_FACTOR;
2812 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2813 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2814 style |= SEEK_ABSOLUTE;
2815 if (amount > 0)
2816 style |= SEEK_FORWARD;
2817 else
2818 style |= SEEK_BACKWARD;
2819 amount += mpctx->sh_video->pts;
2822 /* At least the liba52 decoder wants to read from the input stream
2823 * during initialization, so reinit must be done after the demux_seek()
2824 * call that clears possible stream EOF. */
2825 bool need_reset = false;
2826 if (mpctx->timeline) {
2827 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2828 if (amount == -1) {
2829 mpctx->stop_play = AT_END_OF_FILE;
2830 // Clear audio from current position
2831 if (mpctx->sh_audio) {
2832 mpctx->audio_out->reset();
2833 mpctx->sh_audio->a_buffer_len = 0;
2834 mpctx->sh_audio->a_out_buffer_len = 0;
2836 return -1;
2839 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2840 if (need_reset)
2841 reinit_decoders(mpctx);
2842 if (seekresult == 0)
2843 return -1;
2845 seek_reset(mpctx);
2846 return 0;
2850 double get_time_length(struct MPContext *mpctx)
2852 if (mpctx->timeline)
2853 return mpctx->timeline[mpctx->num_timeline_parts].start;
2855 struct demuxer *demuxer = mpctx->demuxer;
2856 double get_time_ans;
2857 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
2858 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
2859 (void *) &get_time_ans) > 0)
2860 return get_time_ans;
2862 struct sh_video *sh_video = mpctx->d_video->sh;
2863 struct sh_audio *sh_audio = mpctx->d_audio->sh;
2864 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
2865 return (double) (demuxer->movi_end - demuxer->movi_start) /
2866 (sh_video->i_bps + sh_audio->i_bps);
2867 if (sh_video && sh_video->i_bps)
2868 return (double) (demuxer->movi_end - demuxer->movi_start) /
2869 sh_video->i_bps;
2870 if (sh_audio && sh_audio->i_bps)
2871 return (double) (demuxer->movi_end - demuxer->movi_start) /
2872 sh_audio->i_bps;
2873 return 0;
2876 /* If there are timestamps from stream level then use those (for example
2877 * DVDs can have consistent times there while the MPEG-level timestamps
2878 * reset). */
2879 double get_current_time(struct MPContext *mpctx)
2881 struct demuxer *demuxer = mpctx->demuxer;
2882 if (demuxer->stream_pts != MP_NOPTS_VALUE)
2883 return demuxer->stream_pts;
2884 struct sh_video *sh_video = demuxer->video->sh;
2885 if (sh_video)
2886 return sh_video->pts;
2887 return playing_audio_pts(mpctx);
2890 int get_percent_pos(struct MPContext *mpctx)
2892 struct demuxer *demuxer = mpctx->demuxer;
2893 int ans = 0;
2894 if (mpctx->timeline)
2895 ans = get_current_time(mpctx) * 100 /
2896 mpctx->timeline[mpctx->num_timeline_parts].start;
2897 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
2899 else {
2900 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
2901 off_t pos = demuxer->filepos > 0 ?
2902 demuxer->filepos : stream_tell(demuxer->stream);
2903 if (len > 0)
2904 ans = (pos - demuxer->movi_start) / len;
2905 else
2906 ans = 0;
2908 if (ans < 0)
2909 ans = 0;
2910 if (ans > 100)
2911 ans = 100;
2912 return ans;
2915 // -2 is no chapters, -1 is before first chapter
2916 int get_current_chapter(struct MPContext *mpctx)
2918 if (!mpctx->chapters || !mpctx->sh_video)
2919 return FFMAX(mpctx->last_chapter_seek,
2920 demuxer_get_current_chapter(mpctx->demuxer));
2922 int i;
2923 double current_pts = mpctx->sh_video->pts;
2924 for (i = 1; i < mpctx->num_chapters; i++)
2925 if (current_pts < mpctx->chapters[i].start)
2926 break;
2927 return FFMAX(mpctx->last_chapter_seek, i - 1);
2930 // currently returns a string allocated with malloc, not talloc
2931 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2933 if (!mpctx->chapters || !mpctx->sh_video)
2934 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2935 return strdup(mpctx->chapters[chapter].name);
2938 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2939 char **chapter_name)
2941 mpctx->last_chapter_seek = -1;
2942 if (!mpctx->chapters || !mpctx->sh_video) {
2943 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2944 chapter_name);
2945 if (res >= 0) {
2946 if (*seek_pts == -1)
2947 seek_reset(mpctx);
2948 else {
2949 mpctx->last_chapter_seek = res;
2950 mpctx->last_chapter_pts = *seek_pts;
2953 return res;
2956 if (chapter >= mpctx->num_chapters)
2957 return -1;
2958 if (chapter < 0)
2959 chapter = 0;
2960 *seek_pts = mpctx->chapters[chapter].start;
2961 mpctx->last_chapter_seek = chapter;
2962 mpctx->last_chapter_pts = *seek_pts;
2963 if (chapter_name)
2964 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2965 return chapter;
2968 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2969 struct content_source *sources,
2970 int num_sources,
2971 unsigned char uid_map[][16])
2973 int num_filenames = 0;
2974 char **filenames = NULL;
2975 if (num_sources > 1) {
2976 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2977 "other sources.\n");
2978 if (mpctx->stream->type != STREAMTYPE_FILE) {
2979 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2980 "normal disk file. Will not search for related files.\n");
2981 } else {
2982 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2983 "same directory to find referenced sources.\n");
2984 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2985 &num_filenames);
2989 int num_left = num_sources - 1;
2990 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2991 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2992 filename_recode(filenames[i]));
2993 int format;
2994 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2995 if (!s)
2996 continue;
2997 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2998 mpctx->opts.audio_id,
2999 mpctx->opts.video_id,
3000 mpctx->opts.sub_id, filenames[i]);
3001 if (!d) {
3002 free_stream(s);
3003 continue;
3005 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3006 for (int i = 1; i < num_sources; i++) {
3007 if (sources[i].demuxer)
3008 continue;
3009 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3010 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3011 i, filename_recode(d->filename));
3012 sources[i].stream = s;
3013 sources[i].demuxer = d;
3014 num_left--;
3015 goto match;
3019 free_demuxer(d);
3020 free_stream(s);
3021 continue;
3022 match:
3025 talloc_free(filenames);
3026 if (num_left) {
3027 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3028 "There will be parts MISSING from the video!\n");
3029 for (int i = 1, j = 1; i < num_sources; i++)
3030 if (sources[i].demuxer) {
3031 sources[j] = sources[i];
3032 memcpy(uid_map[j], uid_map[i], 16);
3033 j++;
3036 return num_sources - num_left;
3039 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3041 if (!mpctx->opts.ordered_chapters) {
3042 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3043 "you have disabled support for them. Ignoring.\n");
3044 return;
3047 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3048 "edit timeline.\n");
3050 struct demuxer *demuxer = mpctx->demuxer;
3051 struct matroska_data *m = &demuxer->matroska_data;
3053 // +1 because sources/uid_map[0] is original file even if all chapters
3054 // actually use other sources and need separate entries
3055 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3056 m->num_ordered_chapters+1);
3057 sources[0].stream = mpctx->stream;
3058 sources[0].demuxer = mpctx->demuxer;
3059 unsigned char uid_map[m->num_ordered_chapters+1][16];
3060 int num_sources = 1;
3061 memcpy(uid_map[0], m->segment_uid, 16);
3063 for (int i = 0; i < m->num_ordered_chapters; i++) {
3064 struct matroska_chapter *c = m->ordered_chapters + i;
3065 if (!c->has_segment_uid)
3066 memcpy(c->segment_uid, m->segment_uid, 16);
3068 for (int j = 0; j < num_sources; j++)
3069 if (!memcmp(c->segment_uid, uid_map[j], 16))
3070 goto found1;
3071 memcpy(uid_map[num_sources], c->segment_uid, 16);
3072 sources[num_sources] = (struct content_source){};
3073 num_sources++;
3074 found1:
3078 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3079 uid_map);
3082 // +1 for terminating chapter with start time marking end of last real one
3083 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3084 m->num_ordered_chapters + 1);
3085 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3086 m->num_ordered_chapters);
3087 uint64_t starttime = 0;
3088 uint64_t missing_time = 0;
3089 int part_count = 0;
3090 int num_chapters = 0;
3091 uint64_t prev_part_offset = 0;
3092 for (int i = 0; i < m->num_ordered_chapters; i++) {
3093 struct matroska_chapter *c = m->ordered_chapters + i;
3095 int j;
3096 for (j = 0; j < num_sources; j++) {
3097 if (!memcmp(c->segment_uid, uid_map[j], 16))
3098 goto found2;
3100 missing_time += c->end - c->start;
3101 continue;
3102 found2:;
3103 chapters[num_chapters].start = starttime / 1000.;
3104 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3105 /* Only add a separate part if the time or file actually changes.
3106 * Matroska files have chapter divisions that are redundant from
3107 * timeline point of view because the same chapter structure is used
3108 * both to specify the timeline and for normal chapter information.
3109 * Removing a missing inserted external chapter can also cause this. */
3110 if (part_count == 0 || c->start != starttime + prev_part_offset
3111 || sources + j != timeline[part_count - 1].source) {
3112 timeline[part_count].source = sources + j;
3113 timeline[part_count].start = chapters[num_chapters].start;
3114 timeline[part_count].source_start = c->start / 1000.;
3115 prev_part_offset = c->start - starttime;
3116 part_count++;
3118 starttime += c->end - c->start;
3119 num_chapters++;
3121 timeline[part_count].start = starttime / 1000.;
3123 if (!part_count) {
3124 // None of the parts come from the file itself???
3125 talloc_free(sources);
3126 talloc_free(timeline);
3127 talloc_free(chapters);
3128 return;
3131 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3132 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3133 timeline[part_count].start);
3134 if (missing_time)
3135 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3136 "from the timeline!\n", missing_time / 1000.);
3137 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3138 for (int i = 0; i < num_sources; i++)
3139 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3140 filename_recode(sources[i].demuxer->filename));
3141 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3142 "source_start, source):\n");
3143 for (int i = 0; i < part_count; i++) {
3144 struct timeline_part *p = timeline + i;
3145 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3146 p->source_start, p->source - sources);
3148 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3149 mpctx->sources = sources;
3150 mpctx->num_sources = num_sources;
3151 mpctx->timeline = timeline;
3152 mpctx->num_timeline_parts = part_count;
3153 mpctx->num_chapters = num_chapters;
3154 mpctx->chapters = chapters;
3156 mpctx->timeline_part = 0;
3157 mpctx->demuxer = timeline[0].source->demuxer;
3161 static int read_keys(void *ctx, int fd)
3163 getch2(ctx);
3164 return mplayer_get_key(ctx, 0);
3168 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3169 * file for some tools to link against. */
3170 #ifndef DISABLE_MAIN
3171 int main(int argc,char* argv[]){
3174 char * mem_ptr;
3176 // movie info:
3178 /* Flag indicating whether MPlayer should exit without playing anything. */
3179 int opt_exit = 0;
3180 int i;
3182 struct MPContext *mpctx = &(struct MPContext){
3183 .osd_function = OSD_PLAY,
3184 .begin_skip = MP_NOPTS_VALUE,
3185 .play_tree_step = 1,
3186 .global_sub_pos = -1,
3187 .set_of_sub_pos = -1,
3188 .file_format = DEMUXER_TYPE_UNKNOWN,
3189 .last_dvb_step = 1,
3192 InitTimer();
3193 srand(GetTimerMS());
3195 mp_msg_init();
3196 set_av_log_callback();
3198 #ifdef CONFIG_X11
3199 mpctx->x11_state = vo_x11_init_state();
3200 #endif
3201 struct MPOpts *opts = &mpctx->opts;
3202 set_default_mplayer_options(opts);
3203 // Create the config context and register the options
3204 mpctx->mconfig = m_config_new(opts, cfg_include);
3205 m_config_register_options(mpctx->mconfig,mplayer_opts);
3206 m_config_register_options(mpctx->mconfig, common_opts);
3207 mp_input_register_options(mpctx->mconfig);
3209 // Preparse the command line
3210 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3212 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3213 set_path_env();
3214 #endif
3216 #ifdef CONFIG_TV
3217 stream_tv_defaults.immediate = 1;
3218 #endif
3220 parse_cfgfiles(mpctx, mpctx->mconfig);
3222 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3223 if(mpctx->playtree == NULL)
3224 opt_exit = 1;
3225 else {
3226 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3227 if(mpctx->playtree) {
3228 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3229 if(mpctx->playtree_iter) {
3230 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3231 play_tree_iter_free(mpctx->playtree_iter);
3232 mpctx->playtree_iter = NULL;
3234 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3238 mpctx->key_fifo = mp_fifo_create(opts);
3240 print_version("MPlayer");
3242 #if defined(__MINGW32__) || defined(__CYGWIN__)
3244 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3245 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3246 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3247 if (kernel32) {
3248 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3249 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3251 if (setDEP) setDEP(3);
3252 if (setDllDir) setDllDir("");
3254 // stop Windows from showing all kinds of annoying error dialogs
3255 SetErrorMode(0x8003);
3256 // request 1ms timer resolution
3257 timeBeginPeriod(1);
3258 #endif
3260 #ifdef CONFIG_PRIORITY
3261 set_priority();
3262 #endif
3264 if (codec_path)
3265 set_codec_path(codec_path);
3267 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3268 list_video_out();
3269 opt_exit = 1;
3272 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3273 list_audio_out();
3274 opt_exit = 1;
3277 /* Check codecs.conf. */
3278 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3279 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3280 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3281 if(!parse_codec_cfg(NULL)){
3282 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3284 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3287 free( mem_ptr ); // release the buffer created by get_path()
3290 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3291 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3292 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3293 list_codecs(1);
3294 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3295 opt_exit = 1;
3297 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3298 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3299 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3300 list_codecs(0);
3301 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3302 opt_exit = 1;
3304 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3305 vfm_help();
3306 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3307 opt_exit = 1;
3309 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3310 afm_help();
3311 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3312 opt_exit = 1;
3314 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3315 af_help();
3316 printf("\n");
3317 opt_exit = 1;
3319 #ifdef CONFIG_X11
3320 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3321 fstype_help();
3322 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3323 opt_exit = 1;
3325 #endif
3326 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3327 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3328 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3329 demuxer_help();
3330 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3331 opt_exit = 1;
3333 if(list_properties) {
3334 property_print_help();
3335 opt_exit = 1;
3338 if(opt_exit)
3339 exit_player(mpctx, EXIT_NONE);
3341 if(!mpctx->filename && !player_idle_mode){
3342 // no file/vcd/dvd -> show HELP:
3343 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3344 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3347 /* Display what configure line was used */
3348 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3350 // Many users forget to include command line in bugreports...
3351 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3352 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3353 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3354 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3357 //------ load global data first ------
3359 mpctx->osd = osd_create();
3361 // check font
3362 #ifdef CONFIG_FREETYPE
3363 init_freetype();
3364 #endif
3365 #ifdef CONFIG_FONTCONFIG
3366 if(font_fontconfig <= 0)
3368 #endif
3369 #ifdef CONFIG_BITMAP_FONT
3370 if(font_name){
3371 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3372 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3373 filename_recode(font_name));
3374 } else {
3375 // try default:
3376 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3377 free(mem_ptr); // release the buffer created by get_path()
3378 if(!vo_font)
3379 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3381 if (sub_font_name)
3382 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3383 else
3384 mpctx->osd->sub_font = vo_font;
3385 #endif
3386 #ifdef CONFIG_FONTCONFIG
3388 #endif
3390 #ifdef CONFIG_ASS
3391 ass_library = ass_init();
3392 #endif
3394 #ifdef HAVE_RTC
3395 if(!nortc)
3397 // seteuid(0); /* Can't hurt to try to get root here */
3398 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3399 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3400 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3401 else {
3402 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3404 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3405 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3406 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3407 close (rtc_fd);
3408 rtc_fd = -1;
3409 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3410 /* variable only by the root */
3411 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3412 close (rtc_fd);
3413 rtc_fd = -1;
3414 } else
3415 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3418 if(rtc_fd<0)
3419 #endif /* HAVE_RTC */
3420 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3421 softsleep?"software":timer_name);
3423 #ifdef HAVE_TERMCAP
3424 load_termcap(NULL); // load key-codes
3425 #endif
3427 // ========== Init keyboard FIFO (connection to libvo) ============
3429 // Init input system
3430 current_module = "init_input";
3431 mpctx->input = mp_input_init(&opts->input);
3432 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3433 if(slave_mode)
3434 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3435 else if(!noconsolecontrols)
3436 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3437 // Set the libstream interrupt callback
3438 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3440 #ifdef CONFIG_MENU
3441 if(use_menu) {
3442 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3443 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3444 else {
3445 menu_cfg = get_path("menu.conf");
3446 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3447 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3448 else {
3449 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3450 MPLAYER_CONFDIR "/menu.conf"))
3451 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3452 else {
3453 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3454 use_menu = 0;
3459 #endif
3461 current_module = NULL;
3463 /// Catch signals
3464 #ifndef __MINGW32__
3465 signal(SIGCHLD,child_sighandler);
3466 #endif
3468 #ifdef CONFIG_CRASH_DEBUG
3469 prog_path = argv[0];
3470 #endif
3471 //========= Catch terminate signals: ================
3472 // terminate requests:
3473 signal(SIGTERM,exit_sighandler); // kill
3474 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3476 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3478 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3479 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3480 #ifdef CONFIG_SIGHANDLER
3481 // fatal errors:
3482 signal(SIGBUS,exit_sighandler); // bus error
3483 signal(SIGSEGV,exit_sighandler); // segfault
3484 signal(SIGILL,exit_sighandler); // illegal instruction
3485 signal(SIGFPE,exit_sighandler); // floating point exc.
3486 signal(SIGABRT,exit_sighandler); // abort()
3487 #ifdef CONFIG_CRASH_DEBUG
3488 if (crash_debug)
3489 signal(SIGTRAP,exit_sighandler);
3490 #endif
3491 #endif
3493 // ******************* Now, let's see the per-file stuff ********************
3495 play_next_file:
3497 // init global sub numbers
3498 mpctx->global_sub_size = 0;
3499 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3501 if (mpctx->filename) {
3502 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3503 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3504 load_per_file_config (mpctx->mconfig, mpctx->filename);
3507 if (opts->video_driver_list)
3508 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3509 if (opts->audio_driver_list)
3510 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3512 // We must enable getch2 here to be able to interrupt network connection
3513 // or cache filling
3514 if(!noconsolecontrols && !slave_mode){
3515 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3516 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3517 else
3518 getch2_enable(); // prepare stdin for hotkeys...
3519 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3520 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3523 // =================== GUI idle loop (STOP state) ===========================
3524 while (player_idle_mode && !mpctx->filename) {
3525 play_tree_t * entry = NULL;
3526 mp_cmd_t * cmd;
3527 if (mpctx->video_out && mpctx->video_out->config_ok)
3528 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3529 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3530 if (mpctx->video_out)
3531 vo_check_events(mpctx->video_out);
3532 usec_sleep(20000);
3534 switch (cmd->id) {
3535 case MP_CMD_LOADFILE:
3536 // prepare a tree entry with the new filename
3537 entry = play_tree_new();
3538 play_tree_add_file(entry, cmd->args[0].v.s);
3539 // The entry is added to the main playtree after the switch().
3540 break;
3541 case MP_CMD_LOADLIST:
3542 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3543 break;
3544 case MP_CMD_QUIT:
3545 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3546 break;
3547 case MP_CMD_VO_FULLSCREEN:
3548 case MP_CMD_GET_PROPERTY:
3549 case MP_CMD_SET_PROPERTY:
3550 case MP_CMD_STEP_PROPERTY:
3551 run_command(mpctx, cmd);
3552 break;
3555 mp_cmd_free(cmd);
3557 if (entry) { // user entered a command that gave a valid entry
3558 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3559 play_tree_free_list(mpctx->playtree->child, 1);
3560 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3562 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3564 play_tree_set_child(mpctx->playtree, entry);
3566 /* Make iterator start at the top the of tree. */
3567 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3568 if (!mpctx->playtree_iter) continue;
3570 // find the first real item in the tree
3571 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3572 // no items!
3573 play_tree_iter_free(mpctx->playtree_iter);
3574 mpctx->playtree_iter = NULL;
3575 continue; // wait for next command
3577 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3580 //---------------------------------------------------------------------------
3582 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3583 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3585 if (mpctx->filename) {
3586 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3587 filename_recode(mpctx->filename));
3588 if(use_filename_title && opts->vo_wintitle == NULL)
3589 opts->vo_wintitle = strdup(mp_basename2(mpctx->filename));
3592 if (edl_filename) {
3593 if (edl_records) free_edl(edl_records);
3594 next_edl_record = edl_records = edl_parse_file();
3596 if (edl_output_filename) {
3597 if (edl_fd) fclose(edl_fd);
3598 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3600 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3601 filename_recode(edl_output_filename));
3605 //==================== Open VOB-Sub ============================
3607 current_module="vobsub";
3608 if (vobsub_name){
3609 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3610 if(vo_vobsub==NULL)
3611 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3612 filename_recode(vobsub_name));
3613 } else if (sub_auto && mpctx->filename){
3614 /* try to autodetect vobsub from movie filename ::atmos */
3615 char *buf = strdup(mpctx->filename), *psub;
3616 char *pdot = strrchr(buf, '.');
3617 char *pslash = strrchr(buf, '/');
3618 #if defined(__MINGW32__) || defined(__CYGWIN__)
3619 if (!pslash) pslash = strrchr(buf, '\\');
3620 #endif
3621 if (pdot && (!pslash || pdot > pslash))
3622 *pdot = '\0';
3623 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3624 /* try from ~/.mplayer/sub */
3625 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3626 char *bname;
3627 int l;
3628 bname = strrchr(buf,'/');
3629 #if defined(__MINGW32__) || defined(__CYGWIN__)
3630 if(!bname) bname = strrchr(buf,'\\');
3631 #endif
3632 if(bname) bname++;
3633 else bname = buf;
3634 l = strlen(psub) + strlen(bname) + 1;
3635 psub = realloc(psub,l);
3636 strcat(psub,bname);
3637 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3638 free(psub);
3640 free(buf);
3642 if(vo_vobsub){
3643 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3644 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3645 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3647 // setup global sub numbering
3648 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3651 //============ Open & Sync STREAM --- fork cache2 ====================
3653 mpctx->stream=NULL;
3654 mpctx->demuxer=NULL;
3655 if (mpctx->d_audio) {
3656 //free_demuxer_stream(mpctx->d_audio);
3657 mpctx->d_audio=NULL;
3659 if (mpctx->d_video) {
3660 //free_demuxer_stream(d_video);
3661 mpctx->d_video=NULL;
3663 mpctx->sh_audio=NULL;
3664 mpctx->sh_video=NULL;
3666 current_module="open_stream";
3667 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3668 if(!mpctx->stream) { // error...
3669 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3670 goto goto_next_file;
3672 mpctx->initialized_flags|=INITIALIZED_STREAM;
3674 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3675 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3676 "playlist support will not be used automatically.\n"
3677 "MPlayer's playlist code is unsafe and should only be used with "
3678 "trusted sources.\nPlayback will probably fail.\n\n");
3679 #if 0
3680 play_tree_t* entry;
3681 // Handle playlist
3682 current_module="handle_playlist";
3683 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3684 filename_recode(mpctx->filename));
3685 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3686 mpctx->eof=playtree_add_playlist(mpctx, entry);
3687 goto goto_next_file;
3688 #endif
3690 mpctx->stream->start_pos+=seek_to_byte;
3692 if(stream_dump_type==5){
3693 unsigned char buf[4096];
3694 int len;
3695 FILE *f;
3696 current_module="dumpstream";
3697 stream_reset(mpctx->stream);
3698 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3699 f=fopen(opts->stream_dump_name,"wb");
3700 if(!f){
3701 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3702 exit_player(mpctx, EXIT_ERROR);
3704 if (opts->chapterrange[0] > 1) {
3705 int chapter = opts->chapterrange[0] - 1;
3706 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3708 while(!mpctx->stream->eof && !async_quit_request){
3709 len=stream_read(mpctx->stream,buf,4096);
3710 if(len>0) {
3711 if(fwrite(buf,len,1,f) != 1) {
3712 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3713 exit_player(mpctx, EXIT_ERROR);
3716 if (opts->chapterrange[1] > 0) {
3717 int chapter = -1;
3718 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3719 &chapter) == STREAM_OK
3720 && chapter + 1 > opts->chapterrange[1])
3721 break;
3724 if(fclose(f)) {
3725 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3726 exit_player(mpctx, EXIT_ERROR);
3728 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3729 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3732 #ifdef CONFIG_DVDREAD
3733 if(mpctx->stream->type==STREAMTYPE_DVD){
3734 current_module="dvd lang->id";
3735 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3736 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3737 // setup global sub numbering
3738 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3739 current_module=NULL;
3741 #endif
3743 #ifdef CONFIG_DVDNAV
3744 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3745 current_module="dvdnav lang->id";
3746 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3747 dvdsub_lang_id = -3;
3748 if(opts->sub_lang && opts->sub_id==-1)
3749 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3750 // setup global sub numbering
3751 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3752 current_module=NULL;
3754 #endif
3756 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3757 goto_enable_cache:
3758 if(stream_cache_size>0){
3759 int res;
3760 current_module="enable_cache";
3761 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3762 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3763 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3764 if(res == 0)
3765 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3768 //============ Open DEMUXERS --- DETECT file type =======================
3769 current_module="demux_open";
3771 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3773 // HACK to get MOV Reference Files working
3775 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3777 unsigned char* playlist_entry;
3778 play_tree_t *list = NULL, *entry = NULL;
3780 current_module="handle_demux_playlist";
3781 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3783 char *temp, *bname;
3785 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3786 filename_recode(playlist_entry));
3788 bname=mp_basename(playlist_entry);
3789 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3790 continue;
3792 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3793 continue;
3795 entry = play_tree_new();
3797 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3799 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3800 if (temp)
3802 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3803 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3804 strcat(temp, playlist_entry);
3805 if (!strcmp(temp, mpctx->filename)) {
3806 free(temp);
3807 continue;
3809 play_tree_add_file(entry,temp);
3810 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3811 free(temp);
3814 else
3815 play_tree_add_file(entry,playlist_entry);
3817 if(!list)
3818 list = entry;
3819 else
3820 play_tree_append_entry(list,entry);
3822 free_demuxer(mpctx->demuxer);
3823 mpctx->demuxer = NULL;
3825 if (list)
3827 entry = play_tree_new();
3828 play_tree_set_child(entry,list);
3829 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3830 goto goto_next_file;
3834 if(!mpctx->demuxer) {
3835 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
3836 goto goto_next_file;
3839 if (mpctx->demuxer->matroska_data.ordered_chapters)
3840 build_ordered_chapter_timeline(mpctx);
3842 if (!mpctx->sources) {
3843 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3844 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3845 .demuxer = mpctx->demuxer};
3846 mpctx->num_sources = 1;
3849 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3851 #ifdef CONFIG_ASS
3852 if (opts->ass_enabled && ass_library) {
3853 for (int j = 0; j < mpctx->num_sources; j++) {
3854 struct demuxer *d = mpctx->sources[j].demuxer;
3855 for (int i = 0; i < d->num_attachments; i++) {
3856 struct demux_attachment *att = d->attachments + i;
3857 if (use_embedded_fonts && attachment_is_font(att))
3858 ass_add_font(ass_library, att->name, att->data, att->data_size);
3862 #endif
3864 current_module="demux_open2";
3866 mpctx->d_audio=mpctx->demuxer->audio;
3867 mpctx->d_video=mpctx->demuxer->video;
3868 mpctx->d_sub=mpctx->demuxer->sub;
3870 if (ts_prog) {
3871 int tmp = ts_prog;
3872 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3874 // select audio stream
3875 if (mpctx->num_sources)
3876 for (int i = 0; i < mpctx->num_sources; i++)
3877 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3878 opts->audio_lang);
3879 else
3880 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
3882 // DUMP STREAMS:
3883 if((stream_dump_type)&&(stream_dump_type<4)){
3884 FILE *f;
3885 demux_stream_t *ds=NULL;
3886 current_module="dump";
3887 // select stream to dump
3888 switch(stream_dump_type){
3889 case 1: ds=mpctx->d_audio;break;
3890 case 2: ds=mpctx->d_video;break;
3891 case 3: ds=mpctx->d_sub;break;
3893 if(!ds){
3894 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3895 exit_player(mpctx, EXIT_ERROR);
3897 // disable other streams:
3898 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3899 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3900 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3901 // let's dump it!
3902 f=fopen(opts->stream_dump_name,"wb");
3903 if(!f){
3904 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3905 exit_player(mpctx, EXIT_ERROR);
3907 while(!ds->eof){
3908 unsigned char* start;
3909 int in_size=ds_get_packet(ds,&start);
3910 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3911 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3912 if(in_size>0) fwrite(start,in_size,1,f);
3913 if (opts->chapterrange[1] > 0) {
3914 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3915 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3916 break;
3919 fclose(f);
3920 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3921 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3924 mpctx->sh_audio=mpctx->d_audio->sh;
3925 mpctx->sh_video=mpctx->d_video->sh;
3927 if(mpctx->sh_video){
3929 current_module="video_read_properties";
3930 if(!video_read_properties(mpctx->sh_video)) {
3931 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3932 mpctx->sh_video=mpctx->d_video->sh=NULL;
3933 } else {
3934 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3935 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3936 mpctx->sh_video->fps,mpctx->sh_video->frametime
3939 /* need to set fps here for output encoders to pick it up in their init */
3940 if(force_fps){
3941 mpctx->sh_video->fps=force_fps;
3942 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3944 vo_fps = mpctx->sh_video->fps;
3946 if(!mpctx->sh_video->fps && !force_fps){
3947 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3948 mpctx->opts.correct_pts = 1;
3954 if(!mpctx->sh_video && !mpctx->sh_audio){
3955 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3956 #ifdef CONFIG_DVBIN
3957 if(mpctx->stream->type == STREAMTYPE_DVB)
3959 int dir;
3960 int v = mpctx->last_dvb_step;
3961 if(v > 0)
3962 dir = DVB_CHANNEL_HIGHER;
3963 else
3964 dir = DVB_CHANNEL_LOWER;
3966 if(dvb_step_channel(mpctx->stream, dir)) {
3967 mpctx->stop_play = PT_NEXT_ENTRY;
3968 mpctx->dvbin_reopen = 1;
3971 #endif
3972 goto goto_next_file; // exit_player(_("Fatal error"));
3975 /* display clip info */
3976 demux_info_print(mpctx->demuxer);
3978 //================== Read SUBTITLES (DVD & TEXT) ==========================
3979 if(vo_spudec==NULL &&
3980 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3981 init_vo_spudec(mpctx);
3984 // after reading video params we should load subtitles because
3985 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3986 // check .sub
3987 current_module="read_subtitles_file";
3988 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3989 if(sub_name){
3990 for (i = 0; sub_name[i] != NULL; ++i)
3991 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3993 if(sub_auto) { // auto load sub file ...
3994 char *psub = get_path( "sub/" );
3995 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3996 int i = 0;
3997 free(psub); // release the buffer created by get_path() above
3998 while (tmp[i]) {
3999 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4000 free(tmp[i++]);
4002 free(tmp);
4004 if (mpctx->set_of_sub_size > 0)
4005 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4007 if (select_subtitle(mpctx)) {
4008 if(subdata)
4009 switch (stream_dump_type) {
4010 case 3: list_sub_file(subdata); break;
4011 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
4012 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
4013 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
4014 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
4015 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
4019 print_file_properties(mpctx, mpctx->filename);
4021 if(!mpctx->sh_video) goto main; // audio-only
4023 if(!reinit_video_chain(mpctx)) {
4024 if(!mpctx->sh_video){
4025 if(!mpctx->sh_audio) goto goto_next_file;
4026 goto main; // exit_player(_("Fatal error"));
4030 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4031 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4033 #ifdef CONFIG_FREETYPE
4034 force_load_font = 1;
4035 #endif
4037 //================== MAIN: ==========================
4038 main:
4039 current_module="main";
4041 if(playing_msg) {
4042 char* msg = property_expand_string(mpctx, playing_msg);
4043 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4044 free(msg);
4048 // Disable the term OSD in verbose mode
4049 if(verbose) term_osd = 0;
4052 int frame_time_remaining=0; // flag
4053 int blit_frame=0;
4055 // Make sure old OSD does not stay around,
4056 // e.g. with -fixed-vo and same-resolution files
4057 clear_osd_msgs();
4058 update_osd_msg(mpctx);
4060 //================ SETUP AUDIO ==========================
4062 if(mpctx->sh_audio){
4063 reinit_audio_chain(mpctx);
4064 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4065 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4068 current_module="av_init";
4070 if(mpctx->sh_video){
4071 mpctx->sh_video->timer=0;
4072 if (! ignore_start)
4073 audio_delay += mpctx->sh_video->stream_delay;
4075 if(mpctx->sh_audio){
4076 if (start_volume >= 0)
4077 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4078 if (! ignore_start)
4079 audio_delay -= mpctx->sh_audio->stream_delay;
4080 mpctx->delay=-audio_delay;
4083 if(!mpctx->sh_audio){
4084 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4085 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4086 ds_free_packs(mpctx->d_audio); // free buffered chunks
4087 //mpctx->d_audio->id=-2; // do not read audio chunks
4088 //uninit_player(mpctx, INITIALIZED_AO); // close device
4090 if(!mpctx->sh_video){
4091 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4092 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4093 ds_free_packs(mpctx->d_video);
4094 mpctx->d_video->id=-2;
4095 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4098 if (!mpctx->sh_video && !mpctx->sh_audio)
4099 goto goto_next_file;
4101 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4102 if(force_fps && mpctx->sh_video){
4103 vo_fps = mpctx->sh_video->fps=force_fps;
4104 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4105 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4108 mp_input_set_section(mpctx->input, NULL);
4109 //TODO: add desired (stream-based) sections here
4110 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4111 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4113 //==================== START PLAYING =======================
4115 if(opts->loop_times>1) opts->loop_times--; else
4116 if(opts->loop_times==1) opts->loop_times = -1;
4118 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4120 total_time_usage_start=GetTimer();
4121 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4122 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4123 play_n_frames=play_n_frames_mf;
4125 if(play_n_frames==0){
4126 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4129 // If there's a timeline force an absolute seek to initialize state
4130 if (seek_to_sec || mpctx->timeline) {
4131 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4132 end_at.pos += seek_to_sec;
4134 if (opts->chapterrange[0] > 0) {
4135 double pts;
4136 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4137 && pts > -1.0)
4138 seek(mpctx, pts, SEEK_ABSOLUTE);
4141 if (end_at.type == END_AT_SIZE) {
4142 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4143 end_at.type = END_AT_NONE;
4146 #ifdef CONFIG_DVDNAV
4147 mp_dvdnav_context_free(mpctx);
4148 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4149 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4150 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4152 #endif
4154 get_relative_time(mpctx); // reset current delta
4155 mpctx->time_frame = 0;
4156 mpctx->drop_message_shown = 0;
4157 mpctx->restart_playback = true;
4158 mpctx->total_avsync_change = 0;
4159 mpctx->last_chapter_seek = -1;
4160 // Make sure VO knows current pause state
4161 if (mpctx->sh_video)
4162 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4163 NULL);
4165 while(!mpctx->stop_play){
4166 float aq_sleep_time=0;
4168 if (opts->chapterrange[1] > 0) {
4169 int cur_chapter = get_current_chapter(mpctx);
4170 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4171 goto goto_next_file;
4174 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4175 mpctx->sh_audio = mpctx->d_audio->sh;
4176 mpctx->sh_audio->ds = mpctx->d_audio;
4177 reinit_audio_chain(mpctx);
4180 /*========================== PLAY AUDIO ============================*/
4182 if (mpctx->sh_audio && !mpctx->paused)
4183 if (!fill_audio_out_buffers(mpctx))
4184 // at eof, all audio at least written to ao
4185 if (!mpctx->sh_video)
4186 mpctx->stop_play = AT_END_OF_FILE;
4189 if(!mpctx->sh_video) {
4190 // handle audio-only case:
4191 double a_pos=0;
4192 // sh_audio can be NULL due to video stream switching
4193 // TODO: handle this better
4194 if (mpctx->sh_audio)
4195 a_pos = playing_audio_pts(mpctx);
4197 print_status(mpctx, a_pos, false);
4199 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4200 mpctx->stop_play = PT_NEXT_ENTRY;
4201 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4202 mpctx->d_sub, 0);
4203 update_osd_msg(mpctx);
4205 } else {
4207 /*========================== PLAY VIDEO ============================*/
4209 vo_pts=mpctx->sh_video->timer*90000.0;
4210 vo_fps=mpctx->sh_video->fps;
4212 blit_frame = mpctx->video_out->frame_loaded;
4213 if (!blit_frame) {
4214 double frame_time = update_video(mpctx);
4215 blit_frame = mpctx->video_out->frame_loaded;
4216 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4217 if (mpctx->sh_video->vf_initialized < 0) {
4218 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4219 mpctx->stop_play = PT_NEXT_ENTRY;
4220 goto goto_next_file;
4222 if (blit_frame) {
4223 struct sh_video *sh_video = mpctx->sh_video;
4224 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4225 mpctx->video_offset, mpctx->d_sub, 0);
4226 update_teletext(sh_video, mpctx->demuxer, 0);
4227 update_osd_msg(mpctx);
4228 struct vf_instance *vf = mpctx->sh_video->vfilter;
4229 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4230 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4231 vo_osd_changed(0);
4233 if (frame_time < 0)
4234 mpctx->stop_play = AT_END_OF_FILE;
4235 else {
4236 if (mpctx->restart_playback) {
4237 // Show this frame immediately, rest normally
4238 mpctx->restart_playback = false;
4239 } else {
4240 mpctx->time_frame += frame_time / opts->playback_speed;
4241 adjust_sync(mpctx, frame_time);
4245 if (mpctx->timeline) {
4246 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4247 if (mpctx->sh_video->pts >= next->start
4248 || mpctx->stop_play == AT_END_OF_FILE
4249 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4250 seek(mpctx, next->start, SEEK_ABSOLUTE);
4251 continue;
4255 // ==========================================================================
4257 // current_module="draw_osd";
4258 // if(vo_config_count) mpctx->video_out->draw_osd();
4260 current_module="vo_check_events";
4261 vo_check_events(mpctx->video_out);
4263 #ifdef CONFIG_X11
4264 if (stop_xscreensaver) {
4265 current_module = "stop_xscreensaver";
4266 xscreensaver_heartbeat(mpctx->x11_state);
4268 #endif
4269 if (heartbeat_cmd) {
4270 static unsigned last_heartbeat;
4271 unsigned now = GetTimerMS();
4272 if (now - last_heartbeat > 30000) {
4273 last_heartbeat = now;
4274 system(heartbeat_cmd);
4278 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4280 //====================== FLIP PAGE (VIDEO BLT): =========================
4282 current_module="flip_page";
4283 if (!frame_time_remaining && blit_frame) {
4284 unsigned int t2=GetTimer();
4285 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4286 int duration = -1;
4287 double pts2 = mpctx->video_out->next_pts2;
4288 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4289 // expected A/V sync correction is ignored
4290 double diff = (pts2 - mpctx->sh_video->pts);
4291 diff /= opts->playback_speed;
4292 if (mpctx->time_frame < 0)
4293 diff += mpctx->time_frame;
4294 if (diff < 0)
4295 diff = 0;
4296 if (diff > 10)
4297 diff = 10;
4298 duration = diff * 1e6;
4300 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4302 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4303 vout_time_usage += mpctx->last_vo_flip_duration;
4304 if (mpctx->video_out->driver->flip_page_timed) {
4305 // No need to adjust sync based on flip speed
4306 mpctx->last_vo_flip_duration = 0;
4307 // For print_status - VO call finishing early is OK for sync
4308 mpctx->time_frame -= get_relative_time(mpctx);
4310 print_status(mpctx, MP_NOPTS_VALUE, true);
4312 else
4313 print_status(mpctx, MP_NOPTS_VALUE, false);
4315 //============================ Auto QUALITY ============================
4317 /*Output quality adjustments:*/
4318 if(auto_quality>0){
4319 current_module="autoq";
4320 // float total=0.000001f * (GetTimer()-aq_total_time);
4321 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4322 if(output_quality<auto_quality && aq_sleep_time>0)
4323 ++output_quality;
4324 else
4325 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4326 if(output_quality>1 && aq_sleep_time<0)
4327 --output_quality;
4328 else
4329 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4330 output_quality=0;
4331 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4332 set_video_quality(mpctx->sh_video,output_quality);
4335 if (!frame_time_remaining && blit_frame) {
4336 if (play_n_frames >= 0) {
4337 --play_n_frames;
4338 if (play_n_frames <= 0)
4339 mpctx->stop_play = PT_NEXT_ENTRY;
4341 if (mpctx->step_frames > 0) {
4342 mpctx->step_frames--;
4343 if (mpctx->step_frames == 0)
4344 pause_player(mpctx);
4349 // FIXME: add size based support for -endpos
4350 if (end_at.type == END_AT_TIME &&
4351 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4352 mpctx->stop_play = PT_NEXT_ENTRY;
4354 } // end if(mpctx->sh_video)
4356 #ifdef CONFIG_DVDNAV
4357 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4358 nav_highlight_t hl;
4359 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4360 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4361 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4362 vo_osd_changed (OSDTYPE_DVDNAV);
4363 } else {
4364 osd_set_nav_box(0, 0, 0, 0);
4365 vo_osd_changed(OSDTYPE_DVDNAV);
4366 vo_osd_changed(OSDTYPE_SPU);
4369 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4370 double ar = -1.0;
4371 if (mpctx->sh_video &&
4372 stream_control (mpctx->demuxer->stream,
4373 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4374 != STREAM_UNSUPPORTED)
4375 mpctx->sh_video->stream_aspect = ar;
4378 #endif
4380 //================= Keyboard events, SEEKing ====================
4382 current_module="key_events";
4385 while (1) {
4386 mp_cmd_t* cmd;
4387 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4388 run_command(mpctx, cmd);
4389 mp_cmd_free(cmd);
4390 if (mpctx->stop_play)
4391 break;
4392 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4393 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4394 /* Allow seek commands to be combined, but execute the real seek
4395 * before processing other commands */
4396 if (!cmd || cmd->id != MP_CMD_SEEK)
4397 break;
4400 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4401 || mpctx->abs_seek_pos)
4402 break;
4403 if (mpctx->sh_video) {
4404 update_osd_msg(mpctx);
4405 int hack = vo_osd_changed(0);
4406 vo_osd_changed(hack);
4407 if (hack) {
4408 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4409 add_step_frame(mpctx);
4410 break;
4412 else
4413 vo_osd_changed(0);
4416 pause_loop(mpctx);
4420 // handle -sstep
4421 if (step_sec > 0 && !mpctx->paused) {
4422 mpctx->osd_function=OSD_FFW;
4423 mpctx->rel_seek_secs+=step_sec;
4426 edl_update(mpctx);
4428 /* Looping. */
4429 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4430 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4432 if(opts->loop_times>1) opts->loop_times--; else
4433 if(opts->loop_times==1) opts->loop_times=-1;
4434 play_n_frames=play_n_frames_mf;
4435 mpctx->stop_play=0;
4436 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4439 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4440 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4442 mpctx->rel_seek_secs=0;
4443 mpctx->abs_seek_pos=0;
4446 } // while(!mpctx->stop_play)
4448 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4450 #ifdef CONFIG_DVBIN
4451 if(mpctx->dvbin_reopen)
4453 mpctx->stop_play = 0;
4454 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4455 cache_uninit(mpctx->stream);
4456 mpctx->dvbin_reopen = 0;
4457 goto goto_enable_cache;
4459 #endif
4462 goto_next_file: // don't jump here after ao/vo/getch initialization!
4464 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4466 if(benchmark){
4467 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4468 double total_time_usage;
4469 total_time_usage_start=GetTimer()-total_time_usage_start;
4470 total_time_usage = (float)total_time_usage_start*0.000001;
4471 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4472 video_time_usage,vout_time_usage,audio_time_usage,
4473 total_time_usage-tot,total_time_usage);
4474 if(total_time_usage>0.0)
4475 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4476 100.0*video_time_usage/total_time_usage,
4477 100.0*vout_time_usage/total_time_usage,
4478 100.0*audio_time_usage/total_time_usage,
4479 100.0*(total_time_usage-tot)/total_time_usage,
4480 100.0);
4481 if(total_frame_cnt && frame_dropping)
4482 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4483 total_frame_cnt-drop_frame_cnt,
4484 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4485 drop_frame_cnt,
4486 100*drop_frame_cnt/total_frame_cnt,
4487 total_frame_cnt,
4488 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4491 // time to uninit all, except global stuff:
4492 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4494 if(mpctx->set_of_sub_size > 0) {
4495 current_module="sub_free";
4496 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4497 sub_free(mpctx->set_of_subtitles[i]);
4498 #ifdef CONFIG_ASS
4499 if(mpctx->set_of_ass_tracks[i])
4500 ass_free_track( mpctx->set_of_ass_tracks[i] );
4501 #endif
4503 mpctx->set_of_sub_size = 0;
4505 vo_sub_last = vo_sub=NULL;
4506 subdata=NULL;
4507 #ifdef CONFIG_ASS
4508 ass_track = NULL;
4509 if(ass_library)
4510 ass_clear_fonts(ass_library);
4511 #endif
4513 if (!mpctx->stop_play) // In case some goto jumped here...
4514 mpctx->stop_play = PT_NEXT_ENTRY;
4516 int playtree_direction = 1;
4518 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4519 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4520 play_tree_iter_free(mpctx->playtree_iter);
4521 mpctx->playtree_iter = NULL;
4523 mpctx->play_tree_step = 1;
4524 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4525 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4526 if(mpctx->playtree_iter) {
4527 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4528 play_tree_iter_free(mpctx->playtree_iter);
4529 mpctx->playtree_iter = NULL;
4532 } else if (mpctx->stop_play == PT_STOP) {
4533 play_tree_iter_free(mpctx->playtree_iter);
4534 mpctx->playtree_iter = NULL;
4535 } else { // NEXT PREV SRC
4536 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4539 while(mpctx->playtree_iter != NULL) {
4540 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4541 if(mpctx->filename == NULL) {
4542 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4543 play_tree_iter_free(mpctx->playtree_iter);
4544 mpctx->playtree_iter = NULL;
4546 } else
4547 break;
4550 if(mpctx->playtree_iter != NULL || player_idle_mode){
4551 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4552 mpctx->stop_play = 0;
4553 goto play_next_file;
4557 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4559 return 1;
4561 #endif /* DISABLE_MAIN */