core: audio: make ogg missing audio timing workaround more complex
[mplayer/glamo.git] / mplayer.c
blob87490152afbb5160f05e7f74066c78e805a70b15
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 <math.h>
27 #include "config.h"
28 #include "talloc.h"
30 #if defined(__MINGW32__) || defined(__CYGWIN__)
31 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
32 #include <windows.h>
33 #endif
34 #include <string.h>
35 #include <unistd.h>
37 // #include <sys/mman.h>
38 #include <sys/types.h>
39 #ifndef __MINGW32__
40 #include <sys/ioctl.h>
41 #include <sys/wait.h>
42 #else
43 #define SIGHUP 1 /* hangup */
44 #define SIGQUIT 3 /* quit */
45 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
46 #define SIGBUS 10 /* bus error */
47 #define SIGPIPE 13 /* broken pipe */
48 #endif
50 #include <sys/time.h>
51 #include <sys/stat.h>
53 #include <signal.h>
54 #include <time.h>
55 #include <fcntl.h>
56 #include <limits.h>
58 #include <errno.h>
60 #include "mp_msg.h"
61 #include "av_log.h"
64 #include "m_option.h"
65 #include "m_config.h"
66 #include "mplayer.h"
67 #include "access_mpcontext.h"
68 #include "m_property.h"
70 #include "cfg-mplayer-def.h"
72 #include "libavutil/avstring.h"
74 #include "subreader.h"
76 #include "mp_osd.h"
77 #include "libvo/video_out.h"
79 #include "libvo/font_load.h"
80 #include "libvo/sub.h"
82 #ifdef CONFIG_X11
83 #include "libvo/x11_common.h"
84 #endif
86 #include "libao2/audio_out.h"
88 #include "codec-cfg.h"
90 #include "edl.h"
92 #include "spudec.h"
93 #include "vobsub.h"
95 #include "osdep/getch2.h"
96 #include "osdep/timer.h"
97 #include "osdep/findfiles.h"
99 #include "input/input.h"
101 const int under_mencoder = 0;
102 int slave_mode=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 #include "mp_fifo.h"
269 // benchmark:
270 double video_time_usage=0;
271 double vout_time_usage=0;
272 static double audio_time_usage=0;
273 static int total_time_usage_start=0;
274 static int total_frame_cnt=0;
275 static int drop_frame_cnt=0; // total number of dropped frames
277 // options:
278 static int output_quality=0;
280 // seek:
281 static double seek_to_sec;
282 static off_t seek_to_byte=0;
283 static off_t step_sec=0;
285 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
287 // codecs:
288 char **audio_codec_list=NULL; // override audio codec
289 char **video_codec_list=NULL; // override video codec
290 char **audio_fm_list=NULL; // override audio codec family
291 char **video_fm_list=NULL; // override video codec family
293 // this dvdsub_id was selected via slang
294 // use this to allow dvdnav to follow -slang across stream resets,
295 // in particular the subtitle ID for a language changes
296 int dvdsub_lang_id;
297 int vobsub_id=-1;
298 static char* spudec_ifo=NULL;
299 int forced_subs_only=0;
300 int file_filter=1;
302 // cache2:
303 int stream_cache_size=-1;
305 // dump:
306 int stream_dump_type=0;
308 // A-V sync:
309 static float default_max_pts_correction=-1;//0.01f;
310 float audio_delay=0;
311 static int ignore_start=0;
313 double force_fps=0;
314 static int force_srate=0;
315 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
316 static int play_n_frames=-1;
317 static int play_n_frames_mf=-1;
319 // sub:
320 char *font_name=NULL;
321 char *sub_font_name=NULL;
322 extern int font_fontconfig;
323 float font_factor=0.75;
324 char **sub_name=NULL;
325 float sub_delay=0;
326 float sub_fps=0;
327 int sub_auto = 1;
328 char *vobsub_name=NULL;
329 int subcc_enabled=0;
330 int suboverlap_enabled = 1;
332 #include "ass_mp.h"
334 char* current_module=NULL; // for debugging
337 // ---
339 #ifdef CONFIG_MENU
340 #include "m_struct.h"
341 #include "libmenu/menu.h"
342 static const vf_info_t* const libmenu_vfs[] = {
343 &vf_info_menu,
344 NULL
346 static vf_instance_t* vf_menu = NULL;
347 int use_menu = 0;
348 static char* menu_cfg = NULL;
349 static char* menu_root = "main";
350 #endif
353 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
354 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
355 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
356 int use_filedir_conf;
357 int use_filename_title;
359 #include "mpcommon.h"
360 #include "command.h"
362 #include "metadata.h"
364 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
366 const void *mpctx_get_video_out(MPContext *mpctx)
368 return mpctx->video_out;
371 const void *mpctx_get_audio_out(MPContext *mpctx)
373 return mpctx->audio_out;
376 void *mpctx_get_demuxer(MPContext *mpctx)
378 return mpctx->demuxer;
381 void *mpctx_get_playtree_iter(MPContext *mpctx)
383 return mpctx->playtree_iter;
386 void *mpctx_get_mixer(MPContext *mpctx)
388 return &mpctx->mixer;
391 int mpctx_get_global_sub_size(MPContext *mpctx)
393 return mpctx->global_sub_size;
396 int mpctx_get_osd_function(MPContext *mpctx)
398 return mpctx->osd_function;
401 static float get_relative_time(struct MPContext *mpctx)
403 unsigned int new_time = GetTimer();
404 unsigned int delta = new_time - mpctx->last_time;
405 mpctx->last_time = new_time;
406 return delta * 0.000001;
409 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
410 switch (type)
412 /* check for valid video stream */
413 case META_VIDEO_CODEC:
414 case META_VIDEO_BITRATE:
415 case META_VIDEO_RESOLUTION:
417 if (!mpctx->sh_video)
418 return 0;
419 break;
422 /* check for valid audio stream */
423 case META_AUDIO_CODEC:
424 case META_AUDIO_BITRATE:
425 case META_AUDIO_SAMPLES:
427 if (!mpctx->sh_audio)
428 return 0;
429 break;
432 /* check for valid demuxer */
433 case META_INFO_TITLE:
434 case META_INFO_ARTIST:
435 case META_INFO_ALBUM:
436 case META_INFO_YEAR:
437 case META_INFO_COMMENT:
438 case META_INFO_TRACK:
439 case META_INFO_GENRE:
441 if (!mpctx->demuxer)
442 return 0;
443 break;
446 default:
447 break;
450 return 1;
453 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
454 char **info = mpctx->demuxer->info;
455 int n;
457 if (!info || !tag)
458 return NULL;
460 for (n = 0; info[2*n] != NULL ; n++)
461 if (!strcasecmp (info[2*n], tag))
462 break;
464 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
467 char *get_metadata(struct MPContext *mpctx, metadata_t type)
469 char *meta = NULL;
470 sh_audio_t * const sh_audio = mpctx->sh_audio;
471 sh_video_t * const sh_video = mpctx->sh_video;
473 if (!is_valid_metadata_type(mpctx, type))
474 return NULL;
476 switch (type)
478 case META_NAME:
480 return strdup (mp_basename2 (mpctx->filename));
483 case META_VIDEO_CODEC:
485 if (sh_video->format == 0x10000001)
486 meta = strdup ("mpeg1");
487 else if (sh_video->format == 0x10000002)
488 meta = strdup ("mpeg2");
489 else if (sh_video->format == 0x10000004)
490 meta = strdup ("mpeg4");
491 else if (sh_video->format == 0x10000005)
492 meta = strdup ("h264");
493 else if (sh_video->format >= 0x20202020)
495 meta = malloc (8);
496 sprintf (meta, "%.4s", (char *) &sh_video->format);
498 else
500 meta = malloc (8);
501 sprintf (meta, "0x%08X", sh_video->format);
503 return meta;
506 case META_VIDEO_BITRATE:
508 meta = malloc (16);
509 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
510 return meta;
513 case META_VIDEO_RESOLUTION:
515 meta = malloc (16);
516 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
517 return meta;
520 case META_AUDIO_CODEC:
522 if (sh_audio->codec && sh_audio->codec->name)
523 meta = strdup (sh_audio->codec->name);
524 return meta;
527 case META_AUDIO_BITRATE:
529 meta = malloc (16);
530 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
531 return meta;
534 case META_AUDIO_SAMPLES:
536 meta = malloc (16);
537 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
538 return meta;
541 /* check for valid demuxer */
542 case META_INFO_TITLE:
543 return get_demuxer_info(mpctx, "Title");
545 case META_INFO_ARTIST:
546 return get_demuxer_info(mpctx, "Artist");
548 case META_INFO_ALBUM:
549 return get_demuxer_info(mpctx, "Album");
551 case META_INFO_YEAR:
552 return get_demuxer_info(mpctx, "Year");
554 case META_INFO_COMMENT:
555 return get_demuxer_info(mpctx, "Comment");
557 case META_INFO_TRACK:
558 return get_demuxer_info(mpctx, "Track");
560 case META_INFO_GENRE:
561 return get_demuxer_info(mpctx, "Genre");
563 default:
564 break;
567 return meta;
570 static void print_file_properties(struct MPContext *mpctx, const char *filename)
572 double start_pts = MP_NOPTS_VALUE;
573 double video_start_pts = MP_NOPTS_VALUE;
574 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
575 filename_recode(filename));
576 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
577 if (mpctx->sh_video) {
578 /* Assume FOURCC if all bytes >= 0x20 (' ') */
579 if (mpctx->sh_video->format >= 0x20202020)
580 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
581 else
582 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
583 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
584 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
585 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
586 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
587 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
588 video_start_pts = ds_get_next_pts(mpctx->d_video);
590 if (mpctx->sh_audio) {
591 /* Assume FOURCC if all bytes >= 0x20 (' ') */
592 if (mpctx->sh_audio->format >= 0x20202020)
593 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
594 else
595 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
596 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
597 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
598 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
599 start_pts = ds_get_next_pts(mpctx->d_audio);
601 if (video_start_pts != MP_NOPTS_VALUE) {
602 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
603 (mpctx->sh_video && video_start_pts < start_pts))
604 start_pts = video_start_pts;
606 if (start_pts != MP_NOPTS_VALUE)
607 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
608 else
609 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
610 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
611 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
612 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
613 if (mpctx->demuxer) {
614 if (mpctx->demuxer->num_chapters == 0)
615 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
616 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
620 /// step size of mixer changes
621 int volstep = 3;
623 #ifdef CONFIG_DVDNAV
624 static void mp_dvdnav_context_free(MPContext *ctx){
625 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
626 ctx->nav_smpi = NULL;
627 free(ctx->nav_buffer);
628 ctx->nav_buffer = NULL;
629 ctx->nav_start = NULL;
630 ctx->nav_in_size = 0;
632 #endif
634 void uninit_player(struct MPContext *mpctx, unsigned int mask){
635 mask &= mpctx->initialized_flags;
637 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
639 if(mask&INITIALIZED_ACODEC){
640 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
641 current_module="uninit_acodec";
642 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
643 mpctx->sh_audio=NULL;
644 mpctx->mixer.afilter = NULL;
647 if(mask&INITIALIZED_VCODEC){
648 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
649 current_module="uninit_vcodec";
650 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
651 mpctx->sh_video=NULL;
652 #ifdef CONFIG_MENU
653 vf_menu=NULL;
654 #endif
657 if(mask&INITIALIZED_DEMUXER){
658 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
659 current_module="free_demuxer";
660 if (mpctx->num_sources) {
661 mpctx->demuxer = mpctx->sources[0].demuxer;
662 for (int i = 1; i < mpctx->num_sources; i++) {
663 free_stream(mpctx->sources[i].stream);
664 free_demuxer(mpctx->sources[i].demuxer);
667 talloc_free(mpctx->sources);
668 mpctx->sources = NULL;
669 mpctx->num_sources = 0;
670 talloc_free(mpctx->timeline);
671 mpctx->timeline = NULL;
672 mpctx->num_timeline_parts = 0;
673 talloc_free(mpctx->chapters);
674 mpctx->chapters = NULL;
675 mpctx->num_chapters = 0;
676 mpctx->video_offset = 0;
677 if(mpctx->demuxer){
678 mpctx->stream=mpctx->demuxer->stream;
679 free_demuxer(mpctx->demuxer);
681 mpctx->demuxer=NULL;
684 // kill the cache process:
685 if(mask&INITIALIZED_STREAM){
686 mpctx->initialized_flags&=~INITIALIZED_STREAM;
687 current_module="uninit_stream";
688 if(mpctx->stream) free_stream(mpctx->stream);
689 mpctx->stream=NULL;
692 if(mask&INITIALIZED_VO){
693 mpctx->initialized_flags&=~INITIALIZED_VO;
694 current_module="uninit_vo";
695 vo_destroy(mpctx->video_out);
696 mpctx->video_out=NULL;
697 #ifdef CONFIG_DVDNAV
698 mp_dvdnav_context_free(mpctx);
699 #endif
702 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
703 if(mask&INITIALIZED_GETCH2){
704 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
705 current_module="uninit_getch2";
706 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
707 // restore terminal:
708 getch2_disable();
711 if(mask&INITIALIZED_VOBSUB){
712 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
713 current_module="uninit_vobsub";
714 if(vo_vobsub) vobsub_close(vo_vobsub);
715 vo_vobsub=NULL;
718 if (mask&INITIALIZED_SPUDEC){
719 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
720 current_module="uninit_spudec";
721 spudec_free(vo_spudec);
722 vo_spudec=NULL;
725 if(mask&INITIALIZED_AO){
726 mpctx->initialized_flags&=~INITIALIZED_AO;
727 current_module="uninit_ao";
728 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
729 if (mpctx->audio_out)
730 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
731 mpctx->audio_out=NULL;
734 current_module=NULL;
737 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
739 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
740 uninit_player(mpctx, INITIALIZED_ALL);
741 #if defined(__MINGW32__) || defined(__CYGWIN__)
742 timeEndPeriod(1);
743 #endif
744 #ifdef CONFIG_X11
745 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
746 #endif
748 current_module="uninit_input";
749 mp_input_uninit(mpctx->input);
750 #ifdef CONFIG_MENU
751 if (use_menu)
752 menu_uninit();
753 #endif
755 #ifdef CONFIG_FREETYPE
756 current_module="uninit_font";
757 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
758 free_font_desc(mpctx->osd->sub_font);
759 free_font_desc(vo_font);
760 vo_font = NULL;
761 done_freetype();
762 #endif
763 osd_free(mpctx->osd);
765 #ifdef CONFIG_ASS
766 ass_library_done(ass_library);
767 ass_library = NULL;
768 #endif
770 current_module="exit_player";
772 // free mplayer config
773 if(mpctx->mconfig)
774 m_config_free(mpctx->mconfig);
775 mpctx->mconfig = NULL;
777 if(mpctx->playtree_iter)
778 play_tree_iter_free(mpctx->playtree_iter);
779 mpctx->playtree_iter = NULL;
780 if(mpctx->playtree)
781 play_tree_free(mpctx->playtree, 1);
782 mpctx->playtree = NULL;
784 talloc_free(mpctx->key_fifo);
786 free(edl_records); // free mem allocated for EDL
787 edl_records = NULL;
788 switch(how) {
789 case EXIT_QUIT:
790 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
791 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
792 break;
793 case EXIT_EOF:
794 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
795 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
796 break;
797 case EXIT_ERROR:
798 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
799 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
800 break;
801 default:
802 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
804 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
806 exit(rc);
809 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
811 exit_player_with_rc(mpctx, how, 1);
814 #ifndef __MINGW32__
815 static void child_sighandler(int x){
816 pid_t pid;
817 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
819 #endif
821 #ifdef CONFIG_CRASH_DEBUG
822 static char *prog_path;
823 static int crash_debug = 0;
824 #endif
826 static void exit_sighandler(int x){
827 static int sig_count=0;
828 #ifdef CONFIG_CRASH_DEBUG
829 if (!crash_debug || x != SIGTRAP)
830 #endif
831 ++sig_count;
832 if(sig_count==5)
834 /* We're crashing bad and can't uninit cleanly :(
835 * by popular request, we make one last (dirty)
836 * effort to restore the user's
837 * terminal. */
838 getch2_disable();
839 exit(1);
841 if(sig_count==6) exit(1);
842 if(sig_count>6){
843 // can't stop :(
844 #ifndef __MINGW32__
845 kill(getpid(),SIGKILL);
846 #endif
848 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
849 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
850 "\nMPlayer interrupted by signal %d in module: %s\n", x,
851 current_module ? current_module : "unknown");
852 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
853 if(sig_count<=1)
854 switch(x){
855 case SIGINT:
856 case SIGPIPE:
857 case SIGQUIT:
858 case SIGTERM:
859 case SIGKILL:
860 async_quit_request = 1;
861 return; // killed from keyboard (^C) or killed [-9]
862 case SIGILL:
863 #if CONFIG_RUNTIME_CPUDETECT
864 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
865 #else
866 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
867 #endif
868 case SIGFPE:
869 case SIGSEGV:
870 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
871 default:
872 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
873 #ifdef CONFIG_CRASH_DEBUG
874 if (crash_debug) {
875 int gdb_pid;
876 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
877 gdb_pid = fork();
878 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
879 if (gdb_pid == 0) { // We are the child
880 char spid[20];
881 snprintf(spid, sizeof(spid), "%i", getppid());
882 getch2_disable(); // allow terminal to work properly with gdb
883 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
884 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
885 } else if (gdb_pid < 0)
886 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
887 else {
888 waitpid(gdb_pid, NULL, 0);
890 if (x == SIGTRAP) return;
892 #endif
894 getch2_disable();
895 exit(1);
898 #include "cfg-mplayer.h"
900 static int cfg_include(m_option_t *conf, char *filename)
902 return m_config_parse_config_file(conf->priv, filename);
905 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
907 char *conffile;
908 int conffile_fd;
909 if (!disable_system_conf &&
910 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
911 exit_player(mpctx, EXIT_NONE);
912 if ((conffile = get_path("")) == NULL) {
913 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
914 } else {
915 #ifdef __MINGW32__
916 mkdir(conffile);
917 #else
918 mkdir(conffile, 0777);
919 #endif
920 free(conffile);
921 if ((conffile = get_path("config")) == NULL) {
922 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
923 } else {
924 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
925 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
926 write(conffile_fd, default_config, strlen(default_config));
927 close(conffile_fd);
929 if (!disable_user_conf &&
930 m_config_parse_config_file(conf, conffile) < 0)
931 exit_player(mpctx, EXIT_NONE);
932 free(conffile);
937 #define PROFILE_CFG_PROTOCOL "protocol."
939 static void load_per_protocol_config (m_config_t* conf, const char *const file)
941 char *str;
942 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
943 m_profile_t *p;
945 /* does filename actually uses a protocol ? */
946 str = strstr (file, "://");
947 if (!str)
948 return;
950 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
951 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
952 p = m_config_get_profile (conf, protocol);
953 if (p)
955 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
956 m_config_set_profile(conf,p);
960 #define PROFILE_CFG_EXTENSION "extension."
962 static void load_per_extension_config (m_config_t* conf, const char *const file)
964 char *str;
965 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
966 m_profile_t *p;
968 /* does filename actually have an extension ? */
969 str = strrchr (file, '.');
970 if (!str)
971 return;
973 sprintf (extension, PROFILE_CFG_EXTENSION);
974 strncat (extension, ++str, 7);
975 p = m_config_get_profile (conf, extension);
976 if (p)
978 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
979 m_config_set_profile(conf,p);
983 #define PROFILE_CFG_VO "vo."
984 #define PROFILE_CFG_AO "ao."
986 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
988 char profile[strlen (cfg) + strlen (out) + 1];
989 m_profile_t *p;
991 sprintf (profile, "%s%s", cfg, out);
992 p = m_config_get_profile (conf, profile);
993 if (p)
995 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
996 m_config_set_profile(conf,p);
1001 * Tries to load a config file
1002 * @return 0 if file was not found, 1 otherwise
1004 static int try_load_config(m_config_t *conf, const char *file)
1006 struct stat st;
1007 if (stat(file, &st))
1008 return 0;
1009 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1010 m_config_parse_config_file (conf, file);
1011 return 1;
1014 static void load_per_file_config (m_config_t* conf, const char *const file)
1016 char *confpath;
1017 char cfg[PATH_MAX];
1018 char *name;
1020 if (strlen(file) > PATH_MAX - 14) {
1021 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1022 return;
1024 sprintf (cfg, "%s.conf", file);
1026 name = strrchr(cfg, '/');
1027 if (HAVE_DOS_PATHS) {
1028 char *tmp = strrchr(cfg, '\\');
1029 if (!name || tmp > name)
1030 name = tmp;
1031 tmp = strrchr(cfg, ':');
1032 if (!name || tmp > name)
1033 name = tmp;
1035 if (!name)
1036 name = cfg;
1037 else
1038 name++;
1040 if (use_filedir_conf) {
1041 char dircfg[PATH_MAX];
1042 strcpy(dircfg, cfg);
1043 strcpy(dircfg + (name - cfg), "mplayer.conf");
1044 try_load_config(conf, dircfg);
1046 if (try_load_config(conf, cfg))
1047 return;
1050 if ((confpath = get_path (name)) != NULL)
1052 try_load_config(conf, confpath);
1054 free (confpath);
1058 /* When libmpdemux performs a blocking operation (network connection or
1059 * cache filling) if the operation fails we use this function to check
1060 * if it was interrupted by the user.
1061 * The function returns a new value for eof. */
1062 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1064 mp_cmd_t* cmd;
1065 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1066 switch(cmd->id) {
1067 case MP_CMD_QUIT:
1068 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1069 case MP_CMD_PLAY_TREE_STEP: {
1070 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1071 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1072 } break;
1073 case MP_CMD_PLAY_TREE_UP_STEP: {
1074 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1075 } break;
1076 case MP_CMD_PLAY_ALT_SRC_STEP: {
1077 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1078 } break;
1080 mp_cmd_free(cmd);
1082 return stop_play;
1085 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1087 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1089 play_tree_add_bpf(entry,mpctx->filename);
1092 if(!entry) {
1093 entry = mpctx->playtree_iter->tree;
1094 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1095 return PT_NEXT_ENTRY;
1097 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1098 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1099 return PT_NEXT_ENTRY;
1102 play_tree_remove(entry,1,1);
1103 return PT_NEXT_SRC;
1105 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1106 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1107 entry = mpctx->playtree_iter->tree;
1108 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1109 return PT_NEXT_ENTRY;
1111 play_tree_remove(entry,1,1);
1113 return PT_NEXT_SRC;
1116 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1118 struct MPOpts *opts = &mpctx->opts;
1119 sub_data *subd = NULL;
1120 struct ass_track *asst = NULL;
1122 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1123 return;
1126 #ifdef CONFIG_ASS
1127 if (opts->ass_enabled) {
1128 #ifdef CONFIG_ICONV
1129 asst = ass_read_stream(ass_library, filename, sub_cp);
1130 #else
1131 asst = ass_read_stream(ass_library, filename, 0);
1132 #endif
1133 if (!asst) {
1134 subd = sub_read_file(filename, fps);
1135 if (subd) {
1136 asst = ass_read_subdata(ass_library, subd, fps);
1137 if (asst) {
1138 sub_free(subd);
1139 subd = NULL;
1143 } else
1144 #endif
1145 subd = sub_read_file(filename, fps);
1148 if (!asst && !subd) {
1149 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1150 "Cannot load subtitles: %s\n", filename_recode(filename));
1151 return;
1154 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1155 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1156 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1157 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1158 filename_recode(filename));
1159 ++mpctx->set_of_sub_size;
1160 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1161 filename_recode(filename));
1164 void init_vo_spudec(struct MPContext *mpctx)
1166 spudec_free(vo_spudec);
1167 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1168 vo_spudec = NULL;
1170 // we currently can't work without video stream
1171 if (!mpctx->sh_video)
1172 return;
1174 if (spudec_ifo) {
1175 unsigned int palette[16], width, height;
1176 current_module="spudec_init_vobsub";
1177 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1178 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1181 #ifdef CONFIG_DVDREAD
1182 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1183 current_module="spudec_init_dvdread";
1184 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1185 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1186 NULL, 0);
1188 #endif
1190 #ifdef CONFIG_DVDNAV
1191 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1192 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1193 current_module="spudec_init_dvdnav";
1194 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1196 #endif
1198 if (vo_spudec==NULL) {
1199 sh_sub_t *sh = mpctx->d_sub->sh;
1200 current_module="spudec_init_normal";
1201 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1202 spudec_set_font_factor(vo_spudec,font_factor);
1205 if (vo_spudec!=NULL) {
1206 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1207 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1212 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1213 * make it all work is to use the builtin SDL-bootstrap code, which
1214 * will be done automatically by replacing our main() if we include SDL.h.
1216 #if defined(__APPLE__) && defined(CONFIG_SDL)
1217 #ifdef CONFIG_SDL_SDL_H
1218 #include <SDL/SDL.h>
1219 #else
1220 #include <SDL.h>
1221 #endif
1222 #endif
1225 * \brief append a formatted string
1226 * \param buf buffer to print into
1227 * \param pos position of terminating 0 in buf
1228 * \param len maximum number of characters in buf, not including terminating 0
1229 * \param format printf format string
1231 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1233 va_list va;
1234 va_start(va, format);
1235 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1236 va_end(va);
1237 if (*pos >= len ) {
1238 buf[len] = 0;
1239 *pos = len;
1244 * \brief append time in the hh:mm:ss.f format
1245 * \param buf buffer to print into
1246 * \param pos position of terminating 0 in buf
1247 * \param len maximum number of characters in buf, not including terminating 0
1248 * \param time time value to convert/append
1250 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1251 int64_t tenths = 10 * time;
1252 int f1 = tenths % 10;
1253 int ss = (tenths / 10) % 60;
1254 int mm = (tenths / 600) % 60;
1255 int hh = tenths / 36000;
1256 if (time <= 0) {
1257 saddf(buf, pos, len, "unknown");
1258 return;
1260 if (hh > 0)
1261 saddf(buf, pos, len, "%2d:", hh);
1262 if (hh > 0 || mm > 0)
1263 saddf(buf, pos, len, "%02d:", mm);
1264 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1267 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1269 struct MPOpts *opts = &mpctx->opts;
1270 sh_video_t * const sh_video = mpctx->sh_video;
1272 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1273 a_pos = playing_audio_pts(mpctx);
1274 if (mpctx->sh_audio && sh_video && at_frame) {
1275 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1276 if (mpctx->time_frame > 0)
1277 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1278 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1279 && !mpctx->drop_message_shown) {
1280 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1281 mpctx->drop_message_shown = true;
1284 if (opts->quiet)
1285 return;
1288 int width;
1289 char *line;
1290 unsigned pos = 0;
1291 get_screen_size();
1292 if (screen_width > 0)
1293 width = screen_width;
1294 else
1295 width = 80;
1296 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1297 /* Windows command line is broken (MinGW's rxvt works, but we
1298 * should not depend on that). */
1299 width--;
1300 #endif
1301 line = malloc(width + 1); // one additional char for the terminating null
1303 // Audio time
1304 if (mpctx->sh_audio) {
1305 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1306 if (!sh_video) {
1307 float len = get_time_length(mpctx);
1308 saddf(line, &pos, width, "(");
1309 sadd_hhmmssf(line, &pos, width, a_pos);
1310 saddf(line, &pos, width, ") of %.1f (", len);
1311 sadd_hhmmssf(line, &pos, width, len);
1312 saddf(line, &pos, width, ") ");
1316 // Video time
1317 if (sh_video)
1318 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1320 // A-V sync
1321 if (mpctx->sh_audio && sh_video)
1322 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1323 mpctx->last_av_difference, mpctx->total_avsync_change);
1325 // Video stats
1326 if (sh_video)
1327 saddf(line, &pos, width, "%3d/%3d ",
1328 (int)sh_video->num_frames,
1329 (int)sh_video->num_frames_decoded);
1331 // CPU usage
1332 if (sh_video) {
1333 if (sh_video->timer > 0.5)
1334 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1335 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1336 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1337 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1338 else
1339 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1340 } else if (mpctx->sh_audio) {
1341 if (mpctx->delay > 0.5)
1342 saddf(line, &pos, width, "%4.1f%% ",
1343 100.0*audio_time_usage/(double)mpctx->delay);
1344 else
1345 saddf(line, &pos, width, "??,?%% ");
1348 // VO stats
1349 if (sh_video)
1350 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1352 #ifdef CONFIG_STREAM_CACHE
1353 // cache stats
1354 if (stream_cache_size > 0)
1355 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1356 #endif
1358 // other
1359 if (opts->playback_speed != 1)
1360 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1362 // end
1363 if (erase_to_end_of_line) {
1364 line[pos] = 0;
1365 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1366 } else {
1367 memset(&line[pos], ' ', width - pos);
1368 line[width] = 0;
1369 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1371 free(line);
1375 * \brief build a chain of audio filters that converts the input format
1376 * to the ao's format, taking into account the current playback_speed.
1377 * \param sh_audio describes the requested input format of the chain.
1378 * \param ao_data describes the requested output format of the chain.
1380 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1382 struct MPOpts *opts = &mpctx->opts;
1383 int new_srate;
1384 int result;
1385 if (!sh_audio)
1387 mpctx->mixer.afilter = NULL;
1388 return 0;
1390 if(af_control_any_rev(sh_audio->afilter,
1391 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1392 &opts->playback_speed)) {
1393 new_srate = sh_audio->samplerate;
1394 } else {
1395 new_srate = sh_audio->samplerate * opts->playback_speed;
1396 if (new_srate != ao_data->samplerate) {
1397 // limits are taken from libaf/af_resample.c
1398 if (new_srate < 8000)
1399 new_srate = 8000;
1400 if (new_srate > 192000)
1401 new_srate = 192000;
1402 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1405 result = init_audio_filters(sh_audio, new_srate,
1406 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1407 mpctx->mixer.afilter = sh_audio->afilter;
1408 return result;
1412 typedef struct mp_osd_msg mp_osd_msg_t;
1413 struct mp_osd_msg {
1414 /// Previous message on the stack.
1415 mp_osd_msg_t* prev;
1416 /// Message text.
1417 char msg[128];
1418 int id,level,started;
1419 /// Display duration in ms.
1420 unsigned time;
1423 /// OSD message stack.
1424 static mp_osd_msg_t* osd_msg_stack = NULL;
1427 * \brief Add a message on the OSD message stack
1429 * If a message with the same id is already present in the stack
1430 * it is pulled on top of the stack, otherwise a new message is created.
1433 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1434 va_list ap)
1436 mp_osd_msg_t *msg,*last=NULL;
1437 int r;
1439 // look if the id is already in the stack
1440 for(msg = osd_msg_stack ; msg && msg->id != id ;
1441 last = msg, msg = msg->prev);
1442 // not found: alloc it
1443 if(!msg) {
1444 msg = calloc(1,sizeof(mp_osd_msg_t));
1445 msg->prev = osd_msg_stack;
1446 osd_msg_stack = msg;
1447 } else if(last) { // found, but it's not on top of the stack
1448 last->prev = msg->prev;
1449 msg->prev = osd_msg_stack;
1450 osd_msg_stack = msg;
1452 // write the msg
1453 r = vsnprintf(msg->msg, 128, fmt, ap);
1454 if(r >= 128) msg->msg[127] = 0;
1455 // set id and time
1456 msg->id = id;
1457 msg->level = level;
1458 msg->time = time;
1462 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1464 va_list ap;
1465 va_start(ap, fmt);
1466 set_osd_msg_va(id, level, time, fmt, ap);
1467 va_end(ap);
1470 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1472 va_list ap;
1473 va_start(ap, fmt);
1474 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1475 va_end(ap);
1480 * \brief Remove a message from the OSD stack
1482 * This function can be used to get rid of a message right away.
1486 void rm_osd_msg(int id) {
1487 mp_osd_msg_t *msg,*last=NULL;
1489 // Search for the msg
1490 for(msg = osd_msg_stack ; msg && msg->id != id ;
1491 last = msg, msg = msg->prev);
1492 if(!msg) return;
1494 // Detach it from the stack and free it
1495 if(last)
1496 last->prev = msg->prev;
1497 else
1498 osd_msg_stack = msg->prev;
1499 free(msg);
1503 * \brief Remove all messages from the OSD stack
1507 static void clear_osd_msgs(void) {
1508 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1509 while(msg) {
1510 prev = msg->prev;
1511 free(msg);
1512 msg = prev;
1514 osd_msg_stack = NULL;
1518 * \brief Get the current message from the OSD stack.
1520 * This function decrements the message timer and destroys the old ones.
1521 * The message that should be displayed is returned (if any).
1525 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1527 struct MPOpts *opts = &mpctx->opts;
1528 mp_osd_msg_t *msg,*prev,*last = NULL;
1529 static unsigned last_update = 0;
1530 unsigned now = GetTimerMS();
1531 unsigned diff;
1532 char hidden_dec_done = 0;
1534 if (mpctx->osd_visible) {
1535 // 36000000 means max timed visibility is 1 hour into the future, if
1536 // the difference is greater assume it's wrapped around from below 0
1537 if (mpctx->osd_visible - now > 36000000) {
1538 mpctx->osd_visible = 0;
1539 vo_osd_progbar_type = -1; // disable
1540 vo_osd_changed(OSDTYPE_PROGBAR);
1541 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1544 if (mpctx->osd_show_percentage_until - now > 36000000)
1545 mpctx->osd_show_percentage_until = 0;
1547 if(!last_update) last_update = now;
1548 diff = now >= last_update ? now - last_update : 0;
1550 last_update = now;
1552 // Look for the first message in the stack with high enough level.
1553 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1554 prev = msg->prev;
1555 if (msg->level > opts->osd_level && hidden_dec_done)
1556 continue;
1557 // The message has a high enough level or it is the first hidden one
1558 // in both cases we decrement the timer or kill it.
1559 if(!msg->started || msg->time > diff) {
1560 if(msg->started) msg->time -= diff;
1561 else msg->started = 1;
1562 // display it
1563 if (msg->level <= opts->osd_level)
1564 return msg;
1565 hidden_dec_done = 1;
1566 continue;
1568 // kill the message
1569 free(msg);
1570 if(last) {
1571 last->prev = prev;
1572 msg = last;
1573 } else {
1574 osd_msg_stack = prev;
1575 msg = NULL;
1578 // Nothing found
1579 return NULL;
1583 * \brief Display the OSD bar.
1585 * Display the OSD bar or fall back on a simple message.
1589 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1590 struct MPOpts *opts = &mpctx->opts;
1591 if (opts->osd_level < 1)
1592 return;
1594 if(mpctx->sh_video) {
1595 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1596 vo_osd_progbar_type = type;
1597 vo_osd_progbar_value = 256*(val-min)/(max-min);
1598 vo_osd_changed(OSDTYPE_PROGBAR);
1599 return;
1602 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1603 name, ROUND(100*(val-min)/(max-min)));
1607 * \brief Display text subtitles on the OSD
1609 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1611 int i;
1612 vo_sub = subs;
1613 vo_osd_changed(OSDTYPE_SUBTITLE);
1614 if (!mpctx->sh_video) {
1615 // reverse order, since newest set_osd_msg is displayed first
1616 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1617 if (!subs || i >= subs->lines || !subs->text[i])
1618 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1619 else {
1620 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1621 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1622 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1629 * \brief Update the OSD message line.
1631 * This function displays the current message on the vo OSD or on the term.
1632 * If the stack is empty and the OSD level is high enough the timer
1633 * is displayed (only on the vo OSD).
1637 static void update_osd_msg(struct MPContext *mpctx)
1639 struct MPOpts *opts = &mpctx->opts;
1640 mp_osd_msg_t *msg;
1641 struct osd_state *osd = mpctx->osd;
1642 char osd_text_timer[128];
1644 if (mpctx->add_osd_seek_info) {
1645 double percentage = get_percent_pos(mpctx);
1646 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1647 if (mpctx->sh_video)
1648 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1649 mpctx->add_osd_seek_info = false;
1652 // Look if we have a msg
1653 if((msg = get_osd_msg(mpctx))) {
1654 if (strcmp(osd->osd_text, msg->msg)) {
1655 strncpy(osd->osd_text, msg->msg, 127);
1656 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1657 if(opts->term_osd)
1658 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1659 msg->msg);
1661 return;
1664 if(mpctx->sh_video) {
1665 // fallback on the timer
1666 if (opts->osd_level >= 2) {
1667 int len = get_time_length(mpctx);
1668 int percentage = -1;
1669 char percentage_text[10];
1670 int pts = get_current_time(mpctx);
1672 if (mpctx->osd_show_percentage_until)
1673 percentage = get_percent_pos(mpctx);
1675 if (percentage >= 0)
1676 snprintf(percentage_text, 9, " (%d%%)", percentage);
1677 else
1678 percentage_text[0] = 0;
1680 if (opts->osd_level == 3)
1681 snprintf(osd_text_timer, 63,
1682 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1683 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1684 len/3600,(len/60)%60,len%60,percentage_text);
1685 else
1686 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1687 mpctx->osd_function,pts/3600,(pts/60)%60,
1688 pts%60,percentage_text);
1689 } else
1690 osd_text_timer[0]=0;
1692 if (strcmp(osd->osd_text, osd_text_timer)) {
1693 strncpy(osd->osd_text, osd_text_timer, 63);
1694 vo_osd_changed(OSDTYPE_OSD);
1696 return;
1699 // Clear the term osd line
1700 if (opts->term_osd && osd->osd_text[0]) {
1701 osd->osd_text[0] = 0;
1702 printf("%s\n", opts->term_osd_esc);
1706 ///@}
1707 // OSDMsgStack
1710 void reinit_audio_chain(struct MPContext *mpctx)
1712 struct MPOpts *opts = &mpctx->opts;
1713 if (!mpctx->sh_audio)
1714 return;
1715 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1716 current_module="init_audio_codec";
1717 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1718 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1719 goto init_error;
1721 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1722 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1726 current_module="af_preinit";
1727 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1728 ao_data.samplerate=force_srate;
1729 ao_data.channels=0;
1730 ao_data.format = opts->audio_output_format;
1732 // first init to detect best values
1733 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1734 // input:
1735 mpctx->sh_audio->samplerate,
1736 // output:
1737 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1738 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1739 "pre-init!\n");
1740 exit_player(mpctx, EXIT_ERROR);
1742 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1743 current_module="ao2_init";
1744 ao_data.buffersize = opts->ao_buffersize;
1745 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1746 0, // plugin flag
1747 ao_data.samplerate,
1748 ao_data.channels,
1749 ao_data.format, 0);
1750 if(!mpctx->audio_out){
1751 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1752 goto init_error;
1754 mpctx->initialized_flags|=INITIALIZED_AO;
1755 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1756 mpctx->audio_out->info->short_name,
1757 ao_data.samplerate, ao_data.channels,
1758 af_fmt2str_short(ao_data.format),
1759 af_fmt2bits(ao_data.format)/8 );
1760 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1761 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1762 if(strlen(mpctx->audio_out->info->comment) > 0)
1763 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1766 // init audio filters:
1767 current_module="af_init";
1768 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1769 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1770 goto init_error;
1772 mpctx->mixer.audio_out = mpctx->audio_out;
1773 mpctx->mixer.volstep = volstep;
1774 mpctx->syncing_audio = true;
1775 return;
1777 init_error:
1778 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1779 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1780 mpctx->d_audio->id = -2;
1784 ///@}
1785 // Command2Property
1788 // Return pts value corresponding to the end point of audio written to the
1789 // ao so far.
1790 static double written_audio_pts(struct MPContext *mpctx)
1792 sh_audio_t *sh_audio = mpctx->sh_audio;
1793 demux_stream_t *d_audio = mpctx->d_audio;
1794 double buffered_output;
1795 // first calculate the end pts of audio that has been output by decoder
1796 double a_pts = sh_audio->pts;
1797 if (a_pts != MP_NOPTS_VALUE)
1798 // Good, decoder supports new way of calculating audio pts.
1799 // sh_audio->pts is the timestamp of the latest input packet with
1800 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1801 // the amount of bytes the decoder has written after that timestamp.
1802 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1803 else {
1804 // Decoder doesn't support new way of calculating pts (or we're
1805 // being called before it has decoded anything with known timestamp).
1806 // Use the old method of audio pts calculation: take the timestamp
1807 // of last packet with known pts the decoder has read data from,
1808 // and add amount of bytes read after the beginning of that packet
1809 // divided by input bps. This will be inaccurate if the input/output
1810 // ratio is not constant for every audio packet or if it is constant
1811 // but not accurately known in sh_audio->i_bps.
1813 a_pts = d_audio->pts;
1814 // ds_tell_pts returns bytes read after last timestamp from
1815 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1816 // it has read but not decoded
1817 if (sh_audio->i_bps)
1818 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1819 (double)sh_audio->i_bps;
1821 // Now a_pts hopefully holds the pts for end of audio from decoder.
1822 // Substract data in buffers between decoder and audio out.
1824 // Decoded but not filtered
1825 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1827 // Data buffered in audio filters, measured in bytes of "missing" output
1828 buffered_output = af_calc_delay(sh_audio->afilter);
1830 // Data that was ready for ao but was buffered because ao didn't fully
1831 // accept everything to internal buffers yet
1832 buffered_output += sh_audio->a_out_buffer_len;
1834 // Filters divide audio length by playback_speed, so multiply by it
1835 // to get the length in original units without speedup or slowdown
1836 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1838 return a_pts + mpctx->video_offset;
1841 // Return pts value corresponding to currently playing audio.
1842 double playing_audio_pts(struct MPContext *mpctx)
1844 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1845 mpctx->audio_out->get_delay();
1848 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1849 struct MPOpts *opts = &mpctx->opts;
1850 // check for frame-drop:
1851 current_module = "check_framedrop";
1852 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1853 static int dropped_frames;
1854 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1855 float d = delay-mpctx->delay;
1856 ++total_frame_cnt;
1857 // we should avoid dropping too many frames in sequence unless we
1858 // are too late. and we allow 100ms A-V delay here:
1859 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1860 && !mpctx->restart_playback) {
1861 ++drop_frame_cnt;
1862 ++dropped_frames;
1863 return frame_dropping;
1864 } else
1865 dropped_frames = 0;
1867 return 0;
1871 #ifdef HAVE_RTC
1872 int rtc_fd = -1;
1873 #endif
1875 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1877 #ifdef HAVE_RTC
1878 if (rtc_fd >= 0){
1879 // -------- RTC -----------
1880 current_module="sleep_rtc";
1881 while (time_frame > 0.000) {
1882 unsigned long rtc_ts;
1883 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1884 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1885 time_frame -= get_relative_time(mpctx);
1887 } else
1888 #endif
1890 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1891 // unnecessarily high CPU usage
1892 struct MPOpts *opts = &mpctx->opts;
1893 float margin = opts->softsleep ? 0.011 : 0;
1894 current_module = "sleep_timer";
1895 while (time_frame > margin) {
1896 usec_sleep(1000000 * (time_frame - margin));
1897 time_frame -= get_relative_time(mpctx);
1899 if (opts->softsleep){
1900 current_module = "sleep_soft";
1901 if (time_frame < 0)
1902 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1903 while (time_frame > 0)
1904 time_frame -= get_relative_time(mpctx); // burn the CPU
1907 return time_frame;
1910 static int select_subtitle(MPContext *mpctx)
1912 struct MPOpts *opts = &mpctx->opts;
1913 // find the best sub to use
1914 int id;
1915 int found = 0;
1916 mpctx->global_sub_pos = -1; // no subs by default
1917 if (vobsub_id >= 0) {
1918 // if user asks for a vobsub id, use that first.
1919 id = vobsub_id;
1920 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1923 if (!found && opts->sub_id >= 0) {
1924 // if user asks for a dvd sub id, use that next.
1925 id = opts->sub_id;
1926 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1929 if (!found) {
1930 // if there are text subs to use, use those. (autosubs come last here)
1931 id = 0;
1932 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1935 if (!found && opts->sub_id == -1) {
1936 // finally select subs by language and container hints
1937 if (opts->sub_id == -1)
1938 opts->sub_id =
1939 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
1940 opts->sub_lang);
1941 if (opts->sub_id >= 0) {
1942 id = opts->sub_id;
1943 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1946 return found;
1949 #ifdef CONFIG_DVDNAV
1950 #ifndef FF_B_TYPE
1951 #define FF_B_TYPE 3
1952 #endif
1953 /// store decoded video image
1954 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1955 mp_image_t *from_mpi) {
1956 mp_image_t *mpi;
1958 /// Do not store B-frames
1959 if (from_mpi->pict_type == FF_B_TYPE)
1960 return to_mpi;
1962 if (to_mpi &&
1963 to_mpi->w == from_mpi->w &&
1964 to_mpi->h == from_mpi->h &&
1965 to_mpi->imgfmt == from_mpi->imgfmt)
1966 mpi = to_mpi;
1967 else {
1968 if (to_mpi)
1969 free_mp_image(to_mpi);
1970 if (from_mpi->w == 0 || from_mpi->h == 0)
1971 return NULL;
1972 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1975 copy_mpi(mpi,from_mpi);
1976 return mpi;
1979 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1980 struct MPOpts *opts = &ctx->opts;
1981 if (ctx->sh_video) {
1982 /// clear video pts
1983 ctx->d_video->pts = 0.0f;
1984 ctx->sh_video->pts = 0.0f;
1985 ctx->sh_video->i_pts = 0.0f;
1986 ctx->sh_video->last_pts = 0.0f;
1987 ctx->sh_video->num_buffered_pts = 0;
1988 ctx->sh_video->num_frames = 0;
1989 ctx->sh_video->num_frames_decoded = 0;
1990 ctx->sh_video->timer = 0.0f;
1991 ctx->sh_video->stream_delay = 0.0f;
1992 ctx->sh_video->timer = 0;
1993 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1996 if (ctx->sh_audio) {
1997 /// free audio packets and reset
1998 ds_free_packs(ctx->d_audio);
1999 audio_delay -= ctx->sh_audio->stream_delay;
2000 ctx->delay =- audio_delay;
2001 ctx->audio_out->reset();
2002 resync_audio_stream(ctx->sh_audio);
2005 audio_delay = 0.0f;
2006 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2007 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2008 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2009 if (dvdsub_lang_id != opts->sub_id) {
2010 opts->sub_id = dvdsub_lang_id;
2011 select_subtitle(ctx);
2015 /// clear all EOF related flags
2016 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2019 /// Restore last decoded DVDNAV (still frame)
2020 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2021 int *in_size,
2022 unsigned char **start,
2023 mp_image_t *decoded_frame)
2025 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2026 return decoded_frame;
2028 /// a change occured in dvdnav stream
2029 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2030 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2031 mp_dvdnav_context_free(mpctx);
2032 mp_dvdnav_reset_stream(mpctx);
2033 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2034 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2037 if (*in_size < 0) {
2038 float len;
2040 /// Display still frame, if any
2041 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2042 decoded_frame = mpctx->nav_smpi;
2044 /// increment video frame : continue playing after still frame
2045 len = get_time_length(mpctx);
2046 if (mpctx->sh_video->pts >= len &&
2047 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2048 mp_dvdnav_skip_still(mpctx->stream);
2049 mp_dvdnav_skip_wait(mpctx->stream);
2051 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2053 if (mpctx->nav_buffer) {
2054 *start = mpctx->nav_start;
2055 *in_size = mpctx->nav_in_size;
2056 if (mpctx->nav_start)
2057 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2061 return decoded_frame;
2064 /// Save last decoded DVDNAV (still frame)
2065 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2066 unsigned char *start,
2067 mp_image_t *decoded_frame)
2069 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2070 return;
2072 free(mpctx->nav_buffer);
2074 mpctx->nav_buffer = malloc(in_size);
2075 mpctx->nav_start = start;
2076 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2077 if (mpctx->nav_buffer)
2078 memcpy(mpctx->nav_buffer,start,in_size);
2080 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2081 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2083 #endif /* CONFIG_DVDNAV */
2085 /* Modify video timing to match the audio timeline. There are two main
2086 * reasons this is needed. First, video and audio can start from different
2087 * positions at beginning of file or after a seek (MPlayer starts both
2088 * immediately even if they have different pts). Second, the file can have
2089 * audio timestamps that are inconsistent with the duration of the audio
2090 * packets, for example two consecutive timestamp values differing by
2091 * one second but only a packet with enough samples for half a second
2092 * of playback between them.
2094 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2096 current_module = "av_sync";
2098 if (!mpctx->sh_audio || mpctx->syncing_audio)
2099 return;
2101 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2102 double v_pts = mpctx->sh_video->pts;
2103 double av_delay = a_pts - v_pts;
2104 // Try to sync vo_flip() so it will *finish* at given time
2105 av_delay += mpctx->last_vo_flip_duration;
2106 av_delay -= audio_delay; // This much pts difference is desired
2108 double change = av_delay * 0.1;
2109 double max_change = default_max_pts_correction >= 0 ?
2110 default_max_pts_correction : frame_time * 0.1;
2111 if (change < -max_change)
2112 change = -max_change;
2113 else if (change > max_change)
2114 change = max_change;
2115 mpctx->delay += change;
2116 mpctx->total_avsync_change += change;
2119 #define ASYNC_PLAY_DONE -3
2120 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2122 struct MPOpts *opts = &mpctx->opts;
2123 sh_audio_t * const sh_audio = mpctx->sh_audio;
2124 int res;
2126 // Timing info may not be set without
2127 res = decode_audio(sh_audio, 1);
2128 if (res < 0)
2129 return res;
2131 int bytes;
2132 bool did_retry = false;
2133 while (1) {
2134 double written_pts = written_audio_pts(mpctx);
2135 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2136 - audio_delay;
2137 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2138 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2140 // ogg demuxers give packets without timing
2141 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2142 if (!did_retry) {
2143 // Try to read more data to see packets that have pts
2144 int res = decode_audio(sh_audio, ao_data.bps);
2145 if (res < 0)
2146 return res;
2147 did_retry = true;
2148 continue;
2150 bytes = 0;
2153 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2154 bytes = 0;
2156 if (bytes > 0)
2157 break;
2159 mpctx->syncing_audio = false;
2160 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2161 int res = decode_audio(sh_audio, a);
2162 bytes += sh_audio->a_out_buffer_len;
2163 if (bytes >= 0) {
2164 memmove(sh_audio->a_out_buffer,
2165 sh_audio->a_out_buffer +
2166 sh_audio->a_out_buffer_len - bytes,
2167 bytes);
2168 sh_audio->a_out_buffer_len = bytes;
2169 if (res < 0)
2170 return res;
2171 return decode_audio(sh_audio, playsize);
2173 sh_audio->a_out_buffer_len = 0;
2174 if (res < 0)
2175 return res;
2177 int fillbyte = 0;
2178 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2179 fillbyte = 0x80;
2180 if (bytes >= playsize) {
2181 /* This case could fall back to the one below with
2182 * bytes = playsize, but then silence would keep accumulating
2183 * in a_out_buffer if the AO accepts less data than it asks for
2184 * in playsize. */
2185 char *p = malloc(playsize);
2186 memset(p, fillbyte, playsize);
2187 playsize = mpctx->audio_out->play(p, playsize, 0);
2188 free(p);
2189 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2190 return ASYNC_PLAY_DONE;
2192 mpctx->syncing_audio = false;
2193 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2194 return decode_audio(sh_audio, playsize);
2197 static int fill_audio_out_buffers(struct MPContext *mpctx)
2199 struct MPOpts *opts = &mpctx->opts;
2200 unsigned int t;
2201 double tt;
2202 int playsize;
2203 int playflags=0;
2204 int audio_eof=0;
2205 bool format_change = false;
2206 sh_audio_t * const sh_audio = mpctx->sh_audio;
2208 current_module="play_audio";
2210 while (1) {
2211 int sleep_time;
2212 // all the current uses of ao_data.pts seem to be in aos that handle
2213 // sync completely wrong; there should be no need to use ao_data.pts
2214 // in get_space()
2215 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2216 playsize = mpctx->audio_out->get_space();
2217 if (mpctx->sh_video || playsize >= ao_data.outburst)
2218 break;
2220 // handle audio-only case:
2221 // this is where mplayer sleeps during audio-only playback
2222 // to avoid 100% CPU use
2223 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2224 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2225 usec_sleep(sleep_time * 1000);
2228 // Fill buffer if needed:
2229 current_module="decode_audio";
2230 t = GetTimer();
2232 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2233 mpctx->syncing_audio = false;
2235 int res;
2236 if (mpctx->syncing_audio && mpctx->sh_video)
2237 res = audio_start_sync(mpctx, playsize);
2238 else
2239 res = decode_audio(sh_audio, playsize);
2240 if (res < 0) { // EOF, error or format change
2241 if (res == -2)
2242 format_change = true;
2243 else if (res == ASYNC_PLAY_DONE)
2244 return 1;
2245 else if (mpctx->d_audio->eof) {
2246 audio_eof = 1;
2247 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2248 if (sh_audio->a_out_buffer_len < unitsize)
2249 return 0;
2252 t = GetTimer() - t;
2253 tt = t*0.000001f; audio_time_usage+=tt;
2254 if (playsize > sh_audio->a_out_buffer_len) {
2255 playsize = sh_audio->a_out_buffer_len;
2256 if (audio_eof)
2257 playflags |= AOPLAY_FINAL_CHUNK;
2259 if (!playsize)
2260 return 1;
2262 // play audio:
2263 current_module="play_audio";
2265 // Is this pts value actually useful for the aos that access it?
2266 // They're obviously badly broken in the way they handle av sync;
2267 // would not having access to this make them more broken?
2268 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2269 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2271 if (playsize > 0) {
2272 sh_audio->a_out_buffer_len -= playsize;
2273 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2274 sh_audio->a_out_buffer_len);
2275 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2277 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2278 // Sanity check to avoid hanging in case current ao doesn't output
2279 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2280 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2281 sh_audio->a_out_buffer_len = 0;
2284 /* The format change isn't handled too gracefully. A more precise
2285 * implementation would require draining buffered old-format audio
2286 * while displaying video, then doing the output format switch.
2288 if (format_change) {
2289 uninit_player(mpctx, INITIALIZED_AO);
2290 reinit_audio_chain(mpctx);
2293 return 1;
2296 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2297 float *aq_sleep_time)
2299 struct MPOpts *opts = &mpctx->opts;
2300 double audio_limit = 2;
2301 current_module="calc_sleep_time";
2303 *time_frame -= get_relative_time(mpctx); // reset timer
2305 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2306 float delay = mpctx->audio_out->get_delay();
2307 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2309 if (opts->autosync) {
2311 * Adjust this raw delay value by calculating the expected
2312 * delay for this frame and generating a new value which is
2313 * weighted between the two. The higher autosync is, the
2314 * closer to the delay value gets to that which "-nosound"
2315 * would have used, and the longer it will take for A/V
2316 * sync to settle at the right value (but it eventually will.)
2317 * This settling time is very short for values below 100.
2319 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2320 float difference = delay - predicted;
2321 delay = predicted + difference / (float)opts->autosync;
2324 *time_frame = delay - mpctx->delay / opts->playback_speed;
2326 // delay = amount of audio buffered in soundcard/driver
2327 delay = FFMIN(delay, 0.5);
2328 delay = FFMAX(delay, 0.1);
2329 audio_limit = delay;
2330 } else {
2331 // If we're lagging more than 200 ms behind the right playback rate,
2332 // don't try to "catch up".
2333 // If benchmark is set always output frames as fast as possible
2334 // without sleeping.
2335 if (*time_frame < -0.2 || opts->benchmark)
2336 *time_frame = 0;
2339 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2341 if (t <= 0.05)
2342 return 0;
2344 t -= 0.05;
2345 if (t > audio_limit * 0.6)
2346 t = audio_limit * 0.5;
2347 *aq_sleep_time += t;
2348 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2349 return 1;
2352 int reinit_video_chain(struct MPContext *mpctx)
2354 struct MPOpts *opts = &mpctx->opts;
2355 sh_video_t * const sh_video = mpctx->sh_video;
2356 double ar=-1.0;
2357 //================== Init VIDEO (codec & libvo) ==========================
2358 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2359 current_module="preinit_libvo";
2361 //shouldn't we set dvideo->id=-2 when we fail?
2362 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2363 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2364 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2365 goto err_out;
2367 mpctx->initialized_flags|=INITIALIZED_VO;
2370 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2371 mpctx->sh_video->stream_aspect = ar;
2372 current_module="init_video_filters";
2374 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2375 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2377 #ifdef CONFIG_MENU
2378 if(use_menu) {
2379 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2380 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2381 if(!vf_menu) {
2382 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2383 use_menu = 0;
2386 if(vf_menu)
2387 sh_video->vfilter = vf_menu;
2388 #endif
2390 #ifdef CONFIG_ASS
2391 if(opts->ass_enabled) {
2392 int i;
2393 int insert = 1;
2394 if (opts->vf_settings)
2395 for (i = 0; opts->vf_settings[i].name; ++i)
2396 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2397 insert = 0;
2398 break;
2400 if (insert) {
2401 extern vf_info_t vf_info_ass;
2402 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2403 char* vf_arg[] = {"auto", "1", NULL};
2404 int retcode = 0;
2405 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2406 sh_video->vfilter,
2407 "ass", vf_arg,
2408 &retcode);
2409 if (vf_ass)
2410 sh_video->vfilter = vf_ass;
2411 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2412 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2413 else
2414 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2417 #endif
2419 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2421 #ifdef CONFIG_ASS
2422 if (opts->ass_enabled)
2423 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2424 #endif
2426 current_module="init_video_codec";
2428 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2429 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2430 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2432 if(!sh_video->initialized){
2433 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2434 goto err_out;
2437 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2439 if (sh_video->codec)
2440 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2442 sh_video->last_pts = MP_NOPTS_VALUE;
2443 sh_video->num_buffered_pts = 0;
2444 sh_video->next_frame_time = 0;
2446 if (opts->auto_quality > 0) {
2447 // Auto quality option enabled
2448 output_quality=get_video_quality_max(sh_video);
2449 if (opts->auto_quality > output_quality)
2450 opts->auto_quality = output_quality;
2451 else
2452 output_quality = opts->auto_quality;
2453 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2454 set_video_quality(sh_video,output_quality);
2457 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2459 current_module="init_vo";
2461 return 1;
2463 err_out:
2464 mpctx->sh_video = mpctx->d_video->sh = NULL;
2465 return 0;
2468 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2470 struct sh_video *sh_video = mpctx->sh_video;
2471 double frame_time = 0;
2472 struct vo *video_out = mpctx->video_out;
2473 while (1) {
2474 current_module = "filter_video";
2475 // In nocorrect-pts mode there is no way to properly time these frames
2476 if (vo_get_buffered_frame(video_out, 0) >= 0)
2477 break;
2478 if (vf_output_queued_frame(sh_video->vfilter))
2479 break;
2480 unsigned char *packet = NULL;
2481 frame_time = sh_video->next_frame_time;
2482 if (mpctx->restart_playback)
2483 frame_time = 0;
2484 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2485 &packet, force_fps);
2486 if (in_size < 0) {
2487 #ifdef CONFIG_DVDNAV
2488 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2489 if (mp_dvdnav_is_eof(mpctx->stream))
2490 return -1;
2491 if (mpctx->d_video)
2492 mpctx->d_video->eof = 0;
2493 if (mpctx->d_audio)
2494 mpctx->d_audio->eof = 0;
2495 mpctx->stream->eof = 0;
2496 } else
2497 #endif
2498 return -1;
2500 if (in_size > max_framesize)
2501 max_framesize = in_size;
2502 sh_video->timer += frame_time;
2503 if (mpctx->sh_audio)
2504 mpctx->delay -= frame_time;
2505 // video_read_frame can change fps (e.g. for ASF video)
2506 vo_fps = sh_video->fps;
2507 int framedrop_type = check_framedrop(mpctx, frame_time);
2508 current_module = "decode video";
2510 void *decoded_frame;
2511 #ifdef CONFIG_DVDNAV
2512 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2513 if (in_size >= 0 && !decoded_frame)
2514 #endif
2515 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2516 sh_video->pts);
2517 #ifdef CONFIG_DVDNAV
2518 // Save last still frame for future display
2519 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2520 #endif
2521 if (decoded_frame) {
2522 current_module = "filter video";
2523 filter_video(sh_video, decoded_frame, sh_video->pts);
2525 break;
2527 return frame_time;
2530 static void determine_frame_pts(struct MPContext *mpctx)
2532 struct sh_video *sh_video = mpctx->sh_video;
2533 struct MPOpts *opts = &mpctx->opts;
2535 if (opts->user_pts_assoc_mode) {
2536 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2537 } else if (sh_video->pts_assoc_mode == 0) {
2538 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2539 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2540 sh_video->pts_assoc_mode = 1;
2541 else
2542 sh_video->pts_assoc_mode = 2;
2543 } else {
2544 int probcount1 = sh_video->num_reordered_pts_problems;
2545 int probcount2 = sh_video->num_sorted_pts_problems;
2546 if (sh_video->pts_assoc_mode == 2) {
2547 int tmp = probcount1;
2548 probcount1 = probcount2;
2549 probcount2 = tmp;
2551 if (probcount1 >= probcount2 * 1.5 + 2) {
2552 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2553 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2554 "%d.\n", sh_video->pts_assoc_mode);
2557 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2558 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2561 static double update_video(struct MPContext *mpctx)
2563 struct sh_video *sh_video = mpctx->sh_video;
2564 struct vo *video_out = mpctx->video_out;
2565 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2566 mpctx->osd); // hack for vf_expand
2567 if (!mpctx->opts.correct_pts)
2568 return update_video_nocorrect_pts(mpctx);
2570 double pts;
2572 while (1) {
2573 current_module = "filter_video";
2574 if (!mpctx->hrseek_active
2575 && vo_get_buffered_frame(video_out, false) >= 0)
2576 break;
2577 // XXX Time used in this call is not counted in any performance
2578 // timer now
2579 if (vf_output_queued_frame(sh_video->vfilter))
2580 break;
2581 unsigned char *packet = NULL;
2582 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2583 if (pts != MP_NOPTS_VALUE)
2584 pts += mpctx->video_offset;
2585 bool hit_eof = false;
2586 if (in_size < 0) {
2587 // try to extract last frames in case of decoder lag
2588 in_size = 0;
2589 pts = MP_NOPTS_VALUE;
2590 hit_eof = true;
2592 if (in_size > max_framesize)
2593 max_framesize = in_size;
2594 current_module = "decode video";
2595 if (pts >= mpctx->hrseek_pts - .005)
2596 mpctx->hrseek_framedrop = false;
2597 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2598 check_framedrop(mpctx, sh_video->frametime);
2599 void *decoded_frame = decode_video(sh_video, packet, in_size,
2600 framedrop_type, pts);
2601 if (decoded_frame) {
2602 determine_frame_pts(mpctx);
2603 current_module = "filter video";
2604 filter_video(sh_video, decoded_frame, sh_video->pts);
2605 } else if (hit_eof) {
2606 if (vo_get_buffered_frame(video_out, true) < 0)
2607 return -1;
2609 break;
2612 if (!video_out->frame_loaded)
2613 return 0;
2615 pts = video_out->next_pts;
2616 if (pts == MP_NOPTS_VALUE) {
2617 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2618 // Try to use decoder pts from before filters
2619 pts = sh_video->pts;
2620 if (pts == MP_NOPTS_VALUE)
2621 pts = sh_video->last_pts;
2623 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005)
2624 return 0;
2625 mpctx->hrseek_active = false;
2626 sh_video->pts = pts;
2627 if (sh_video->last_pts == MP_NOPTS_VALUE)
2628 sh_video->last_pts = sh_video->pts;
2629 else if (sh_video->last_pts > sh_video->pts) {
2630 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2631 sh_video->pts, sh_video->last_pts);
2632 /* If the difference in pts is small treat it as jitter around the
2633 * right value (possibly caused by incorrect timestamp ordering) and
2634 * just show this frame immediately after the last one.
2635 * Treat bigger differences as timestamp resets and start counting
2636 * timing of later frames from the position of this one. */
2637 if (sh_video->last_pts - sh_video->pts > 0.5)
2638 sh_video->last_pts = sh_video->pts;
2639 else
2640 sh_video->pts = sh_video->last_pts;
2642 double frame_time = sh_video->pts - sh_video->last_pts;
2643 sh_video->last_pts = sh_video->pts;
2644 sh_video->timer += frame_time;
2645 if (mpctx->sh_audio)
2646 mpctx->delay -= frame_time;
2647 return frame_time;
2650 void pause_player(struct MPContext *mpctx)
2652 if (mpctx->paused)
2653 return;
2654 mpctx->paused = 1;
2655 mpctx->step_frames = 0;
2656 mpctx->time_frame -= get_relative_time(mpctx);
2658 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2659 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2661 if (mpctx->audio_out && mpctx->sh_audio)
2662 mpctx->audio_out->pause(); // pause audio, keep data if possible
2665 void unpause_player(struct MPContext *mpctx)
2667 if (!mpctx->paused)
2668 return;
2669 mpctx->paused = 0;
2671 if (mpctx->audio_out && mpctx->sh_audio)
2672 mpctx->audio_out->resume(); // resume audio
2673 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2674 && !mpctx->step_frames)
2675 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2676 (void)get_relative_time(mpctx); // ignore time that passed during pause
2679 void add_step_frame(struct MPContext *mpctx)
2681 mpctx->step_frames++;
2682 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2683 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2684 unpause_player(mpctx);
2687 static void pause_loop(struct MPContext *mpctx)
2689 struct MPOpts *opts = &mpctx->opts;
2690 mp_cmd_t* cmd;
2691 if (!opts->quiet) {
2692 // Small hack to display the pause message on the OSD line.
2693 // The pause string is: "\n == PAUSE == \r" so we need to
2694 // take the first and the last char out
2695 if (opts->term_osd && !mpctx->sh_video) {
2696 char msg[128] = _("\n ===== PAUSE =====\r");
2697 int mlen = strlen(msg);
2698 msg[mlen-1] = '\0';
2699 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2700 update_osd_msg(mpctx);
2701 } else
2702 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2703 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2706 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2707 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2708 if (cmd) {
2709 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2710 run_command(mpctx, cmd);
2711 mp_cmd_free(cmd);
2712 continue;
2714 if (mpctx->sh_video && mpctx->video_out)
2715 vo_check_events(mpctx->video_out);
2716 #ifdef CONFIG_MENU
2717 if (vf_menu)
2718 vf_menu_pause_update(vf_menu);
2719 #endif
2720 usec_sleep(20000);
2721 update_osd_msg(mpctx);
2722 int hack = vo_osd_changed(0);
2723 vo_osd_changed(hack);
2724 if (hack)
2725 break;
2730 // Find the right mute status and record position for new file position
2731 static void edl_seek_reset(MPContext *mpctx)
2733 mpctx->edl_muted = 0;
2734 next_edl_record = edl_records;
2736 while (next_edl_record) {
2737 if (next_edl_record->start_sec >= get_current_time(mpctx))
2738 break;
2740 if (next_edl_record->action == EDL_MUTE)
2741 mpctx->edl_muted = !mpctx->edl_muted;
2742 next_edl_record = next_edl_record->next;
2744 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2745 mixer_mute(&mpctx->mixer);
2749 // Execute EDL command for the current position if one exists
2750 static void edl_update(MPContext *mpctx)
2752 if (!next_edl_record)
2753 return;
2755 if (!mpctx->sh_video) {
2756 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2757 free_edl(edl_records);
2758 next_edl_record = NULL;
2759 edl_records = NULL;
2760 return;
2763 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2764 if (next_edl_record->action == EDL_SKIP) {
2765 mpctx->osd_function = OSD_FFW;
2766 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2767 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2768 "[%f], length [%f]\n", next_edl_record->start_sec,
2769 next_edl_record->stop_sec, next_edl_record->length_sec);
2771 else if (next_edl_record->action == EDL_MUTE) {
2772 mpctx->edl_muted = !mpctx->edl_muted;
2773 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2774 mixer_mute(&mpctx->mixer);
2775 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2776 next_edl_record->start_sec );
2778 next_edl_record = next_edl_record->next;
2782 static void reinit_decoders(struct MPContext *mpctx)
2784 reinit_video_chain(mpctx);
2785 reinit_audio_chain(mpctx);
2786 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2789 static void seek_reset(struct MPContext *mpctx)
2791 if (mpctx->sh_video) {
2792 current_module = "seek_video_reset";
2793 resync_video_stream(mpctx->sh_video);
2794 mpctx->sh_video->timer = 0;
2795 vo_seek_reset(mpctx->video_out);
2796 mpctx->sh_video->timer = 0;
2797 mpctx->sh_video->num_buffered_pts = 0;
2798 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2799 mpctx->delay = 0;
2800 mpctx->time_frame = 0;
2801 mpctx->restart_playback = true;
2802 // Not all demuxers set d_video->pts during seek, so this value
2803 // (which is used by at least vobsub and edl code below) may
2804 // be completely wrong (probably 0).
2805 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2806 mpctx->video_pts = mpctx->sh_video->pts;
2807 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2808 mpctx->sh_video->pts, mpctx->video_offset,
2809 mpctx->d_sub, 1);
2810 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2813 if (mpctx->sh_audio) {
2814 current_module = "seek_audio_reset";
2815 resync_audio_stream(mpctx->sh_audio);
2816 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2817 mpctx->sh_audio->a_buffer_len = 0;
2818 mpctx->sh_audio->a_out_buffer_len = 0;
2819 if (!mpctx->sh_video)
2820 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2821 mpctx->video_offset, mpctx->d_sub, 1);
2824 if (vo_vobsub && mpctx->sh_video) {
2825 current_module = "seek_vobsub_reset";
2826 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2829 edl_seek_reset(mpctx);
2831 mpctx->hrseek_active = false;
2832 mpctx->hrseek_framedrop = false;
2833 mpctx->total_avsync_change = 0;
2834 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2835 drop_frame_cnt = 0;
2837 current_module = NULL;
2840 static bool timeline_set_part(struct MPContext *mpctx, int i)
2842 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2843 struct timeline_part *n = mpctx->timeline + i;
2844 mpctx->timeline_part = i;
2845 mpctx->video_offset = n->start - n->source_start;
2846 if (n->source == p->source)
2847 return false;
2848 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2849 mpctx->demuxer = n->source->demuxer;
2850 mpctx->d_video = mpctx->demuxer->video;
2851 mpctx->d_audio = mpctx->demuxer->audio;
2852 mpctx->d_sub = mpctx->demuxer->sub;
2853 mpctx->sh_video = mpctx->d_video->sh;
2854 mpctx->sh_audio = mpctx->d_audio->sh;
2855 return true;
2858 // Given pts, switch playback to the corresponding part.
2859 // Return offset within that part.
2860 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2861 bool *need_reset)
2863 if (pts < 0)
2864 pts = 0;
2865 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2866 struct timeline_part *p = mpctx->timeline + i;
2867 if (pts < (p+1)->start) {
2868 *need_reset = timeline_set_part(mpctx, i);
2869 return pts - p->start + p->source_start;
2872 return -1;
2876 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2877 static int seek(MPContext *mpctx, struct seek_params seek)
2879 struct MPOpts *opts = &mpctx->opts;
2881 current_module = "seek";
2882 if (mpctx->stop_play == AT_END_OF_FILE)
2883 mpctx->stop_play = KEEP_PLAYING;
2884 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
2885 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
2886 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
2887 || opts->hr_seek > 0 || seek.exact > 0;
2888 if (seek.type == MPSEEK_FACTOR
2889 || seek.type == MPSEEK_ABSOLUTE
2890 && seek.amount < mpctx->last_chapter_pts
2891 || seek.amount < 0)
2892 mpctx->last_chapter_seek = -1;
2893 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
2894 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2895 seek.type = MPSEEK_ABSOLUTE;
2897 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
2898 && seek.type == MPSEEK_RELATIVE) {
2899 seek.type = MPSEEK_ABSOLUTE;
2900 seek.direction = seek.amount > 0 ? 1 : -1;
2901 seek.amount += get_current_time(mpctx);
2904 /* At least the liba52 decoder wants to read from the input stream
2905 * during initialization, so reinit must be done after the demux_seek()
2906 * call that clears possible stream EOF. */
2907 bool need_reset = false;
2908 double demuxer_amount = seek.amount;
2909 if (mpctx->timeline) {
2910 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
2911 &need_reset);
2912 if (demuxer_amount == -1) {
2913 mpctx->stop_play = AT_END_OF_FILE;
2914 // Clear audio from current position
2915 if (mpctx->sh_audio) {
2916 mpctx->audio_out->reset();
2917 mpctx->sh_audio->a_buffer_len = 0;
2918 mpctx->sh_audio->a_out_buffer_len = 0;
2920 return -1;
2923 int demuxer_style = 0;
2924 switch (seek.type) {
2925 case MPSEEK_FACTOR:
2926 demuxer_style |= SEEK_FACTOR; // fallthrough
2927 case MPSEEK_ABSOLUTE:
2928 demuxer_style |= SEEK_ABSOLUTE;
2930 if (hr_seek || seek.direction < 0)
2931 demuxer_style |= SEEK_BACKWARD;
2932 else if (seek.direction > 0)
2933 demuxer_style |= SEEK_FORWARD;
2935 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
2936 demuxer_style);
2937 if (need_reset)
2938 reinit_decoders(mpctx);
2939 if (seekresult == 0)
2940 return -1;
2942 seek_reset(mpctx);
2944 /* Use the target time as "current position" for further relative
2945 * seeks etc until a new video frame has been decoded */
2946 if (seek.type == MPSEEK_ABSOLUTE)
2947 mpctx->video_pts = seek.amount;
2949 if (hr_seek) {
2950 mpctx->hrseek_active = true;
2951 mpctx->hrseek_framedrop = true;
2952 mpctx->hrseek_pts = seek.amount;
2955 mpctx->start_timestamp = GetTimerMS();
2957 return 0;
2960 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
2961 int exact)
2963 struct seek_params *seek = &mpctx->seek;
2964 switch (type) {
2965 case MPSEEK_RELATIVE:
2966 if (seek->type == MPSEEK_FACTOR)
2967 return; // Well... not common enough to bother doing better
2968 seek->amount += amount;
2969 seek->exact = FFMAX(seek->exact, exact);
2970 if (seek->type == MPSEEK_NONE)
2971 seek->exact = exact;
2972 if (seek->type == MPSEEK_ABSOLUTE)
2973 return;
2974 if (seek->amount == 0) {
2975 *seek = (struct seek_params){0};
2976 return;
2978 seek->type = MPSEEK_RELATIVE;
2979 return;
2980 case MPSEEK_ABSOLUTE:
2981 case MPSEEK_FACTOR:
2982 *seek = (struct seek_params) {
2983 .type = type,
2984 .amount = amount,
2985 .exact = exact,
2987 return;
2988 case MPSEEK_NONE:
2989 *seek = (struct seek_params){0};
2990 return;
2992 abort();
2996 double get_time_length(struct MPContext *mpctx)
2998 if (mpctx->timeline)
2999 return mpctx->timeline[mpctx->num_timeline_parts].start;
3001 struct demuxer *demuxer = mpctx->demuxer;
3002 double get_time_ans;
3003 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3004 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3005 (void *) &get_time_ans) > 0)
3006 return get_time_ans;
3008 struct sh_video *sh_video = mpctx->d_video->sh;
3009 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3010 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3011 return (double) (demuxer->movi_end - demuxer->movi_start) /
3012 (sh_video->i_bps + sh_audio->i_bps);
3013 if (sh_video && sh_video->i_bps)
3014 return (double) (demuxer->movi_end - demuxer->movi_start) /
3015 sh_video->i_bps;
3016 if (sh_audio && sh_audio->i_bps)
3017 return (double) (demuxer->movi_end - demuxer->movi_start) /
3018 sh_audio->i_bps;
3019 return 0;
3022 /* If there are timestamps from stream level then use those (for example
3023 * DVDs can have consistent times there while the MPEG-level timestamps
3024 * reset). */
3025 double get_current_time(struct MPContext *mpctx)
3027 struct demuxer *demuxer = mpctx->demuxer;
3028 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3029 return demuxer->stream_pts;
3030 struct sh_video *sh_video = demuxer->video->sh;
3031 if (sh_video)
3032 return mpctx->video_pts;
3033 return playing_audio_pts(mpctx);
3036 int get_percent_pos(struct MPContext *mpctx)
3038 struct demuxer *demuxer = mpctx->demuxer;
3039 int ans = 0;
3040 if (mpctx->timeline)
3041 ans = get_current_time(mpctx) * 100 /
3042 mpctx->timeline[mpctx->num_timeline_parts].start;
3043 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3045 else {
3046 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3047 off_t pos = demuxer->filepos > 0 ?
3048 demuxer->filepos : stream_tell(demuxer->stream);
3049 if (len > 0)
3050 ans = (pos - demuxer->movi_start) / len;
3051 else
3052 ans = 0;
3054 if (ans < 0)
3055 ans = 0;
3056 if (ans > 100)
3057 ans = 100;
3058 return ans;
3061 // -2 is no chapters, -1 is before first chapter
3062 int get_current_chapter(struct MPContext *mpctx)
3064 double current_pts = get_current_time(mpctx);
3065 if (!mpctx->chapters)
3066 return FFMAX(mpctx->last_chapter_seek,
3067 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3069 int i;
3070 for (i = 1; i < mpctx->num_chapters; i++)
3071 if (current_pts < mpctx->chapters[i].start)
3072 break;
3073 return FFMAX(mpctx->last_chapter_seek, i - 1);
3076 // currently returns a string allocated with malloc, not talloc
3077 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3079 if (!mpctx->chapters || !mpctx->sh_video)
3080 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3081 return strdup(mpctx->chapters[chapter].name);
3084 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3085 char **chapter_name)
3087 mpctx->last_chapter_seek = -1;
3088 if (!mpctx->chapters || !mpctx->sh_video) {
3089 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3090 chapter_name);
3091 if (res >= 0) {
3092 if (*seek_pts == -1)
3093 seek_reset(mpctx);
3094 else {
3095 mpctx->last_chapter_seek = res;
3096 mpctx->last_chapter_pts = *seek_pts;
3099 return res;
3102 if (chapter >= mpctx->num_chapters)
3103 return -1;
3104 if (chapter < 0)
3105 chapter = 0;
3106 *seek_pts = mpctx->chapters[chapter].start;
3107 mpctx->last_chapter_seek = chapter;
3108 mpctx->last_chapter_pts = *seek_pts;
3109 if (chapter_name)
3110 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3111 return chapter;
3115 static void run_playloop(struct MPContext *mpctx)
3117 struct MPOpts *opts = &mpctx->opts;
3118 float aq_sleep_time = 0;
3120 if (opts->chapterrange[1] > 0) {
3121 int cur_chapter = get_current_chapter(mpctx);
3122 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3123 mpctx->stop_play = PT_NEXT_ENTRY;
3126 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3127 mpctx->sh_audio = mpctx->d_audio->sh;
3128 mpctx->sh_audio->ds = mpctx->d_audio;
3129 reinit_audio_chain(mpctx);
3132 /*========================== PLAY AUDIO ============================*/
3134 if (mpctx->sh_audio && !mpctx->paused
3135 && (!mpctx->restart_playback || !mpctx->sh_video))
3136 if (!fill_audio_out_buffers(mpctx))
3137 // at eof, all audio at least written to ao
3138 if (!mpctx->sh_video)
3139 mpctx->stop_play = AT_END_OF_FILE;
3142 if (!mpctx->sh_video) {
3143 mpctx->restart_playback = false;
3144 // handle audio-only case:
3145 double a_pos = 0;
3146 // sh_audio can be NULL due to video stream switching
3147 // TODO: handle this better
3148 if (mpctx->sh_audio)
3149 a_pos = playing_audio_pts(mpctx);
3151 print_status(mpctx, a_pos, false);
3153 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3154 mpctx->stop_play = PT_NEXT_ENTRY;
3155 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
3156 mpctx->d_sub, 0);
3157 update_osd_msg(mpctx);
3158 } else {
3160 /*========================== PLAY VIDEO ============================*/
3162 vo_pts = mpctx->sh_video->timer * 90000.0;
3163 vo_fps = mpctx->sh_video->fps;
3165 bool blit_frame = mpctx->video_out->frame_loaded;
3166 if (!blit_frame || mpctx->hrseek_active) {
3167 double frame_time = update_video(mpctx);
3168 blit_frame = mpctx->video_out->frame_loaded;
3169 blit_frame &= !mpctx->hrseek_active;
3170 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3171 if (mpctx->sh_video->vf_initialized < 0) {
3172 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3173 "\nFATAL: Could not initialize video filters (-vf) "
3174 "or video output (-vo).\n");
3175 mpctx->stop_play = PT_NEXT_ENTRY;
3176 return;
3178 if (frame_time < 0)
3179 mpctx->stop_play = AT_END_OF_FILE;
3180 else if (!mpctx->restart_playback) {
3181 mpctx->time_frame += frame_time / opts->playback_speed;
3182 adjust_sync(mpctx, frame_time);
3185 if (mpctx->timeline) {
3186 struct timeline_part *next =
3187 mpctx->timeline + mpctx->timeline_part + 1;
3188 if (mpctx->sh_video->pts >= next->start
3189 || mpctx->stop_play == AT_END_OF_FILE
3190 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3191 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3192 .amount = next->start });
3193 return;
3197 // ==========================================================================
3199 current_module = "vo_check_events";
3200 vo_check_events(mpctx->video_out);
3202 #ifdef CONFIG_X11
3203 if (stop_xscreensaver) {
3204 current_module = "stop_xscreensaver";
3205 xscreensaver_heartbeat(mpctx->x11_state);
3207 #endif
3208 if (heartbeat_cmd) {
3209 static unsigned last_heartbeat;
3210 unsigned now = GetTimerMS();
3211 if (now - last_heartbeat > 30000) {
3212 last_heartbeat = now;
3213 system(heartbeat_cmd);
3217 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3218 &mpctx->time_frame,
3219 &aq_sleep_time);
3221 //====================== FLIP PAGE (VIDEO BLT): =========================
3223 current_module = "flip_page";
3224 if (!frame_time_remaining && blit_frame) {
3225 struct sh_video *sh_video = mpctx->sh_video;
3226 mpctx->video_pts = sh_video->pts;
3227 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
3228 mpctx->video_offset, mpctx->d_sub, 0);
3229 update_teletext(sh_video, mpctx->demuxer, 0);
3230 update_osd_msg(mpctx);
3231 struct vf_instance *vf = sh_video->vfilter;
3232 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3233 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3234 vo_osd_changed(0);
3236 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3237 aq_sleep_time += mpctx->time_frame;
3238 // flag 256 means: libvo driver does its timing (dvb card)
3239 if (mpctx->time_frame > 0.001
3240 && !(mpctx->sh_video->output_flags&256))
3241 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3242 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3244 unsigned int t2 = GetTimer();
3245 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
3246 int duration = -1;
3247 double pts2 = mpctx->video_out->next_pts2;
3248 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3249 && !mpctx->restart_playback) {
3250 // expected A/V sync correction is ignored
3251 double diff = (pts2 - mpctx->video_pts);
3252 diff /= opts->playback_speed;
3253 if (mpctx->time_frame < 0)
3254 diff += mpctx->time_frame;
3255 if (diff < 0)
3256 diff = 0;
3257 if (diff > 10)
3258 diff = 10;
3259 duration = diff * 1e6;
3261 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3263 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3264 vout_time_usage += mpctx->last_vo_flip_duration;
3265 if (mpctx->video_out->driver->flip_page_timed) {
3266 // No need to adjust sync based on flip speed
3267 mpctx->last_vo_flip_duration = 0;
3268 // For print_status - VO call finishing early is OK for sync
3269 mpctx->time_frame -= get_relative_time(mpctx);
3271 if (mpctx->restart_playback) {
3272 mpctx->syncing_audio = true;
3273 if (mpctx->sh_audio && !mpctx->paused)
3274 fill_audio_out_buffers(mpctx);
3275 mpctx->restart_playback = false;
3276 mpctx->time_frame = 0;
3277 get_relative_time(mpctx);
3279 print_status(mpctx, MP_NOPTS_VALUE, true);
3280 } else
3281 print_status(mpctx, MP_NOPTS_VALUE, false);
3283 //============================ Auto QUALITY ============================
3285 /*Output quality adjustments:*/
3286 if (opts->auto_quality > 0) {
3287 current_module = "autoq";
3288 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3289 ++output_quality;
3290 else
3291 if (output_quality>1 && aq_sleep_time<0)
3292 --output_quality;
3293 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3294 output_quality = 0;
3295 set_video_quality(mpctx->sh_video, output_quality);
3298 if (!frame_time_remaining && blit_frame) {
3299 if (play_n_frames >= 0) {
3300 --play_n_frames;
3301 if (play_n_frames <= 0)
3302 mpctx->stop_play = PT_NEXT_ENTRY;
3304 if (mpctx->step_frames > 0) {
3305 mpctx->step_frames--;
3306 if (mpctx->step_frames == 0)
3307 pause_player(mpctx);
3311 // FIXME: add size based support for -endpos
3312 if (end_at.type == END_AT_TIME &&
3313 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3314 mpctx->stop_play = PT_NEXT_ENTRY;
3316 } // end if(mpctx->sh_video)
3318 #ifdef CONFIG_DVDNAV
3319 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3320 nav_highlight_t hl;
3321 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3322 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3323 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3324 vo_osd_changed(OSDTYPE_DVDNAV);
3325 } else {
3326 osd_set_nav_box(0, 0, 0, 0);
3327 vo_osd_changed(OSDTYPE_DVDNAV);
3328 vo_osd_changed(OSDTYPE_SPU);
3331 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3332 double ar = -1.0;
3333 if (mpctx->sh_video &&
3334 stream_control(mpctx->demuxer->stream,
3335 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3336 != STREAM_UNSUPPORTED)
3337 mpctx->sh_video->stream_aspect = ar;
3340 #endif
3342 //================= Keyboard events, SEEKing ====================
3344 current_module = "key_events";
3346 while (1) {
3347 mp_cmd_t *cmd;
3348 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3349 /* Allow running consecutive seek commands to combine them,
3350 * but execute the seek before running other commands.
3351 * If the user seeks continuously (keeps arrow key down)
3352 * try to finish showing a frame from one location before doing
3353 * another seek (which could lead to unchanging display). */
3354 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3355 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3356 && GetTimerMS() - mpctx->start_timestamp < 300)
3357 break;
3358 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3359 run_command(mpctx, cmd);
3360 mp_cmd_free(cmd);
3361 if (mpctx->stop_play)
3362 break;
3364 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3365 || mpctx->restart_playback)
3366 break;
3367 if (mpctx->sh_video) {
3368 update_osd_msg(mpctx);
3369 int hack = vo_osd_changed(0);
3370 vo_osd_changed(hack);
3371 if (hack) {
3372 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3373 add_step_frame(mpctx);
3374 break;
3375 } else
3376 vo_osd_changed(0);
3379 pause_loop(mpctx);
3382 // handle -sstep
3383 if (step_sec > 0 && !mpctx->paused) {
3384 mpctx->osd_function = OSD_FFW;
3385 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3388 edl_update(mpctx);
3390 /* Looping. */
3391 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3392 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3394 if (opts->loop_times>1)
3395 opts->loop_times--;
3396 else if (opts->loop_times==1)
3397 opts->loop_times = -1;
3398 play_n_frames = play_n_frames_mf;
3399 mpctx->stop_play = 0;
3400 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3403 if (mpctx->seek.type) {
3404 seek(mpctx, mpctx->seek);
3405 mpctx->seek = (struct seek_params){0};
3410 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3411 struct content_source *sources,
3412 int num_sources,
3413 unsigned char uid_map[][16])
3415 int num_filenames = 0;
3416 char **filenames = NULL;
3417 if (num_sources > 1) {
3418 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3419 "other sources.\n");
3420 if (mpctx->stream->type != STREAMTYPE_FILE) {
3421 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3422 "normal disk file. Will not search for related files.\n");
3423 } else {
3424 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3425 "same directory to find referenced sources.\n");
3426 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3427 &num_filenames);
3431 int num_left = num_sources - 1;
3432 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3433 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3434 filename_recode(filenames[i]));
3435 int format;
3436 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3437 if (!s)
3438 continue;
3439 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3440 mpctx->opts.audio_id,
3441 mpctx->opts.video_id,
3442 mpctx->opts.sub_id, filenames[i]);
3443 if (!d) {
3444 free_stream(s);
3445 continue;
3447 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3448 for (int i = 1; i < num_sources; i++) {
3449 if (sources[i].demuxer)
3450 continue;
3451 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3452 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3453 i, filename_recode(d->filename));
3454 sources[i].stream = s;
3455 sources[i].demuxer = d;
3456 num_left--;
3457 goto match;
3461 free_demuxer(d);
3462 free_stream(s);
3463 continue;
3464 match:
3467 talloc_free(filenames);
3468 if (num_left) {
3469 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3470 "There will be parts MISSING from the video!\n");
3471 for (int i = 1, j = 1; i < num_sources; i++)
3472 if (sources[i].demuxer) {
3473 sources[j] = sources[i];
3474 memcpy(uid_map[j], uid_map[i], 16);
3475 j++;
3478 return num_sources - num_left;
3481 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3483 struct MPOpts *opts = &mpctx->opts;
3485 if (!opts->ordered_chapters) {
3486 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3487 "you have disabled support for them. Ignoring.\n");
3488 return;
3491 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3492 "edit timeline.\n");
3494 struct demuxer *demuxer = mpctx->demuxer;
3495 struct matroska_data *m = &demuxer->matroska_data;
3497 // +1 because sources/uid_map[0] is original file even if all chapters
3498 // actually use other sources and need separate entries
3499 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3500 m->num_ordered_chapters+1);
3501 sources[0].stream = mpctx->stream;
3502 sources[0].demuxer = mpctx->demuxer;
3503 unsigned char uid_map[m->num_ordered_chapters+1][16];
3504 int num_sources = 1;
3505 memcpy(uid_map[0], m->segment_uid, 16);
3507 for (int i = 0; i < m->num_ordered_chapters; i++) {
3508 struct matroska_chapter *c = m->ordered_chapters + i;
3509 if (!c->has_segment_uid)
3510 memcpy(c->segment_uid, m->segment_uid, 16);
3512 for (int j = 0; j < num_sources; j++)
3513 if (!memcmp(c->segment_uid, uid_map[j], 16))
3514 goto found1;
3515 memcpy(uid_map[num_sources], c->segment_uid, 16);
3516 sources[num_sources] = (struct content_source){};
3517 num_sources++;
3518 found1:
3522 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3523 uid_map);
3526 // +1 for terminating chapter with start time marking end of last real one
3527 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3528 m->num_ordered_chapters + 1);
3529 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3530 m->num_ordered_chapters);
3531 uint64_t starttime = 0;
3532 uint64_t missing_time = 0;
3533 int part_count = 0;
3534 int num_chapters = 0;
3535 uint64_t prev_part_offset = 0;
3536 for (int i = 0; i < m->num_ordered_chapters; i++) {
3537 struct matroska_chapter *c = m->ordered_chapters + i;
3539 int j;
3540 for (j = 0; j < num_sources; j++) {
3541 if (!memcmp(c->segment_uid, uid_map[j], 16))
3542 goto found2;
3544 missing_time += c->end - c->start;
3545 continue;
3546 found2:;
3547 /* Only add a separate part if the time or file actually changes.
3548 * Matroska files have chapter divisions that are redundant from
3549 * timeline point of view because the same chapter structure is used
3550 * both to specify the timeline and for normal chapter information.
3551 * Removing a missing inserted external chapter can also cause this.
3552 * We allow for a configurable fudge factor because of files which
3553 * specify chapter end times that are one frame too early;
3554 * we don't want to try seeking over a one frame gap. */
3555 int64_t join_diff = c->start - starttime - prev_part_offset;
3556 if (part_count == 0 || FFABS(join_diff) > opts->chapter_merge_threshold
3557 || sources + j != timeline[part_count - 1].source) {
3558 timeline[part_count].source = sources + j;
3559 timeline[part_count].start = starttime / 1000.;
3560 timeline[part_count].source_start = c->start / 1000.;
3561 prev_part_offset = c->start - starttime;
3562 part_count++;
3563 } else if (part_count > 0 && join_diff) {
3564 /* Chapter was merged at an inexact boundary;
3565 * adjust timestamps to match. */
3566 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3567 "offset %d ms.\n", i, (int) join_diff);
3568 starttime += join_diff;
3570 chapters[num_chapters].start = starttime / 1000.;
3571 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3572 starttime += c->end - c->start;
3573 num_chapters++;
3575 timeline[part_count].start = starttime / 1000.;
3577 if (!part_count) {
3578 // None of the parts come from the file itself???
3579 talloc_free(sources);
3580 talloc_free(timeline);
3581 talloc_free(chapters);
3582 return;
3585 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3586 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3587 timeline[part_count].start);
3588 if (missing_time)
3589 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3590 "from the timeline!\n", missing_time / 1000.);
3591 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3592 for (int i = 0; i < num_sources; i++)
3593 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3594 filename_recode(sources[i].demuxer->filename));
3595 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3596 "source_start, source):\n");
3597 for (int i = 0; i < part_count; i++) {
3598 struct timeline_part *p = timeline + i;
3599 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3600 p->source_start, p->source - sources);
3602 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3603 mpctx->sources = sources;
3604 mpctx->num_sources = num_sources;
3605 mpctx->timeline = timeline;
3606 mpctx->num_timeline_parts = part_count;
3607 mpctx->num_chapters = num_chapters;
3608 mpctx->chapters = chapters;
3610 mpctx->timeline_part = 0;
3611 mpctx->demuxer = timeline[0].source->demuxer;
3615 static int read_keys(void *ctx, int fd)
3617 getch2(ctx);
3618 return mplayer_get_key(ctx, 0);
3622 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3623 * file for some tools to link against. */
3624 #ifndef DISABLE_MAIN
3625 int main(int argc,char* argv[]){
3628 char * mem_ptr;
3630 // movie info:
3632 /* Flag indicating whether MPlayer should exit without playing anything. */
3633 int opt_exit = 0;
3634 int i;
3636 struct MPContext *mpctx = &(struct MPContext){
3637 .osd_function = OSD_PLAY,
3638 .begin_skip = MP_NOPTS_VALUE,
3639 .play_tree_step = 1,
3640 .global_sub_pos = -1,
3641 .set_of_sub_pos = -1,
3642 .file_format = DEMUXER_TYPE_UNKNOWN,
3643 .last_dvb_step = 1,
3646 InitTimer();
3647 srand(GetTimerMS());
3649 mp_msg_init();
3650 set_av_log_callback();
3652 #ifdef CONFIG_X11
3653 mpctx->x11_state = vo_x11_init_state();
3654 #endif
3655 struct MPOpts *opts = &mpctx->opts;
3656 set_default_mplayer_options(opts);
3657 // Create the config context and register the options
3658 mpctx->mconfig = m_config_new(opts, cfg_include);
3659 m_config_register_options(mpctx->mconfig,mplayer_opts);
3660 m_config_register_options(mpctx->mconfig, common_opts);
3661 mp_input_register_options(mpctx->mconfig);
3663 // Preparse the command line
3664 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3666 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3667 set_path_env();
3668 #endif
3670 #ifdef CONFIG_TV
3671 stream_tv_defaults.immediate = 1;
3672 #endif
3674 parse_cfgfiles(mpctx, mpctx->mconfig);
3676 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3677 if(mpctx->playtree == NULL)
3678 opt_exit = 1;
3679 else {
3680 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3681 if(mpctx->playtree) {
3682 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3683 if(mpctx->playtree_iter) {
3684 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3685 play_tree_iter_free(mpctx->playtree_iter);
3686 mpctx->playtree_iter = NULL;
3688 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3692 mpctx->key_fifo = mp_fifo_create(opts);
3694 print_version("MPlayer");
3696 #if defined(__MINGW32__) || defined(__CYGWIN__)
3698 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3699 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3700 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3701 if (kernel32) {
3702 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3703 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3705 if (setDEP) setDEP(3);
3706 if (setDllDir) setDllDir("");
3708 // stop Windows from showing all kinds of annoying error dialogs
3709 SetErrorMode(0x8003);
3710 // request 1ms timer resolution
3711 timeBeginPeriod(1);
3712 #endif
3714 #ifdef CONFIG_PRIORITY
3715 set_priority();
3716 #endif
3718 if (codec_path)
3719 set_codec_path(codec_path);
3721 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3722 list_video_out();
3723 opt_exit = 1;
3726 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3727 list_audio_out();
3728 opt_exit = 1;
3731 /* Check codecs.conf. */
3732 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3733 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3734 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3735 if(!parse_codec_cfg(NULL)){
3736 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3738 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3741 free( mem_ptr ); // release the buffer created by get_path()
3744 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3745 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3746 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3747 list_codecs(1);
3748 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3749 opt_exit = 1;
3751 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3752 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3753 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3754 list_codecs(0);
3755 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3756 opt_exit = 1;
3758 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3759 vfm_help();
3760 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3761 opt_exit = 1;
3763 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3764 afm_help();
3765 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3766 opt_exit = 1;
3768 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3769 af_help();
3770 printf("\n");
3771 opt_exit = 1;
3773 #ifdef CONFIG_X11
3774 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3775 fstype_help();
3776 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3777 opt_exit = 1;
3779 #endif
3780 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3781 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3782 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3783 demuxer_help();
3784 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3785 opt_exit = 1;
3787 if (opts->list_properties) {
3788 property_print_help();
3789 opt_exit = 1;
3792 if(opt_exit)
3793 exit_player(mpctx, EXIT_NONE);
3795 if (!mpctx->filename && !opts->player_idle_mode) {
3796 // no file/vcd/dvd -> show HELP:
3797 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3798 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3801 /* Display what configure line was used */
3802 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3804 // Many users forget to include command line in bugreports...
3805 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3806 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3807 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3808 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3811 //------ load global data first ------
3813 mpctx->osd = osd_create();
3815 // check font
3816 #ifdef CONFIG_FREETYPE
3817 init_freetype();
3818 #endif
3819 #ifdef CONFIG_FONTCONFIG
3820 if(font_fontconfig <= 0)
3822 #endif
3823 #ifdef CONFIG_BITMAP_FONT
3824 if(font_name){
3825 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3826 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3827 filename_recode(font_name));
3828 } else {
3829 // try default:
3830 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3831 free(mem_ptr); // release the buffer created by get_path()
3832 if(!vo_font)
3833 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3835 if (sub_font_name)
3836 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3837 else
3838 mpctx->osd->sub_font = vo_font;
3839 #endif
3840 #ifdef CONFIG_FONTCONFIG
3842 #endif
3844 #ifdef CONFIG_ASS
3845 ass_library = ass_init();
3846 #endif
3848 #ifdef HAVE_RTC
3849 if(opts->rtc)
3851 char *rtc_device = opts->rtc_device;
3852 // seteuid(0); /* Can't hurt to try to get root here */
3853 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3854 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3855 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3856 else {
3857 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3859 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3860 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3861 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3862 close (rtc_fd);
3863 rtc_fd = -1;
3864 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3865 /* variable only by the root */
3866 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3867 close (rtc_fd);
3868 rtc_fd = -1;
3869 } else
3870 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3873 if(rtc_fd<0)
3874 #endif /* HAVE_RTC */
3875 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3876 opts->softsleep ? "software" : timer_name);
3878 #ifdef HAVE_TERMCAP
3879 load_termcap(NULL); // load key-codes
3880 #endif
3882 // ========== Init keyboard FIFO (connection to libvo) ============
3884 // Init input system
3885 current_module = "init_input";
3886 mpctx->input = mp_input_init(&opts->input);
3887 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3888 if(slave_mode)
3889 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3890 else if (opts->consolecontrols)
3891 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3892 // Set the libstream interrupt callback
3893 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3895 #ifdef CONFIG_MENU
3896 if(use_menu) {
3897 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3898 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3899 else {
3900 menu_cfg = get_path("menu.conf");
3901 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3902 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3903 else {
3904 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3905 MPLAYER_CONFDIR "/menu.conf"))
3906 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3907 else {
3908 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3909 use_menu = 0;
3914 #endif
3916 current_module = NULL;
3918 /// Catch signals
3919 #ifndef __MINGW32__
3920 signal(SIGCHLD,child_sighandler);
3921 #endif
3923 #ifdef CONFIG_CRASH_DEBUG
3924 prog_path = argv[0];
3925 #endif
3926 //========= Catch terminate signals: ================
3927 // terminate requests:
3928 signal(SIGTERM,exit_sighandler); // kill
3929 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3931 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3933 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3934 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3935 #ifdef CONFIG_SIGHANDLER
3936 // fatal errors:
3937 signal(SIGBUS,exit_sighandler); // bus error
3938 signal(SIGSEGV,exit_sighandler); // segfault
3939 signal(SIGILL,exit_sighandler); // illegal instruction
3940 signal(SIGFPE,exit_sighandler); // floating point exc.
3941 signal(SIGABRT,exit_sighandler); // abort()
3942 #ifdef CONFIG_CRASH_DEBUG
3943 if (crash_debug)
3944 signal(SIGTRAP,exit_sighandler);
3945 #endif
3946 #endif
3948 // ******************* Now, let's see the per-file stuff ********************
3950 play_next_file:
3952 // init global sub numbers
3953 mpctx->global_sub_size = 0;
3954 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3956 if (mpctx->filename) {
3957 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3958 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3959 load_per_file_config (mpctx->mconfig, mpctx->filename);
3962 if (opts->video_driver_list)
3963 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3964 if (opts->audio_driver_list)
3965 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3967 // We must enable getch2 here to be able to interrupt network connection
3968 // or cache filling
3969 if (opts->consolecontrols && !slave_mode) {
3970 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3971 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3972 else
3973 getch2_enable(); // prepare stdin for hotkeys...
3974 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3975 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3978 // =================== GUI idle loop (STOP state) ===========================
3979 while (opts->player_idle_mode && !mpctx->filename) {
3980 play_tree_t * entry = NULL;
3981 mp_cmd_t * cmd;
3982 if (mpctx->video_out && mpctx->video_out->config_ok)
3983 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3984 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3985 if (mpctx->video_out)
3986 vo_check_events(mpctx->video_out);
3987 usec_sleep(20000);
3989 switch (cmd->id) {
3990 case MP_CMD_LOADFILE:
3991 // prepare a tree entry with the new filename
3992 entry = play_tree_new();
3993 play_tree_add_file(entry, cmd->args[0].v.s);
3994 // The entry is added to the main playtree after the switch().
3995 break;
3996 case MP_CMD_LOADLIST:
3997 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3998 break;
3999 case MP_CMD_QUIT:
4000 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4001 break;
4002 case MP_CMD_VO_FULLSCREEN:
4003 case MP_CMD_GET_PROPERTY:
4004 case MP_CMD_SET_PROPERTY:
4005 case MP_CMD_STEP_PROPERTY:
4006 run_command(mpctx, cmd);
4007 break;
4010 mp_cmd_free(cmd);
4012 if (entry) { // user entered a command that gave a valid entry
4013 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4014 play_tree_free_list(mpctx->playtree->child, 1);
4015 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4017 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4019 play_tree_set_child(mpctx->playtree, entry);
4021 /* Make iterator start at the top the of tree. */
4022 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4023 if (!mpctx->playtree_iter) continue;
4025 // find the first real item in the tree
4026 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4027 // no items!
4028 play_tree_iter_free(mpctx->playtree_iter);
4029 mpctx->playtree_iter = NULL;
4030 continue; // wait for next command
4032 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4035 //---------------------------------------------------------------------------
4037 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4038 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4040 if (mpctx->filename) {
4041 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4042 filename_recode(mpctx->filename));
4043 if(use_filename_title && opts->vo_wintitle == NULL)
4044 opts->vo_wintitle = strdup(mp_basename2(mpctx->filename));
4047 if (edl_filename) {
4048 if (edl_records) free_edl(edl_records);
4049 next_edl_record = edl_records = edl_parse_file();
4051 if (edl_output_filename) {
4052 if (edl_fd) fclose(edl_fd);
4053 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4055 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4056 filename_recode(edl_output_filename));
4060 //==================== Open VOB-Sub ============================
4062 current_module="vobsub";
4063 if (vobsub_name){
4064 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
4065 if(vo_vobsub==NULL)
4066 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4067 filename_recode(vobsub_name));
4068 } else if (sub_auto && mpctx->filename){
4069 /* try to autodetect vobsub from movie filename ::atmos */
4070 char *buf = strdup(mpctx->filename), *psub;
4071 char *pdot = strrchr(buf, '.');
4072 char *pslash = strrchr(buf, '/');
4073 #if defined(__MINGW32__) || defined(__CYGWIN__)
4074 if (!pslash) pslash = strrchr(buf, '\\');
4075 #endif
4076 if (pdot && (!pslash || pdot > pslash))
4077 *pdot = '\0';
4078 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4079 /* try from ~/.mplayer/sub */
4080 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4081 char *bname;
4082 int l;
4083 bname = strrchr(buf,'/');
4084 #if defined(__MINGW32__) || defined(__CYGWIN__)
4085 if(!bname) bname = strrchr(buf,'\\');
4086 #endif
4087 if(bname) bname++;
4088 else bname = buf;
4089 l = strlen(psub) + strlen(bname) + 1;
4090 psub = realloc(psub,l);
4091 strcat(psub,bname);
4092 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4093 free(psub);
4095 free(buf);
4097 if(vo_vobsub){
4098 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4099 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4100 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4102 // setup global sub numbering
4103 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4106 //============ Open & Sync STREAM --- fork cache2 ====================
4108 mpctx->stream=NULL;
4109 mpctx->demuxer=NULL;
4110 if (mpctx->d_audio) {
4111 //free_demuxer_stream(mpctx->d_audio);
4112 mpctx->d_audio=NULL;
4114 if (mpctx->d_video) {
4115 //free_demuxer_stream(d_video);
4116 mpctx->d_video=NULL;
4118 mpctx->sh_audio=NULL;
4119 mpctx->sh_video=NULL;
4121 current_module="open_stream";
4122 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4123 if(!mpctx->stream) { // error...
4124 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4125 goto goto_next_file;
4127 mpctx->initialized_flags|=INITIALIZED_STREAM;
4129 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4130 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4131 "playlist support will not be used automatically.\n"
4132 "MPlayer's playlist code is unsafe and should only be used with "
4133 "trusted sources.\nPlayback will probably fail.\n\n");
4134 #if 0
4135 play_tree_t* entry;
4136 // Handle playlist
4137 current_module="handle_playlist";
4138 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4139 filename_recode(mpctx->filename));
4140 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4141 mpctx->eof=playtree_add_playlist(mpctx, entry);
4142 goto goto_next_file;
4143 #endif
4145 mpctx->stream->start_pos+=seek_to_byte;
4147 if(stream_dump_type==5){
4148 unsigned char buf[4096];
4149 int len;
4150 FILE *f;
4151 current_module="dumpstream";
4152 stream_reset(mpctx->stream);
4153 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4154 f=fopen(opts->stream_dump_name,"wb");
4155 if(!f){
4156 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4157 exit_player(mpctx, EXIT_ERROR);
4159 if (opts->chapterrange[0] > 1) {
4160 int chapter = opts->chapterrange[0] - 1;
4161 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4163 while(!mpctx->stream->eof && !async_quit_request){
4164 len=stream_read(mpctx->stream,buf,4096);
4165 if(len>0) {
4166 if(fwrite(buf,len,1,f) != 1) {
4167 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4168 exit_player(mpctx, EXIT_ERROR);
4171 if (opts->chapterrange[1] > 0) {
4172 int chapter = -1;
4173 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4174 &chapter) == STREAM_OK
4175 && chapter + 1 > opts->chapterrange[1])
4176 break;
4179 if(fclose(f)) {
4180 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4181 exit_player(mpctx, EXIT_ERROR);
4183 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4184 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4187 #ifdef CONFIG_DVDREAD
4188 if(mpctx->stream->type==STREAMTYPE_DVD){
4189 current_module="dvd lang->id";
4190 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4191 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4192 // setup global sub numbering
4193 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4194 current_module=NULL;
4196 #endif
4198 #ifdef CONFIG_DVDNAV
4199 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4200 current_module="dvdnav lang->id";
4201 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4202 dvdsub_lang_id = -3;
4203 if(opts->sub_lang && opts->sub_id==-1)
4204 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4205 // setup global sub numbering
4206 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4207 current_module=NULL;
4209 #endif
4211 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4212 goto_enable_cache:
4213 if(stream_cache_size>0){
4214 int res;
4215 float stream_cache_min_percent = opts->stream_cache_min_percent;
4216 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4217 current_module="enable_cache";
4218 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4219 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4220 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4221 if(res == 0)
4222 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4225 //============ Open DEMUXERS --- DETECT file type =======================
4226 current_module="demux_open";
4228 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4230 // HACK to get MOV Reference Files working
4232 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4234 unsigned char* playlist_entry;
4235 play_tree_t *list = NULL, *entry = NULL;
4237 current_module="handle_demux_playlist";
4238 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4240 char *temp, *bname;
4242 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4243 filename_recode(playlist_entry));
4245 bname=mp_basename(playlist_entry);
4246 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4247 continue;
4249 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4250 continue;
4252 entry = play_tree_new();
4254 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4256 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4257 if (temp)
4259 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4260 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4261 strcat(temp, playlist_entry);
4262 if (!strcmp(temp, mpctx->filename)) {
4263 free(temp);
4264 continue;
4266 play_tree_add_file(entry,temp);
4267 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4268 free(temp);
4271 else
4272 play_tree_add_file(entry,playlist_entry);
4274 if(!list)
4275 list = entry;
4276 else
4277 play_tree_append_entry(list,entry);
4279 free_demuxer(mpctx->demuxer);
4280 mpctx->demuxer = NULL;
4282 if (list)
4284 entry = play_tree_new();
4285 play_tree_set_child(entry,list);
4286 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4287 goto goto_next_file;
4291 if(!mpctx->demuxer) {
4292 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4293 goto goto_next_file;
4296 if (mpctx->demuxer->matroska_data.ordered_chapters)
4297 build_ordered_chapter_timeline(mpctx);
4299 if (!mpctx->sources) {
4300 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4301 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4302 .demuxer = mpctx->demuxer};
4303 mpctx->num_sources = 1;
4306 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4308 #ifdef CONFIG_ASS
4309 if (opts->ass_enabled && ass_library) {
4310 for (int j = 0; j < mpctx->num_sources; j++) {
4311 struct demuxer *d = mpctx->sources[j].demuxer;
4312 for (int i = 0; i < d->num_attachments; i++) {
4313 struct demux_attachment *att = d->attachments + i;
4314 if (use_embedded_fonts && attachment_is_font(att))
4315 ass_add_font(ass_library, att->name, att->data, att->data_size);
4319 #endif
4321 current_module="demux_open2";
4323 mpctx->d_audio=mpctx->demuxer->audio;
4324 mpctx->d_video=mpctx->demuxer->video;
4325 mpctx->d_sub=mpctx->demuxer->sub;
4327 if (ts_prog) {
4328 int tmp = ts_prog;
4329 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4331 // select audio stream
4332 if (mpctx->num_sources)
4333 for (int i = 0; i < mpctx->num_sources; i++)
4334 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
4335 opts->audio_lang);
4336 else
4337 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
4339 // DUMP STREAMS:
4340 if((stream_dump_type)&&(stream_dump_type<4)){
4341 FILE *f;
4342 demux_stream_t *ds=NULL;
4343 current_module="dump";
4344 // select stream to dump
4345 switch(stream_dump_type){
4346 case 1: ds=mpctx->d_audio;break;
4347 case 2: ds=mpctx->d_video;break;
4348 case 3: ds=mpctx->d_sub;break;
4350 if(!ds){
4351 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4352 exit_player(mpctx, EXIT_ERROR);
4354 // disable other streams:
4355 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4356 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4357 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4358 // let's dump it!
4359 f=fopen(opts->stream_dump_name,"wb");
4360 if(!f){
4361 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4362 exit_player(mpctx, EXIT_ERROR);
4364 while(!ds->eof){
4365 unsigned char* start;
4366 int in_size=ds_get_packet(ds,&start);
4367 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4368 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4369 if(in_size>0) fwrite(start,in_size,1,f);
4370 if (opts->chapterrange[1] > 0) {
4371 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4372 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4373 break;
4376 fclose(f);
4377 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4378 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4381 mpctx->sh_audio=mpctx->d_audio->sh;
4382 mpctx->sh_video=mpctx->d_video->sh;
4384 if(mpctx->sh_video){
4386 current_module="video_read_properties";
4387 if(!video_read_properties(mpctx->sh_video)) {
4388 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4389 mpctx->sh_video=mpctx->d_video->sh=NULL;
4390 } else {
4391 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4392 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4393 mpctx->sh_video->fps,mpctx->sh_video->frametime
4396 /* need to set fps here for output encoders to pick it up in their init */
4397 if(force_fps){
4398 mpctx->sh_video->fps=force_fps;
4399 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4401 vo_fps = mpctx->sh_video->fps;
4403 if(!mpctx->sh_video->fps && !force_fps){
4404 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4405 mpctx->opts.correct_pts = 1;
4411 if(!mpctx->sh_video && !mpctx->sh_audio){
4412 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4413 #ifdef CONFIG_DVBIN
4414 if(mpctx->stream->type == STREAMTYPE_DVB)
4416 int dir;
4417 int v = mpctx->last_dvb_step;
4418 if(v > 0)
4419 dir = DVB_CHANNEL_HIGHER;
4420 else
4421 dir = DVB_CHANNEL_LOWER;
4423 if(dvb_step_channel(mpctx->stream, dir)) {
4424 mpctx->stop_play = PT_NEXT_ENTRY;
4425 mpctx->dvbin_reopen = 1;
4428 #endif
4429 goto goto_next_file; // exit_player(_("Fatal error"));
4432 /* display clip info */
4433 demux_info_print(mpctx->demuxer);
4435 //================== Read SUBTITLES (DVD & TEXT) ==========================
4436 if(vo_spudec==NULL &&
4437 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4438 init_vo_spudec(mpctx);
4441 // after reading video params we should load subtitles because
4442 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4443 // check .sub
4444 current_module="read_subtitles_file";
4445 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4446 if(sub_name){
4447 for (i = 0; sub_name[i] != NULL; ++i)
4448 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4450 if(sub_auto) { // auto load sub file ...
4451 char *psub = get_path( "sub/" );
4452 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4453 int i = 0;
4454 free(psub); // release the buffer created by get_path() above
4455 while (tmp[i]) {
4456 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4457 free(tmp[i++]);
4459 free(tmp);
4461 if (mpctx->set_of_sub_size > 0)
4462 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4464 if (select_subtitle(mpctx)) {
4465 if(subdata)
4466 switch (stream_dump_type) {
4467 case 3: list_sub_file(subdata); break;
4468 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
4469 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
4470 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
4471 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
4472 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
4476 print_file_properties(mpctx, mpctx->filename);
4478 if(!mpctx->sh_video) goto main; // audio-only
4480 if(!reinit_video_chain(mpctx)) {
4481 if(!mpctx->sh_video){
4482 if(!mpctx->sh_audio) goto goto_next_file;
4483 goto main; // exit_player(_("Fatal error"));
4487 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4488 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4490 #ifdef CONFIG_FREETYPE
4491 force_load_font = 1;
4492 #endif
4494 //================== MAIN: ==========================
4495 main:
4496 current_module="main";
4498 if (opts->playing_msg) {
4499 char* msg = property_expand_string(mpctx, opts->playing_msg);
4500 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4501 free(msg);
4505 // Disable the term OSD in verbose mode
4506 if (verbose)
4507 opts->term_osd = 0;
4511 // Make sure old OSD does not stay around,
4512 // e.g. with -fixed-vo and same-resolution files
4513 clear_osd_msgs();
4514 update_osd_msg(mpctx);
4516 //================ SETUP AUDIO ==========================
4518 if(mpctx->sh_audio){
4519 reinit_audio_chain(mpctx);
4520 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4521 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4524 current_module="av_init";
4526 if(mpctx->sh_video){
4527 mpctx->sh_video->timer=0;
4528 if (! ignore_start)
4529 audio_delay += mpctx->sh_video->stream_delay;
4531 if(mpctx->sh_audio){
4532 if (start_volume >= 0)
4533 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4534 if (! ignore_start)
4535 audio_delay -= mpctx->sh_audio->stream_delay;
4536 mpctx->delay=-audio_delay;
4539 if(!mpctx->sh_audio){
4540 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4541 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4542 ds_free_packs(mpctx->d_audio); // free buffered chunks
4543 //mpctx->d_audio->id=-2; // do not read audio chunks
4544 //uninit_player(mpctx, INITIALIZED_AO); // close device
4546 if(!mpctx->sh_video){
4547 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4548 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4549 ds_free_packs(mpctx->d_video);
4550 mpctx->d_video->id=-2;
4551 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4554 if (!mpctx->sh_video && !mpctx->sh_audio)
4555 goto goto_next_file;
4557 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4558 if(force_fps && mpctx->sh_video){
4559 vo_fps = mpctx->sh_video->fps=force_fps;
4560 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4561 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4564 mp_input_set_section(mpctx->input, NULL);
4565 //TODO: add desired (stream-based) sections here
4566 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4567 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4569 //==================== START PLAYING =======================
4571 if(opts->loop_times>1) opts->loop_times--; else
4572 if(opts->loop_times==1) opts->loop_times = -1;
4574 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4576 total_time_usage_start=GetTimer();
4577 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4578 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4579 play_n_frames=play_n_frames_mf;
4581 if(play_n_frames==0){
4582 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4585 mpctx->time_frame = 0;
4586 mpctx->drop_message_shown = 0;
4587 mpctx->restart_playback = true;
4588 mpctx->video_pts = 0;
4589 mpctx->hrseek_active = false;
4590 mpctx->hrseek_framedrop = false;
4591 mpctx->total_avsync_change = 0;
4592 mpctx->last_chapter_seek = -1;
4594 // If there's a timeline force an absolute seek to initialize state
4595 if (seek_to_sec || mpctx->timeline) {
4596 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4597 seek(mpctx, mpctx->seek);
4598 end_at.pos += seek_to_sec;
4600 if (opts->chapterrange[0] > 0) {
4601 double pts;
4602 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4603 && pts > -1.0) {
4604 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4605 seek(mpctx, mpctx->seek);
4609 if (end_at.type == END_AT_SIZE) {
4610 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4611 end_at.type = END_AT_NONE;
4614 #ifdef CONFIG_DVDNAV
4615 mp_dvdnav_context_free(mpctx);
4616 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4617 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4618 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4620 #endif
4622 mpctx->seek = (struct seek_params){0};
4623 get_relative_time(mpctx); // reset current delta
4624 // Make sure VO knows current pause state
4625 if (mpctx->sh_video)
4626 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4627 NULL);
4629 while (!mpctx->stop_play)
4630 run_playloop(mpctx);
4632 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4634 #ifdef CONFIG_DVBIN
4635 if(mpctx->dvbin_reopen)
4637 mpctx->stop_play = 0;
4638 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4639 cache_uninit(mpctx->stream);
4640 mpctx->dvbin_reopen = 0;
4641 goto goto_enable_cache;
4643 #endif
4646 goto_next_file: // don't jump here after ao/vo/getch initialization!
4648 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4650 if (opts->benchmark) {
4651 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4652 double total_time_usage;
4653 total_time_usage_start=GetTimer()-total_time_usage_start;
4654 total_time_usage = (float)total_time_usage_start*0.000001;
4655 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4656 video_time_usage,vout_time_usage,audio_time_usage,
4657 total_time_usage-tot,total_time_usage);
4658 if(total_time_usage>0.0)
4659 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4660 100.0*video_time_usage/total_time_usage,
4661 100.0*vout_time_usage/total_time_usage,
4662 100.0*audio_time_usage/total_time_usage,
4663 100.0*(total_time_usage-tot)/total_time_usage,
4664 100.0);
4665 if(total_frame_cnt && frame_dropping)
4666 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4667 total_frame_cnt-drop_frame_cnt,
4668 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4669 drop_frame_cnt,
4670 100*drop_frame_cnt/total_frame_cnt,
4671 total_frame_cnt,
4672 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4675 // time to uninit all, except global stuff:
4676 int uninitialize_parts = INITIALIZED_ALL;
4677 if (opts->fixed_vo)
4678 uninitialize_parts -= INITIALIZED_VO;
4679 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4680 uninitialize_parts -= INITIALIZED_AO;
4681 uninit_player(mpctx, uninitialize_parts);
4683 if(mpctx->set_of_sub_size > 0) {
4684 current_module="sub_free";
4685 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4686 sub_free(mpctx->set_of_subtitles[i]);
4687 #ifdef CONFIG_ASS
4688 if(mpctx->set_of_ass_tracks[i])
4689 ass_free_track( mpctx->set_of_ass_tracks[i] );
4690 #endif
4692 mpctx->set_of_sub_size = 0;
4694 vo_sub_last = vo_sub=NULL;
4695 subdata=NULL;
4696 #ifdef CONFIG_ASS
4697 ass_track = NULL;
4698 if(ass_library)
4699 ass_clear_fonts(ass_library);
4700 #endif
4702 if (!mpctx->stop_play) // In case some goto jumped here...
4703 mpctx->stop_play = PT_NEXT_ENTRY;
4705 int playtree_direction = 1;
4707 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4708 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4709 play_tree_iter_free(mpctx->playtree_iter);
4710 mpctx->playtree_iter = NULL;
4712 mpctx->play_tree_step = 1;
4713 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4714 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4715 if(mpctx->playtree_iter) {
4716 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4717 play_tree_iter_free(mpctx->playtree_iter);
4718 mpctx->playtree_iter = NULL;
4721 } else if (mpctx->stop_play == PT_STOP) {
4722 play_tree_iter_free(mpctx->playtree_iter);
4723 mpctx->playtree_iter = NULL;
4724 } else { // NEXT PREV SRC
4725 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4728 while(mpctx->playtree_iter != NULL) {
4729 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4730 if(mpctx->filename == NULL) {
4731 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4732 play_tree_iter_free(mpctx->playtree_iter);
4733 mpctx->playtree_iter = NULL;
4735 } else
4736 break;
4739 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4740 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4741 mpctx->stop_play = 0;
4742 goto play_next_file;
4746 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4748 return 1;
4750 #endif /* DISABLE_MAIN */