demux_demuxers: Fix crash with -audiofile and audio disabled
[mplayer/glamo.git] / mplayer.c
blob51ce9a8bf1f9dddb5beac1efdb7162daa7618f61
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 const void *mpctx_get_video_out(MPContext *mpctx)
366 return mpctx->video_out;
369 const void *mpctx_get_audio_out(MPContext *mpctx)
371 return mpctx->audio_out;
374 void *mpctx_get_demuxer(MPContext *mpctx)
376 return mpctx->demuxer;
379 void *mpctx_get_playtree_iter(MPContext *mpctx)
381 return mpctx->playtree_iter;
384 void *mpctx_get_mixer(MPContext *mpctx)
386 return &mpctx->mixer;
389 int mpctx_get_global_sub_size(MPContext *mpctx)
391 return mpctx->global_sub_size;
394 int mpctx_get_osd_function(MPContext *mpctx)
396 return mpctx->osd_function;
399 static float get_relative_time(struct MPContext *mpctx)
401 unsigned int new_time = GetTimer();
402 unsigned int delta = new_time - mpctx->last_time;
403 mpctx->last_time = new_time;
404 return delta * 0.000001;
407 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
408 switch (type)
410 /* check for valid video stream */
411 case META_VIDEO_CODEC:
412 case META_VIDEO_BITRATE:
413 case META_VIDEO_RESOLUTION:
415 if (!mpctx->sh_video)
416 return 0;
417 break;
420 /* check for valid audio stream */
421 case META_AUDIO_CODEC:
422 case META_AUDIO_BITRATE:
423 case META_AUDIO_SAMPLES:
425 if (!mpctx->sh_audio)
426 return 0;
427 break;
430 /* check for valid demuxer */
431 case META_INFO_TITLE:
432 case META_INFO_ARTIST:
433 case META_INFO_ALBUM:
434 case META_INFO_YEAR:
435 case META_INFO_COMMENT:
436 case META_INFO_TRACK:
437 case META_INFO_GENRE:
439 if (!mpctx->demuxer)
440 return 0;
441 break;
444 default:
445 break;
448 return 1;
451 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
452 char **info = mpctx->demuxer->info;
453 int n;
455 if (!info || !tag)
456 return NULL;
458 for (n = 0; info[2*n] != NULL ; n++)
459 if (!strcasecmp (info[2*n], tag))
460 break;
462 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
465 char *get_metadata(struct MPContext *mpctx, metadata_t type)
467 char *meta = NULL;
468 sh_audio_t * const sh_audio = mpctx->sh_audio;
469 sh_video_t * const sh_video = mpctx->sh_video;
471 if (!is_valid_metadata_type(mpctx, type))
472 return NULL;
474 switch (type)
476 case META_NAME:
478 return strdup(mp_basename(mpctx->filename));
481 case META_VIDEO_CODEC:
483 if (sh_video->format == 0x10000001)
484 meta = strdup ("mpeg1");
485 else if (sh_video->format == 0x10000002)
486 meta = strdup ("mpeg2");
487 else if (sh_video->format == 0x10000004)
488 meta = strdup ("mpeg4");
489 else if (sh_video->format == 0x10000005)
490 meta = strdup ("h264");
491 else if (sh_video->format >= 0x20202020)
493 meta = malloc (8);
494 sprintf (meta, "%.4s", (char *) &sh_video->format);
496 else
498 meta = malloc (8);
499 sprintf (meta, "0x%08X", sh_video->format);
501 return meta;
504 case META_VIDEO_BITRATE:
506 meta = malloc (16);
507 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
508 return meta;
511 case META_VIDEO_RESOLUTION:
513 meta = malloc (16);
514 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
515 return meta;
518 case META_AUDIO_CODEC:
520 if (sh_audio->codec && sh_audio->codec->name)
521 meta = strdup (sh_audio->codec->name);
522 return meta;
525 case META_AUDIO_BITRATE:
527 meta = malloc (16);
528 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
529 return meta;
532 case META_AUDIO_SAMPLES:
534 meta = malloc (16);
535 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
536 return meta;
539 /* check for valid demuxer */
540 case META_INFO_TITLE:
541 return get_demuxer_info(mpctx, "Title");
543 case META_INFO_ARTIST:
544 return get_demuxer_info(mpctx, "Artist");
546 case META_INFO_ALBUM:
547 return get_demuxer_info(mpctx, "Album");
549 case META_INFO_YEAR:
550 return get_demuxer_info(mpctx, "Year");
552 case META_INFO_COMMENT:
553 return get_demuxer_info(mpctx, "Comment");
555 case META_INFO_TRACK:
556 return get_demuxer_info(mpctx, "Track");
558 case META_INFO_GENRE:
559 return get_demuxer_info(mpctx, "Genre");
561 default:
562 break;
565 return meta;
568 static void print_file_properties(struct MPContext *mpctx, const char *filename)
570 double start_pts = MP_NOPTS_VALUE;
571 double video_start_pts = MP_NOPTS_VALUE;
572 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
573 filename_recode(filename));
574 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
575 if (mpctx->sh_video) {
576 /* Assume FOURCC if all bytes >= 0x20 (' ') */
577 if (mpctx->sh_video->format >= 0x20202020)
578 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
579 else
580 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
581 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
582 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
583 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
584 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
585 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
586 video_start_pts = ds_get_next_pts(mpctx->d_video);
588 if (mpctx->sh_audio) {
589 /* Assume FOURCC if all bytes >= 0x20 (' ') */
590 if (mpctx->sh_audio->format >= 0x20202020)
591 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
592 else
593 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
594 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
595 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
596 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
597 start_pts = ds_get_next_pts(mpctx->d_audio);
599 if (video_start_pts != MP_NOPTS_VALUE) {
600 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
601 (mpctx->sh_video && video_start_pts < start_pts))
602 start_pts = video_start_pts;
604 if (start_pts != MP_NOPTS_VALUE)
605 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
606 else
607 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
608 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
609 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
610 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
611 if (mpctx->demuxer) {
612 if (mpctx->demuxer->num_chapters == 0)
613 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
614 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
618 /// step size of mixer changes
619 int volstep = 3;
621 #ifdef CONFIG_DVDNAV
622 static void mp_dvdnav_context_free(MPContext *ctx){
623 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
624 ctx->nav_smpi = NULL;
625 free(ctx->nav_buffer);
626 ctx->nav_buffer = NULL;
627 ctx->nav_start = NULL;
628 ctx->nav_in_size = 0;
630 #endif
632 void uninit_player(struct MPContext *mpctx, unsigned int mask){
633 mask &= mpctx->initialized_flags;
635 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
637 if(mask&INITIALIZED_ACODEC){
638 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
639 current_module="uninit_acodec";
640 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
641 mpctx->sh_audio=NULL;
642 mpctx->mixer.afilter = NULL;
645 if(mask&INITIALIZED_VCODEC){
646 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
647 current_module="uninit_vcodec";
648 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
649 mpctx->sh_video=NULL;
650 #ifdef CONFIG_MENU
651 vf_menu=NULL;
652 #endif
655 if(mask&INITIALIZED_DEMUXER){
656 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
657 current_module="free_demuxer";
658 if (mpctx->num_sources) {
659 mpctx->demuxer = mpctx->sources[0].demuxer;
660 for (int i = 1; i < mpctx->num_sources; i++) {
661 free_stream(mpctx->sources[i].stream);
662 free_demuxer(mpctx->sources[i].demuxer);
665 talloc_free(mpctx->sources);
666 mpctx->sources = NULL;
667 mpctx->num_sources = 0;
668 talloc_free(mpctx->timeline);
669 mpctx->timeline = NULL;
670 mpctx->num_timeline_parts = 0;
671 talloc_free(mpctx->chapters);
672 mpctx->chapters = NULL;
673 mpctx->num_chapters = 0;
674 mpctx->video_offset = 0;
675 if(mpctx->demuxer){
676 mpctx->stream=mpctx->demuxer->stream;
677 free_demuxer(mpctx->demuxer);
679 mpctx->demuxer=NULL;
682 // kill the cache process:
683 if(mask&INITIALIZED_STREAM){
684 mpctx->initialized_flags&=~INITIALIZED_STREAM;
685 current_module="uninit_stream";
686 if(mpctx->stream) free_stream(mpctx->stream);
687 mpctx->stream=NULL;
690 if(mask&INITIALIZED_VO){
691 mpctx->initialized_flags&=~INITIALIZED_VO;
692 current_module="uninit_vo";
693 vo_destroy(mpctx->video_out);
694 mpctx->video_out=NULL;
695 #ifdef CONFIG_DVDNAV
696 mp_dvdnav_context_free(mpctx);
697 #endif
700 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
701 if(mask&INITIALIZED_GETCH2){
702 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
703 current_module="uninit_getch2";
704 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
705 // restore terminal:
706 getch2_disable();
709 if(mask&INITIALIZED_VOBSUB){
710 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
711 current_module="uninit_vobsub";
712 if(vo_vobsub) vobsub_close(vo_vobsub);
713 vo_vobsub=NULL;
716 if (mask&INITIALIZED_SPUDEC){
717 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
718 current_module="uninit_spudec";
719 spudec_free(vo_spudec);
720 vo_spudec=NULL;
723 if(mask&INITIALIZED_AO){
724 mpctx->initialized_flags&=~INITIALIZED_AO;
725 current_module="uninit_ao";
726 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
727 if (mpctx->audio_out)
728 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
729 mpctx->audio_out=NULL;
732 current_module=NULL;
735 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
737 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
738 uninit_player(mpctx, INITIALIZED_ALL);
739 #if defined(__MINGW32__) || defined(__CYGWIN__)
740 timeEndPeriod(1);
741 #endif
742 #ifdef CONFIG_X11
743 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
744 #endif
746 current_module="uninit_input";
747 mp_input_uninit(mpctx->input);
748 #ifdef CONFIG_MENU
749 if (use_menu)
750 menu_uninit();
751 #endif
753 #ifdef CONFIG_FREETYPE
754 current_module="uninit_font";
755 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
756 free_font_desc(mpctx->osd->sub_font);
757 free_font_desc(vo_font);
758 vo_font = NULL;
759 done_freetype();
760 #endif
761 osd_free(mpctx->osd);
763 #ifdef CONFIG_ASS
764 ass_library_done(ass_library);
765 ass_library = NULL;
766 #endif
768 current_module="exit_player";
770 // free mplayer config
771 if(mpctx->mconfig)
772 m_config_free(mpctx->mconfig);
773 mpctx->mconfig = NULL;
775 if(mpctx->playtree_iter)
776 play_tree_iter_free(mpctx->playtree_iter);
777 mpctx->playtree_iter = NULL;
778 if(mpctx->playtree)
779 play_tree_free(mpctx->playtree, 1);
780 mpctx->playtree = NULL;
782 talloc_free(mpctx->key_fifo);
784 free(edl_records); // free mem allocated for EDL
785 edl_records = NULL;
786 switch(how) {
787 case EXIT_QUIT:
788 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
789 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
790 break;
791 case EXIT_EOF:
792 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
793 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
794 break;
795 case EXIT_ERROR:
796 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
797 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
798 break;
799 default:
800 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
802 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
804 exit(rc);
807 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
809 exit_player_with_rc(mpctx, how, 1);
812 #ifndef __MINGW32__
813 static void child_sighandler(int x){
814 pid_t pid;
815 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
817 #endif
819 #ifdef CONFIG_CRASH_DEBUG
820 static char *prog_path;
821 static int crash_debug = 0;
822 #endif
824 static void exit_sighandler(int x){
825 static int sig_count=0;
826 #ifdef CONFIG_CRASH_DEBUG
827 if (!crash_debug || x != SIGTRAP)
828 #endif
829 ++sig_count;
830 if(sig_count==5)
832 /* We're crashing bad and can't uninit cleanly :(
833 * by popular request, we make one last (dirty)
834 * effort to restore the user's
835 * terminal. */
836 getch2_disable();
837 exit(1);
839 if(sig_count==6) exit(1);
840 if(sig_count>6){
841 // can't stop :(
842 #ifndef __MINGW32__
843 kill(getpid(),SIGKILL);
844 #endif
846 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
847 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
848 "\nMPlayer interrupted by signal %d in module: %s\n", x,
849 current_module ? current_module : "unknown");
850 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
851 if(sig_count<=1)
852 switch(x){
853 case SIGINT:
854 case SIGPIPE:
855 case SIGQUIT:
856 case SIGTERM:
857 case SIGKILL:
858 async_quit_request = 1;
859 return; // killed from keyboard (^C) or killed [-9]
860 case SIGILL:
861 #if CONFIG_RUNTIME_CPUDETECT
862 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
863 #else
864 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
865 #endif
866 case SIGFPE:
867 case SIGSEGV:
868 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
869 default:
870 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
871 #ifdef CONFIG_CRASH_DEBUG
872 if (crash_debug) {
873 int gdb_pid;
874 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
875 gdb_pid = fork();
876 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
877 if (gdb_pid == 0) { // We are the child
878 char spid[20];
879 snprintf(spid, sizeof(spid), "%i", getppid());
880 getch2_disable(); // allow terminal to work properly with gdb
881 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
882 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
883 } else if (gdb_pid < 0)
884 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
885 else {
886 waitpid(gdb_pid, NULL, 0);
888 if (x == SIGTRAP) return;
890 #endif
892 getch2_disable();
893 exit(1);
896 #include "cfg-mplayer.h"
898 static int cfg_include(m_option_t *conf, char *filename)
900 return m_config_parse_config_file(conf->priv, filename);
903 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
905 char *conffile;
906 int conffile_fd;
907 if (!disable_system_conf &&
908 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
909 exit_player(mpctx, EXIT_NONE);
910 if ((conffile = get_path("")) == NULL) {
911 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
912 } else {
913 #ifdef __MINGW32__
914 mkdir(conffile);
915 #else
916 mkdir(conffile, 0777);
917 #endif
918 free(conffile);
919 if ((conffile = get_path("config")) == NULL) {
920 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
921 } else {
922 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
923 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
924 write(conffile_fd, default_config, strlen(default_config));
925 close(conffile_fd);
927 if (!disable_user_conf &&
928 m_config_parse_config_file(conf, conffile) < 0)
929 exit_player(mpctx, EXIT_NONE);
930 free(conffile);
935 #define PROFILE_CFG_PROTOCOL "protocol."
937 static void load_per_protocol_config (m_config_t* conf, const char *const file)
939 char *str;
940 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
941 m_profile_t *p;
943 /* does filename actually uses a protocol ? */
944 str = strstr (file, "://");
945 if (!str)
946 return;
948 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
949 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
950 p = m_config_get_profile (conf, protocol);
951 if (p)
953 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
954 m_config_set_profile(conf,p);
958 #define PROFILE_CFG_EXTENSION "extension."
960 static void load_per_extension_config (m_config_t* conf, const char *const file)
962 char *str;
963 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
964 m_profile_t *p;
966 /* does filename actually have an extension ? */
967 str = strrchr (file, '.');
968 if (!str)
969 return;
971 sprintf (extension, PROFILE_CFG_EXTENSION);
972 strncat (extension, ++str, 7);
973 p = m_config_get_profile (conf, extension);
974 if (p)
976 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
977 m_config_set_profile(conf,p);
981 #define PROFILE_CFG_VO "vo."
982 #define PROFILE_CFG_AO "ao."
984 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
986 char profile[strlen (cfg) + strlen (out) + 1];
987 m_profile_t *p;
989 sprintf (profile, "%s%s", cfg, out);
990 p = m_config_get_profile (conf, profile);
991 if (p)
993 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
994 m_config_set_profile(conf,p);
999 * Tries to load a config file
1000 * @return 0 if file was not found, 1 otherwise
1002 static int try_load_config(m_config_t *conf, const char *file)
1004 struct stat st;
1005 if (stat(file, &st))
1006 return 0;
1007 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1008 m_config_parse_config_file (conf, file);
1009 return 1;
1012 static void load_per_file_config (m_config_t* conf, const char *const file)
1014 char *confpath;
1015 char cfg[PATH_MAX];
1016 const char *name;
1018 if (strlen(file) > PATH_MAX - 14) {
1019 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1020 return;
1022 sprintf (cfg, "%s.conf", file);
1024 name = mp_basename(cfg);
1025 if (use_filedir_conf) {
1026 char dircfg[PATH_MAX];
1027 strcpy(dircfg, cfg);
1028 strcpy(dircfg + (name - cfg), "mplayer.conf");
1029 try_load_config(conf, dircfg);
1031 if (try_load_config(conf, cfg))
1032 return;
1035 if ((confpath = get_path (name)) != NULL)
1037 try_load_config(conf, confpath);
1039 free (confpath);
1043 /* When libmpdemux performs a blocking operation (network connection or
1044 * cache filling) if the operation fails we use this function to check
1045 * if it was interrupted by the user.
1046 * The function returns a new value for eof. */
1047 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1049 mp_cmd_t* cmd;
1050 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1051 switch(cmd->id) {
1052 case MP_CMD_QUIT:
1053 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1054 case MP_CMD_PLAY_TREE_STEP: {
1055 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1056 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1057 } break;
1058 case MP_CMD_PLAY_TREE_UP_STEP: {
1059 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1060 } break;
1061 case MP_CMD_PLAY_ALT_SRC_STEP: {
1062 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1063 } break;
1065 mp_cmd_free(cmd);
1067 return stop_play;
1070 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1072 play_tree_add_bpf(entry,mpctx->filename);
1075 if(!entry) {
1076 entry = mpctx->playtree_iter->tree;
1077 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1078 return PT_NEXT_ENTRY;
1080 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1081 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1082 return PT_NEXT_ENTRY;
1085 play_tree_remove(entry,1,1);
1086 return PT_NEXT_SRC;
1088 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1089 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1090 entry = mpctx->playtree_iter->tree;
1091 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1092 return PT_NEXT_ENTRY;
1094 play_tree_remove(entry,1,1);
1096 return PT_NEXT_SRC;
1099 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1101 struct MPOpts *opts = &mpctx->opts;
1102 sub_data *subd = NULL;
1103 struct ass_track *asst = NULL;
1105 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1106 return;
1109 #ifdef CONFIG_ASS
1110 if (opts->ass_enabled) {
1111 #ifdef CONFIG_ICONV
1112 asst = ass_read_stream(ass_library, filename, sub_cp);
1113 #else
1114 asst = ass_read_stream(ass_library, filename, 0);
1115 #endif
1116 if (!asst) {
1117 subd = sub_read_file(filename, fps);
1118 if (subd) {
1119 asst = ass_read_subdata(ass_library, subd, fps);
1120 if (asst) {
1121 sub_free(subd);
1122 subd = NULL;
1126 } else
1127 #endif
1128 subd = sub_read_file(filename, fps);
1131 if (!asst && !subd) {
1132 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1133 "Cannot load subtitles: %s\n", filename_recode(filename));
1134 return;
1137 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1138 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1139 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1140 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1141 filename_recode(filename));
1142 ++mpctx->set_of_sub_size;
1143 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1144 filename_recode(filename));
1147 void init_vo_spudec(struct MPContext *mpctx)
1149 spudec_free(vo_spudec);
1150 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1151 vo_spudec = NULL;
1153 // we currently can't work without video stream
1154 if (!mpctx->sh_video)
1155 return;
1157 if (spudec_ifo) {
1158 unsigned int palette[16], width, height;
1159 current_module="spudec_init_vobsub";
1160 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1161 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1164 #ifdef CONFIG_DVDREAD
1165 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1166 current_module="spudec_init_dvdread";
1167 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1168 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1169 NULL, 0);
1171 #endif
1173 #ifdef CONFIG_DVDNAV
1174 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1175 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1176 current_module="spudec_init_dvdnav";
1177 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1179 #endif
1181 if (vo_spudec==NULL) {
1182 sh_sub_t *sh = mpctx->d_sub->sh;
1183 current_module="spudec_init_normal";
1184 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1185 spudec_set_font_factor(vo_spudec,font_factor);
1188 if (vo_spudec!=NULL) {
1189 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1190 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1195 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1196 * make it all work is to use the builtin SDL-bootstrap code, which
1197 * will be done automatically by replacing our main() if we include SDL.h.
1199 #if defined(__APPLE__) && defined(CONFIG_SDL)
1200 #ifdef CONFIG_SDL_SDL_H
1201 #include <SDL/SDL.h>
1202 #else
1203 #include <SDL.h>
1204 #endif
1205 #endif
1208 * \brief append a formatted string
1209 * \param buf buffer to print into
1210 * \param pos position of terminating 0 in buf
1211 * \param len maximum number of characters in buf, not including terminating 0
1212 * \param format printf format string
1214 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1216 va_list va;
1217 va_start(va, format);
1218 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1219 va_end(va);
1220 if (*pos >= len ) {
1221 buf[len] = 0;
1222 *pos = len;
1227 * \brief append time in the hh:mm:ss.f format
1228 * \param buf buffer to print into
1229 * \param pos position of terminating 0 in buf
1230 * \param len maximum number of characters in buf, not including terminating 0
1231 * \param time time value to convert/append
1233 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1234 int64_t tenths = 10 * time;
1235 int f1 = tenths % 10;
1236 int ss = (tenths / 10) % 60;
1237 int mm = (tenths / 600) % 60;
1238 int hh = tenths / 36000;
1239 if (time <= 0) {
1240 saddf(buf, pos, len, "unknown");
1241 return;
1243 if (hh > 0)
1244 saddf(buf, pos, len, "%2d:", hh);
1245 if (hh > 0 || mm > 0)
1246 saddf(buf, pos, len, "%02d:", mm);
1247 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1250 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1252 struct MPOpts *opts = &mpctx->opts;
1253 sh_video_t * const sh_video = mpctx->sh_video;
1255 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1256 a_pos = playing_audio_pts(mpctx);
1257 if (mpctx->sh_audio && sh_video && at_frame) {
1258 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1259 if (mpctx->time_frame > 0)
1260 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1261 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1262 && !mpctx->drop_message_shown) {
1263 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1264 mpctx->drop_message_shown = true;
1267 if (opts->quiet)
1268 return;
1271 int width;
1272 char *line;
1273 unsigned pos = 0;
1274 get_screen_size();
1275 if (screen_width > 0)
1276 width = screen_width;
1277 else
1278 width = 80;
1279 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1280 /* Windows command line is broken (MinGW's rxvt works, but we
1281 * should not depend on that). */
1282 width--;
1283 #endif
1284 line = malloc(width + 1); // one additional char for the terminating null
1286 // Audio time
1287 if (mpctx->sh_audio) {
1288 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1289 if (!sh_video) {
1290 float len = get_time_length(mpctx);
1291 saddf(line, &pos, width, "(");
1292 sadd_hhmmssf(line, &pos, width, a_pos);
1293 saddf(line, &pos, width, ") of %.1f (", len);
1294 sadd_hhmmssf(line, &pos, width, len);
1295 saddf(line, &pos, width, ") ");
1299 // Video time
1300 if (sh_video)
1301 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1303 // A-V sync
1304 if (mpctx->sh_audio && sh_video)
1305 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1306 mpctx->last_av_difference, mpctx->total_avsync_change);
1308 // Video stats
1309 if (sh_video)
1310 saddf(line, &pos, width, "%3d/%3d ",
1311 (int)sh_video->num_frames,
1312 (int)sh_video->num_frames_decoded);
1314 // CPU usage
1315 if (sh_video) {
1316 if (sh_video->timer > 0.5)
1317 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1318 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1319 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1320 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1321 else
1322 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1323 } else if (mpctx->sh_audio) {
1324 if (mpctx->delay > 0.5)
1325 saddf(line, &pos, width, "%4.1f%% ",
1326 100.0*audio_time_usage/(double)mpctx->delay);
1327 else
1328 saddf(line, &pos, width, "??,?%% ");
1331 // VO stats
1332 if (sh_video)
1333 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1335 #ifdef CONFIG_STREAM_CACHE
1336 // cache stats
1337 if (stream_cache_size > 0)
1338 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1339 #endif
1341 // other
1342 if (opts->playback_speed != 1)
1343 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1345 // end
1346 if (erase_to_end_of_line) {
1347 line[pos] = 0;
1348 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1349 } else {
1350 memset(&line[pos], ' ', width - pos);
1351 line[width] = 0;
1352 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1354 free(line);
1358 * \brief build a chain of audio filters that converts the input format
1359 * to the ao's format, taking into account the current playback_speed.
1360 * \param sh_audio describes the requested input format of the chain.
1361 * \param ao_data describes the requested output format of the chain.
1363 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1364 ao_data_t *ao_data)
1366 struct MPOpts *opts = &mpctx->opts;
1367 int new_srate;
1368 int result;
1369 if (!sh_audio)
1371 mpctx->mixer.afilter = NULL;
1372 return 0;
1374 if(af_control_any_rev(sh_audio->afilter,
1375 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1376 &opts->playback_speed)) {
1377 new_srate = sh_audio->samplerate;
1378 } else {
1379 new_srate = sh_audio->samplerate * opts->playback_speed;
1380 if (new_srate != ao_data->samplerate) {
1381 // limits are taken from libaf/af_resample.c
1382 if (new_srate < 8000)
1383 new_srate = 8000;
1384 if (new_srate > 192000)
1385 new_srate = 192000;
1386 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1389 result = init_audio_filters(sh_audio, new_srate,
1390 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1391 mpctx->mixer.afilter = sh_audio->afilter;
1392 return result;
1396 typedef struct mp_osd_msg mp_osd_msg_t;
1397 struct mp_osd_msg {
1398 /// Previous message on the stack.
1399 mp_osd_msg_t* prev;
1400 /// Message text.
1401 char msg[128];
1402 int id,level,started;
1403 /// Display duration in ms.
1404 unsigned time;
1407 /// OSD message stack.
1408 static mp_osd_msg_t* osd_msg_stack = NULL;
1411 * \brief Add a message on the OSD message stack
1413 * If a message with the same id is already present in the stack
1414 * it is pulled on top of the stack, otherwise a new message is created.
1417 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1418 va_list ap)
1420 mp_osd_msg_t *msg,*last=NULL;
1421 int r;
1423 // look if the id is already in the stack
1424 for(msg = osd_msg_stack ; msg && msg->id != id ;
1425 last = msg, msg = msg->prev);
1426 // not found: alloc it
1427 if(!msg) {
1428 msg = calloc(1,sizeof(mp_osd_msg_t));
1429 msg->prev = osd_msg_stack;
1430 osd_msg_stack = msg;
1431 } else if(last) { // found, but it's not on top of the stack
1432 last->prev = msg->prev;
1433 msg->prev = osd_msg_stack;
1434 osd_msg_stack = msg;
1436 // write the msg
1437 r = vsnprintf(msg->msg, 128, fmt, ap);
1438 if(r >= 128) msg->msg[127] = 0;
1439 // set id and time
1440 msg->id = id;
1441 msg->level = level;
1442 msg->time = time;
1446 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1448 va_list ap;
1449 va_start(ap, fmt);
1450 set_osd_msg_va(id, level, time, fmt, ap);
1451 va_end(ap);
1454 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1456 va_list ap;
1457 va_start(ap, fmt);
1458 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1459 va_end(ap);
1464 * \brief Remove a message from the OSD stack
1466 * This function can be used to get rid of a message right away.
1470 void rm_osd_msg(int id) {
1471 mp_osd_msg_t *msg,*last=NULL;
1473 // Search for the msg
1474 for(msg = osd_msg_stack ; msg && msg->id != id ;
1475 last = msg, msg = msg->prev);
1476 if(!msg) return;
1478 // Detach it from the stack and free it
1479 if(last)
1480 last->prev = msg->prev;
1481 else
1482 osd_msg_stack = msg->prev;
1483 free(msg);
1487 * \brief Remove all messages from the OSD stack
1491 static void clear_osd_msgs(void) {
1492 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1493 while(msg) {
1494 prev = msg->prev;
1495 free(msg);
1496 msg = prev;
1498 osd_msg_stack = NULL;
1502 * \brief Get the current message from the OSD stack.
1504 * This function decrements the message timer and destroys the old ones.
1505 * The message that should be displayed is returned (if any).
1509 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1511 struct MPOpts *opts = &mpctx->opts;
1512 mp_osd_msg_t *msg,*prev,*last = NULL;
1513 static unsigned last_update = 0;
1514 unsigned now = GetTimerMS();
1515 unsigned diff;
1516 char hidden_dec_done = 0;
1518 if (mpctx->osd_visible) {
1519 // 36000000 means max timed visibility is 1 hour into the future, if
1520 // the difference is greater assume it's wrapped around from below 0
1521 if (mpctx->osd_visible - now > 36000000) {
1522 mpctx->osd_visible = 0;
1523 vo_osd_progbar_type = -1; // disable
1524 vo_osd_changed(OSDTYPE_PROGBAR);
1525 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1528 if (mpctx->osd_show_percentage_until - now > 36000000)
1529 mpctx->osd_show_percentage_until = 0;
1531 if(!last_update) last_update = now;
1532 diff = now >= last_update ? now - last_update : 0;
1534 last_update = now;
1536 // Look for the first message in the stack with high enough level.
1537 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1538 prev = msg->prev;
1539 if (msg->level > opts->osd_level && hidden_dec_done)
1540 continue;
1541 // The message has a high enough level or it is the first hidden one
1542 // in both cases we decrement the timer or kill it.
1543 if(!msg->started || msg->time > diff) {
1544 if(msg->started) msg->time -= diff;
1545 else msg->started = 1;
1546 // display it
1547 if (msg->level <= opts->osd_level)
1548 return msg;
1549 hidden_dec_done = 1;
1550 continue;
1552 // kill the message
1553 free(msg);
1554 if(last) {
1555 last->prev = prev;
1556 msg = last;
1557 } else {
1558 osd_msg_stack = prev;
1559 msg = NULL;
1562 // Nothing found
1563 return NULL;
1567 * \brief Display the OSD bar.
1569 * Display the OSD bar or fall back on a simple message.
1573 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1574 struct MPOpts *opts = &mpctx->opts;
1575 if (opts->osd_level < 1)
1576 return;
1578 if(mpctx->sh_video) {
1579 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1580 vo_osd_progbar_type = type;
1581 vo_osd_progbar_value = 256*(val-min)/(max-min);
1582 vo_osd_changed(OSDTYPE_PROGBAR);
1583 return;
1586 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1587 name, ROUND(100*(val-min)/(max-min)));
1591 * \brief Display text subtitles on the OSD
1593 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1595 int i;
1596 vo_sub = subs;
1597 vo_osd_changed(OSDTYPE_SUBTITLE);
1598 if (!mpctx->sh_video) {
1599 // reverse order, since newest set_osd_msg is displayed first
1600 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1601 if (!subs || i >= subs->lines || !subs->text[i])
1602 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1603 else {
1604 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1605 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1606 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1613 * \brief Update the OSD message line.
1615 * This function displays the current message on the vo OSD or on the term.
1616 * If the stack is empty and the OSD level is high enough the timer
1617 * is displayed (only on the vo OSD).
1621 static void update_osd_msg(struct MPContext *mpctx)
1623 struct MPOpts *opts = &mpctx->opts;
1624 mp_osd_msg_t *msg;
1625 struct osd_state *osd = mpctx->osd;
1626 char osd_text_timer[128];
1628 if (mpctx->add_osd_seek_info) {
1629 double percentage = get_percent_pos(mpctx);
1630 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1631 if (mpctx->sh_video)
1632 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1633 mpctx->add_osd_seek_info = false;
1636 // Look if we have a msg
1637 if((msg = get_osd_msg(mpctx))) {
1638 if (strcmp(osd->osd_text, msg->msg)) {
1639 strncpy(osd->osd_text, msg->msg, 127);
1640 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1641 if(opts->term_osd)
1642 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1643 msg->msg);
1645 return;
1648 if(mpctx->sh_video) {
1649 // fallback on the timer
1650 if (opts->osd_level >= 2) {
1651 int len = get_time_length(mpctx);
1652 int percentage = -1;
1653 char percentage_text[10];
1654 int pts = get_current_time(mpctx);
1656 if (mpctx->osd_show_percentage_until)
1657 percentage = get_percent_pos(mpctx);
1659 if (percentage >= 0)
1660 snprintf(percentage_text, 9, " (%d%%)", percentage);
1661 else
1662 percentage_text[0] = 0;
1664 if (opts->osd_level == 3)
1665 snprintf(osd_text_timer, 63,
1666 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1667 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1668 len/3600,(len/60)%60,len%60,percentage_text);
1669 else
1670 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1671 mpctx->osd_function,pts/3600,(pts/60)%60,
1672 pts%60,percentage_text);
1673 } else
1674 osd_text_timer[0]=0;
1676 if (strcmp(osd->osd_text, osd_text_timer)) {
1677 strncpy(osd->osd_text, osd_text_timer, 63);
1678 vo_osd_changed(OSDTYPE_OSD);
1680 return;
1683 // Clear the term osd line
1684 if (opts->term_osd && osd->osd_text[0]) {
1685 osd->osd_text[0] = 0;
1686 printf("%s\n", opts->term_osd_esc);
1690 ///@}
1691 // OSDMsgStack
1694 void reinit_audio_chain(struct MPContext *mpctx)
1696 struct MPOpts *opts = &mpctx->opts;
1697 if (!mpctx->sh_audio)
1698 return;
1699 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1700 current_module="init_audio_codec";
1701 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1702 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1703 goto init_error;
1705 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1706 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1710 current_module="af_preinit";
1711 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1712 ao_data.samplerate=force_srate;
1713 ao_data.channels=0;
1714 ao_data.format = opts->audio_output_format;
1716 // first init to detect best values
1717 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1718 // input:
1719 mpctx->sh_audio->samplerate,
1720 // output:
1721 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1722 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1723 "pre-init!\n");
1724 exit_player(mpctx, EXIT_ERROR);
1726 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1727 current_module="ao2_init";
1728 ao_data.buffersize = opts->ao_buffersize;
1729 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1730 0, // plugin flag
1731 ao_data.samplerate,
1732 ao_data.channels,
1733 ao_data.format, 0);
1734 if(!mpctx->audio_out){
1735 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1736 goto init_error;
1738 mpctx->initialized_flags|=INITIALIZED_AO;
1739 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1740 mpctx->audio_out->info->short_name,
1741 ao_data.samplerate, ao_data.channels,
1742 af_fmt2str_short(ao_data.format),
1743 af_fmt2bits(ao_data.format)/8 );
1744 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1745 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1746 if(strlen(mpctx->audio_out->info->comment) > 0)
1747 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1750 // init audio filters:
1751 current_module="af_init";
1752 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1753 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1754 goto init_error;
1756 mpctx->mixer.audio_out = mpctx->audio_out;
1757 mpctx->mixer.volstep = volstep;
1758 mpctx->syncing_audio = true;
1759 return;
1761 init_error:
1762 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1763 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1764 mpctx->d_audio->id = -2;
1768 ///@}
1769 // Command2Property
1772 // Return pts value corresponding to the end point of audio written to the
1773 // ao so far.
1774 static double written_audio_pts(struct MPContext *mpctx)
1776 sh_audio_t *sh_audio = mpctx->sh_audio;
1777 demux_stream_t *d_audio = mpctx->d_audio;
1778 double buffered_output;
1779 // first calculate the end pts of audio that has been output by decoder
1780 double a_pts = sh_audio->pts;
1781 if (a_pts != MP_NOPTS_VALUE)
1782 // Good, decoder supports new way of calculating audio pts.
1783 // sh_audio->pts is the timestamp of the latest input packet with
1784 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1785 // the amount of bytes the decoder has written after that timestamp.
1786 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1787 else {
1788 // Decoder doesn't support new way of calculating pts (or we're
1789 // being called before it has decoded anything with known timestamp).
1790 // Use the old method of audio pts calculation: take the timestamp
1791 // of last packet with known pts the decoder has read data from,
1792 // and add amount of bytes read after the beginning of that packet
1793 // divided by input bps. This will be inaccurate if the input/output
1794 // ratio is not constant for every audio packet or if it is constant
1795 // but not accurately known in sh_audio->i_bps.
1797 a_pts = d_audio->pts;
1798 // ds_tell_pts returns bytes read after last timestamp from
1799 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1800 // it has read but not decoded
1801 if (sh_audio->i_bps)
1802 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1803 (double)sh_audio->i_bps;
1805 // Now a_pts hopefully holds the pts for end of audio from decoder.
1806 // Substract data in buffers between decoder and audio out.
1808 // Decoded but not filtered
1809 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1811 // Data buffered in audio filters, measured in bytes of "missing" output
1812 buffered_output = af_calc_delay(sh_audio->afilter);
1814 // Data that was ready for ao but was buffered because ao didn't fully
1815 // accept everything to internal buffers yet
1816 buffered_output += sh_audio->a_out_buffer_len;
1818 // Filters divide audio length by playback_speed, so multiply by it
1819 // to get the length in original units without speedup or slowdown
1820 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1822 return a_pts + mpctx->video_offset;
1825 // Return pts value corresponding to currently playing audio.
1826 double playing_audio_pts(struct MPContext *mpctx)
1828 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1829 mpctx->audio_out->get_delay();
1832 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1833 struct MPOpts *opts = &mpctx->opts;
1834 // check for frame-drop:
1835 current_module = "check_framedrop";
1836 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1837 static int dropped_frames;
1838 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1839 float d = delay-mpctx->delay;
1840 ++total_frame_cnt;
1841 // we should avoid dropping too many frames in sequence unless we
1842 // are too late. and we allow 100ms A-V delay here:
1843 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1844 && !mpctx->restart_playback) {
1845 ++drop_frame_cnt;
1846 ++dropped_frames;
1847 return frame_dropping;
1848 } else
1849 dropped_frames = 0;
1851 return 0;
1855 #ifdef HAVE_RTC
1856 int rtc_fd = -1;
1857 #endif
1859 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1861 #ifdef HAVE_RTC
1862 if (rtc_fd >= 0){
1863 // -------- RTC -----------
1864 current_module="sleep_rtc";
1865 while (time_frame > 0.000) {
1866 unsigned long rtc_ts;
1867 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1868 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1869 time_frame -= get_relative_time(mpctx);
1871 } else
1872 #endif
1874 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1875 // unnecessarily high CPU usage
1876 struct MPOpts *opts = &mpctx->opts;
1877 float margin = opts->softsleep ? 0.011 : 0;
1878 current_module = "sleep_timer";
1879 while (time_frame > margin) {
1880 usec_sleep(1000000 * (time_frame - margin));
1881 time_frame -= get_relative_time(mpctx);
1883 if (opts->softsleep){
1884 current_module = "sleep_soft";
1885 if (time_frame < 0)
1886 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1887 while (time_frame > 0)
1888 time_frame -= get_relative_time(mpctx); // burn the CPU
1891 return time_frame;
1894 static int select_subtitle(MPContext *mpctx)
1896 struct MPOpts *opts = &mpctx->opts;
1897 // find the best sub to use
1898 int id;
1899 int found = 0;
1900 mpctx->global_sub_pos = -1; // no subs by default
1901 if (vobsub_id >= 0) {
1902 // if user asks for a vobsub id, use that first.
1903 id = vobsub_id;
1904 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1907 if (!found && opts->sub_id >= 0) {
1908 // if user asks for a dvd sub id, use that next.
1909 id = opts->sub_id;
1910 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1913 if (!found) {
1914 // if there are text subs to use, use those. (autosubs come last here)
1915 id = 0;
1916 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1919 if (!found && opts->sub_id == -1) {
1920 // finally select subs by language and container hints
1921 if (opts->sub_id == -1)
1922 opts->sub_id =
1923 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
1924 opts->sub_lang);
1925 if (opts->sub_id >= 0) {
1926 id = opts->sub_id;
1927 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1930 return found;
1933 #ifdef CONFIG_DVDNAV
1934 #ifndef FF_B_TYPE
1935 #define FF_B_TYPE 3
1936 #endif
1937 /// store decoded video image
1938 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1939 mp_image_t *from_mpi) {
1940 mp_image_t *mpi;
1942 /// Do not store B-frames
1943 if (from_mpi->pict_type == FF_B_TYPE)
1944 return to_mpi;
1946 if (to_mpi &&
1947 to_mpi->w == from_mpi->w &&
1948 to_mpi->h == from_mpi->h &&
1949 to_mpi->imgfmt == from_mpi->imgfmt)
1950 mpi = to_mpi;
1951 else {
1952 if (to_mpi)
1953 free_mp_image(to_mpi);
1954 if (from_mpi->w == 0 || from_mpi->h == 0)
1955 return NULL;
1956 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1959 copy_mpi(mpi,from_mpi);
1960 return mpi;
1963 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1964 struct MPOpts *opts = &ctx->opts;
1965 if (ctx->sh_video) {
1966 /// clear video pts
1967 ctx->d_video->pts = 0.0f;
1968 ctx->sh_video->pts = 0.0f;
1969 ctx->sh_video->i_pts = 0.0f;
1970 ctx->sh_video->last_pts = 0.0f;
1971 ctx->sh_video->num_buffered_pts = 0;
1972 ctx->sh_video->num_frames = 0;
1973 ctx->sh_video->num_frames_decoded = 0;
1974 ctx->sh_video->timer = 0.0f;
1975 ctx->sh_video->stream_delay = 0.0f;
1976 ctx->sh_video->timer = 0;
1977 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1980 if (ctx->sh_audio) {
1981 /// free audio packets and reset
1982 ds_free_packs(ctx->d_audio);
1983 audio_delay -= ctx->sh_audio->stream_delay;
1984 ctx->delay =- audio_delay;
1985 ctx->audio_out->reset();
1986 resync_audio_stream(ctx->sh_audio);
1989 audio_delay = 0.0f;
1990 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
1991 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
1992 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
1993 if (dvdsub_lang_id != opts->sub_id) {
1994 opts->sub_id = dvdsub_lang_id;
1995 select_subtitle(ctx);
1999 /// clear all EOF related flags
2000 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2003 /// Restore last decoded DVDNAV (still frame)
2004 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2005 int *in_size,
2006 unsigned char **start,
2007 mp_image_t *decoded_frame)
2009 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2010 return decoded_frame;
2012 /// a change occured in dvdnav stream
2013 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2014 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2015 mp_dvdnav_context_free(mpctx);
2016 mp_dvdnav_reset_stream(mpctx);
2017 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2018 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2021 if (*in_size < 0) {
2022 float len;
2024 /// Display still frame, if any
2025 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2026 decoded_frame = mpctx->nav_smpi;
2028 /// increment video frame : continue playing after still frame
2029 len = get_time_length(mpctx);
2030 if (mpctx->sh_video->pts >= len &&
2031 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2032 mp_dvdnav_skip_still(mpctx->stream);
2033 mp_dvdnav_skip_wait(mpctx->stream);
2035 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2037 if (mpctx->nav_buffer) {
2038 *start = mpctx->nav_start;
2039 *in_size = mpctx->nav_in_size;
2040 if (mpctx->nav_start)
2041 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2045 return decoded_frame;
2048 /// Save last decoded DVDNAV (still frame)
2049 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2050 unsigned char *start,
2051 mp_image_t *decoded_frame)
2053 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2054 return;
2056 free(mpctx->nav_buffer);
2058 mpctx->nav_buffer = malloc(in_size);
2059 mpctx->nav_start = start;
2060 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2061 if (mpctx->nav_buffer)
2062 memcpy(mpctx->nav_buffer,start,in_size);
2064 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2065 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2067 #endif /* CONFIG_DVDNAV */
2069 /* Modify video timing to match the audio timeline. There are two main
2070 * reasons this is needed. First, video and audio can start from different
2071 * positions at beginning of file or after a seek (MPlayer starts both
2072 * immediately even if they have different pts). Second, the file can have
2073 * audio timestamps that are inconsistent with the duration of the audio
2074 * packets, for example two consecutive timestamp values differing by
2075 * one second but only a packet with enough samples for half a second
2076 * of playback between them.
2078 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2080 current_module = "av_sync";
2082 if (!mpctx->sh_audio || mpctx->syncing_audio)
2083 return;
2085 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2086 double v_pts = mpctx->sh_video->pts;
2087 double av_delay = a_pts - v_pts;
2088 // Try to sync vo_flip() so it will *finish* at given time
2089 av_delay += mpctx->last_vo_flip_duration;
2090 av_delay -= audio_delay; // This much pts difference is desired
2092 double change = av_delay * 0.1;
2093 double max_change = default_max_pts_correction >= 0 ?
2094 default_max_pts_correction : frame_time * 0.1;
2095 if (change < -max_change)
2096 change = -max_change;
2097 else if (change > max_change)
2098 change = max_change;
2099 mpctx->delay += change;
2100 mpctx->total_avsync_change += change;
2103 #define ASYNC_PLAY_DONE -3
2104 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2106 struct MPOpts *opts = &mpctx->opts;
2107 sh_audio_t * const sh_audio = mpctx->sh_audio;
2108 int res;
2110 // Timing info may not be set without
2111 res = decode_audio(sh_audio, 1);
2112 if (res < 0)
2113 return res;
2115 int bytes;
2116 while (1) {
2117 double written_pts = written_audio_pts(mpctx);
2118 double ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2119 - audio_delay;
2120 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2121 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2123 if (fabs(ptsdiff) > 300 // pts reset or just broken?
2124 || written_pts <= 0) // ogg demuxers give packets without timing
2125 bytes = 0;
2127 if (bytes > 0)
2128 break;
2130 mpctx->syncing_audio = false;
2131 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2132 int res = decode_audio(sh_audio, a);
2133 bytes += sh_audio->a_out_buffer_len;
2134 if (bytes >= 0) {
2135 memmove(sh_audio->a_out_buffer,
2136 sh_audio->a_out_buffer +
2137 sh_audio->a_out_buffer_len - bytes,
2138 bytes);
2139 sh_audio->a_out_buffer_len = bytes;
2140 if (res < 0)
2141 return res;
2142 return decode_audio(sh_audio, playsize);
2144 sh_audio->a_out_buffer_len = 0;
2145 if (res < 0)
2146 return res;
2148 int fillbyte = 0;
2149 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2150 fillbyte = 0x80;
2151 if (bytes >= playsize) {
2152 /* This case could fall back to the one below with
2153 * bytes = playsize, but then silence would keep accumulating
2154 * in a_out_buffer if the AO accepts less data than it asks for
2155 * in playsize. */
2156 char *p = malloc(playsize);
2157 memset(p, fillbyte, playsize);
2158 playsize = mpctx->audio_out->play(p, playsize, 0);
2159 free(p);
2160 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2161 return ASYNC_PLAY_DONE;
2163 mpctx->syncing_audio = false;
2164 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2165 return decode_audio(sh_audio, playsize);
2168 static int fill_audio_out_buffers(struct MPContext *mpctx)
2170 struct MPOpts *opts = &mpctx->opts;
2171 unsigned int t;
2172 double tt;
2173 int playsize;
2174 int playflags=0;
2175 int audio_eof=0;
2176 bool format_change = false;
2177 sh_audio_t * const sh_audio = mpctx->sh_audio;
2179 current_module="play_audio";
2181 while (1) {
2182 int sleep_time;
2183 // all the current uses of ao_data.pts seem to be in aos that handle
2184 // sync completely wrong; there should be no need to use ao_data.pts
2185 // in get_space()
2186 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2187 playsize = mpctx->audio_out->get_space();
2188 if (mpctx->sh_video || playsize >= ao_data.outburst)
2189 break;
2191 // handle audio-only case:
2192 // this is where mplayer sleeps during audio-only playback
2193 // to avoid 100% CPU use
2194 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2195 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2196 usec_sleep(sleep_time * 1000);
2199 // Fill buffer if needed:
2200 current_module="decode_audio";
2201 t = GetTimer();
2203 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2204 mpctx->syncing_audio = false;
2206 int res;
2207 if (mpctx->syncing_audio && mpctx->sh_video)
2208 res = audio_start_sync(mpctx, playsize);
2209 else
2210 res = decode_audio(sh_audio, playsize);
2211 if (res < 0) { // EOF, error or format change
2212 if (res == -2)
2213 format_change = true;
2214 else if (res == ASYNC_PLAY_DONE)
2215 return 1;
2216 else if (mpctx->d_audio->eof) {
2217 audio_eof = 1;
2218 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2219 if (sh_audio->a_out_buffer_len < unitsize)
2220 return 0;
2223 t = GetTimer() - t;
2224 tt = t*0.000001f; audio_time_usage+=tt;
2225 if (playsize > sh_audio->a_out_buffer_len) {
2226 playsize = sh_audio->a_out_buffer_len;
2227 if (audio_eof)
2228 playflags |= AOPLAY_FINAL_CHUNK;
2230 if (!playsize)
2231 return 1;
2233 // play audio:
2234 current_module="play_audio";
2236 // Is this pts value actually useful for the aos that access it?
2237 // They're obviously badly broken in the way they handle av sync;
2238 // would not having access to this make them more broken?
2239 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2240 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2242 if (playsize > 0) {
2243 sh_audio->a_out_buffer_len -= playsize;
2244 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2245 sh_audio->a_out_buffer_len);
2246 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2248 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2249 // Sanity check to avoid hanging in case current ao doesn't output
2250 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2251 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2252 sh_audio->a_out_buffer_len = 0;
2255 /* The format change isn't handled too gracefully. A more precise
2256 * implementation would require draining buffered old-format audio
2257 * while displaying video, then doing the output format switch.
2259 if (format_change) {
2260 uninit_player(mpctx, INITIALIZED_AO);
2261 reinit_audio_chain(mpctx);
2264 return 1;
2267 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2268 float *aq_sleep_time)
2270 struct MPOpts *opts = &mpctx->opts;
2271 int frame_time_remaining = 0;
2272 current_module="calc_sleep_time";
2274 *time_frame -= get_relative_time(mpctx); // reset timer
2276 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2277 float delay = mpctx->audio_out->get_delay();
2278 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2280 if (opts->autosync) {
2282 * Adjust this raw delay value by calculating the expected
2283 * delay for this frame and generating a new value which is
2284 * weighted between the two. The higher autosync is, the
2285 * closer to the delay value gets to that which "-nosound"
2286 * would have used, and the longer it will take for A/V
2287 * sync to settle at the right value (but it eventually will.)
2288 * This settling time is very short for values below 100.
2290 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2291 float difference = delay - predicted;
2292 delay = predicted + difference / (float)opts->autosync;
2295 *time_frame = delay - mpctx->delay / opts->playback_speed;
2296 *time_frame -= mpctx->video_out->flip_queue_offset;
2298 // delay = amount of audio buffered in soundcard/driver
2299 if (delay > 0.25) delay=0.25; else
2300 if (delay < 0.10) delay=0.10;
2302 if (*time_frame > delay*0.6) {
2303 // sleep time too big - may cause audio drops (buffer underrun)
2304 frame_time_remaining = 1;
2305 *time_frame = delay*0.5;
2307 } else {
2308 // If we're lagging more than 200 ms behind the right playback rate,
2309 // don't try to "catch up".
2310 // If benchmark is set always output frames as fast as possible
2311 // without sleeping.
2312 if (*time_frame < -0.2 || opts->benchmark)
2313 *time_frame = 0;
2314 *time_frame -= mpctx->video_out->flip_queue_offset;
2317 *aq_sleep_time += *time_frame;
2320 //============================== SLEEP: ===================================
2322 // flag 256 means: libvo driver does its timing (dvb card)
2323 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2324 *time_frame = timing_sleep(mpctx, *time_frame);
2325 *time_frame += mpctx->video_out->flip_queue_offset;
2326 return frame_time_remaining;
2329 int reinit_video_chain(struct MPContext *mpctx)
2331 struct MPOpts *opts = &mpctx->opts;
2332 sh_video_t * const sh_video = mpctx->sh_video;
2333 double ar=-1.0;
2334 //================== Init VIDEO (codec & libvo) ==========================
2335 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2336 current_module="preinit_libvo";
2338 //shouldn't we set dvideo->id=-2 when we fail?
2339 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2340 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2341 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2342 goto err_out;
2344 mpctx->initialized_flags|=INITIALIZED_VO;
2347 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2348 mpctx->sh_video->stream_aspect = ar;
2349 current_module="init_video_filters";
2351 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2352 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2354 #ifdef CONFIG_MENU
2355 if(use_menu) {
2356 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2357 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2358 if(!vf_menu) {
2359 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2360 use_menu = 0;
2363 if(vf_menu)
2364 sh_video->vfilter = vf_menu;
2365 #endif
2367 #ifdef CONFIG_ASS
2368 if(opts->ass_enabled) {
2369 int i;
2370 int insert = 1;
2371 if (opts->vf_settings)
2372 for (i = 0; opts->vf_settings[i].name; ++i)
2373 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2374 insert = 0;
2375 break;
2377 if (insert) {
2378 extern vf_info_t vf_info_ass;
2379 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2380 char* vf_arg[] = {"auto", "1", NULL};
2381 int retcode = 0;
2382 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2383 sh_video->vfilter,
2384 "ass", vf_arg,
2385 &retcode);
2386 if (vf_ass)
2387 sh_video->vfilter = vf_ass;
2388 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2389 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2390 else
2391 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2394 #endif
2396 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2398 #ifdef CONFIG_ASS
2399 if (opts->ass_enabled)
2400 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2401 #endif
2403 current_module="init_video_codec";
2405 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2406 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2407 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2409 if(!sh_video->initialized){
2410 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2411 goto err_out;
2414 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2416 if (sh_video->codec)
2417 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2419 sh_video->last_pts = MP_NOPTS_VALUE;
2420 sh_video->num_buffered_pts = 0;
2421 sh_video->next_frame_time = 0;
2423 if (opts->auto_quality > 0) {
2424 // Auto quality option enabled
2425 output_quality=get_video_quality_max(sh_video);
2426 if (opts->auto_quality > output_quality)
2427 opts->auto_quality = output_quality;
2428 else
2429 output_quality = opts->auto_quality;
2430 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2431 set_video_quality(sh_video,output_quality);
2434 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2436 current_module="init_vo";
2438 return 1;
2440 err_out:
2441 mpctx->sh_video = mpctx->d_video->sh = NULL;
2442 return 0;
2445 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2447 struct sh_video *sh_video = mpctx->sh_video;
2448 double frame_time = 0;
2449 struct vo *video_out = mpctx->video_out;
2450 while (!video_out->frame_loaded) {
2451 current_module = "filter_video";
2452 // In nocorrect-pts mode there is no way to properly time these frames
2453 if (vo_get_buffered_frame(video_out, 0) >= 0)
2454 break;
2455 if (vf_output_queued_frame(sh_video->vfilter))
2456 continue;
2457 unsigned char *packet = NULL;
2458 frame_time = sh_video->next_frame_time;
2459 if (mpctx->restart_playback)
2460 frame_time = 0;
2461 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2462 &packet, force_fps);
2463 if (in_size < 0) {
2464 #ifdef CONFIG_DVDNAV
2465 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2466 if (mp_dvdnav_is_eof(mpctx->stream))
2467 return -1;
2468 if (mpctx->d_video)
2469 mpctx->d_video->eof = 0;
2470 if (mpctx->d_audio)
2471 mpctx->d_audio->eof = 0;
2472 mpctx->stream->eof = 0;
2473 } else
2474 #endif
2475 return -1;
2477 if (in_size > max_framesize)
2478 max_framesize = in_size;
2479 sh_video->timer += frame_time;
2480 if (mpctx->sh_audio)
2481 mpctx->delay -= frame_time;
2482 // video_read_frame can change fps (e.g. for ASF video)
2483 vo_fps = sh_video->fps;
2484 int framedrop_type = check_framedrop(mpctx, frame_time);
2485 current_module = "decode video";
2487 void *decoded_frame;
2488 #ifdef CONFIG_DVDNAV
2489 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2490 if (in_size >= 0 && !decoded_frame)
2491 #endif
2492 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2493 sh_video->pts);
2494 #ifdef CONFIG_DVDNAV
2495 // Save last still frame for future display
2496 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2497 #endif
2498 if (decoded_frame) {
2499 current_module = "filter video";
2500 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2501 if (!video_out->config_ok)
2502 break;
2505 return frame_time;
2508 static void determine_frame_pts(struct MPContext *mpctx)
2510 struct sh_video *sh_video = mpctx->sh_video;
2511 struct MPOpts *opts = &mpctx->opts;
2513 if (opts->user_pts_assoc_mode) {
2514 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2515 } else if (sh_video->pts_assoc_mode == 0) {
2516 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2517 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2518 sh_video->pts_assoc_mode = 1;
2519 else
2520 sh_video->pts_assoc_mode = 2;
2521 } else {
2522 int probcount1 = sh_video->num_reordered_pts_problems;
2523 int probcount2 = sh_video->num_sorted_pts_problems;
2524 if (sh_video->pts_assoc_mode == 2) {
2525 int tmp = probcount1;
2526 probcount1 = probcount2;
2527 probcount2 = tmp;
2529 if (probcount1 >= probcount2 * 1.5 + 2) {
2530 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2531 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2532 "%d.\n", sh_video->pts_assoc_mode);
2535 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2536 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2539 static double update_video(struct MPContext *mpctx)
2541 struct sh_video *sh_video = mpctx->sh_video;
2542 struct vo *video_out = mpctx->video_out;
2543 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2544 mpctx->osd); // hack for vf_expand
2545 if (!mpctx->opts.correct_pts)
2546 return update_video_nocorrect_pts(mpctx);
2548 double pts;
2550 bool hit_eof = false;
2551 while (!video_out->frame_loaded) {
2552 current_module = "filter_video";
2553 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2554 break;
2555 // XXX Time used in this call is not counted in any performance
2556 // timer now, OSD time is not updated correctly for filter-added frames
2557 if (vf_output_queued_frame(sh_video->vfilter))
2558 continue;
2559 if (hit_eof)
2560 return -1;
2561 unsigned char *packet = NULL;
2562 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2563 if (pts != MP_NOPTS_VALUE)
2564 pts += mpctx->video_offset;
2565 if (in_size < 0) {
2566 // try to extract last frames in case of decoder lag
2567 in_size = 0;
2568 pts = MP_NOPTS_VALUE;
2569 hit_eof = true;
2571 if (in_size > max_framesize)
2572 max_framesize = in_size;
2573 current_module = "decode video";
2574 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2575 void *decoded_frame = decode_video(sh_video, packet, in_size,
2576 framedrop_type, pts);
2577 if (decoded_frame) {
2578 determine_frame_pts(mpctx);
2579 current_module = "filter video";
2580 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2581 if (!video_out->config_ok)
2582 break; // We'd likely hang in this loop otherwise
2586 pts = video_out->next_pts;
2587 if (pts == MP_NOPTS_VALUE) {
2588 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2589 // Try to use decoder pts from before filters
2590 pts = sh_video->pts;
2591 if (pts == MP_NOPTS_VALUE)
2592 pts = sh_video->last_pts;
2594 sh_video->pts = pts;
2595 if (sh_video->last_pts == MP_NOPTS_VALUE)
2596 sh_video->last_pts = sh_video->pts;
2597 else if (sh_video->last_pts > sh_video->pts) {
2598 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2599 sh_video->pts, sh_video->last_pts);
2600 /* If the difference in pts is small treat it as jitter around the
2601 * right value (possibly caused by incorrect timestamp ordering) and
2602 * just show this frame immediately after the last one.
2603 * Treat bigger differences as timestamp resets and start counting
2604 * timing of later frames from the position of this one. */
2605 if (sh_video->last_pts - sh_video->pts > 0.5)
2606 sh_video->last_pts = sh_video->pts;
2607 else
2608 sh_video->pts = sh_video->last_pts;
2610 double frame_time = sh_video->pts - sh_video->last_pts;
2611 sh_video->last_pts = sh_video->pts;
2612 sh_video->timer += frame_time;
2613 if (mpctx->sh_audio)
2614 mpctx->delay -= frame_time;
2615 return frame_time;
2618 void pause_player(struct MPContext *mpctx)
2620 if (mpctx->paused)
2621 return;
2622 mpctx->paused = 1;
2623 mpctx->step_frames = 0;
2624 mpctx->time_frame -= get_relative_time(mpctx);
2626 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2627 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2629 if (mpctx->audio_out && mpctx->sh_audio)
2630 mpctx->audio_out->pause(); // pause audio, keep data if possible
2633 void unpause_player(struct MPContext *mpctx)
2635 if (!mpctx->paused)
2636 return;
2637 mpctx->paused = 0;
2639 if (mpctx->audio_out && mpctx->sh_audio)
2640 mpctx->audio_out->resume(); // resume audio
2641 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2642 && !mpctx->step_frames)
2643 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2644 (void)get_relative_time(mpctx); // ignore time that passed during pause
2647 void add_step_frame(struct MPContext *mpctx)
2649 mpctx->step_frames++;
2650 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2651 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2652 unpause_player(mpctx);
2655 static void pause_loop(struct MPContext *mpctx)
2657 struct MPOpts *opts = &mpctx->opts;
2658 mp_cmd_t* cmd;
2659 if (!opts->quiet) {
2660 // Small hack to display the pause message on the OSD line.
2661 // The pause string is: "\n == PAUSE == \r" so we need to
2662 // take the first and the last char out
2663 if (opts->term_osd && !mpctx->sh_video) {
2664 char msg[128] = _("\n ===== PAUSE =====\r");
2665 int mlen = strlen(msg);
2666 msg[mlen-1] = '\0';
2667 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2668 update_osd_msg(mpctx);
2669 } else
2670 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2671 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2674 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2675 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2676 if (cmd) {
2677 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2678 run_command(mpctx, cmd);
2679 mp_cmd_free(cmd);
2680 continue;
2682 if (mpctx->sh_video && mpctx->video_out)
2683 vo_check_events(mpctx->video_out);
2684 #ifdef CONFIG_MENU
2685 if (vf_menu)
2686 vf_menu_pause_update(vf_menu);
2687 #endif
2688 usec_sleep(20000);
2689 update_osd_msg(mpctx);
2690 int hack = vo_osd_changed(0);
2691 vo_osd_changed(hack);
2692 if (hack)
2693 break;
2698 // Find the right mute status and record position for new file position
2699 static void edl_seek_reset(MPContext *mpctx)
2701 mpctx->edl_muted = 0;
2702 next_edl_record = edl_records;
2704 while (next_edl_record) {
2705 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2706 break;
2708 if (next_edl_record->action == EDL_MUTE)
2709 mpctx->edl_muted = !mpctx->edl_muted;
2710 next_edl_record = next_edl_record->next;
2712 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2713 mixer_mute(&mpctx->mixer);
2717 // Execute EDL command for the current position if one exists
2718 static void edl_update(MPContext *mpctx)
2720 if (!next_edl_record)
2721 return;
2723 if (!mpctx->sh_video) {
2724 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2725 free_edl(edl_records);
2726 next_edl_record = NULL;
2727 edl_records = NULL;
2728 return;
2731 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2732 if (next_edl_record->action == EDL_SKIP) {
2733 mpctx->osd_function = OSD_FFW;
2734 mpctx->abs_seek_pos = 0;
2735 mpctx->rel_seek_secs = next_edl_record->length_sec;
2736 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2737 "[%f], length [%f]\n", next_edl_record->start_sec,
2738 next_edl_record->stop_sec, next_edl_record->length_sec);
2740 else if (next_edl_record->action == EDL_MUTE) {
2741 mpctx->edl_muted = !mpctx->edl_muted;
2742 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2743 mixer_mute(&mpctx->mixer);
2744 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2745 next_edl_record->start_sec );
2747 next_edl_record = next_edl_record->next;
2751 static void reinit_decoders(struct MPContext *mpctx)
2753 reinit_video_chain(mpctx);
2754 reinit_audio_chain(mpctx);
2755 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2758 static void seek_reset(struct MPContext *mpctx)
2760 if (mpctx->sh_video) {
2761 current_module = "seek_video_reset";
2762 resync_video_stream(mpctx->sh_video);
2763 mpctx->sh_video->timer = 0;
2764 vo_seek_reset(mpctx->video_out);
2765 mpctx->sh_video->timer = 0;
2766 mpctx->sh_video->num_buffered_pts = 0;
2767 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2768 mpctx->delay = 0;
2769 mpctx->time_frame = 0;
2770 mpctx->restart_playback = true;
2771 // Not all demuxers set d_video->pts during seek, so this value
2772 // (which is used by at least vobsub and edl code below) may
2773 // be completely wrong (probably 0).
2774 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2775 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2776 mpctx->sh_video->pts, mpctx->video_offset,
2777 mpctx->d_sub, 1);
2778 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2781 if (mpctx->sh_audio) {
2782 current_module = "seek_audio_reset";
2783 resync_audio_stream(mpctx->sh_audio);
2784 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2785 mpctx->sh_audio->a_buffer_len = 0;
2786 mpctx->sh_audio->a_out_buffer_len = 0;
2787 if (!mpctx->sh_video)
2788 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2789 mpctx->video_offset, mpctx->d_sub, 1);
2792 if (vo_vobsub && mpctx->sh_video) {
2793 current_module = "seek_vobsub_reset";
2794 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2797 edl_seek_reset(mpctx);
2799 mpctx->total_avsync_change = 0;
2800 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2801 drop_frame_cnt = 0;
2803 current_module = NULL;
2806 static bool timeline_set_part(struct MPContext *mpctx, int i)
2808 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2809 struct timeline_part *n = mpctx->timeline + i;
2810 mpctx->timeline_part = i;
2811 mpctx->video_offset = n->start - n->source_start;
2812 if (n->source == p->source)
2813 return false;
2814 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2815 mpctx->demuxer = n->source->demuxer;
2816 mpctx->d_video = mpctx->demuxer->video;
2817 mpctx->d_audio = mpctx->demuxer->audio;
2818 mpctx->d_sub = mpctx->demuxer->sub;
2819 mpctx->sh_video = mpctx->d_video->sh;
2820 mpctx->sh_audio = mpctx->d_audio->sh;
2821 return true;
2824 // Given pts, switch playback to the corresponding part.
2825 // Return offset within that part.
2826 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2827 bool *need_reset)
2829 if (pts < 0)
2830 pts = 0;
2831 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2832 struct timeline_part *p = mpctx->timeline + i;
2833 if (pts < (p+1)->start) {
2834 *need_reset = timeline_set_part(mpctx, i);
2835 return pts - p->start + p->source_start;
2838 return -1;
2842 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2843 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2844 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2845 static int seek(MPContext *mpctx, double amount, int style)
2847 current_module = "seek";
2848 if (mpctx->stop_play == AT_END_OF_FILE)
2849 mpctx->stop_play = KEEP_PLAYING;
2850 if (style & SEEK_FACTOR
2851 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2852 || amount < 0)
2853 mpctx->last_chapter_seek = -1;
2854 if (mpctx->timeline && style & SEEK_FACTOR) {
2855 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2856 style &= ~SEEK_FACTOR;
2858 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2859 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2860 style |= SEEK_ABSOLUTE;
2861 if (amount > 0)
2862 style |= SEEK_FORWARD;
2863 else
2864 style |= SEEK_BACKWARD;
2865 amount += mpctx->sh_video->pts;
2868 /* At least the liba52 decoder wants to read from the input stream
2869 * during initialization, so reinit must be done after the demux_seek()
2870 * call that clears possible stream EOF. */
2871 bool need_reset = false;
2872 if (mpctx->timeline) {
2873 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2874 if (amount == -1) {
2875 mpctx->stop_play = AT_END_OF_FILE;
2876 // Clear audio from current position
2877 if (mpctx->sh_audio) {
2878 mpctx->audio_out->reset();
2879 mpctx->sh_audio->a_buffer_len = 0;
2880 mpctx->sh_audio->a_out_buffer_len = 0;
2882 return -1;
2885 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2886 if (need_reset)
2887 reinit_decoders(mpctx);
2888 if (seekresult == 0)
2889 return -1;
2891 seek_reset(mpctx);
2892 return 0;
2896 double get_time_length(struct MPContext *mpctx)
2898 if (mpctx->timeline)
2899 return mpctx->timeline[mpctx->num_timeline_parts].start;
2901 struct demuxer *demuxer = mpctx->demuxer;
2902 double get_time_ans;
2903 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
2904 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
2905 (void *) &get_time_ans) > 0)
2906 return get_time_ans;
2908 struct sh_video *sh_video = mpctx->d_video->sh;
2909 struct sh_audio *sh_audio = mpctx->d_audio->sh;
2910 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
2911 return (double) (demuxer->movi_end - demuxer->movi_start) /
2912 (sh_video->i_bps + sh_audio->i_bps);
2913 if (sh_video && sh_video->i_bps)
2914 return (double) (demuxer->movi_end - demuxer->movi_start) /
2915 sh_video->i_bps;
2916 if (sh_audio && sh_audio->i_bps)
2917 return (double) (demuxer->movi_end - demuxer->movi_start) /
2918 sh_audio->i_bps;
2919 return 0;
2922 /* If there are timestamps from stream level then use those (for example
2923 * DVDs can have consistent times there while the MPEG-level timestamps
2924 * reset). */
2925 double get_current_time(struct MPContext *mpctx)
2927 struct demuxer *demuxer = mpctx->demuxer;
2928 if (demuxer->stream_pts != MP_NOPTS_VALUE)
2929 return demuxer->stream_pts;
2930 struct sh_video *sh_video = demuxer->video->sh;
2931 if (sh_video)
2932 return sh_video->pts;
2933 return playing_audio_pts(mpctx);
2936 int get_percent_pos(struct MPContext *mpctx)
2938 struct demuxer *demuxer = mpctx->demuxer;
2939 int ans = 0;
2940 if (mpctx->timeline)
2941 ans = get_current_time(mpctx) * 100 /
2942 mpctx->timeline[mpctx->num_timeline_parts].start;
2943 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
2945 else {
2946 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
2947 off_t pos = demuxer->filepos > 0 ?
2948 demuxer->filepos : stream_tell(demuxer->stream);
2949 if (len > 0)
2950 ans = (pos - demuxer->movi_start) / len;
2951 else
2952 ans = 0;
2954 if (ans < 0)
2955 ans = 0;
2956 if (ans > 100)
2957 ans = 100;
2958 return ans;
2961 // -2 is no chapters, -1 is before first chapter
2962 int get_current_chapter(struct MPContext *mpctx)
2964 double current_pts = get_current_time(mpctx);
2965 if (!mpctx->chapters)
2966 return FFMAX(mpctx->last_chapter_seek,
2967 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
2969 int i;
2970 for (i = 1; i < mpctx->num_chapters; i++)
2971 if (current_pts < mpctx->chapters[i].start)
2972 break;
2973 return FFMAX(mpctx->last_chapter_seek, i - 1);
2976 // currently returns a string allocated with malloc, not talloc
2977 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2979 if (!mpctx->chapters || !mpctx->sh_video)
2980 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2981 return strdup(mpctx->chapters[chapter].name);
2984 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2985 char **chapter_name)
2987 mpctx->last_chapter_seek = -1;
2988 if (!mpctx->chapters || !mpctx->sh_video) {
2989 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2990 chapter_name);
2991 if (res >= 0) {
2992 if (*seek_pts == -1)
2993 seek_reset(mpctx);
2994 else {
2995 mpctx->last_chapter_seek = res;
2996 mpctx->last_chapter_pts = *seek_pts;
2999 return res;
3002 if (chapter >= mpctx->num_chapters)
3003 return -1;
3004 if (chapter < 0)
3005 chapter = 0;
3006 *seek_pts = mpctx->chapters[chapter].start;
3007 mpctx->last_chapter_seek = chapter;
3008 mpctx->last_chapter_pts = *seek_pts;
3009 if (chapter_name)
3010 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3011 return chapter;
3014 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3015 struct content_source *sources,
3016 int num_sources,
3017 unsigned char uid_map[][16])
3019 int num_filenames = 0;
3020 char **filenames = NULL;
3021 if (num_sources > 1) {
3022 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3023 "other sources.\n");
3024 if (mpctx->stream->type != STREAMTYPE_FILE) {
3025 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3026 "normal disk file. Will not search for related files.\n");
3027 } else {
3028 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3029 "same directory to find referenced sources.\n");
3030 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3031 &num_filenames);
3035 int num_left = num_sources - 1;
3036 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3037 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3038 filename_recode(filenames[i]));
3039 int format;
3040 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3041 if (!s)
3042 continue;
3043 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3044 mpctx->opts.audio_id,
3045 mpctx->opts.video_id,
3046 mpctx->opts.sub_id, filenames[i]);
3047 if (!d) {
3048 free_stream(s);
3049 continue;
3051 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3052 for (int i = 1; i < num_sources; i++) {
3053 if (sources[i].demuxer)
3054 continue;
3055 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3056 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3057 i, filename_recode(d->filename));
3058 sources[i].stream = s;
3059 sources[i].demuxer = d;
3060 num_left--;
3061 goto match;
3065 free_demuxer(d);
3066 free_stream(s);
3067 continue;
3068 match:
3071 talloc_free(filenames);
3072 if (num_left) {
3073 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3074 "There will be parts MISSING from the video!\n");
3075 for (int i = 1, j = 1; i < num_sources; i++)
3076 if (sources[i].demuxer) {
3077 sources[j] = sources[i];
3078 memcpy(uid_map[j], uid_map[i], 16);
3079 j++;
3082 return num_sources - num_left;
3085 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3087 struct MPOpts *opts = &mpctx->opts;
3089 if (!opts->ordered_chapters) {
3090 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3091 "you have disabled support for them. Ignoring.\n");
3092 return;
3095 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3096 "edit timeline.\n");
3098 struct demuxer *demuxer = mpctx->demuxer;
3099 struct matroska_data *m = &demuxer->matroska_data;
3101 // +1 because sources/uid_map[0] is original file even if all chapters
3102 // actually use other sources and need separate entries
3103 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3104 m->num_ordered_chapters+1);
3105 sources[0].stream = mpctx->stream;
3106 sources[0].demuxer = mpctx->demuxer;
3107 unsigned char uid_map[m->num_ordered_chapters+1][16];
3108 int num_sources = 1;
3109 memcpy(uid_map[0], m->segment_uid, 16);
3111 for (int i = 0; i < m->num_ordered_chapters; i++) {
3112 struct matroska_chapter *c = m->ordered_chapters + i;
3113 if (!c->has_segment_uid)
3114 memcpy(c->segment_uid, m->segment_uid, 16);
3116 for (int j = 0; j < num_sources; j++)
3117 if (!memcmp(c->segment_uid, uid_map[j], 16))
3118 goto found1;
3119 memcpy(uid_map[num_sources], c->segment_uid, 16);
3120 sources[num_sources] = (struct content_source){};
3121 num_sources++;
3122 found1:
3126 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3127 uid_map);
3130 // +1 for terminating chapter with start time marking end of last real one
3131 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3132 m->num_ordered_chapters + 1);
3133 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3134 m->num_ordered_chapters);
3135 uint64_t starttime = 0;
3136 uint64_t missing_time = 0;
3137 int part_count = 0;
3138 int num_chapters = 0;
3139 uint64_t prev_part_offset = 0;
3140 for (int i = 0; i < m->num_ordered_chapters; i++) {
3141 struct matroska_chapter *c = m->ordered_chapters + i;
3143 int j;
3144 for (j = 0; j < num_sources; j++) {
3145 if (!memcmp(c->segment_uid, uid_map[j], 16))
3146 goto found2;
3148 missing_time += c->end - c->start;
3149 continue;
3150 found2:;
3151 /* Only add a separate part if the time or file actually changes.
3152 * Matroska files have chapter divisions that are redundant from
3153 * timeline point of view because the same chapter structure is used
3154 * both to specify the timeline and for normal chapter information.
3155 * Removing a missing inserted external chapter can also cause this.
3156 * We allow for a configurable fudge factor because of files which
3157 * specify chapter end times that are one frame too early;
3158 * we don't want to try seeking over a one frame gap. */
3159 int64_t join_diff = c->start - starttime - prev_part_offset;
3160 if (part_count == 0 || FFABS(join_diff) > opts->chapter_merge_threshold
3161 || sources + j != timeline[part_count - 1].source) {
3162 timeline[part_count].source = sources + j;
3163 timeline[part_count].start = starttime / 1000.;
3164 timeline[part_count].source_start = c->start / 1000.;
3165 prev_part_offset = c->start - starttime;
3166 part_count++;
3167 } else if (part_count > 0 && join_diff) {
3168 /* Chapter was merged at an inexact boundary;
3169 * adjust timestamps to match. */
3170 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3171 "offset %d ms.\n", i, (int) join_diff);
3172 starttime += join_diff;
3174 chapters[num_chapters].start = starttime / 1000.;
3175 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3176 starttime += c->end - c->start;
3177 num_chapters++;
3179 timeline[part_count].start = starttime / 1000.;
3181 if (!part_count) {
3182 // None of the parts come from the file itself???
3183 talloc_free(sources);
3184 talloc_free(timeline);
3185 talloc_free(chapters);
3186 return;
3189 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3190 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3191 timeline[part_count].start);
3192 if (missing_time)
3193 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3194 "from the timeline!\n", missing_time / 1000.);
3195 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3196 for (int i = 0; i < num_sources; i++)
3197 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3198 filename_recode(sources[i].demuxer->filename));
3199 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3200 "source_start, source):\n");
3201 for (int i = 0; i < part_count; i++) {
3202 struct timeline_part *p = timeline + i;
3203 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3204 p->source_start, p->source - sources);
3206 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3207 mpctx->sources = sources;
3208 mpctx->num_sources = num_sources;
3209 mpctx->timeline = timeline;
3210 mpctx->num_timeline_parts = part_count;
3211 mpctx->num_chapters = num_chapters;
3212 mpctx->chapters = chapters;
3214 mpctx->timeline_part = 0;
3215 mpctx->demuxer = timeline[0].source->demuxer;
3219 static int read_keys(void *ctx, int fd)
3221 getch2(ctx);
3222 return mplayer_get_key(ctx, 0);
3226 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3227 * file for some tools to link against. */
3228 #ifndef DISABLE_MAIN
3229 int main(int argc,char* argv[]){
3232 char * mem_ptr;
3234 // movie info:
3236 /* Flag indicating whether MPlayer should exit without playing anything. */
3237 int opt_exit = 0;
3238 int i;
3240 struct MPContext *mpctx = &(struct MPContext){
3241 .osd_function = OSD_PLAY,
3242 .begin_skip = MP_NOPTS_VALUE,
3243 .play_tree_step = 1,
3244 .global_sub_pos = -1,
3245 .set_of_sub_pos = -1,
3246 .file_format = DEMUXER_TYPE_UNKNOWN,
3247 .last_dvb_step = 1,
3250 InitTimer();
3251 srand(GetTimerMS());
3253 mp_msg_init();
3254 set_av_log_callback();
3256 #ifdef CONFIG_X11
3257 mpctx->x11_state = vo_x11_init_state();
3258 #endif
3259 struct MPOpts *opts = &mpctx->opts;
3260 set_default_mplayer_options(opts);
3261 // Create the config context and register the options
3262 mpctx->mconfig = m_config_new(opts, cfg_include);
3263 m_config_register_options(mpctx->mconfig,mplayer_opts);
3264 m_config_register_options(mpctx->mconfig, common_opts);
3265 mp_input_register_options(mpctx->mconfig);
3267 // Preparse the command line
3268 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3270 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3271 set_path_env();
3272 #endif
3274 #ifdef CONFIG_TV
3275 stream_tv_defaults.immediate = 1;
3276 #endif
3278 parse_cfgfiles(mpctx, mpctx->mconfig);
3280 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3281 if(mpctx->playtree == NULL)
3282 opt_exit = 1;
3283 else {
3284 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3285 if(mpctx->playtree) {
3286 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3287 if(mpctx->playtree_iter) {
3288 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3289 play_tree_iter_free(mpctx->playtree_iter);
3290 mpctx->playtree_iter = NULL;
3292 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3296 mpctx->key_fifo = mp_fifo_create(opts);
3298 print_version("MPlayer");
3300 #if defined(__MINGW32__) || defined(__CYGWIN__)
3302 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3303 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3304 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3305 if (kernel32) {
3306 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3307 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3309 if (setDEP) setDEP(3);
3310 if (setDllDir) setDllDir("");
3312 // stop Windows from showing all kinds of annoying error dialogs
3313 SetErrorMode(0x8003);
3314 // request 1ms timer resolution
3315 timeBeginPeriod(1);
3316 #endif
3318 #ifdef CONFIG_PRIORITY
3319 set_priority();
3320 #endif
3322 if (codec_path)
3323 set_codec_path(codec_path);
3325 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3326 list_video_out();
3327 opt_exit = 1;
3330 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3331 list_audio_out();
3332 opt_exit = 1;
3335 /* Check codecs.conf. */
3336 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3337 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3338 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3339 if(!parse_codec_cfg(NULL)){
3340 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3342 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3345 free( mem_ptr ); // release the buffer created by get_path()
3348 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3349 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3350 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3351 list_codecs(1);
3352 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3353 opt_exit = 1;
3355 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3356 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3357 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3358 list_codecs(0);
3359 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3360 opt_exit = 1;
3362 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3363 vfm_help();
3364 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3365 opt_exit = 1;
3367 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3368 afm_help();
3369 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3370 opt_exit = 1;
3372 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3373 af_help();
3374 printf("\n");
3375 opt_exit = 1;
3377 #ifdef CONFIG_X11
3378 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3379 fstype_help();
3380 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3381 opt_exit = 1;
3383 #endif
3384 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3385 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3386 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3387 demuxer_help();
3388 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3389 opt_exit = 1;
3391 if (opts->list_properties) {
3392 property_print_help();
3393 opt_exit = 1;
3396 if(opt_exit)
3397 exit_player(mpctx, EXIT_NONE);
3399 if (!mpctx->filename && !opts->player_idle_mode) {
3400 // no file/vcd/dvd -> show HELP:
3401 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3402 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3405 /* Display what configure line was used */
3406 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3408 // Many users forget to include command line in bugreports...
3409 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3410 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3411 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3412 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3415 //------ load global data first ------
3417 mpctx->osd = osd_create();
3419 // check font
3420 #ifdef CONFIG_FREETYPE
3421 init_freetype();
3422 #endif
3423 #ifdef CONFIG_FONTCONFIG
3424 if(font_fontconfig <= 0)
3426 #endif
3427 #ifdef CONFIG_BITMAP_FONT
3428 if(font_name){
3429 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3430 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3431 filename_recode(font_name));
3432 } else {
3433 // try default:
3434 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3435 free(mem_ptr); // release the buffer created by get_path()
3436 if(!vo_font)
3437 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3439 if (sub_font_name)
3440 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3441 else
3442 mpctx->osd->sub_font = vo_font;
3443 #endif
3444 #ifdef CONFIG_FONTCONFIG
3446 #endif
3448 #ifdef CONFIG_ASS
3449 ass_library = ass_init();
3450 #endif
3452 #ifdef HAVE_RTC
3453 if(opts->rtc)
3455 char *rtc_device = opts->rtc_device;
3456 // seteuid(0); /* Can't hurt to try to get root here */
3457 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3458 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3459 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3460 else {
3461 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3463 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3464 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3465 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3466 close (rtc_fd);
3467 rtc_fd = -1;
3468 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3469 /* variable only by the root */
3470 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3471 close (rtc_fd);
3472 rtc_fd = -1;
3473 } else
3474 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3477 if(rtc_fd<0)
3478 #endif /* HAVE_RTC */
3479 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3480 opts->softsleep ? "software" : timer_name);
3482 #ifdef HAVE_TERMCAP
3483 load_termcap(NULL); // load key-codes
3484 #endif
3486 // ========== Init keyboard FIFO (connection to libvo) ============
3488 // Init input system
3489 current_module = "init_input";
3490 mpctx->input = mp_input_init(&opts->input);
3491 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3492 if(slave_mode)
3493 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3494 else if (opts->consolecontrols)
3495 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3496 // Set the libstream interrupt callback
3497 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3499 #ifdef CONFIG_MENU
3500 if(use_menu) {
3501 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3502 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3503 else {
3504 menu_cfg = get_path("menu.conf");
3505 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3506 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3507 else {
3508 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3509 MPLAYER_CONFDIR "/menu.conf"))
3510 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3511 else {
3512 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3513 use_menu = 0;
3518 #endif
3520 current_module = NULL;
3522 /// Catch signals
3523 #ifndef __MINGW32__
3524 signal(SIGCHLD,child_sighandler);
3525 #endif
3527 #ifdef CONFIG_CRASH_DEBUG
3528 prog_path = argv[0];
3529 #endif
3530 //========= Catch terminate signals: ================
3531 // terminate requests:
3532 signal(SIGTERM,exit_sighandler); // kill
3533 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3535 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3537 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3538 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3539 #ifdef CONFIG_SIGHANDLER
3540 // fatal errors:
3541 signal(SIGBUS,exit_sighandler); // bus error
3542 signal(SIGSEGV,exit_sighandler); // segfault
3543 signal(SIGILL,exit_sighandler); // illegal instruction
3544 signal(SIGFPE,exit_sighandler); // floating point exc.
3545 signal(SIGABRT,exit_sighandler); // abort()
3546 #ifdef CONFIG_CRASH_DEBUG
3547 if (crash_debug)
3548 signal(SIGTRAP,exit_sighandler);
3549 #endif
3550 #endif
3552 // ******************* Now, let's see the per-file stuff ********************
3554 play_next_file:
3556 // init global sub numbers
3557 mpctx->global_sub_size = 0;
3558 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3560 if (mpctx->filename) {
3561 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3562 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3563 load_per_file_config (mpctx->mconfig, mpctx->filename);
3566 if (opts->video_driver_list)
3567 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3568 if (opts->audio_driver_list)
3569 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3571 // We must enable getch2 here to be able to interrupt network connection
3572 // or cache filling
3573 if (opts->consolecontrols && !slave_mode) {
3574 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3575 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3576 else
3577 getch2_enable(); // prepare stdin for hotkeys...
3578 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3579 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3582 // =================== GUI idle loop (STOP state) ===========================
3583 while (opts->player_idle_mode && !mpctx->filename) {
3584 play_tree_t * entry = NULL;
3585 mp_cmd_t * cmd;
3586 if (mpctx->video_out && mpctx->video_out->config_ok)
3587 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3588 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3589 if (mpctx->video_out)
3590 vo_check_events(mpctx->video_out);
3591 usec_sleep(20000);
3593 switch (cmd->id) {
3594 case MP_CMD_LOADFILE:
3595 // prepare a tree entry with the new filename
3596 entry = play_tree_new();
3597 play_tree_add_file(entry, cmd->args[0].v.s);
3598 // The entry is added to the main playtree after the switch().
3599 break;
3600 case MP_CMD_LOADLIST:
3601 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3602 break;
3603 case MP_CMD_QUIT:
3604 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3605 break;
3606 case MP_CMD_VO_FULLSCREEN:
3607 case MP_CMD_GET_PROPERTY:
3608 case MP_CMD_SET_PROPERTY:
3609 case MP_CMD_STEP_PROPERTY:
3610 run_command(mpctx, cmd);
3611 break;
3614 mp_cmd_free(cmd);
3616 if (entry) { // user entered a command that gave a valid entry
3617 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3618 play_tree_free_list(mpctx->playtree->child, 1);
3619 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3621 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3623 play_tree_set_child(mpctx->playtree, entry);
3625 /* Make iterator start at the top the of tree. */
3626 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3627 if (!mpctx->playtree_iter) continue;
3629 // find the first real item in the tree
3630 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3631 // no items!
3632 play_tree_iter_free(mpctx->playtree_iter);
3633 mpctx->playtree_iter = NULL;
3634 continue; // wait for next command
3636 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3639 //---------------------------------------------------------------------------
3641 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3642 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3644 if (mpctx->filename) {
3645 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3646 filename_recode(mpctx->filename));
3647 if(use_filename_title && opts->vo_wintitle == NULL)
3648 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
3651 if (edl_filename) {
3652 if (edl_records) free_edl(edl_records);
3653 next_edl_record = edl_records = edl_parse_file();
3655 if (edl_output_filename) {
3656 if (edl_fd) fclose(edl_fd);
3657 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3659 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3660 filename_recode(edl_output_filename));
3664 //==================== Open VOB-Sub ============================
3666 current_module="vobsub";
3667 if (vobsub_name){
3668 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3669 if(vo_vobsub==NULL)
3670 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3671 filename_recode(vobsub_name));
3672 } else if (sub_auto && mpctx->filename){
3673 /* try to autodetect vobsub from movie filename ::atmos */
3674 char *buf = strdup(mpctx->filename), *psub;
3675 char *pdot = strrchr(buf, '.');
3676 char *pslash = strrchr(buf, '/');
3677 #if defined(__MINGW32__) || defined(__CYGWIN__)
3678 if (!pslash) pslash = strrchr(buf, '\\');
3679 #endif
3680 if (pdot && (!pslash || pdot > pslash))
3681 *pdot = '\0';
3682 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3683 /* try from ~/.mplayer/sub */
3684 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3685 const char *bname = mp_basename(buf);
3686 int l;
3687 l = strlen(psub) + strlen(bname) + 1;
3688 psub = realloc(psub,l);
3689 strcat(psub,bname);
3690 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3691 free(psub);
3693 free(buf);
3695 if(vo_vobsub){
3696 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3697 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3698 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3700 // setup global sub numbering
3701 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3704 //============ Open & Sync STREAM --- fork cache2 ====================
3706 mpctx->stream=NULL;
3707 mpctx->demuxer=NULL;
3708 if (mpctx->d_audio) {
3709 //free_demuxer_stream(mpctx->d_audio);
3710 mpctx->d_audio=NULL;
3712 if (mpctx->d_video) {
3713 //free_demuxer_stream(d_video);
3714 mpctx->d_video=NULL;
3716 mpctx->sh_audio=NULL;
3717 mpctx->sh_video=NULL;
3719 current_module="open_stream";
3720 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3721 if(!mpctx->stream) { // error...
3722 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3723 goto goto_next_file;
3725 mpctx->initialized_flags|=INITIALIZED_STREAM;
3727 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3728 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3729 "playlist support will not be used automatically.\n"
3730 "MPlayer's playlist code is unsafe and should only be used with "
3731 "trusted sources.\nPlayback will probably fail.\n\n");
3732 #if 0
3733 play_tree_t* entry;
3734 // Handle playlist
3735 current_module="handle_playlist";
3736 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3737 filename_recode(mpctx->filename));
3738 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3739 mpctx->eof=playtree_add_playlist(mpctx, entry);
3740 goto goto_next_file;
3741 #endif
3743 mpctx->stream->start_pos+=seek_to_byte;
3745 if(stream_dump_type==5){
3746 unsigned char buf[4096];
3747 int len;
3748 FILE *f;
3749 current_module="dumpstream";
3750 stream_reset(mpctx->stream);
3751 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3752 f=fopen(opts->stream_dump_name,"wb");
3753 if(!f){
3754 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3755 exit_player(mpctx, EXIT_ERROR);
3757 if (opts->chapterrange[0] > 1) {
3758 int chapter = opts->chapterrange[0] - 1;
3759 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3761 while(!mpctx->stream->eof && !async_quit_request){
3762 len=stream_read(mpctx->stream,buf,4096);
3763 if(len>0) {
3764 if(fwrite(buf,len,1,f) != 1) {
3765 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3766 exit_player(mpctx, EXIT_ERROR);
3769 if (opts->chapterrange[1] > 0) {
3770 int chapter = -1;
3771 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3772 &chapter) == STREAM_OK
3773 && chapter + 1 > opts->chapterrange[1])
3774 break;
3777 if(fclose(f)) {
3778 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3779 exit_player(mpctx, EXIT_ERROR);
3781 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3782 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3785 #ifdef CONFIG_DVDREAD
3786 if(mpctx->stream->type==STREAMTYPE_DVD){
3787 current_module="dvd lang->id";
3788 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3789 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3790 // setup global sub numbering
3791 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3792 current_module=NULL;
3794 #endif
3796 #ifdef CONFIG_DVDNAV
3797 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3798 current_module="dvdnav lang->id";
3799 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3800 dvdsub_lang_id = -3;
3801 if(opts->sub_lang && opts->sub_id==-1)
3802 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3803 // setup global sub numbering
3804 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3805 current_module=NULL;
3807 #endif
3809 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3810 goto_enable_cache:
3811 if(stream_cache_size>0){
3812 int res;
3813 float stream_cache_min_percent = opts->stream_cache_min_percent;
3814 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
3815 current_module="enable_cache";
3816 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3817 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3818 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3819 if(res == 0)
3820 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3823 //============ Open DEMUXERS --- DETECT file type =======================
3824 current_module="demux_open";
3826 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3828 // HACK to get MOV Reference Files working
3830 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3832 unsigned char* playlist_entry;
3833 play_tree_t *list = NULL, *entry = NULL;
3835 current_module="handle_demux_playlist";
3836 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3838 char *temp;
3839 const char *bname;
3841 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3842 filename_recode(playlist_entry));
3844 bname=mp_basename(playlist_entry);
3845 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3846 continue;
3848 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3849 continue;
3851 entry = play_tree_new();
3853 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3855 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3856 if (temp)
3858 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3859 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3860 strcat(temp, playlist_entry);
3861 if (!strcmp(temp, mpctx->filename)) {
3862 free(temp);
3863 continue;
3865 play_tree_add_file(entry,temp);
3866 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3867 free(temp);
3870 else
3871 play_tree_add_file(entry,playlist_entry);
3873 if(!list)
3874 list = entry;
3875 else
3876 play_tree_append_entry(list,entry);
3878 free_demuxer(mpctx->demuxer);
3879 mpctx->demuxer = NULL;
3881 if (list)
3883 entry = play_tree_new();
3884 play_tree_set_child(entry,list);
3885 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3886 goto goto_next_file;
3890 if(!mpctx->demuxer) {
3891 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
3892 goto goto_next_file;
3895 if (mpctx->demuxer->matroska_data.ordered_chapters)
3896 build_ordered_chapter_timeline(mpctx);
3898 if (!mpctx->sources) {
3899 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3900 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3901 .demuxer = mpctx->demuxer};
3902 mpctx->num_sources = 1;
3905 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3907 #ifdef CONFIG_ASS
3908 if (opts->ass_enabled && ass_library) {
3909 for (int j = 0; j < mpctx->num_sources; j++) {
3910 struct demuxer *d = mpctx->sources[j].demuxer;
3911 for (int i = 0; i < d->num_attachments; i++) {
3912 struct demux_attachment *att = d->attachments + i;
3913 if (use_embedded_fonts && attachment_is_font(att))
3914 ass_add_font(ass_library, att->name, att->data, att->data_size);
3918 #endif
3920 current_module="demux_open2";
3922 mpctx->d_audio=mpctx->demuxer->audio;
3923 mpctx->d_video=mpctx->demuxer->video;
3924 mpctx->d_sub=mpctx->demuxer->sub;
3926 if (ts_prog) {
3927 int tmp = ts_prog;
3928 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3930 // select audio stream
3931 if (mpctx->num_sources)
3932 for (int i = 0; i < mpctx->num_sources; i++)
3933 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3934 opts->audio_lang);
3935 else
3936 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
3938 // DUMP STREAMS:
3939 if((stream_dump_type)&&(stream_dump_type<4)){
3940 FILE *f;
3941 demux_stream_t *ds=NULL;
3942 current_module="dump";
3943 // select stream to dump
3944 switch(stream_dump_type){
3945 case 1: ds=mpctx->d_audio;break;
3946 case 2: ds=mpctx->d_video;break;
3947 case 3: ds=mpctx->d_sub;break;
3949 if(!ds){
3950 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3951 exit_player(mpctx, EXIT_ERROR);
3953 // disable other streams:
3954 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3955 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3956 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3957 // let's dump it!
3958 f=fopen(opts->stream_dump_name,"wb");
3959 if(!f){
3960 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3961 exit_player(mpctx, EXIT_ERROR);
3963 while(!ds->eof){
3964 unsigned char* start;
3965 int in_size=ds_get_packet(ds,&start);
3966 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3967 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3968 if(in_size>0) fwrite(start,in_size,1,f);
3969 if (opts->chapterrange[1] > 0) {
3970 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
3971 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3972 break;
3975 fclose(f);
3976 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3977 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3980 mpctx->sh_audio=mpctx->d_audio->sh;
3981 mpctx->sh_video=mpctx->d_video->sh;
3983 if(mpctx->sh_video){
3985 current_module="video_read_properties";
3986 if(!video_read_properties(mpctx->sh_video)) {
3987 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3988 mpctx->sh_video=mpctx->d_video->sh=NULL;
3989 } else {
3990 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3991 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3992 mpctx->sh_video->fps,mpctx->sh_video->frametime
3995 /* need to set fps here for output encoders to pick it up in their init */
3996 if(force_fps){
3997 mpctx->sh_video->fps=force_fps;
3998 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4000 vo_fps = mpctx->sh_video->fps;
4002 if(!mpctx->sh_video->fps && !force_fps){
4003 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4004 mpctx->opts.correct_pts = 1;
4010 if(!mpctx->sh_video && !mpctx->sh_audio){
4011 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4012 #ifdef CONFIG_DVBIN
4013 if(mpctx->stream->type == STREAMTYPE_DVB)
4015 int dir;
4016 int v = mpctx->last_dvb_step;
4017 if(v > 0)
4018 dir = DVB_CHANNEL_HIGHER;
4019 else
4020 dir = DVB_CHANNEL_LOWER;
4022 if(dvb_step_channel(mpctx->stream, dir)) {
4023 mpctx->stop_play = PT_NEXT_ENTRY;
4024 mpctx->dvbin_reopen = 1;
4027 #endif
4028 goto goto_next_file; // exit_player(_("Fatal error"));
4031 /* display clip info */
4032 demux_info_print(mpctx->demuxer);
4034 //================== Read SUBTITLES (DVD & TEXT) ==========================
4035 if(vo_spudec==NULL &&
4036 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4037 init_vo_spudec(mpctx);
4040 // after reading video params we should load subtitles because
4041 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4042 // check .sub
4043 current_module="read_subtitles_file";
4044 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4045 if(sub_name){
4046 for (i = 0; sub_name[i] != NULL; ++i)
4047 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4049 if(sub_auto) { // auto load sub file ...
4050 char *psub = get_path( "sub/" );
4051 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4052 int i = 0;
4053 free(psub); // release the buffer created by get_path() above
4054 while (tmp[i]) {
4055 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4056 free(tmp[i++]);
4058 free(tmp);
4060 if (mpctx->set_of_sub_size > 0)
4061 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4063 if (select_subtitle(mpctx)) {
4064 if(subdata)
4065 switch (stream_dump_type) {
4066 case 3: list_sub_file(subdata); break;
4067 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
4068 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
4069 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
4070 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
4071 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
4075 print_file_properties(mpctx, mpctx->filename);
4077 if(!mpctx->sh_video) goto main; // audio-only
4079 if(!reinit_video_chain(mpctx)) {
4080 if(!mpctx->sh_video){
4081 if(!mpctx->sh_audio) goto goto_next_file;
4082 goto main; // exit_player(_("Fatal error"));
4086 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4087 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4089 #ifdef CONFIG_FREETYPE
4090 force_load_font = 1;
4091 #endif
4093 //================== MAIN: ==========================
4094 main:
4095 current_module="main";
4097 if (opts->playing_msg) {
4098 char* msg = property_expand_string(mpctx, opts->playing_msg);
4099 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4100 free(msg);
4104 // Disable the term OSD in verbose mode
4105 if (verbose)
4106 opts->term_osd = 0;
4109 int frame_time_remaining=0; // flag
4110 int blit_frame=0;
4112 // Make sure old OSD does not stay around,
4113 // e.g. with -fixed-vo and same-resolution files
4114 clear_osd_msgs();
4115 update_osd_msg(mpctx);
4117 //================ SETUP AUDIO ==========================
4119 if(mpctx->sh_audio){
4120 reinit_audio_chain(mpctx);
4121 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4122 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4125 current_module="av_init";
4127 if(mpctx->sh_video){
4128 mpctx->sh_video->timer=0;
4129 if (! ignore_start)
4130 audio_delay += mpctx->sh_video->stream_delay;
4132 if(mpctx->sh_audio){
4133 if (start_volume >= 0)
4134 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4135 if (! ignore_start)
4136 audio_delay -= mpctx->sh_audio->stream_delay;
4137 mpctx->delay=-audio_delay;
4140 if(!mpctx->sh_audio){
4141 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4142 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4143 ds_free_packs(mpctx->d_audio); // free buffered chunks
4144 //mpctx->d_audio->id=-2; // do not read audio chunks
4145 //uninit_player(mpctx, INITIALIZED_AO); // close device
4147 if(!mpctx->sh_video){
4148 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4149 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4150 ds_free_packs(mpctx->d_video);
4151 mpctx->d_video->id=-2;
4152 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4155 if (!mpctx->sh_video && !mpctx->sh_audio)
4156 goto goto_next_file;
4158 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4159 if(force_fps && mpctx->sh_video){
4160 vo_fps = mpctx->sh_video->fps=force_fps;
4161 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4162 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4165 mp_input_set_section(mpctx->input, NULL);
4166 //TODO: add desired (stream-based) sections here
4167 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4168 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4170 //==================== START PLAYING =======================
4172 if(opts->loop_times>1) opts->loop_times--; else
4173 if(opts->loop_times==1) opts->loop_times = -1;
4175 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4177 total_time_usage_start=GetTimer();
4178 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4179 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4180 play_n_frames=play_n_frames_mf;
4182 if(play_n_frames==0){
4183 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4186 // If there's a timeline force an absolute seek to initialize state
4187 if (seek_to_sec || mpctx->timeline) {
4188 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4189 end_at.pos += seek_to_sec;
4191 if (opts->chapterrange[0] > 0) {
4192 double pts;
4193 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4194 && pts > -1.0)
4195 seek(mpctx, pts, SEEK_ABSOLUTE);
4198 if (end_at.type == END_AT_SIZE) {
4199 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4200 end_at.type = END_AT_NONE;
4203 #ifdef CONFIG_DVDNAV
4204 mp_dvdnav_context_free(mpctx);
4205 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4206 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4207 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4209 #endif
4211 get_relative_time(mpctx); // reset current delta
4212 mpctx->time_frame = 0;
4213 mpctx->drop_message_shown = 0;
4214 mpctx->restart_playback = true;
4215 mpctx->total_avsync_change = 0;
4216 mpctx->last_chapter_seek = -1;
4217 // Make sure VO knows current pause state
4218 if (mpctx->sh_video)
4219 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4220 NULL);
4222 while(!mpctx->stop_play){
4223 float aq_sleep_time=0;
4225 if (opts->chapterrange[1] > 0) {
4226 int cur_chapter = get_current_chapter(mpctx);
4227 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4228 goto goto_next_file;
4231 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4232 mpctx->sh_audio = mpctx->d_audio->sh;
4233 mpctx->sh_audio->ds = mpctx->d_audio;
4234 reinit_audio_chain(mpctx);
4237 /*========================== PLAY AUDIO ============================*/
4239 if (mpctx->sh_audio && !mpctx->paused
4240 && (!mpctx->restart_playback || !mpctx->sh_video))
4241 if (!fill_audio_out_buffers(mpctx))
4242 // at eof, all audio at least written to ao
4243 if (!mpctx->sh_video)
4244 mpctx->stop_play = AT_END_OF_FILE;
4247 if(!mpctx->sh_video) {
4248 // handle audio-only case:
4249 double a_pos=0;
4250 // sh_audio can be NULL due to video stream switching
4251 // TODO: handle this better
4252 if (mpctx->sh_audio)
4253 a_pos = playing_audio_pts(mpctx);
4255 print_status(mpctx, a_pos, false);
4257 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4258 mpctx->stop_play = PT_NEXT_ENTRY;
4259 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4260 mpctx->d_sub, 0);
4261 update_osd_msg(mpctx);
4263 } else {
4265 /*========================== PLAY VIDEO ============================*/
4267 vo_pts=mpctx->sh_video->timer*90000.0;
4268 vo_fps=mpctx->sh_video->fps;
4270 blit_frame = mpctx->video_out->frame_loaded;
4271 if (!blit_frame) {
4272 double frame_time = update_video(mpctx);
4273 blit_frame = mpctx->video_out->frame_loaded;
4274 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4275 if (mpctx->sh_video->vf_initialized < 0) {
4276 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4277 mpctx->stop_play = PT_NEXT_ENTRY;
4278 goto goto_next_file;
4280 if (blit_frame) {
4281 struct sh_video *sh_video = mpctx->sh_video;
4282 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4283 mpctx->video_offset, mpctx->d_sub, 0);
4284 update_teletext(sh_video, mpctx->demuxer, 0);
4285 update_osd_msg(mpctx);
4286 struct vf_instance *vf = mpctx->sh_video->vfilter;
4287 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4288 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4289 vo_osd_changed(0);
4291 if (frame_time < 0)
4292 mpctx->stop_play = AT_END_OF_FILE;
4293 else if (!mpctx->restart_playback) {
4294 mpctx->time_frame += frame_time / opts->playback_speed;
4295 adjust_sync(mpctx, frame_time);
4298 if (mpctx->timeline) {
4299 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4300 if (mpctx->sh_video->pts >= next->start
4301 || mpctx->stop_play == AT_END_OF_FILE
4302 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4303 seek(mpctx, next->start, SEEK_ABSOLUTE);
4304 continue;
4308 // ==========================================================================
4310 // current_module="draw_osd";
4311 // if(vo_config_count) mpctx->video_out->draw_osd();
4313 current_module="vo_check_events";
4314 vo_check_events(mpctx->video_out);
4316 #ifdef CONFIG_X11
4317 if (stop_xscreensaver) {
4318 current_module = "stop_xscreensaver";
4319 xscreensaver_heartbeat(mpctx->x11_state);
4321 #endif
4322 if (heartbeat_cmd) {
4323 static unsigned last_heartbeat;
4324 unsigned now = GetTimerMS();
4325 if (now - last_heartbeat > 30000) {
4326 last_heartbeat = now;
4327 system(heartbeat_cmd);
4331 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4333 //====================== FLIP PAGE (VIDEO BLT): =========================
4335 current_module="flip_page";
4336 if (!frame_time_remaining && blit_frame) {
4337 unsigned int t2=GetTimer();
4338 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4339 int duration = -1;
4340 double pts2 = mpctx->video_out->next_pts2;
4341 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
4342 && !mpctx->restart_playback) {
4343 // expected A/V sync correction is ignored
4344 double diff = (pts2 - mpctx->sh_video->pts);
4345 diff /= opts->playback_speed;
4346 if (mpctx->time_frame < 0)
4347 diff += mpctx->time_frame;
4348 if (diff < 0)
4349 diff = 0;
4350 if (diff > 10)
4351 diff = 10;
4352 duration = diff * 1e6;
4354 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4356 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4357 vout_time_usage += mpctx->last_vo_flip_duration;
4358 if (mpctx->video_out->driver->flip_page_timed) {
4359 // No need to adjust sync based on flip speed
4360 mpctx->last_vo_flip_duration = 0;
4361 // For print_status - VO call finishing early is OK for sync
4362 mpctx->time_frame -= get_relative_time(mpctx);
4364 if (mpctx->restart_playback) {
4365 mpctx->syncing_audio = true;
4366 if (mpctx->sh_audio && !mpctx->paused)
4367 fill_audio_out_buffers(mpctx);
4368 mpctx->restart_playback = false;
4369 mpctx->time_frame = 0;
4370 get_relative_time(mpctx);
4372 print_status(mpctx, MP_NOPTS_VALUE, true);
4374 else
4375 print_status(mpctx, MP_NOPTS_VALUE, false);
4377 //============================ Auto QUALITY ============================
4379 /*Output quality adjustments:*/
4380 if (opts->auto_quality > 0) {
4381 current_module="autoq";
4382 // float total=0.000001f * (GetTimer()-aq_total_time);
4383 // if (output_quality < opts->auto_quality && aq_sleep_time > 0.05f * total)
4384 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
4385 ++output_quality;
4386 else
4387 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4388 if(output_quality>1 && aq_sleep_time<0)
4389 --output_quality;
4390 else
4391 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4392 output_quality=0;
4393 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4394 set_video_quality(mpctx->sh_video,output_quality);
4397 if (!frame_time_remaining && blit_frame) {
4398 if (play_n_frames >= 0) {
4399 --play_n_frames;
4400 if (play_n_frames <= 0)
4401 mpctx->stop_play = PT_NEXT_ENTRY;
4403 if (mpctx->step_frames > 0) {
4404 mpctx->step_frames--;
4405 if (mpctx->step_frames == 0)
4406 pause_player(mpctx);
4411 // FIXME: add size based support for -endpos
4412 if (end_at.type == END_AT_TIME &&
4413 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4414 mpctx->stop_play = PT_NEXT_ENTRY;
4416 } // end if(mpctx->sh_video)
4418 #ifdef CONFIG_DVDNAV
4419 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4420 nav_highlight_t hl;
4421 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4422 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4423 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4424 vo_osd_changed (OSDTYPE_DVDNAV);
4425 } else {
4426 osd_set_nav_box(0, 0, 0, 0);
4427 vo_osd_changed(OSDTYPE_DVDNAV);
4428 vo_osd_changed(OSDTYPE_SPU);
4431 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4432 double ar = -1.0;
4433 if (mpctx->sh_video &&
4434 stream_control (mpctx->demuxer->stream,
4435 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4436 != STREAM_UNSUPPORTED)
4437 mpctx->sh_video->stream_aspect = ar;
4440 #endif
4442 //================= Keyboard events, SEEKing ====================
4444 current_module="key_events";
4447 while (1) {
4448 mp_cmd_t* cmd;
4449 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4450 run_command(mpctx, cmd);
4451 mp_cmd_free(cmd);
4452 if (mpctx->stop_play)
4453 break;
4454 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4455 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4456 /* Allow seek commands to be combined, but execute the real seek
4457 * before processing other commands */
4458 if (!cmd || cmd->id != MP_CMD_SEEK)
4459 break;
4462 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4463 || mpctx->abs_seek_pos)
4464 break;
4465 if (mpctx->sh_video) {
4466 update_osd_msg(mpctx);
4467 int hack = vo_osd_changed(0);
4468 vo_osd_changed(hack);
4469 if (hack) {
4470 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4471 add_step_frame(mpctx);
4472 break;
4474 else
4475 vo_osd_changed(0);
4478 pause_loop(mpctx);
4482 // handle -sstep
4483 if (step_sec > 0 && !mpctx->paused) {
4484 mpctx->osd_function=OSD_FFW;
4485 mpctx->rel_seek_secs+=step_sec;
4488 edl_update(mpctx);
4490 /* Looping. */
4491 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4492 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4494 if(opts->loop_times>1) opts->loop_times--; else
4495 if(opts->loop_times==1) opts->loop_times=-1;
4496 play_n_frames=play_n_frames_mf;
4497 mpctx->stop_play=0;
4498 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4501 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4502 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4504 mpctx->rel_seek_secs=0;
4505 mpctx->abs_seek_pos=0;
4508 } // while(!mpctx->stop_play)
4510 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4512 #ifdef CONFIG_DVBIN
4513 if(mpctx->dvbin_reopen)
4515 mpctx->stop_play = 0;
4516 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4517 cache_uninit(mpctx->stream);
4518 mpctx->dvbin_reopen = 0;
4519 goto goto_enable_cache;
4521 #endif
4524 goto_next_file: // don't jump here after ao/vo/getch initialization!
4526 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4528 if (opts->benchmark) {
4529 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4530 double total_time_usage;
4531 total_time_usage_start=GetTimer()-total_time_usage_start;
4532 total_time_usage = (float)total_time_usage_start*0.000001;
4533 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4534 video_time_usage,vout_time_usage,audio_time_usage,
4535 total_time_usage-tot,total_time_usage);
4536 if(total_time_usage>0.0)
4537 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4538 100.0*video_time_usage/total_time_usage,
4539 100.0*vout_time_usage/total_time_usage,
4540 100.0*audio_time_usage/total_time_usage,
4541 100.0*(total_time_usage-tot)/total_time_usage,
4542 100.0);
4543 if(total_frame_cnt && frame_dropping)
4544 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4545 total_frame_cnt-drop_frame_cnt,
4546 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4547 drop_frame_cnt,
4548 100*drop_frame_cnt/total_frame_cnt,
4549 total_frame_cnt,
4550 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4553 // time to uninit all, except global stuff:
4554 int uninitialize_parts = INITIALIZED_ALL;
4555 if (opts->fixed_vo)
4556 uninitialize_parts -= INITIALIZED_VO;
4557 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4558 uninitialize_parts -= INITIALIZED_AO;
4559 uninit_player(mpctx, uninitialize_parts);
4561 if(mpctx->set_of_sub_size > 0) {
4562 current_module="sub_free";
4563 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4564 sub_free(mpctx->set_of_subtitles[i]);
4565 #ifdef CONFIG_ASS
4566 if(mpctx->set_of_ass_tracks[i])
4567 ass_free_track( mpctx->set_of_ass_tracks[i] );
4568 #endif
4570 mpctx->set_of_sub_size = 0;
4572 vo_sub_last = vo_sub=NULL;
4573 subdata=NULL;
4574 #ifdef CONFIG_ASS
4575 ass_track = NULL;
4576 if(ass_library)
4577 ass_clear_fonts(ass_library);
4578 #endif
4580 if (!mpctx->stop_play) // In case some goto jumped here...
4581 mpctx->stop_play = PT_NEXT_ENTRY;
4583 int playtree_direction = 1;
4585 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4586 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4587 play_tree_iter_free(mpctx->playtree_iter);
4588 mpctx->playtree_iter = NULL;
4590 mpctx->play_tree_step = 1;
4591 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4592 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4593 if(mpctx->playtree_iter) {
4594 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4595 play_tree_iter_free(mpctx->playtree_iter);
4596 mpctx->playtree_iter = NULL;
4599 } else if (mpctx->stop_play == PT_STOP) {
4600 play_tree_iter_free(mpctx->playtree_iter);
4601 mpctx->playtree_iter = NULL;
4602 } else { // NEXT PREV SRC
4603 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4606 while(mpctx->playtree_iter != NULL) {
4607 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4608 if(mpctx->filename == NULL) {
4609 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4610 play_tree_iter_free(mpctx->playtree_iter);
4611 mpctx->playtree_iter = NULL;
4613 } else
4614 break;
4617 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4618 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4619 mpctx->stop_play = 0;
4620 goto play_next_file;
4624 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4626 return 1;
4628 #endif /* DISABLE_MAIN */