core: give pts as parameter to demuxer_get_current_chapter()
[mplayer/glamo.git] / mplayer.c
blob83c6328b5d64b77c32c97d6a440e8a40ead917be
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;
318 // dump:
319 int stream_dump_type=0;
321 // A-V sync:
322 static float default_max_pts_correction=-1;//0.01f;
323 float audio_delay=0;
324 static int ignore_start=0;
326 static int softsleep=0;
328 double force_fps=0;
329 static int force_srate=0;
330 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
331 static int play_n_frames=-1;
332 static int play_n_frames_mf=-1;
334 // sub:
335 char *font_name=NULL;
336 char *sub_font_name=NULL;
337 extern int font_fontconfig;
338 float font_factor=0.75;
339 char **sub_name=NULL;
340 float sub_delay=0;
341 float sub_fps=0;
342 int sub_auto = 1;
343 char *vobsub_name=NULL;
344 int subcc_enabled=0;
345 int suboverlap_enabled = 1;
347 #include "ass_mp.h"
349 char* current_module=NULL; // for debugging
352 // ---
354 #ifdef CONFIG_MENU
355 #include "m_struct.h"
356 #include "libmenu/menu.h"
357 static const vf_info_t* const libmenu_vfs[] = {
358 &vf_info_menu,
359 NULL
361 static vf_instance_t* vf_menu = NULL;
362 int use_menu = 0;
363 static char* menu_cfg = NULL;
364 static char* menu_root = "main";
365 #endif
368 #ifdef HAVE_RTC
369 static int nortc = 1;
370 static char* rtc_device;
371 #endif
373 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
374 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
375 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
376 int use_filedir_conf;
377 int use_filename_title;
379 #include "mpcommon.h"
380 #include "command.h"
382 #include "metadata.h"
384 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
386 const void *mpctx_get_video_out(MPContext *mpctx)
388 return mpctx->video_out;
391 const void *mpctx_get_audio_out(MPContext *mpctx)
393 return mpctx->audio_out;
396 void *mpctx_get_demuxer(MPContext *mpctx)
398 return mpctx->demuxer;
401 void *mpctx_get_playtree_iter(MPContext *mpctx)
403 return mpctx->playtree_iter;
406 void *mpctx_get_mixer(MPContext *mpctx)
408 return &mpctx->mixer;
411 int mpctx_get_global_sub_size(MPContext *mpctx)
413 return mpctx->global_sub_size;
416 int mpctx_get_osd_function(MPContext *mpctx)
418 return mpctx->osd_function;
421 static float get_relative_time(struct MPContext *mpctx)
423 unsigned int new_time = GetTimer();
424 unsigned int delta = new_time - mpctx->last_time;
425 mpctx->last_time = new_time;
426 return delta * 0.000001;
429 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
430 switch (type)
432 /* check for valid video stream */
433 case META_VIDEO_CODEC:
434 case META_VIDEO_BITRATE:
435 case META_VIDEO_RESOLUTION:
437 if (!mpctx->sh_video)
438 return 0;
439 break;
442 /* check for valid audio stream */
443 case META_AUDIO_CODEC:
444 case META_AUDIO_BITRATE:
445 case META_AUDIO_SAMPLES:
447 if (!mpctx->sh_audio)
448 return 0;
449 break;
452 /* check for valid demuxer */
453 case META_INFO_TITLE:
454 case META_INFO_ARTIST:
455 case META_INFO_ALBUM:
456 case META_INFO_YEAR:
457 case META_INFO_COMMENT:
458 case META_INFO_TRACK:
459 case META_INFO_GENRE:
461 if (!mpctx->demuxer)
462 return 0;
463 break;
466 default:
467 break;
470 return 1;
473 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
474 char **info = mpctx->demuxer->info;
475 int n;
477 if (!info || !tag)
478 return NULL;
480 for (n = 0; info[2*n] != NULL ; n++)
481 if (!strcasecmp (info[2*n], tag))
482 break;
484 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
487 char *get_metadata(struct MPContext *mpctx, metadata_t type)
489 char *meta = NULL;
490 sh_audio_t * const sh_audio = mpctx->sh_audio;
491 sh_video_t * const sh_video = mpctx->sh_video;
493 if (!is_valid_metadata_type(mpctx, type))
494 return NULL;
496 switch (type)
498 case META_NAME:
500 return strdup (mp_basename2 (mpctx->filename));
503 case META_VIDEO_CODEC:
505 if (sh_video->format == 0x10000001)
506 meta = strdup ("mpeg1");
507 else if (sh_video->format == 0x10000002)
508 meta = strdup ("mpeg2");
509 else if (sh_video->format == 0x10000004)
510 meta = strdup ("mpeg4");
511 else if (sh_video->format == 0x10000005)
512 meta = strdup ("h264");
513 else if (sh_video->format >= 0x20202020)
515 meta = malloc (8);
516 sprintf (meta, "%.4s", (char *) &sh_video->format);
518 else
520 meta = malloc (8);
521 sprintf (meta, "0x%08X", sh_video->format);
523 return meta;
526 case META_VIDEO_BITRATE:
528 meta = malloc (16);
529 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
530 return meta;
533 case META_VIDEO_RESOLUTION:
535 meta = malloc (16);
536 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
537 return meta;
540 case META_AUDIO_CODEC:
542 if (sh_audio->codec && sh_audio->codec->name)
543 meta = strdup (sh_audio->codec->name);
544 return meta;
547 case META_AUDIO_BITRATE:
549 meta = malloc (16);
550 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
551 return meta;
554 case META_AUDIO_SAMPLES:
556 meta = malloc (16);
557 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
558 return meta;
561 /* check for valid demuxer */
562 case META_INFO_TITLE:
563 return get_demuxer_info(mpctx, "Title");
565 case META_INFO_ARTIST:
566 return get_demuxer_info(mpctx, "Artist");
568 case META_INFO_ALBUM:
569 return get_demuxer_info(mpctx, "Album");
571 case META_INFO_YEAR:
572 return get_demuxer_info(mpctx, "Year");
574 case META_INFO_COMMENT:
575 return get_demuxer_info(mpctx, "Comment");
577 case META_INFO_TRACK:
578 return get_demuxer_info(mpctx, "Track");
580 case META_INFO_GENRE:
581 return get_demuxer_info(mpctx, "Genre");
583 default:
584 break;
587 return meta;
590 static void print_file_properties(struct MPContext *mpctx, const char *filename)
592 double start_pts = MP_NOPTS_VALUE;
593 double video_start_pts = MP_NOPTS_VALUE;
594 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
595 filename_recode(filename));
596 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
597 if (mpctx->sh_video) {
598 /* Assume FOURCC if all bytes >= 0x20 (' ') */
599 if (mpctx->sh_video->format >= 0x20202020)
600 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
601 else
602 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
603 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
604 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
605 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
606 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
607 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
608 video_start_pts = ds_get_next_pts(mpctx->d_video);
610 if (mpctx->sh_audio) {
611 /* Assume FOURCC if all bytes >= 0x20 (' ') */
612 if (mpctx->sh_audio->format >= 0x20202020)
613 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
614 else
615 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
616 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
617 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
618 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
619 start_pts = ds_get_next_pts(mpctx->d_audio);
621 if (video_start_pts != MP_NOPTS_VALUE) {
622 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
623 (mpctx->sh_video && video_start_pts < start_pts))
624 start_pts = video_start_pts;
626 if (start_pts != MP_NOPTS_VALUE)
627 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
628 else
629 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
630 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
631 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
632 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
633 if (mpctx->demuxer) {
634 if (mpctx->demuxer->num_chapters == 0)
635 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
636 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
640 /// step size of mixer changes
641 int volstep = 3;
643 #ifdef CONFIG_DVDNAV
644 static void mp_dvdnav_context_free(MPContext *ctx){
645 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
646 ctx->nav_smpi = NULL;
647 free(ctx->nav_buffer);
648 ctx->nav_buffer = NULL;
649 ctx->nav_start = NULL;
650 ctx->nav_in_size = 0;
652 #endif
654 void uninit_player(struct MPContext *mpctx, unsigned int mask){
655 mask &= mpctx->initialized_flags;
657 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
659 if(mask&INITIALIZED_ACODEC){
660 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
661 current_module="uninit_acodec";
662 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
663 mpctx->sh_audio=NULL;
664 mpctx->mixer.afilter = NULL;
667 if(mask&INITIALIZED_VCODEC){
668 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
669 current_module="uninit_vcodec";
670 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
671 mpctx->sh_video=NULL;
672 #ifdef CONFIG_MENU
673 vf_menu=NULL;
674 #endif
677 if(mask&INITIALIZED_DEMUXER){
678 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
679 current_module="free_demuxer";
680 if (mpctx->num_sources) {
681 mpctx->demuxer = mpctx->sources[0].demuxer;
682 for (int i = 1; i < mpctx->num_sources; i++) {
683 free_stream(mpctx->sources[i].stream);
684 free_demuxer(mpctx->sources[i].demuxer);
687 talloc_free(mpctx->sources);
688 mpctx->sources = NULL;
689 mpctx->num_sources = 0;
690 talloc_free(mpctx->timeline);
691 mpctx->timeline = NULL;
692 mpctx->num_timeline_parts = 0;
693 talloc_free(mpctx->chapters);
694 mpctx->chapters = NULL;
695 mpctx->num_chapters = 0;
696 mpctx->video_offset = 0;
697 if(mpctx->demuxer){
698 mpctx->stream=mpctx->demuxer->stream;
699 free_demuxer(mpctx->demuxer);
701 mpctx->demuxer=NULL;
704 // kill the cache process:
705 if(mask&INITIALIZED_STREAM){
706 mpctx->initialized_flags&=~INITIALIZED_STREAM;
707 current_module="uninit_stream";
708 if(mpctx->stream) free_stream(mpctx->stream);
709 mpctx->stream=NULL;
712 if(mask&INITIALIZED_VO){
713 mpctx->initialized_flags&=~INITIALIZED_VO;
714 current_module="uninit_vo";
715 vo_destroy(mpctx->video_out);
716 mpctx->video_out=NULL;
717 #ifdef CONFIG_DVDNAV
718 mp_dvdnav_context_free(mpctx);
719 #endif
722 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
723 if(mask&INITIALIZED_GETCH2){
724 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
725 current_module="uninit_getch2";
726 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
727 // restore terminal:
728 getch2_disable();
731 if(mask&INITIALIZED_VOBSUB){
732 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
733 current_module="uninit_vobsub";
734 if(vo_vobsub) vobsub_close(vo_vobsub);
735 vo_vobsub=NULL;
738 if (mask&INITIALIZED_SPUDEC){
739 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
740 current_module="uninit_spudec";
741 spudec_free(vo_spudec);
742 vo_spudec=NULL;
745 if(mask&INITIALIZED_AO){
746 mpctx->initialized_flags&=~INITIALIZED_AO;
747 current_module="uninit_ao";
748 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
749 if (mpctx->audio_out)
750 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
751 mpctx->audio_out=NULL;
754 current_module=NULL;
757 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
759 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
760 uninit_player(mpctx, INITIALIZED_ALL);
761 #if defined(__MINGW32__) || defined(__CYGWIN__)
762 timeEndPeriod(1);
763 #endif
764 #ifdef CONFIG_X11
765 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
766 #endif
768 current_module="uninit_input";
769 mp_input_uninit(mpctx->input);
770 #ifdef CONFIG_MENU
771 if (use_menu)
772 menu_uninit();
773 #endif
775 #ifdef CONFIG_FREETYPE
776 current_module="uninit_font";
777 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
778 free_font_desc(mpctx->osd->sub_font);
779 free_font_desc(vo_font);
780 vo_font = NULL;
781 done_freetype();
782 #endif
783 osd_free(mpctx->osd);
785 #ifdef CONFIG_ASS
786 ass_library_done(ass_library);
787 ass_library = NULL;
788 #endif
790 current_module="exit_player";
792 // free mplayer config
793 if(mpctx->mconfig)
794 m_config_free(mpctx->mconfig);
795 mpctx->mconfig = NULL;
797 if(mpctx->playtree_iter)
798 play_tree_iter_free(mpctx->playtree_iter);
799 mpctx->playtree_iter = NULL;
800 if(mpctx->playtree)
801 play_tree_free(mpctx->playtree, 1);
802 mpctx->playtree = NULL;
804 talloc_free(mpctx->key_fifo);
806 free(edl_records); // free mem allocated for EDL
807 edl_records = NULL;
808 switch(how) {
809 case EXIT_QUIT:
810 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
811 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
812 break;
813 case EXIT_EOF:
814 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
815 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
816 break;
817 case EXIT_ERROR:
818 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
819 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
820 break;
821 default:
822 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
824 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
826 exit(rc);
829 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
831 exit_player_with_rc(mpctx, how, 1);
834 #ifndef __MINGW32__
835 static void child_sighandler(int x){
836 pid_t pid;
837 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
839 #endif
841 #ifdef CONFIG_CRASH_DEBUG
842 static char *prog_path;
843 static int crash_debug = 0;
844 #endif
846 static void exit_sighandler(int x){
847 static int sig_count=0;
848 #ifdef CONFIG_CRASH_DEBUG
849 if (!crash_debug || x != SIGTRAP)
850 #endif
851 ++sig_count;
852 if(sig_count==5)
854 /* We're crashing bad and can't uninit cleanly :(
855 * by popular request, we make one last (dirty)
856 * effort to restore the user's
857 * terminal. */
858 getch2_disable();
859 exit(1);
861 if(sig_count==6) exit(1);
862 if(sig_count>6){
863 // can't stop :(
864 #ifndef __MINGW32__
865 kill(getpid(),SIGKILL);
866 #endif
868 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
869 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
870 "\nMPlayer interrupted by signal %d in module: %s\n", x,
871 current_module ? current_module : "unknown");
872 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
873 if(sig_count<=1)
874 switch(x){
875 case SIGINT:
876 case SIGPIPE:
877 case SIGQUIT:
878 case SIGTERM:
879 case SIGKILL:
880 async_quit_request = 1;
881 return; // killed from keyboard (^C) or killed [-9]
882 case SIGILL:
883 #if CONFIG_RUNTIME_CPUDETECT
884 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
885 #else
886 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
887 #endif
888 case SIGFPE:
889 case SIGSEGV:
890 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
891 default:
892 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
893 #ifdef CONFIG_CRASH_DEBUG
894 if (crash_debug) {
895 int gdb_pid;
896 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
897 gdb_pid = fork();
898 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
899 if (gdb_pid == 0) { // We are the child
900 char spid[20];
901 snprintf(spid, sizeof(spid), "%i", getppid());
902 getch2_disable(); // allow terminal to work properly with gdb
903 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
904 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
905 } else if (gdb_pid < 0)
906 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
907 else {
908 waitpid(gdb_pid, NULL, 0);
910 if (x == SIGTRAP) return;
912 #endif
914 getch2_disable();
915 exit(1);
918 #include "cfg-mplayer.h"
920 static int cfg_include(m_option_t *conf, char *filename)
922 return m_config_parse_config_file(conf->priv, filename);
925 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
927 char *conffile;
928 int conffile_fd;
929 if (!disable_system_conf &&
930 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
931 exit_player(mpctx, EXIT_NONE);
932 if ((conffile = get_path("")) == NULL) {
933 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
934 } else {
935 #ifdef __MINGW32__
936 mkdir(conffile);
937 #else
938 mkdir(conffile, 0777);
939 #endif
940 free(conffile);
941 if ((conffile = get_path("config")) == NULL) {
942 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
943 } else {
944 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
945 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
946 write(conffile_fd, default_config, strlen(default_config));
947 close(conffile_fd);
949 if (!disable_user_conf &&
950 m_config_parse_config_file(conf, conffile) < 0)
951 exit_player(mpctx, EXIT_NONE);
952 free(conffile);
957 #define PROFILE_CFG_PROTOCOL "protocol."
959 static void load_per_protocol_config (m_config_t* conf, const char *const file)
961 char *str;
962 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
963 m_profile_t *p;
965 /* does filename actually uses a protocol ? */
966 str = strstr (file, "://");
967 if (!str)
968 return;
970 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
971 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
972 p = m_config_get_profile (conf, protocol);
973 if (p)
975 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
976 m_config_set_profile(conf,p);
980 #define PROFILE_CFG_EXTENSION "extension."
982 static void load_per_extension_config (m_config_t* conf, const char *const file)
984 char *str;
985 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
986 m_profile_t *p;
988 /* does filename actually have an extension ? */
989 str = strrchr (file, '.');
990 if (!str)
991 return;
993 sprintf (extension, PROFILE_CFG_EXTENSION);
994 strncat (extension, ++str, 7);
995 p = m_config_get_profile (conf, extension);
996 if (p)
998 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
999 m_config_set_profile(conf,p);
1003 #define PROFILE_CFG_VO "vo."
1004 #define PROFILE_CFG_AO "ao."
1006 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
1008 char profile[strlen (cfg) + strlen (out) + 1];
1009 m_profile_t *p;
1011 sprintf (profile, "%s%s", cfg, out);
1012 p = m_config_get_profile (conf, profile);
1013 if (p)
1015 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
1016 m_config_set_profile(conf,p);
1021 * Tries to load a config file
1022 * @return 0 if file was not found, 1 otherwise
1024 static int try_load_config(m_config_t *conf, const char *file)
1026 struct stat st;
1027 if (stat(file, &st))
1028 return 0;
1029 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1030 m_config_parse_config_file (conf, file);
1031 return 1;
1034 static void load_per_file_config (m_config_t* conf, const char *const file)
1036 char *confpath;
1037 char cfg[PATH_MAX];
1038 char *name;
1040 if (strlen(file) > PATH_MAX - 14) {
1041 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1042 return;
1044 sprintf (cfg, "%s.conf", file);
1046 name = strrchr(cfg, '/');
1047 if (HAVE_DOS_PATHS) {
1048 char *tmp = strrchr(cfg, '\\');
1049 if (!name || tmp > name)
1050 name = tmp;
1051 tmp = strrchr(cfg, ':');
1052 if (!name || tmp > name)
1053 name = tmp;
1055 if (!name)
1056 name = cfg;
1057 else
1058 name++;
1060 if (use_filedir_conf) {
1061 char dircfg[PATH_MAX];
1062 strcpy(dircfg, cfg);
1063 strcpy(dircfg + (name - cfg), "mplayer.conf");
1064 try_load_config(conf, dircfg);
1066 if (try_load_config(conf, cfg))
1067 return;
1070 if ((confpath = get_path (name)) != NULL)
1072 try_load_config(conf, confpath);
1074 free (confpath);
1078 /* When libmpdemux performs a blocking operation (network connection or
1079 * cache filling) if the operation fails we use this function to check
1080 * if it was interrupted by the user.
1081 * The function returns a new value for eof. */
1082 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1084 mp_cmd_t* cmd;
1085 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1086 switch(cmd->id) {
1087 case MP_CMD_QUIT:
1088 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1089 case MP_CMD_PLAY_TREE_STEP: {
1090 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1091 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1092 } break;
1093 case MP_CMD_PLAY_TREE_UP_STEP: {
1094 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1095 } break;
1096 case MP_CMD_PLAY_ALT_SRC_STEP: {
1097 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1098 } break;
1100 mp_cmd_free(cmd);
1102 return stop_play;
1105 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1107 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1109 play_tree_add_bpf(entry,mpctx->filename);
1112 if(!entry) {
1113 entry = mpctx->playtree_iter->tree;
1114 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1115 return PT_NEXT_ENTRY;
1117 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1118 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1119 return PT_NEXT_ENTRY;
1122 play_tree_remove(entry,1,1);
1123 return PT_NEXT_SRC;
1125 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1126 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1127 entry = mpctx->playtree_iter->tree;
1128 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1129 return PT_NEXT_ENTRY;
1131 play_tree_remove(entry,1,1);
1133 return PT_NEXT_SRC;
1136 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1138 struct MPOpts *opts = &mpctx->opts;
1139 sub_data *subd = NULL;
1140 struct ass_track *asst = NULL;
1142 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1143 return;
1146 #ifdef CONFIG_ASS
1147 if (opts->ass_enabled) {
1148 #ifdef CONFIG_ICONV
1149 asst = ass_read_stream(ass_library, filename, sub_cp);
1150 #else
1151 asst = ass_read_stream(ass_library, filename, 0);
1152 #endif
1153 if (!asst) {
1154 subd = sub_read_file(filename, fps);
1155 if (subd) {
1156 asst = ass_read_subdata(ass_library, subd, fps);
1157 if (asst) {
1158 sub_free(subd);
1159 subd = NULL;
1163 } else
1164 #endif
1165 subd = sub_read_file(filename, fps);
1168 if (!asst && !subd) {
1169 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1170 "Cannot load subtitles: %s\n", filename_recode(filename));
1171 return;
1174 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1175 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1176 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1177 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1178 filename_recode(filename));
1179 ++mpctx->set_of_sub_size;
1180 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1181 filename_recode(filename));
1184 void init_vo_spudec(struct MPContext *mpctx)
1186 if (vo_spudec)
1187 spudec_free(vo_spudec);
1188 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1189 vo_spudec = NULL;
1191 // we currently can't work without video stream
1192 if (!mpctx->sh_video)
1193 return;
1195 if (spudec_ifo) {
1196 unsigned int palette[16], width, height;
1197 current_module="spudec_init_vobsub";
1198 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1199 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1202 #ifdef CONFIG_DVDREAD
1203 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1204 current_module="spudec_init_dvdread";
1205 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1206 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1207 NULL, 0);
1209 #endif
1211 #ifdef CONFIG_DVDNAV
1212 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1213 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1214 current_module="spudec_init_dvdnav";
1215 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1217 #endif
1219 if (vo_spudec==NULL) {
1220 sh_sub_t *sh = mpctx->d_sub->sh;
1221 current_module="spudec_init_normal";
1222 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1223 spudec_set_font_factor(vo_spudec,font_factor);
1226 if (vo_spudec!=NULL) {
1227 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1228 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1233 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1234 * make it all work is to use the builtin SDL-bootstrap code, which
1235 * will be done automatically by replacing our main() if we include SDL.h.
1237 #if defined(__APPLE__) && defined(CONFIG_SDL)
1238 #ifdef CONFIG_SDL_SDL_H
1239 #include <SDL/SDL.h>
1240 #else
1241 #include <SDL.h>
1242 #endif
1243 #endif
1246 * \brief append a formatted string
1247 * \param buf buffer to print into
1248 * \param pos position of terminating 0 in buf
1249 * \param len maximum number of characters in buf, not including terminating 0
1250 * \param format printf format string
1252 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1254 va_list va;
1255 va_start(va, format);
1256 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1257 va_end(va);
1258 if (*pos >= len ) {
1259 buf[len] = 0;
1260 *pos = len;
1265 * \brief append time in the hh:mm:ss.f format
1266 * \param buf buffer to print into
1267 * \param pos position of terminating 0 in buf
1268 * \param len maximum number of characters in buf, not including terminating 0
1269 * \param time time value to convert/append
1271 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1272 int64_t tenths = 10 * time;
1273 int f1 = tenths % 10;
1274 int ss = (tenths / 10) % 60;
1275 int mm = (tenths / 600) % 60;
1276 int hh = tenths / 36000;
1277 if (time <= 0) {
1278 saddf(buf, pos, len, "unknown");
1279 return;
1281 if (hh > 0)
1282 saddf(buf, pos, len, "%2d:", hh);
1283 if (hh > 0 || mm > 0)
1284 saddf(buf, pos, len, "%02d:", mm);
1285 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1288 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1290 struct MPOpts *opts = &mpctx->opts;
1291 sh_video_t * const sh_video = mpctx->sh_video;
1293 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1294 a_pos = playing_audio_pts(mpctx);
1295 if (mpctx->sh_audio && sh_video && at_frame) {
1296 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1297 if (mpctx->time_frame > 0)
1298 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1299 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1300 && !mpctx->drop_message_shown) {
1301 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1302 mpctx->drop_message_shown = true;
1305 if (quiet)
1306 return;
1309 int width;
1310 char *line;
1311 unsigned pos = 0;
1312 get_screen_size();
1313 if (screen_width > 0)
1314 width = screen_width;
1315 else
1316 width = 80;
1317 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1318 /* Windows command line is broken (MinGW's rxvt works, but we
1319 * should not depend on that). */
1320 width--;
1321 #endif
1322 line = malloc(width + 1); // one additional char for the terminating null
1324 // Audio time
1325 if (mpctx->sh_audio) {
1326 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1327 if (!sh_video) {
1328 float len = get_time_length(mpctx);
1329 saddf(line, &pos, width, "(");
1330 sadd_hhmmssf(line, &pos, width, a_pos);
1331 saddf(line, &pos, width, ") of %.1f (", len);
1332 sadd_hhmmssf(line, &pos, width, len);
1333 saddf(line, &pos, width, ") ");
1337 // Video time
1338 if (sh_video)
1339 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1341 // A-V sync
1342 if (mpctx->sh_audio && sh_video)
1343 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1344 mpctx->last_av_difference, mpctx->total_avsync_change);
1346 // Video stats
1347 if (sh_video)
1348 saddf(line, &pos, width, "%3d/%3d ",
1349 (int)sh_video->num_frames,
1350 (int)sh_video->num_frames_decoded);
1352 // CPU usage
1353 if (sh_video) {
1354 if (sh_video->timer > 0.5)
1355 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1356 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1357 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1358 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1359 else
1360 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1361 } else if (mpctx->sh_audio) {
1362 if (mpctx->delay > 0.5)
1363 saddf(line, &pos, width, "%4.1f%% ",
1364 100.0*audio_time_usage/(double)mpctx->delay);
1365 else
1366 saddf(line, &pos, width, "??,?%% ");
1369 // VO stats
1370 if (sh_video)
1371 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1373 #ifdef CONFIG_STREAM_CACHE
1374 // cache stats
1375 if (stream_cache_size > 0)
1376 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1377 #endif
1379 // other
1380 if (opts->playback_speed != 1)
1381 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1383 // end
1384 if (erase_to_end_of_line) {
1385 line[pos] = 0;
1386 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1387 } else {
1388 memset(&line[pos], ' ', width - pos);
1389 line[width] = 0;
1390 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1392 free(line);
1396 * \brief build a chain of audio filters that converts the input format
1397 * to the ao's format, taking into account the current playback_speed.
1398 * \param sh_audio describes the requested input format of the chain.
1399 * \param ao_data describes the requested output format of the chain.
1401 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1403 struct MPOpts *opts = &mpctx->opts;
1404 int new_srate;
1405 int result;
1406 if (!sh_audio)
1408 mpctx->mixer.afilter = NULL;
1409 return 0;
1411 if(af_control_any_rev(sh_audio->afilter,
1412 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1413 &opts->playback_speed)) {
1414 new_srate = sh_audio->samplerate;
1415 } else {
1416 new_srate = sh_audio->samplerate * opts->playback_speed;
1417 if (new_srate != ao_data->samplerate) {
1418 // limits are taken from libaf/af_resample.c
1419 if (new_srate < 8000)
1420 new_srate = 8000;
1421 if (new_srate > 192000)
1422 new_srate = 192000;
1423 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1426 result = init_audio_filters(sh_audio, new_srate,
1427 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1428 mpctx->mixer.afilter = sh_audio->afilter;
1429 return result;
1433 typedef struct mp_osd_msg mp_osd_msg_t;
1434 struct mp_osd_msg {
1435 /// Previous message on the stack.
1436 mp_osd_msg_t* prev;
1437 /// Message text.
1438 char msg[128];
1439 int id,level,started;
1440 /// Display duration in ms.
1441 unsigned time;
1444 /// OSD message stack.
1445 static mp_osd_msg_t* osd_msg_stack = NULL;
1448 * \brief Add a message on the OSD message stack
1450 * If a message with the same id is already present in the stack
1451 * it is pulled on top of the stack, otherwise a new message is created.
1454 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1455 va_list ap)
1457 mp_osd_msg_t *msg,*last=NULL;
1458 int r;
1460 // look if the id is already in the stack
1461 for(msg = osd_msg_stack ; msg && msg->id != id ;
1462 last = msg, msg = msg->prev);
1463 // not found: alloc it
1464 if(!msg) {
1465 msg = calloc(1,sizeof(mp_osd_msg_t));
1466 msg->prev = osd_msg_stack;
1467 osd_msg_stack = msg;
1468 } else if(last) { // found, but it's not on top of the stack
1469 last->prev = msg->prev;
1470 msg->prev = osd_msg_stack;
1471 osd_msg_stack = msg;
1473 // write the msg
1474 r = vsnprintf(msg->msg, 128, fmt, ap);
1475 if(r >= 128) msg->msg[127] = 0;
1476 // set id and time
1477 msg->id = id;
1478 msg->level = level;
1479 msg->time = time;
1483 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1485 va_list ap;
1486 va_start(ap, fmt);
1487 set_osd_msg_va(id, level, time, fmt, ap);
1488 va_end(ap);
1491 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1493 va_list ap;
1494 va_start(ap, fmt);
1495 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1496 va_end(ap);
1501 * \brief Remove a message from the OSD stack
1503 * This function can be used to get rid of a message right away.
1507 void rm_osd_msg(int id) {
1508 mp_osd_msg_t *msg,*last=NULL;
1510 // Search for the msg
1511 for(msg = osd_msg_stack ; msg && msg->id != id ;
1512 last = msg, msg = msg->prev);
1513 if(!msg) return;
1515 // Detach it from the stack and free it
1516 if(last)
1517 last->prev = msg->prev;
1518 else
1519 osd_msg_stack = msg->prev;
1520 free(msg);
1524 * \brief Remove all messages from the OSD stack
1528 static void clear_osd_msgs(void) {
1529 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1530 while(msg) {
1531 prev = msg->prev;
1532 free(msg);
1533 msg = prev;
1535 osd_msg_stack = NULL;
1539 * \brief Get the current message from the OSD stack.
1541 * This function decrements the message timer and destroys the old ones.
1542 * The message that should be displayed is returned (if any).
1546 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1548 struct MPOpts *opts = &mpctx->opts;
1549 mp_osd_msg_t *msg,*prev,*last = NULL;
1550 static unsigned last_update = 0;
1551 unsigned now = GetTimerMS();
1552 unsigned diff;
1553 char hidden_dec_done = 0;
1555 if (mpctx->osd_visible) {
1556 // 36000000 means max timed visibility is 1 hour into the future, if
1557 // the difference is greater assume it's wrapped around from below 0
1558 if (mpctx->osd_visible - now > 36000000) {
1559 mpctx->osd_visible = 0;
1560 vo_osd_progbar_type = -1; // disable
1561 vo_osd_changed(OSDTYPE_PROGBAR);
1562 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1565 if (mpctx->osd_show_percentage_until - now > 36000000)
1566 mpctx->osd_show_percentage_until = 0;
1568 if(!last_update) last_update = now;
1569 diff = now >= last_update ? now - last_update : 0;
1571 last_update = now;
1573 // Look for the first message in the stack with high enough level.
1574 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1575 prev = msg->prev;
1576 if (msg->level > opts->osd_level && hidden_dec_done)
1577 continue;
1578 // The message has a high enough level or it is the first hidden one
1579 // in both cases we decrement the timer or kill it.
1580 if(!msg->started || msg->time > diff) {
1581 if(msg->started) msg->time -= diff;
1582 else msg->started = 1;
1583 // display it
1584 if (msg->level <= opts->osd_level)
1585 return msg;
1586 hidden_dec_done = 1;
1587 continue;
1589 // kill the message
1590 free(msg);
1591 if(last) {
1592 last->prev = prev;
1593 msg = last;
1594 } else {
1595 osd_msg_stack = prev;
1596 msg = NULL;
1599 // Nothing found
1600 return NULL;
1604 * \brief Display the OSD bar.
1606 * Display the OSD bar or fall back on a simple message.
1610 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1611 struct MPOpts *opts = &mpctx->opts;
1612 if (opts->osd_level < 1)
1613 return;
1615 if(mpctx->sh_video) {
1616 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1617 vo_osd_progbar_type = type;
1618 vo_osd_progbar_value = 256*(val-min)/(max-min);
1619 vo_osd_changed(OSDTYPE_PROGBAR);
1620 return;
1623 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1624 name, ROUND(100*(val-min)/(max-min)));
1628 * \brief Display text subtitles on the OSD
1630 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1632 int i;
1633 vo_sub = subs;
1634 vo_osd_changed(OSDTYPE_SUBTITLE);
1635 if (!mpctx->sh_video) {
1636 // reverse order, since newest set_osd_msg is displayed first
1637 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1638 if (!subs || i >= subs->lines || !subs->text[i])
1639 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1640 else {
1641 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1642 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1643 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1650 * \brief Update the OSD message line.
1652 * This function displays the current message on the vo OSD or on the term.
1653 * If the stack is empty and the OSD level is high enough the timer
1654 * is displayed (only on the vo OSD).
1658 static void update_osd_msg(struct MPContext *mpctx)
1660 struct MPOpts *opts = &mpctx->opts;
1661 mp_osd_msg_t *msg;
1662 struct osd_state *osd = mpctx->osd;
1663 char osd_text_timer[128];
1665 if (mpctx->add_osd_seek_info) {
1666 double percentage = get_percent_pos(mpctx);
1667 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1668 if (mpctx->sh_video)
1669 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1670 mpctx->add_osd_seek_info = false;
1673 // Look if we have a msg
1674 if((msg = get_osd_msg(mpctx))) {
1675 if (strcmp(osd->osd_text, msg->msg)) {
1676 strncpy(osd->osd_text, msg->msg, 127);
1677 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1678 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1680 return;
1683 if(mpctx->sh_video) {
1684 // fallback on the timer
1685 if (opts->osd_level >= 2) {
1686 int len = get_time_length(mpctx);
1687 int percentage = -1;
1688 char percentage_text[10];
1689 int pts = get_current_time(mpctx);
1691 if (mpctx->osd_show_percentage_until)
1692 percentage = get_percent_pos(mpctx);
1694 if (percentage >= 0)
1695 snprintf(percentage_text, 9, " (%d%%)", percentage);
1696 else
1697 percentage_text[0] = 0;
1699 if (opts->osd_level == 3)
1700 snprintf(osd_text_timer, 63,
1701 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1702 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1703 len/3600,(len/60)%60,len%60,percentage_text);
1704 else
1705 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1706 mpctx->osd_function,pts/3600,(pts/60)%60,
1707 pts%60,percentage_text);
1708 } else
1709 osd_text_timer[0]=0;
1711 if (strcmp(osd->osd_text, osd_text_timer)) {
1712 strncpy(osd->osd_text, osd_text_timer, 63);
1713 vo_osd_changed(OSDTYPE_OSD);
1715 return;
1718 // Clear the term osd line
1719 if (term_osd && osd->osd_text[0]) {
1720 osd->osd_text[0] = 0;
1721 printf("%s\n",term_osd_esc);
1725 ///@}
1726 // OSDMsgStack
1729 void reinit_audio_chain(struct MPContext *mpctx)
1731 struct MPOpts *opts = &mpctx->opts;
1732 if (!mpctx->sh_audio)
1733 return;
1734 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1735 current_module="init_audio_codec";
1736 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1737 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1738 goto init_error;
1740 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1741 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1745 current_module="af_preinit";
1746 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1747 ao_data.samplerate=force_srate;
1748 ao_data.channels=0;
1749 ao_data.format = opts->audio_output_format;
1751 // first init to detect best values
1752 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1753 // input:
1754 mpctx->sh_audio->samplerate,
1755 // output:
1756 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1757 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1758 "pre-init!\n");
1759 exit_player(mpctx, EXIT_ERROR);
1761 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1762 current_module="ao2_init";
1763 ao_data.buffersize = opts->ao_buffersize;
1764 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1765 0, // plugin flag
1766 ao_data.samplerate,
1767 ao_data.channels,
1768 ao_data.format, 0);
1769 if(!mpctx->audio_out){
1770 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1771 goto init_error;
1773 mpctx->initialized_flags|=INITIALIZED_AO;
1774 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1775 mpctx->audio_out->info->short_name,
1776 ao_data.samplerate, ao_data.channels,
1777 af_fmt2str_short(ao_data.format),
1778 af_fmt2bits(ao_data.format)/8 );
1779 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1780 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1781 if(strlen(mpctx->audio_out->info->comment) > 0)
1782 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1785 // init audio filters:
1786 current_module="af_init";
1787 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1788 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1789 goto init_error;
1791 mpctx->mixer.audio_out = mpctx->audio_out;
1792 mpctx->mixer.volstep = volstep;
1793 return;
1795 init_error:
1796 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1797 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1798 mpctx->d_audio->id = -2;
1802 ///@}
1803 // Command2Property
1806 // Return pts value corresponding to the end point of audio written to the
1807 // ao so far.
1808 static double written_audio_pts(struct MPContext *mpctx)
1810 sh_audio_t *sh_audio = mpctx->sh_audio;
1811 demux_stream_t *d_audio = mpctx->d_audio;
1812 double buffered_output;
1813 // first calculate the end pts of audio that has been output by decoder
1814 double a_pts = sh_audio->pts;
1815 if (a_pts != MP_NOPTS_VALUE)
1816 // Good, decoder supports new way of calculating audio pts.
1817 // sh_audio->pts is the timestamp of the latest input packet with
1818 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1819 // the amount of bytes the decoder has written after that timestamp.
1820 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1821 else {
1822 // Decoder doesn't support new way of calculating pts (or we're
1823 // being called before it has decoded anything with known timestamp).
1824 // Use the old method of audio pts calculation: take the timestamp
1825 // of last packet with known pts the decoder has read data from,
1826 // and add amount of bytes read after the beginning of that packet
1827 // divided by input bps. This will be inaccurate if the input/output
1828 // ratio is not constant for every audio packet or if it is constant
1829 // but not accurately known in sh_audio->i_bps.
1831 a_pts = d_audio->pts;
1832 // ds_tell_pts returns bytes read after last timestamp from
1833 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1834 // it has read but not decoded
1835 if (sh_audio->i_bps)
1836 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1837 (double)sh_audio->i_bps;
1839 // Now a_pts hopefully holds the pts for end of audio from decoder.
1840 // Substract data in buffers between decoder and audio out.
1842 // Decoded but not filtered
1843 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1845 // Data buffered in audio filters, measured in bytes of "missing" output
1846 buffered_output = af_calc_delay(sh_audio->afilter);
1848 // Data that was ready for ao but was buffered because ao didn't fully
1849 // accept everything to internal buffers yet
1850 buffered_output += sh_audio->a_out_buffer_len;
1852 // Filters divide audio length by playback_speed, so multiply by it
1853 // to get the length in original units without speedup or slowdown
1854 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1856 return a_pts + mpctx->video_offset;
1859 // Return pts value corresponding to currently playing audio.
1860 double playing_audio_pts(struct MPContext *mpctx)
1862 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1863 mpctx->audio_out->get_delay();
1866 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1867 struct MPOpts *opts = &mpctx->opts;
1868 // check for frame-drop:
1869 current_module = "check_framedrop";
1870 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1871 static int dropped_frames;
1872 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1873 float d = delay-mpctx->delay;
1874 ++total_frame_cnt;
1875 // we should avoid dropping too many frames in sequence unless we
1876 // are too late. and we allow 100ms A-V delay here:
1877 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1878 && !mpctx->restart_playback) {
1879 ++drop_frame_cnt;
1880 ++dropped_frames;
1881 return frame_dropping;
1882 } else
1883 dropped_frames = 0;
1885 return 0;
1889 #ifdef HAVE_RTC
1890 int rtc_fd = -1;
1891 #endif
1893 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1895 #ifdef HAVE_RTC
1896 if (rtc_fd >= 0){
1897 // -------- RTC -----------
1898 current_module="sleep_rtc";
1899 while (time_frame > 0.000) {
1900 unsigned long rtc_ts;
1901 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1902 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1903 time_frame -= get_relative_time(mpctx);
1905 } else
1906 #endif
1908 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1909 // unnecessarily high CPU usage
1910 float margin = softsleep ? 0.011 : 0;
1911 current_module = "sleep_timer";
1912 while (time_frame > margin) {
1913 usec_sleep(1000000 * (time_frame - margin));
1914 time_frame -= get_relative_time(mpctx);
1916 if (softsleep){
1917 current_module = "sleep_soft";
1918 if (time_frame < 0)
1919 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1920 while (time_frame > 0)
1921 time_frame -= get_relative_time(mpctx); // burn the CPU
1924 return time_frame;
1927 static int select_subtitle(MPContext *mpctx)
1929 struct MPOpts *opts = &mpctx->opts;
1930 // find the best sub to use
1931 int id;
1932 int found = 0;
1933 mpctx->global_sub_pos = -1; // no subs by default
1934 if (vobsub_id >= 0) {
1935 // if user asks for a vobsub id, use that first.
1936 id = vobsub_id;
1937 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1940 if (!found && opts->sub_id >= 0) {
1941 // if user asks for a dvd sub id, use that next.
1942 id = opts->sub_id;
1943 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1946 if (!found) {
1947 // if there are text subs to use, use those. (autosubs come last here)
1948 id = 0;
1949 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1952 if (!found && opts->sub_id == -1) {
1953 // finally select subs by language and container hints
1954 if (opts->sub_id == -1)
1955 opts->sub_id =
1956 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
1957 opts->sub_lang);
1958 if (opts->sub_id >= 0) {
1959 id = opts->sub_id;
1960 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1963 return found;
1966 #ifdef CONFIG_DVDNAV
1967 #ifndef FF_B_TYPE
1968 #define FF_B_TYPE 3
1969 #endif
1970 /// store decoded video image
1971 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1972 mp_image_t *from_mpi) {
1973 mp_image_t *mpi;
1975 /// Do not store B-frames
1976 if (from_mpi->pict_type == FF_B_TYPE)
1977 return to_mpi;
1979 if (to_mpi &&
1980 to_mpi->w == from_mpi->w &&
1981 to_mpi->h == from_mpi->h &&
1982 to_mpi->imgfmt == from_mpi->imgfmt)
1983 mpi = to_mpi;
1984 else {
1985 if (to_mpi)
1986 free_mp_image(to_mpi);
1987 if (from_mpi->w == 0 || from_mpi->h == 0)
1988 return NULL;
1989 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1992 copy_mpi(mpi,from_mpi);
1993 return mpi;
1996 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1997 struct MPOpts *opts = &ctx->opts;
1998 if (ctx->sh_video) {
1999 /// clear video pts
2000 ctx->d_video->pts = 0.0f;
2001 ctx->sh_video->pts = 0.0f;
2002 ctx->sh_video->i_pts = 0.0f;
2003 ctx->sh_video->last_pts = 0.0f;
2004 ctx->sh_video->num_buffered_pts = 0;
2005 ctx->sh_video->num_frames = 0;
2006 ctx->sh_video->num_frames_decoded = 0;
2007 ctx->sh_video->timer = 0.0f;
2008 ctx->sh_video->stream_delay = 0.0f;
2009 ctx->sh_video->timer = 0;
2010 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2013 if (ctx->sh_audio) {
2014 /// free audio packets and reset
2015 ds_free_packs(ctx->d_audio);
2016 audio_delay -= ctx->sh_audio->stream_delay;
2017 ctx->delay =- audio_delay;
2018 ctx->audio_out->reset();
2019 resync_audio_stream(ctx->sh_audio);
2022 audio_delay = 0.0f;
2023 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2024 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2025 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2026 if (dvdsub_lang_id != opts->sub_id) {
2027 opts->sub_id = dvdsub_lang_id;
2028 select_subtitle(ctx);
2032 /// clear all EOF related flags
2033 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2036 /// Restore last decoded DVDNAV (still frame)
2037 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2038 int *in_size,
2039 unsigned char **start,
2040 mp_image_t *decoded_frame)
2042 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2043 return decoded_frame;
2045 /// a change occured in dvdnav stream
2046 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2047 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2048 mp_dvdnav_context_free(mpctx);
2049 mp_dvdnav_reset_stream(mpctx);
2050 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2051 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2054 if (*in_size < 0) {
2055 float len;
2057 /// Display still frame, if any
2058 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2059 decoded_frame = mpctx->nav_smpi;
2061 /// increment video frame : continue playing after still frame
2062 len = get_time_length(mpctx);
2063 if (mpctx->sh_video->pts >= len &&
2064 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2065 mp_dvdnav_skip_still(mpctx->stream);
2066 mp_dvdnav_skip_wait(mpctx->stream);
2068 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2070 if (mpctx->nav_buffer) {
2071 *start = mpctx->nav_start;
2072 *in_size = mpctx->nav_in_size;
2073 if (mpctx->nav_start)
2074 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2078 return decoded_frame;
2081 /// Save last decoded DVDNAV (still frame)
2082 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2083 unsigned char *start,
2084 mp_image_t *decoded_frame)
2086 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2087 return;
2089 free(mpctx->nav_buffer);
2091 mpctx->nav_buffer = malloc(in_size);
2092 mpctx->nav_start = start;
2093 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2094 if (mpctx->nav_buffer)
2095 memcpy(mpctx->nav_buffer,start,in_size);
2097 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2098 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2100 #endif /* CONFIG_DVDNAV */
2102 /* Modify video timing to match the audio timeline. There are two main
2103 * reasons this is needed. First, video and audio can start from different
2104 * positions at beginning of file or after a seek (MPlayer starts both
2105 * immediately even if they have different pts). Second, the file can have
2106 * audio timestamps that are inconsistent with the duration of the audio
2107 * packets, for example two consecutive timestamp values differing by
2108 * one second but only a packet with enough samples for half a second
2109 * of playback between them.
2111 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2113 current_module = "av_sync";
2115 if (!mpctx->sh_audio)
2116 return;
2118 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2119 double v_pts = mpctx->sh_video->pts;
2120 double av_delay = a_pts - v_pts;
2121 // Try to sync vo_flip() so it will *finish* at given time
2122 av_delay += mpctx->last_vo_flip_duration;
2123 av_delay -= audio_delay; // This much pts difference is desired
2125 double change = av_delay * 0.1;
2126 double max_change = default_max_pts_correction >= 0 ?
2127 default_max_pts_correction : frame_time * 0.1;
2128 if (change < -max_change)
2129 change = -max_change;
2130 else if (change > max_change)
2131 change = max_change;
2132 mpctx->delay += change;
2133 mpctx->total_avsync_change += change;
2136 static int fill_audio_out_buffers(struct MPContext *mpctx)
2138 struct MPOpts *opts = &mpctx->opts;
2139 unsigned int t;
2140 double tt;
2141 int playsize;
2142 int playflags=0;
2143 int audio_eof=0;
2144 bool format_change = false;
2145 sh_audio_t * const sh_audio = mpctx->sh_audio;
2147 current_module="play_audio";
2149 while (1) {
2150 int sleep_time;
2151 // all the current uses of ao_data.pts seem to be in aos that handle
2152 // sync completely wrong; there should be no need to use ao_data.pts
2153 // in get_space()
2154 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2155 playsize = mpctx->audio_out->get_space();
2156 if (mpctx->sh_video || playsize >= ao_data.outburst)
2157 break;
2159 // handle audio-only case:
2160 // this is where mplayer sleeps during audio-only playback
2161 // to avoid 100% CPU use
2162 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2163 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2164 usec_sleep(sleep_time * 1000);
2167 // Fill buffer if needed:
2168 current_module="decode_audio";
2169 t = GetTimer();
2170 int res = decode_audio(sh_audio, playsize);
2171 if (res < 0) { // EOF, error or format change
2172 if (res == -2)
2173 format_change = true;
2174 else if (mpctx->d_audio->eof) {
2175 audio_eof = 1;
2176 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2177 if (sh_audio->a_out_buffer_len < unitsize)
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 double current_pts = get_current_time(mpctx);
2919 if (!mpctx->chapters)
2920 return FFMAX(mpctx->last_chapter_seek,
2921 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
2923 int i;
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 float stream_cache_min_percent = opts->stream_cache_min_percent;
3761 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
3762 current_module="enable_cache";
3763 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3764 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3765 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3766 if(res == 0)
3767 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3770 //============ Open DEMUXERS --- DETECT file type =======================
3771 current_module="demux_open";
3773 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3775 // HACK to get MOV Reference Files working
3777 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3779 unsigned char* playlist_entry;
3780 play_tree_t *list = NULL, *entry = NULL;
3782 current_module="handle_demux_playlist";
3783 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3785 char *temp, *bname;
3787 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3788 filename_recode(playlist_entry));
3790 bname=mp_basename(playlist_entry);
3791 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3792 continue;
3794 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3795 continue;
3797 entry = play_tree_new();
3799 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3801 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3802 if (temp)
3804 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3805 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3806 strcat(temp, playlist_entry);
3807 if (!strcmp(temp, mpctx->filename)) {
3808 free(temp);
3809 continue;
3811 play_tree_add_file(entry,temp);
3812 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3813 free(temp);
3816 else
3817 play_tree_add_file(entry,playlist_entry);
3819 if(!list)
3820 list = entry;
3821 else
3822 play_tree_append_entry(list,entry);
3824 free_demuxer(mpctx->demuxer);
3825 mpctx->demuxer = NULL;
3827 if (list)
3829 entry = play_tree_new();
3830 play_tree_set_child(entry,list);
3831 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3832 goto goto_next_file;
3836 if(!mpctx->demuxer) {
3837 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
3838 goto goto_next_file;
3841 if (mpctx->demuxer->matroska_data.ordered_chapters)
3842 build_ordered_chapter_timeline(mpctx);
3844 if (!mpctx->sources) {
3845 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3846 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3847 .demuxer = mpctx->demuxer};
3848 mpctx->num_sources = 1;
3851 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3853 #ifdef CONFIG_ASS
3854 if (opts->ass_enabled && ass_library) {
3855 for (int j = 0; j < mpctx->num_sources; j++) {
3856 struct demuxer *d = mpctx->sources[j].demuxer;
3857 for (int i = 0; i < d->num_attachments; i++) {
3858 struct demux_attachment *att = d->attachments + i;
3859 if (use_embedded_fonts && attachment_is_font(att))
3860 ass_add_font(ass_library, att->name, att->data, att->data_size);
3864 #endif
3866 current_module="demux_open2";
3868 mpctx->d_audio=mpctx->demuxer->audio;
3869 mpctx->d_video=mpctx->demuxer->video;
3870 mpctx->d_sub=mpctx->demuxer->sub;
3872 if (ts_prog) {
3873 int tmp = ts_prog;
3874 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3876 // select audio stream
3877 if (mpctx->num_sources)
3878 for (int i = 0; i < mpctx->num_sources; i++)
3879 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3880 opts->audio_lang);
3881 else
3882 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
3884 // DUMP STREAMS:
3885 if((stream_dump_type)&&(stream_dump_type<4)){
3886 FILE *f;
3887 demux_stream_t *ds=NULL;
3888 current_module="dump";
3889 // select stream to dump
3890 switch(stream_dump_type){
3891 case 1: ds=mpctx->d_audio;break;
3892 case 2: ds=mpctx->d_video;break;
3893 case 3: ds=mpctx->d_sub;break;
3895 if(!ds){
3896 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3897 exit_player(mpctx, EXIT_ERROR);
3899 // disable other streams:
3900 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3901 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3902 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3903 // let's dump it!
3904 f=fopen(opts->stream_dump_name,"wb");
3905 if(!f){
3906 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3907 exit_player(mpctx, EXIT_ERROR);
3909 while(!ds->eof){
3910 unsigned char* start;
3911 int in_size=ds_get_packet(ds,&start);
3912 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3913 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3914 if(in_size>0) fwrite(start,in_size,1,f);
3915 if (opts->chapterrange[1] > 0) {
3916 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
3917 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3918 break;
3921 fclose(f);
3922 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3923 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3926 mpctx->sh_audio=mpctx->d_audio->sh;
3927 mpctx->sh_video=mpctx->d_video->sh;
3929 if(mpctx->sh_video){
3931 current_module="video_read_properties";
3932 if(!video_read_properties(mpctx->sh_video)) {
3933 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3934 mpctx->sh_video=mpctx->d_video->sh=NULL;
3935 } else {
3936 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3937 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3938 mpctx->sh_video->fps,mpctx->sh_video->frametime
3941 /* need to set fps here for output encoders to pick it up in their init */
3942 if(force_fps){
3943 mpctx->sh_video->fps=force_fps;
3944 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3946 vo_fps = mpctx->sh_video->fps;
3948 if(!mpctx->sh_video->fps && !force_fps){
3949 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3950 mpctx->opts.correct_pts = 1;
3956 if(!mpctx->sh_video && !mpctx->sh_audio){
3957 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3958 #ifdef CONFIG_DVBIN
3959 if(mpctx->stream->type == STREAMTYPE_DVB)
3961 int dir;
3962 int v = mpctx->last_dvb_step;
3963 if(v > 0)
3964 dir = DVB_CHANNEL_HIGHER;
3965 else
3966 dir = DVB_CHANNEL_LOWER;
3968 if(dvb_step_channel(mpctx->stream, dir)) {
3969 mpctx->stop_play = PT_NEXT_ENTRY;
3970 mpctx->dvbin_reopen = 1;
3973 #endif
3974 goto goto_next_file; // exit_player(_("Fatal error"));
3977 /* display clip info */
3978 demux_info_print(mpctx->demuxer);
3980 //================== Read SUBTITLES (DVD & TEXT) ==========================
3981 if(vo_spudec==NULL &&
3982 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3983 init_vo_spudec(mpctx);
3986 // after reading video params we should load subtitles because
3987 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3988 // check .sub
3989 current_module="read_subtitles_file";
3990 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3991 if(sub_name){
3992 for (i = 0; sub_name[i] != NULL; ++i)
3993 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3995 if(sub_auto) { // auto load sub file ...
3996 char *psub = get_path( "sub/" );
3997 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3998 int i = 0;
3999 free(psub); // release the buffer created by get_path() above
4000 while (tmp[i]) {
4001 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4002 free(tmp[i++]);
4004 free(tmp);
4006 if (mpctx->set_of_sub_size > 0)
4007 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4009 if (select_subtitle(mpctx)) {
4010 if(subdata)
4011 switch (stream_dump_type) {
4012 case 3: list_sub_file(subdata); break;
4013 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
4014 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
4015 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
4016 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
4017 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
4021 print_file_properties(mpctx, mpctx->filename);
4023 if(!mpctx->sh_video) goto main; // audio-only
4025 if(!reinit_video_chain(mpctx)) {
4026 if(!mpctx->sh_video){
4027 if(!mpctx->sh_audio) goto goto_next_file;
4028 goto main; // exit_player(_("Fatal error"));
4032 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4033 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4035 #ifdef CONFIG_FREETYPE
4036 force_load_font = 1;
4037 #endif
4039 //================== MAIN: ==========================
4040 main:
4041 current_module="main";
4043 if(playing_msg) {
4044 char* msg = property_expand_string(mpctx, playing_msg);
4045 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4046 free(msg);
4050 // Disable the term OSD in verbose mode
4051 if(verbose) term_osd = 0;
4054 int frame_time_remaining=0; // flag
4055 int blit_frame=0;
4057 // Make sure old OSD does not stay around,
4058 // e.g. with -fixed-vo and same-resolution files
4059 clear_osd_msgs();
4060 update_osd_msg(mpctx);
4062 //================ SETUP AUDIO ==========================
4064 if(mpctx->sh_audio){
4065 reinit_audio_chain(mpctx);
4066 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4067 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4070 current_module="av_init";
4072 if(mpctx->sh_video){
4073 mpctx->sh_video->timer=0;
4074 if (! ignore_start)
4075 audio_delay += mpctx->sh_video->stream_delay;
4077 if(mpctx->sh_audio){
4078 if (start_volume >= 0)
4079 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4080 if (! ignore_start)
4081 audio_delay -= mpctx->sh_audio->stream_delay;
4082 mpctx->delay=-audio_delay;
4085 if(!mpctx->sh_audio){
4086 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4087 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4088 ds_free_packs(mpctx->d_audio); // free buffered chunks
4089 //mpctx->d_audio->id=-2; // do not read audio chunks
4090 //uninit_player(mpctx, INITIALIZED_AO); // close device
4092 if(!mpctx->sh_video){
4093 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4094 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4095 ds_free_packs(mpctx->d_video);
4096 mpctx->d_video->id=-2;
4097 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4100 if (!mpctx->sh_video && !mpctx->sh_audio)
4101 goto goto_next_file;
4103 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4104 if(force_fps && mpctx->sh_video){
4105 vo_fps = mpctx->sh_video->fps=force_fps;
4106 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4107 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4110 mp_input_set_section(mpctx->input, NULL);
4111 //TODO: add desired (stream-based) sections here
4112 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4113 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4115 //==================== START PLAYING =======================
4117 if(opts->loop_times>1) opts->loop_times--; else
4118 if(opts->loop_times==1) opts->loop_times = -1;
4120 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4122 total_time_usage_start=GetTimer();
4123 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4124 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4125 play_n_frames=play_n_frames_mf;
4127 if(play_n_frames==0){
4128 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4131 // If there's a timeline force an absolute seek to initialize state
4132 if (seek_to_sec || mpctx->timeline) {
4133 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4134 end_at.pos += seek_to_sec;
4136 if (opts->chapterrange[0] > 0) {
4137 double pts;
4138 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4139 && pts > -1.0)
4140 seek(mpctx, pts, SEEK_ABSOLUTE);
4143 if (end_at.type == END_AT_SIZE) {
4144 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4145 end_at.type = END_AT_NONE;
4148 #ifdef CONFIG_DVDNAV
4149 mp_dvdnav_context_free(mpctx);
4150 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4151 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4152 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4154 #endif
4156 get_relative_time(mpctx); // reset current delta
4157 mpctx->time_frame = 0;
4158 mpctx->drop_message_shown = 0;
4159 mpctx->restart_playback = true;
4160 mpctx->total_avsync_change = 0;
4161 mpctx->last_chapter_seek = -1;
4162 // Make sure VO knows current pause state
4163 if (mpctx->sh_video)
4164 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4165 NULL);
4167 while(!mpctx->stop_play){
4168 float aq_sleep_time=0;
4170 if (opts->chapterrange[1] > 0) {
4171 int cur_chapter = get_current_chapter(mpctx);
4172 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4173 goto goto_next_file;
4176 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4177 mpctx->sh_audio = mpctx->d_audio->sh;
4178 mpctx->sh_audio->ds = mpctx->d_audio;
4179 reinit_audio_chain(mpctx);
4182 /*========================== PLAY AUDIO ============================*/
4184 if (mpctx->sh_audio && !mpctx->paused)
4185 if (!fill_audio_out_buffers(mpctx))
4186 // at eof, all audio at least written to ao
4187 if (!mpctx->sh_video)
4188 mpctx->stop_play = AT_END_OF_FILE;
4191 if(!mpctx->sh_video) {
4192 // handle audio-only case:
4193 double a_pos=0;
4194 // sh_audio can be NULL due to video stream switching
4195 // TODO: handle this better
4196 if (mpctx->sh_audio)
4197 a_pos = playing_audio_pts(mpctx);
4199 print_status(mpctx, a_pos, false);
4201 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4202 mpctx->stop_play = PT_NEXT_ENTRY;
4203 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4204 mpctx->d_sub, 0);
4205 update_osd_msg(mpctx);
4207 } else {
4209 /*========================== PLAY VIDEO ============================*/
4211 vo_pts=mpctx->sh_video->timer*90000.0;
4212 vo_fps=mpctx->sh_video->fps;
4214 blit_frame = mpctx->video_out->frame_loaded;
4215 if (!blit_frame) {
4216 double frame_time = update_video(mpctx);
4217 blit_frame = mpctx->video_out->frame_loaded;
4218 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4219 if (mpctx->sh_video->vf_initialized < 0) {
4220 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4221 mpctx->stop_play = PT_NEXT_ENTRY;
4222 goto goto_next_file;
4224 if (blit_frame) {
4225 struct sh_video *sh_video = mpctx->sh_video;
4226 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4227 mpctx->video_offset, mpctx->d_sub, 0);
4228 update_teletext(sh_video, mpctx->demuxer, 0);
4229 update_osd_msg(mpctx);
4230 struct vf_instance *vf = mpctx->sh_video->vfilter;
4231 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4232 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4233 vo_osd_changed(0);
4235 if (frame_time < 0)
4236 mpctx->stop_play = AT_END_OF_FILE;
4237 else {
4238 if (mpctx->restart_playback) {
4239 // Show this frame immediately, rest normally
4240 mpctx->restart_playback = false;
4241 } else {
4242 mpctx->time_frame += frame_time / opts->playback_speed;
4243 adjust_sync(mpctx, frame_time);
4247 if (mpctx->timeline) {
4248 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4249 if (mpctx->sh_video->pts >= next->start
4250 || mpctx->stop_play == AT_END_OF_FILE
4251 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4252 seek(mpctx, next->start, SEEK_ABSOLUTE);
4253 continue;
4257 // ==========================================================================
4259 // current_module="draw_osd";
4260 // if(vo_config_count) mpctx->video_out->draw_osd();
4262 current_module="vo_check_events";
4263 vo_check_events(mpctx->video_out);
4265 #ifdef CONFIG_X11
4266 if (stop_xscreensaver) {
4267 current_module = "stop_xscreensaver";
4268 xscreensaver_heartbeat(mpctx->x11_state);
4270 #endif
4271 if (heartbeat_cmd) {
4272 static unsigned last_heartbeat;
4273 unsigned now = GetTimerMS();
4274 if (now - last_heartbeat > 30000) {
4275 last_heartbeat = now;
4276 system(heartbeat_cmd);
4280 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4282 //====================== FLIP PAGE (VIDEO BLT): =========================
4284 current_module="flip_page";
4285 if (!frame_time_remaining && blit_frame) {
4286 unsigned int t2=GetTimer();
4287 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4288 int duration = -1;
4289 double pts2 = mpctx->video_out->next_pts2;
4290 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4291 // expected A/V sync correction is ignored
4292 double diff = (pts2 - mpctx->sh_video->pts);
4293 diff /= opts->playback_speed;
4294 if (mpctx->time_frame < 0)
4295 diff += mpctx->time_frame;
4296 if (diff < 0)
4297 diff = 0;
4298 if (diff > 10)
4299 diff = 10;
4300 duration = diff * 1e6;
4302 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4304 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4305 vout_time_usage += mpctx->last_vo_flip_duration;
4306 if (mpctx->video_out->driver->flip_page_timed) {
4307 // No need to adjust sync based on flip speed
4308 mpctx->last_vo_flip_duration = 0;
4309 // For print_status - VO call finishing early is OK for sync
4310 mpctx->time_frame -= get_relative_time(mpctx);
4312 print_status(mpctx, MP_NOPTS_VALUE, true);
4314 else
4315 print_status(mpctx, MP_NOPTS_VALUE, false);
4317 //============================ Auto QUALITY ============================
4319 /*Output quality adjustments:*/
4320 if(auto_quality>0){
4321 current_module="autoq";
4322 // float total=0.000001f * (GetTimer()-aq_total_time);
4323 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4324 if(output_quality<auto_quality && aq_sleep_time>0)
4325 ++output_quality;
4326 else
4327 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4328 if(output_quality>1 && aq_sleep_time<0)
4329 --output_quality;
4330 else
4331 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4332 output_quality=0;
4333 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4334 set_video_quality(mpctx->sh_video,output_quality);
4337 if (!frame_time_remaining && blit_frame) {
4338 if (play_n_frames >= 0) {
4339 --play_n_frames;
4340 if (play_n_frames <= 0)
4341 mpctx->stop_play = PT_NEXT_ENTRY;
4343 if (mpctx->step_frames > 0) {
4344 mpctx->step_frames--;
4345 if (mpctx->step_frames == 0)
4346 pause_player(mpctx);
4351 // FIXME: add size based support for -endpos
4352 if (end_at.type == END_AT_TIME &&
4353 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4354 mpctx->stop_play = PT_NEXT_ENTRY;
4356 } // end if(mpctx->sh_video)
4358 #ifdef CONFIG_DVDNAV
4359 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4360 nav_highlight_t hl;
4361 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4362 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4363 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4364 vo_osd_changed (OSDTYPE_DVDNAV);
4365 } else {
4366 osd_set_nav_box(0, 0, 0, 0);
4367 vo_osd_changed(OSDTYPE_DVDNAV);
4368 vo_osd_changed(OSDTYPE_SPU);
4371 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4372 double ar = -1.0;
4373 if (mpctx->sh_video &&
4374 stream_control (mpctx->demuxer->stream,
4375 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4376 != STREAM_UNSUPPORTED)
4377 mpctx->sh_video->stream_aspect = ar;
4380 #endif
4382 //================= Keyboard events, SEEKing ====================
4384 current_module="key_events";
4387 while (1) {
4388 mp_cmd_t* cmd;
4389 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4390 run_command(mpctx, cmd);
4391 mp_cmd_free(cmd);
4392 if (mpctx->stop_play)
4393 break;
4394 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4395 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4396 /* Allow seek commands to be combined, but execute the real seek
4397 * before processing other commands */
4398 if (!cmd || cmd->id != MP_CMD_SEEK)
4399 break;
4402 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4403 || mpctx->abs_seek_pos)
4404 break;
4405 if (mpctx->sh_video) {
4406 update_osd_msg(mpctx);
4407 int hack = vo_osd_changed(0);
4408 vo_osd_changed(hack);
4409 if (hack) {
4410 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4411 add_step_frame(mpctx);
4412 break;
4414 else
4415 vo_osd_changed(0);
4418 pause_loop(mpctx);
4422 // handle -sstep
4423 if (step_sec > 0 && !mpctx->paused) {
4424 mpctx->osd_function=OSD_FFW;
4425 mpctx->rel_seek_secs+=step_sec;
4428 edl_update(mpctx);
4430 /* Looping. */
4431 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4432 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4434 if(opts->loop_times>1) opts->loop_times--; else
4435 if(opts->loop_times==1) opts->loop_times=-1;
4436 play_n_frames=play_n_frames_mf;
4437 mpctx->stop_play=0;
4438 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4441 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4442 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4444 mpctx->rel_seek_secs=0;
4445 mpctx->abs_seek_pos=0;
4448 } // while(!mpctx->stop_play)
4450 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4452 #ifdef CONFIG_DVBIN
4453 if(mpctx->dvbin_reopen)
4455 mpctx->stop_play = 0;
4456 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4457 cache_uninit(mpctx->stream);
4458 mpctx->dvbin_reopen = 0;
4459 goto goto_enable_cache;
4461 #endif
4464 goto_next_file: // don't jump here after ao/vo/getch initialization!
4466 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4468 if(benchmark){
4469 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4470 double total_time_usage;
4471 total_time_usage_start=GetTimer()-total_time_usage_start;
4472 total_time_usage = (float)total_time_usage_start*0.000001;
4473 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4474 video_time_usage,vout_time_usage,audio_time_usage,
4475 total_time_usage-tot,total_time_usage);
4476 if(total_time_usage>0.0)
4477 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4478 100.0*video_time_usage/total_time_usage,
4479 100.0*vout_time_usage/total_time_usage,
4480 100.0*audio_time_usage/total_time_usage,
4481 100.0*(total_time_usage-tot)/total_time_usage,
4482 100.0);
4483 if(total_frame_cnt && frame_dropping)
4484 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4485 total_frame_cnt-drop_frame_cnt,
4486 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4487 drop_frame_cnt,
4488 100*drop_frame_cnt/total_frame_cnt,
4489 total_frame_cnt,
4490 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4493 // time to uninit all, except global stuff:
4494 int uninitialize_parts = INITIALIZED_ALL;
4495 if (opts->fixed_vo)
4496 uninitialize_parts -= INITIALIZED_VO;
4497 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4498 uninitialize_parts -= INITIALIZED_AO;
4499 uninit_player(mpctx, uninitialize_parts);
4501 if(mpctx->set_of_sub_size > 0) {
4502 current_module="sub_free";
4503 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4504 sub_free(mpctx->set_of_subtitles[i]);
4505 #ifdef CONFIG_ASS
4506 if(mpctx->set_of_ass_tracks[i])
4507 ass_free_track( mpctx->set_of_ass_tracks[i] );
4508 #endif
4510 mpctx->set_of_sub_size = 0;
4512 vo_sub_last = vo_sub=NULL;
4513 subdata=NULL;
4514 #ifdef CONFIG_ASS
4515 ass_track = NULL;
4516 if(ass_library)
4517 ass_clear_fonts(ass_library);
4518 #endif
4520 if (!mpctx->stop_play) // In case some goto jumped here...
4521 mpctx->stop_play = PT_NEXT_ENTRY;
4523 int playtree_direction = 1;
4525 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4526 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4527 play_tree_iter_free(mpctx->playtree_iter);
4528 mpctx->playtree_iter = NULL;
4530 mpctx->play_tree_step = 1;
4531 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4532 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4533 if(mpctx->playtree_iter) {
4534 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4535 play_tree_iter_free(mpctx->playtree_iter);
4536 mpctx->playtree_iter = NULL;
4539 } else if (mpctx->stop_play == PT_STOP) {
4540 play_tree_iter_free(mpctx->playtree_iter);
4541 mpctx->playtree_iter = NULL;
4542 } else { // NEXT PREV SRC
4543 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4546 while(mpctx->playtree_iter != NULL) {
4547 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4548 if(mpctx->filename == NULL) {
4549 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4550 play_tree_iter_free(mpctx->playtree_iter);
4551 mpctx->playtree_iter = NULL;
4553 } else
4554 break;
4557 if(mpctx->playtree_iter != NULL || player_idle_mode){
4558 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4559 mpctx->stop_play = 0;
4560 goto play_next_file;
4564 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4566 return 1;
4568 #endif /* DISABLE_MAIN */