av_sub: Support clearing subtitles
[mplayer/glamo.git] / mplayer.c
blob8386bb1afd0e1ab6e51adfe220138f416904e584
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 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 = strrchr(cfg, '/');
1025 if (HAVE_DOS_PATHS) {
1026 char *tmp = strrchr(cfg, '\\');
1027 if (!name || tmp > name)
1028 name = tmp;
1029 tmp = strrchr(cfg, ':');
1030 if (!name || tmp > name)
1031 name = tmp;
1033 if (!name)
1034 name = cfg;
1035 else
1036 name++;
1038 if (use_filedir_conf) {
1039 char dircfg[PATH_MAX];
1040 strcpy(dircfg, cfg);
1041 strcpy(dircfg + (name - cfg), "mplayer.conf");
1042 try_load_config(conf, dircfg);
1044 if (try_load_config(conf, cfg))
1045 return;
1048 if ((confpath = get_path (name)) != NULL)
1050 try_load_config(conf, confpath);
1052 free (confpath);
1056 /* When libmpdemux performs a blocking operation (network connection or
1057 * cache filling) if the operation fails we use this function to check
1058 * if it was interrupted by the user.
1059 * The function returns a new value for eof. */
1060 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1062 mp_cmd_t* cmd;
1063 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1064 switch(cmd->id) {
1065 case MP_CMD_QUIT:
1066 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1067 case MP_CMD_PLAY_TREE_STEP: {
1068 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1069 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1070 } break;
1071 case MP_CMD_PLAY_TREE_UP_STEP: {
1072 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1073 } break;
1074 case MP_CMD_PLAY_ALT_SRC_STEP: {
1075 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1076 } break;
1078 mp_cmd_free(cmd);
1080 return stop_play;
1083 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1085 play_tree_add_bpf(entry,mpctx->filename);
1088 if(!entry) {
1089 entry = mpctx->playtree_iter->tree;
1090 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1091 return PT_NEXT_ENTRY;
1093 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1094 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1095 return PT_NEXT_ENTRY;
1098 play_tree_remove(entry,1,1);
1099 return PT_NEXT_SRC;
1101 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1102 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1103 entry = mpctx->playtree_iter->tree;
1104 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1105 return PT_NEXT_ENTRY;
1107 play_tree_remove(entry,1,1);
1109 return PT_NEXT_SRC;
1112 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1114 struct MPOpts *opts = &mpctx->opts;
1115 sub_data *subd = NULL;
1116 struct ass_track *asst = NULL;
1118 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1119 return;
1122 #ifdef CONFIG_ASS
1123 if (opts->ass_enabled) {
1124 #ifdef CONFIG_ICONV
1125 asst = ass_read_stream(ass_library, filename, sub_cp);
1126 #else
1127 asst = ass_read_stream(ass_library, filename, 0);
1128 #endif
1129 if (!asst) {
1130 subd = sub_read_file(filename, fps);
1131 if (subd) {
1132 asst = ass_read_subdata(ass_library, subd, fps);
1133 if (asst) {
1134 sub_free(subd);
1135 subd = NULL;
1139 } else
1140 #endif
1141 subd = sub_read_file(filename, fps);
1144 if (!asst && !subd) {
1145 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1146 "Cannot load subtitles: %s\n", filename_recode(filename));
1147 return;
1150 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1151 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1152 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1153 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1154 filename_recode(filename));
1155 ++mpctx->set_of_sub_size;
1156 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1157 filename_recode(filename));
1160 void init_vo_spudec(struct MPContext *mpctx)
1162 spudec_free(vo_spudec);
1163 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1164 vo_spudec = NULL;
1166 // we currently can't work without video stream
1167 if (!mpctx->sh_video)
1168 return;
1170 if (spudec_ifo) {
1171 unsigned int palette[16], width, height;
1172 current_module="spudec_init_vobsub";
1173 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1174 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1177 #ifdef CONFIG_DVDREAD
1178 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1179 current_module="spudec_init_dvdread";
1180 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1181 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1182 NULL, 0);
1184 #endif
1186 #ifdef CONFIG_DVDNAV
1187 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1188 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1189 current_module="spudec_init_dvdnav";
1190 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1192 #endif
1194 if (vo_spudec==NULL) {
1195 sh_sub_t *sh = mpctx->d_sub->sh;
1196 current_module="spudec_init_normal";
1197 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1198 spudec_set_font_factor(vo_spudec,font_factor);
1201 if (vo_spudec!=NULL) {
1202 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1203 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1208 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1209 * make it all work is to use the builtin SDL-bootstrap code, which
1210 * will be done automatically by replacing our main() if we include SDL.h.
1212 #if defined(__APPLE__) && defined(CONFIG_SDL)
1213 #ifdef CONFIG_SDL_SDL_H
1214 #include <SDL/SDL.h>
1215 #else
1216 #include <SDL.h>
1217 #endif
1218 #endif
1221 * \brief append a formatted string
1222 * \param buf buffer to print into
1223 * \param pos position of terminating 0 in buf
1224 * \param len maximum number of characters in buf, not including terminating 0
1225 * \param format printf format string
1227 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1229 va_list va;
1230 va_start(va, format);
1231 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1232 va_end(va);
1233 if (*pos >= len ) {
1234 buf[len] = 0;
1235 *pos = len;
1240 * \brief append time in the hh:mm:ss.f format
1241 * \param buf buffer to print into
1242 * \param pos position of terminating 0 in buf
1243 * \param len maximum number of characters in buf, not including terminating 0
1244 * \param time time value to convert/append
1246 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1247 int64_t tenths = 10 * time;
1248 int f1 = tenths % 10;
1249 int ss = (tenths / 10) % 60;
1250 int mm = (tenths / 600) % 60;
1251 int hh = tenths / 36000;
1252 if (time <= 0) {
1253 saddf(buf, pos, len, "unknown");
1254 return;
1256 if (hh > 0)
1257 saddf(buf, pos, len, "%2d:", hh);
1258 if (hh > 0 || mm > 0)
1259 saddf(buf, pos, len, "%02d:", mm);
1260 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1263 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1265 struct MPOpts *opts = &mpctx->opts;
1266 sh_video_t * const sh_video = mpctx->sh_video;
1268 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1269 a_pos = playing_audio_pts(mpctx);
1270 if (mpctx->sh_audio && sh_video && at_frame) {
1271 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1272 if (mpctx->time_frame > 0)
1273 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1274 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1275 && !mpctx->drop_message_shown) {
1276 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1277 mpctx->drop_message_shown = true;
1280 if (opts->quiet)
1281 return;
1284 int width;
1285 char *line;
1286 unsigned pos = 0;
1287 get_screen_size();
1288 if (screen_width > 0)
1289 width = screen_width;
1290 else
1291 width = 80;
1292 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1293 /* Windows command line is broken (MinGW's rxvt works, but we
1294 * should not depend on that). */
1295 width--;
1296 #endif
1297 line = malloc(width + 1); // one additional char for the terminating null
1299 // Audio time
1300 if (mpctx->sh_audio) {
1301 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1302 if (!sh_video) {
1303 float len = get_time_length(mpctx);
1304 saddf(line, &pos, width, "(");
1305 sadd_hhmmssf(line, &pos, width, a_pos);
1306 saddf(line, &pos, width, ") of %.1f (", len);
1307 sadd_hhmmssf(line, &pos, width, len);
1308 saddf(line, &pos, width, ") ");
1312 // Video time
1313 if (sh_video)
1314 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1316 // A-V sync
1317 if (mpctx->sh_audio && sh_video)
1318 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1319 mpctx->last_av_difference, mpctx->total_avsync_change);
1321 // Video stats
1322 if (sh_video)
1323 saddf(line, &pos, width, "%3d/%3d ",
1324 (int)sh_video->num_frames,
1325 (int)sh_video->num_frames_decoded);
1327 // CPU usage
1328 if (sh_video) {
1329 if (sh_video->timer > 0.5)
1330 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1331 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1332 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1333 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1334 else
1335 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1336 } else if (mpctx->sh_audio) {
1337 if (mpctx->delay > 0.5)
1338 saddf(line, &pos, width, "%4.1f%% ",
1339 100.0*audio_time_usage/(double)mpctx->delay);
1340 else
1341 saddf(line, &pos, width, "??,?%% ");
1344 // VO stats
1345 if (sh_video)
1346 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1348 #ifdef CONFIG_STREAM_CACHE
1349 // cache stats
1350 if (stream_cache_size > 0)
1351 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1352 #endif
1354 // other
1355 if (opts->playback_speed != 1)
1356 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1358 // end
1359 if (erase_to_end_of_line) {
1360 line[pos] = 0;
1361 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1362 } else {
1363 memset(&line[pos], ' ', width - pos);
1364 line[width] = 0;
1365 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1367 free(line);
1371 * \brief build a chain of audio filters that converts the input format
1372 * to the ao's format, taking into account the current playback_speed.
1373 * \param sh_audio describes the requested input format of the chain.
1374 * \param ao_data describes the requested output format of the chain.
1376 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1377 ao_data_t *ao_data)
1379 struct MPOpts *opts = &mpctx->opts;
1380 int new_srate;
1381 int result;
1382 if (!sh_audio)
1384 mpctx->mixer.afilter = NULL;
1385 return 0;
1387 if(af_control_any_rev(sh_audio->afilter,
1388 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1389 &opts->playback_speed)) {
1390 new_srate = sh_audio->samplerate;
1391 } else {
1392 new_srate = sh_audio->samplerate * opts->playback_speed;
1393 if (new_srate != ao_data->samplerate) {
1394 // limits are taken from libaf/af_resample.c
1395 if (new_srate < 8000)
1396 new_srate = 8000;
1397 if (new_srate > 192000)
1398 new_srate = 192000;
1399 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1402 result = init_audio_filters(sh_audio, new_srate,
1403 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1404 mpctx->mixer.afilter = sh_audio->afilter;
1405 return result;
1409 typedef struct mp_osd_msg mp_osd_msg_t;
1410 struct mp_osd_msg {
1411 /// Previous message on the stack.
1412 mp_osd_msg_t* prev;
1413 /// Message text.
1414 char msg[128];
1415 int id,level,started;
1416 /// Display duration in ms.
1417 unsigned time;
1420 /// OSD message stack.
1421 static mp_osd_msg_t* osd_msg_stack = NULL;
1424 * \brief Add a message on the OSD message stack
1426 * If a message with the same id is already present in the stack
1427 * it is pulled on top of the stack, otherwise a new message is created.
1430 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1431 va_list ap)
1433 mp_osd_msg_t *msg,*last=NULL;
1434 int r;
1436 // look if the id is already in the stack
1437 for(msg = osd_msg_stack ; msg && msg->id != id ;
1438 last = msg, msg = msg->prev);
1439 // not found: alloc it
1440 if(!msg) {
1441 msg = calloc(1,sizeof(mp_osd_msg_t));
1442 msg->prev = osd_msg_stack;
1443 osd_msg_stack = msg;
1444 } else if(last) { // found, but it's not on top of the stack
1445 last->prev = msg->prev;
1446 msg->prev = osd_msg_stack;
1447 osd_msg_stack = msg;
1449 // write the msg
1450 r = vsnprintf(msg->msg, 128, fmt, ap);
1451 if(r >= 128) msg->msg[127] = 0;
1452 // set id and time
1453 msg->id = id;
1454 msg->level = level;
1455 msg->time = time;
1459 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1461 va_list ap;
1462 va_start(ap, fmt);
1463 set_osd_msg_va(id, level, time, fmt, ap);
1464 va_end(ap);
1467 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1469 va_list ap;
1470 va_start(ap, fmt);
1471 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1472 va_end(ap);
1477 * \brief Remove a message from the OSD stack
1479 * This function can be used to get rid of a message right away.
1483 void rm_osd_msg(int id) {
1484 mp_osd_msg_t *msg,*last=NULL;
1486 // Search for the msg
1487 for(msg = osd_msg_stack ; msg && msg->id != id ;
1488 last = msg, msg = msg->prev);
1489 if(!msg) return;
1491 // Detach it from the stack and free it
1492 if(last)
1493 last->prev = msg->prev;
1494 else
1495 osd_msg_stack = msg->prev;
1496 free(msg);
1500 * \brief Remove all messages from the OSD stack
1504 static void clear_osd_msgs(void) {
1505 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1506 while(msg) {
1507 prev = msg->prev;
1508 free(msg);
1509 msg = prev;
1511 osd_msg_stack = NULL;
1515 * \brief Get the current message from the OSD stack.
1517 * This function decrements the message timer and destroys the old ones.
1518 * The message that should be displayed is returned (if any).
1522 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1524 struct MPOpts *opts = &mpctx->opts;
1525 mp_osd_msg_t *msg,*prev,*last = NULL;
1526 static unsigned last_update = 0;
1527 unsigned now = GetTimerMS();
1528 unsigned diff;
1529 char hidden_dec_done = 0;
1531 if (mpctx->osd_visible) {
1532 // 36000000 means max timed visibility is 1 hour into the future, if
1533 // the difference is greater assume it's wrapped around from below 0
1534 if (mpctx->osd_visible - now > 36000000) {
1535 mpctx->osd_visible = 0;
1536 vo_osd_progbar_type = -1; // disable
1537 vo_osd_changed(OSDTYPE_PROGBAR);
1538 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1541 if (mpctx->osd_show_percentage_until - now > 36000000)
1542 mpctx->osd_show_percentage_until = 0;
1544 if(!last_update) last_update = now;
1545 diff = now >= last_update ? now - last_update : 0;
1547 last_update = now;
1549 // Look for the first message in the stack with high enough level.
1550 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1551 prev = msg->prev;
1552 if (msg->level > opts->osd_level && hidden_dec_done)
1553 continue;
1554 // The message has a high enough level or it is the first hidden one
1555 // in both cases we decrement the timer or kill it.
1556 if(!msg->started || msg->time > diff) {
1557 if(msg->started) msg->time -= diff;
1558 else msg->started = 1;
1559 // display it
1560 if (msg->level <= opts->osd_level)
1561 return msg;
1562 hidden_dec_done = 1;
1563 continue;
1565 // kill the message
1566 free(msg);
1567 if(last) {
1568 last->prev = prev;
1569 msg = last;
1570 } else {
1571 osd_msg_stack = prev;
1572 msg = NULL;
1575 // Nothing found
1576 return NULL;
1580 * \brief Display the OSD bar.
1582 * Display the OSD bar or fall back on a simple message.
1586 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1587 struct MPOpts *opts = &mpctx->opts;
1588 if (opts->osd_level < 1)
1589 return;
1591 if(mpctx->sh_video) {
1592 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1593 vo_osd_progbar_type = type;
1594 vo_osd_progbar_value = 256*(val-min)/(max-min);
1595 vo_osd_changed(OSDTYPE_PROGBAR);
1596 return;
1599 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1600 name, ROUND(100*(val-min)/(max-min)));
1604 * \brief Display text subtitles on the OSD
1606 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1608 int i;
1609 vo_sub = subs;
1610 vo_osd_changed(OSDTYPE_SUBTITLE);
1611 if (!mpctx->sh_video) {
1612 // reverse order, since newest set_osd_msg is displayed first
1613 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1614 if (!subs || i >= subs->lines || !subs->text[i])
1615 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1616 else {
1617 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1618 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1619 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1626 * \brief Update the OSD message line.
1628 * This function displays the current message on the vo OSD or on the term.
1629 * If the stack is empty and the OSD level is high enough the timer
1630 * is displayed (only on the vo OSD).
1634 static void update_osd_msg(struct MPContext *mpctx)
1636 struct MPOpts *opts = &mpctx->opts;
1637 mp_osd_msg_t *msg;
1638 struct osd_state *osd = mpctx->osd;
1639 char osd_text_timer[128];
1641 if (mpctx->add_osd_seek_info) {
1642 double percentage = get_percent_pos(mpctx);
1643 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1644 if (mpctx->sh_video)
1645 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1646 mpctx->add_osd_seek_info = false;
1649 // Look if we have a msg
1650 if((msg = get_osd_msg(mpctx))) {
1651 if (strcmp(osd->osd_text, msg->msg)) {
1652 strncpy(osd->osd_text, msg->msg, 127);
1653 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1654 if(opts->term_osd)
1655 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1656 msg->msg);
1658 return;
1661 if(mpctx->sh_video) {
1662 // fallback on the timer
1663 if (opts->osd_level >= 2) {
1664 int len = get_time_length(mpctx);
1665 int percentage = -1;
1666 char percentage_text[10];
1667 int pts = get_current_time(mpctx);
1669 if (mpctx->osd_show_percentage_until)
1670 percentage = get_percent_pos(mpctx);
1672 if (percentage >= 0)
1673 snprintf(percentage_text, 9, " (%d%%)", percentage);
1674 else
1675 percentage_text[0] = 0;
1677 if (opts->osd_level == 3)
1678 snprintf(osd_text_timer, 63,
1679 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1680 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1681 len/3600,(len/60)%60,len%60,percentage_text);
1682 else
1683 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1684 mpctx->osd_function,pts/3600,(pts/60)%60,
1685 pts%60,percentage_text);
1686 } else
1687 osd_text_timer[0]=0;
1689 if (strcmp(osd->osd_text, osd_text_timer)) {
1690 strncpy(osd->osd_text, osd_text_timer, 63);
1691 vo_osd_changed(OSDTYPE_OSD);
1693 return;
1696 // Clear the term osd line
1697 if (opts->term_osd && osd->osd_text[0]) {
1698 osd->osd_text[0] = 0;
1699 printf("%s\n", opts->term_osd_esc);
1703 ///@}
1704 // OSDMsgStack
1707 void reinit_audio_chain(struct MPContext *mpctx)
1709 struct MPOpts *opts = &mpctx->opts;
1710 if (!mpctx->sh_audio)
1711 return;
1712 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1713 current_module="init_audio_codec";
1714 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1715 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1716 goto init_error;
1718 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1719 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1723 current_module="af_preinit";
1724 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1725 ao_data.samplerate=force_srate;
1726 ao_data.channels=0;
1727 ao_data.format = opts->audio_output_format;
1729 // first init to detect best values
1730 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1731 // input:
1732 mpctx->sh_audio->samplerate,
1733 // output:
1734 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1735 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1736 "pre-init!\n");
1737 exit_player(mpctx, EXIT_ERROR);
1739 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1740 current_module="ao2_init";
1741 ao_data.buffersize = opts->ao_buffersize;
1742 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1743 0, // plugin flag
1744 ao_data.samplerate,
1745 ao_data.channels,
1746 ao_data.format, 0);
1747 if(!mpctx->audio_out){
1748 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1749 goto init_error;
1751 mpctx->initialized_flags|=INITIALIZED_AO;
1752 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1753 mpctx->audio_out->info->short_name,
1754 ao_data.samplerate, ao_data.channels,
1755 af_fmt2str_short(ao_data.format),
1756 af_fmt2bits(ao_data.format)/8 );
1757 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1758 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1759 if(strlen(mpctx->audio_out->info->comment) > 0)
1760 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1763 // init audio filters:
1764 current_module="af_init";
1765 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1766 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1767 goto init_error;
1769 mpctx->mixer.audio_out = mpctx->audio_out;
1770 mpctx->mixer.volstep = volstep;
1771 mpctx->syncing_audio = true;
1772 return;
1774 init_error:
1775 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1776 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1777 mpctx->d_audio->id = -2;
1781 ///@}
1782 // Command2Property
1785 // Return pts value corresponding to the end point of audio written to the
1786 // ao so far.
1787 static double written_audio_pts(struct MPContext *mpctx)
1789 sh_audio_t *sh_audio = mpctx->sh_audio;
1790 demux_stream_t *d_audio = mpctx->d_audio;
1791 double buffered_output;
1792 // first calculate the end pts of audio that has been output by decoder
1793 double a_pts = sh_audio->pts;
1794 if (a_pts != MP_NOPTS_VALUE)
1795 // Good, decoder supports new way of calculating audio pts.
1796 // sh_audio->pts is the timestamp of the latest input packet with
1797 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1798 // the amount of bytes the decoder has written after that timestamp.
1799 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1800 else {
1801 // Decoder doesn't support new way of calculating pts (or we're
1802 // being called before it has decoded anything with known timestamp).
1803 // Use the old method of audio pts calculation: take the timestamp
1804 // of last packet with known pts the decoder has read data from,
1805 // and add amount of bytes read after the beginning of that packet
1806 // divided by input bps. This will be inaccurate if the input/output
1807 // ratio is not constant for every audio packet or if it is constant
1808 // but not accurately known in sh_audio->i_bps.
1810 a_pts = d_audio->pts;
1811 // ds_tell_pts returns bytes read after last timestamp from
1812 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1813 // it has read but not decoded
1814 if (sh_audio->i_bps)
1815 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1816 (double)sh_audio->i_bps;
1818 // Now a_pts hopefully holds the pts for end of audio from decoder.
1819 // Substract data in buffers between decoder and audio out.
1821 // Decoded but not filtered
1822 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1824 // Data buffered in audio filters, measured in bytes of "missing" output
1825 buffered_output = af_calc_delay(sh_audio->afilter);
1827 // Data that was ready for ao but was buffered because ao didn't fully
1828 // accept everything to internal buffers yet
1829 buffered_output += sh_audio->a_out_buffer_len;
1831 // Filters divide audio length by playback_speed, so multiply by it
1832 // to get the length in original units without speedup or slowdown
1833 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1835 return a_pts + mpctx->video_offset;
1838 // Return pts value corresponding to currently playing audio.
1839 double playing_audio_pts(struct MPContext *mpctx)
1841 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1842 mpctx->audio_out->get_delay();
1845 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1846 struct MPOpts *opts = &mpctx->opts;
1847 // check for frame-drop:
1848 current_module = "check_framedrop";
1849 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1850 static int dropped_frames;
1851 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1852 float d = delay-mpctx->delay;
1853 ++total_frame_cnt;
1854 // we should avoid dropping too many frames in sequence unless we
1855 // are too late. and we allow 100ms A-V delay here:
1856 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1857 && !mpctx->restart_playback) {
1858 ++drop_frame_cnt;
1859 ++dropped_frames;
1860 return frame_dropping;
1861 } else
1862 dropped_frames = 0;
1864 return 0;
1868 #ifdef HAVE_RTC
1869 int rtc_fd = -1;
1870 #endif
1872 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1874 #ifdef HAVE_RTC
1875 if (rtc_fd >= 0){
1876 // -------- RTC -----------
1877 current_module="sleep_rtc";
1878 while (time_frame > 0.000) {
1879 unsigned long rtc_ts;
1880 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1881 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1882 time_frame -= get_relative_time(mpctx);
1884 } else
1885 #endif
1887 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1888 // unnecessarily high CPU usage
1889 struct MPOpts *opts = &mpctx->opts;
1890 float margin = opts->softsleep ? 0.011 : 0;
1891 current_module = "sleep_timer";
1892 while (time_frame > margin) {
1893 usec_sleep(1000000 * (time_frame - margin));
1894 time_frame -= get_relative_time(mpctx);
1896 if (opts->softsleep){
1897 current_module = "sleep_soft";
1898 if (time_frame < 0)
1899 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1900 while (time_frame > 0)
1901 time_frame -= get_relative_time(mpctx); // burn the CPU
1904 return time_frame;
1907 static int select_subtitle(MPContext *mpctx)
1909 struct MPOpts *opts = &mpctx->opts;
1910 // find the best sub to use
1911 int id;
1912 int found = 0;
1913 mpctx->global_sub_pos = -1; // no subs by default
1914 if (vobsub_id >= 0) {
1915 // if user asks for a vobsub id, use that first.
1916 id = vobsub_id;
1917 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1920 if (!found && opts->sub_id >= 0) {
1921 // if user asks for a dvd sub id, use that next.
1922 id = opts->sub_id;
1923 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1926 if (!found) {
1927 // if there are text subs to use, use those. (autosubs come last here)
1928 id = 0;
1929 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1932 if (!found && opts->sub_id == -1) {
1933 // finally select subs by language and container hints
1934 if (opts->sub_id == -1)
1935 opts->sub_id =
1936 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
1937 opts->sub_lang);
1938 if (opts->sub_id >= 0) {
1939 id = opts->sub_id;
1940 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1943 return found;
1946 #ifdef CONFIG_DVDNAV
1947 #ifndef FF_B_TYPE
1948 #define FF_B_TYPE 3
1949 #endif
1950 /// store decoded video image
1951 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1952 mp_image_t *from_mpi) {
1953 mp_image_t *mpi;
1955 /// Do not store B-frames
1956 if (from_mpi->pict_type == FF_B_TYPE)
1957 return to_mpi;
1959 if (to_mpi &&
1960 to_mpi->w == from_mpi->w &&
1961 to_mpi->h == from_mpi->h &&
1962 to_mpi->imgfmt == from_mpi->imgfmt)
1963 mpi = to_mpi;
1964 else {
1965 if (to_mpi)
1966 free_mp_image(to_mpi);
1967 if (from_mpi->w == 0 || from_mpi->h == 0)
1968 return NULL;
1969 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1972 copy_mpi(mpi,from_mpi);
1973 return mpi;
1976 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1977 struct MPOpts *opts = &ctx->opts;
1978 if (ctx->sh_video) {
1979 /// clear video pts
1980 ctx->d_video->pts = 0.0f;
1981 ctx->sh_video->pts = 0.0f;
1982 ctx->sh_video->i_pts = 0.0f;
1983 ctx->sh_video->last_pts = 0.0f;
1984 ctx->sh_video->num_buffered_pts = 0;
1985 ctx->sh_video->num_frames = 0;
1986 ctx->sh_video->num_frames_decoded = 0;
1987 ctx->sh_video->timer = 0.0f;
1988 ctx->sh_video->stream_delay = 0.0f;
1989 ctx->sh_video->timer = 0;
1990 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1993 if (ctx->sh_audio) {
1994 /// free audio packets and reset
1995 ds_free_packs(ctx->d_audio);
1996 audio_delay -= ctx->sh_audio->stream_delay;
1997 ctx->delay =- audio_delay;
1998 ctx->audio_out->reset();
1999 resync_audio_stream(ctx->sh_audio);
2002 audio_delay = 0.0f;
2003 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2004 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2005 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2006 if (dvdsub_lang_id != opts->sub_id) {
2007 opts->sub_id = dvdsub_lang_id;
2008 select_subtitle(ctx);
2012 /// clear all EOF related flags
2013 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2016 /// Restore last decoded DVDNAV (still frame)
2017 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2018 int *in_size,
2019 unsigned char **start,
2020 mp_image_t *decoded_frame)
2022 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2023 return decoded_frame;
2025 /// a change occured in dvdnav stream
2026 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2027 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2028 mp_dvdnav_context_free(mpctx);
2029 mp_dvdnav_reset_stream(mpctx);
2030 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2031 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2034 if (*in_size < 0) {
2035 float len;
2037 /// Display still frame, if any
2038 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2039 decoded_frame = mpctx->nav_smpi;
2041 /// increment video frame : continue playing after still frame
2042 len = get_time_length(mpctx);
2043 if (mpctx->sh_video->pts >= len &&
2044 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2045 mp_dvdnav_skip_still(mpctx->stream);
2046 mp_dvdnav_skip_wait(mpctx->stream);
2048 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2050 if (mpctx->nav_buffer) {
2051 *start = mpctx->nav_start;
2052 *in_size = mpctx->nav_in_size;
2053 if (mpctx->nav_start)
2054 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2058 return decoded_frame;
2061 /// Save last decoded DVDNAV (still frame)
2062 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2063 unsigned char *start,
2064 mp_image_t *decoded_frame)
2066 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2067 return;
2069 free(mpctx->nav_buffer);
2071 mpctx->nav_buffer = malloc(in_size);
2072 mpctx->nav_start = start;
2073 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2074 if (mpctx->nav_buffer)
2075 memcpy(mpctx->nav_buffer,start,in_size);
2077 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2078 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2080 #endif /* CONFIG_DVDNAV */
2082 /* Modify video timing to match the audio timeline. There are two main
2083 * reasons this is needed. First, video and audio can start from different
2084 * positions at beginning of file or after a seek (MPlayer starts both
2085 * immediately even if they have different pts). Second, the file can have
2086 * audio timestamps that are inconsistent with the duration of the audio
2087 * packets, for example two consecutive timestamp values differing by
2088 * one second but only a packet with enough samples for half a second
2089 * of playback between them.
2091 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2093 current_module = "av_sync";
2095 if (!mpctx->sh_audio || mpctx->syncing_audio)
2096 return;
2098 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2099 double v_pts = mpctx->sh_video->pts;
2100 double av_delay = a_pts - v_pts;
2101 // Try to sync vo_flip() so it will *finish* at given time
2102 av_delay += mpctx->last_vo_flip_duration;
2103 av_delay -= audio_delay; // This much pts difference is desired
2105 double change = av_delay * 0.1;
2106 double max_change = default_max_pts_correction >= 0 ?
2107 default_max_pts_correction : frame_time * 0.1;
2108 if (change < -max_change)
2109 change = -max_change;
2110 else if (change > max_change)
2111 change = max_change;
2112 mpctx->delay += change;
2113 mpctx->total_avsync_change += change;
2116 #define ASYNC_PLAY_DONE -3
2117 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2119 struct MPOpts *opts = &mpctx->opts;
2120 sh_audio_t * const sh_audio = mpctx->sh_audio;
2121 int res;
2123 // Timing info may not be set without
2124 res = decode_audio(sh_audio, 1);
2125 if (res < 0)
2126 return res;
2128 int bytes;
2129 while (1) {
2130 double written_pts = written_audio_pts(mpctx);
2131 double ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2132 - audio_delay;
2133 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2134 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2136 if (fabs(ptsdiff) > 300 // pts reset or just broken?
2137 || written_pts <= 0) // ogg demuxers give packets without timing
2138 bytes = 0;
2140 if (bytes > 0)
2141 break;
2143 mpctx->syncing_audio = false;
2144 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2145 int res = decode_audio(sh_audio, a);
2146 bytes += sh_audio->a_out_buffer_len;
2147 if (bytes >= 0) {
2148 memmove(sh_audio->a_out_buffer,
2149 sh_audio->a_out_buffer +
2150 sh_audio->a_out_buffer_len - bytes,
2151 bytes);
2152 sh_audio->a_out_buffer_len = bytes;
2153 if (res < 0)
2154 return res;
2155 return decode_audio(sh_audio, playsize);
2157 sh_audio->a_out_buffer_len = 0;
2158 if (res < 0)
2159 return res;
2161 int fillbyte = 0;
2162 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2163 fillbyte = 0x80;
2164 if (bytes >= playsize) {
2165 /* This case could fall back to the one below with
2166 * bytes = playsize, but then silence would keep accumulating
2167 * in a_out_buffer if the AO accepts less data than it asks for
2168 * in playsize. */
2169 char *p = malloc(playsize);
2170 memset(p, fillbyte, playsize);
2171 playsize = mpctx->audio_out->play(p, playsize, 0);
2172 free(p);
2173 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2174 return ASYNC_PLAY_DONE;
2176 mpctx->syncing_audio = false;
2177 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2178 return decode_audio(sh_audio, playsize);
2181 static int fill_audio_out_buffers(struct MPContext *mpctx)
2183 struct MPOpts *opts = &mpctx->opts;
2184 unsigned int t;
2185 double tt;
2186 int playsize;
2187 int playflags=0;
2188 int audio_eof=0;
2189 bool format_change = false;
2190 sh_audio_t * const sh_audio = mpctx->sh_audio;
2192 current_module="play_audio";
2194 while (1) {
2195 int sleep_time;
2196 // all the current uses of ao_data.pts seem to be in aos that handle
2197 // sync completely wrong; there should be no need to use ao_data.pts
2198 // in get_space()
2199 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2200 playsize = mpctx->audio_out->get_space();
2201 if (mpctx->sh_video || playsize >= ao_data.outburst)
2202 break;
2204 // handle audio-only case:
2205 // this is where mplayer sleeps during audio-only playback
2206 // to avoid 100% CPU use
2207 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2208 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2209 usec_sleep(sleep_time * 1000);
2212 // Fill buffer if needed:
2213 current_module="decode_audio";
2214 t = GetTimer();
2216 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2217 mpctx->syncing_audio = false;
2219 int res;
2220 if (mpctx->syncing_audio && mpctx->sh_video)
2221 res = audio_start_sync(mpctx, playsize);
2222 else
2223 res = decode_audio(sh_audio, playsize);
2224 if (res < 0) { // EOF, error or format change
2225 if (res == -2)
2226 format_change = true;
2227 else if (res == ASYNC_PLAY_DONE)
2228 return 1;
2229 else if (mpctx->d_audio->eof) {
2230 audio_eof = 1;
2231 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2232 if (sh_audio->a_out_buffer_len < unitsize)
2233 return 0;
2236 t = GetTimer() - t;
2237 tt = t*0.000001f; audio_time_usage+=tt;
2238 if (playsize > sh_audio->a_out_buffer_len) {
2239 playsize = sh_audio->a_out_buffer_len;
2240 if (audio_eof)
2241 playflags |= AOPLAY_FINAL_CHUNK;
2243 if (!playsize)
2244 return 1;
2246 // play audio:
2247 current_module="play_audio";
2249 // Is this pts value actually useful for the aos that access it?
2250 // They're obviously badly broken in the way they handle av sync;
2251 // would not having access to this make them more broken?
2252 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2253 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2255 if (playsize > 0) {
2256 sh_audio->a_out_buffer_len -= playsize;
2257 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2258 sh_audio->a_out_buffer_len);
2259 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2261 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2262 // Sanity check to avoid hanging in case current ao doesn't output
2263 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2264 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2265 sh_audio->a_out_buffer_len = 0;
2268 /* The format change isn't handled too gracefully. A more precise
2269 * implementation would require draining buffered old-format audio
2270 * while displaying video, then doing the output format switch.
2272 if (format_change) {
2273 uninit_player(mpctx, INITIALIZED_AO);
2274 reinit_audio_chain(mpctx);
2277 return 1;
2280 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2281 float *aq_sleep_time)
2283 struct MPOpts *opts = &mpctx->opts;
2284 int frame_time_remaining = 0;
2285 current_module="calc_sleep_time";
2287 *time_frame -= get_relative_time(mpctx); // reset timer
2289 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2290 float delay = mpctx->audio_out->get_delay();
2291 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2293 if (opts->autosync) {
2295 * Adjust this raw delay value by calculating the expected
2296 * delay for this frame and generating a new value which is
2297 * weighted between the two. The higher autosync is, the
2298 * closer to the delay value gets to that which "-nosound"
2299 * would have used, and the longer it will take for A/V
2300 * sync to settle at the right value (but it eventually will.)
2301 * This settling time is very short for values below 100.
2303 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2304 float difference = delay - predicted;
2305 delay = predicted + difference / (float)opts->autosync;
2308 *time_frame = delay - mpctx->delay / opts->playback_speed;
2309 *time_frame -= mpctx->video_out->flip_queue_offset;
2311 // delay = amount of audio buffered in soundcard/driver
2312 if (delay > 0.25) delay=0.25; else
2313 if (delay < 0.10) delay=0.10;
2315 if (*time_frame > delay*0.6) {
2316 // sleep time too big - may cause audio drops (buffer underrun)
2317 frame_time_remaining = 1;
2318 *time_frame = delay*0.5;
2320 } else {
2321 // If we're lagging more than 200 ms behind the right playback rate,
2322 // don't try to "catch up".
2323 // If benchmark is set always output frames as fast as possible
2324 // without sleeping.
2325 if (*time_frame < -0.2 || opts->benchmark)
2326 *time_frame = 0;
2327 *time_frame -= mpctx->video_out->flip_queue_offset;
2330 *aq_sleep_time += *time_frame;
2333 //============================== SLEEP: ===================================
2335 // flag 256 means: libvo driver does its timing (dvb card)
2336 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2337 *time_frame = timing_sleep(mpctx, *time_frame);
2338 *time_frame += mpctx->video_out->flip_queue_offset;
2339 return frame_time_remaining;
2342 int reinit_video_chain(struct MPContext *mpctx)
2344 struct MPOpts *opts = &mpctx->opts;
2345 sh_video_t * const sh_video = mpctx->sh_video;
2346 double ar=-1.0;
2347 //================== Init VIDEO (codec & libvo) ==========================
2348 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2349 current_module="preinit_libvo";
2351 //shouldn't we set dvideo->id=-2 when we fail?
2352 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2353 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2354 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2355 goto err_out;
2357 mpctx->initialized_flags|=INITIALIZED_VO;
2360 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2361 mpctx->sh_video->stream_aspect = ar;
2362 current_module="init_video_filters";
2364 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2365 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2367 #ifdef CONFIG_MENU
2368 if(use_menu) {
2369 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2370 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2371 if(!vf_menu) {
2372 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2373 use_menu = 0;
2376 if(vf_menu)
2377 sh_video->vfilter = vf_menu;
2378 #endif
2380 #ifdef CONFIG_ASS
2381 if(opts->ass_enabled) {
2382 int i;
2383 int insert = 1;
2384 if (opts->vf_settings)
2385 for (i = 0; opts->vf_settings[i].name; ++i)
2386 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2387 insert = 0;
2388 break;
2390 if (insert) {
2391 extern vf_info_t vf_info_ass;
2392 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2393 char* vf_arg[] = {"auto", "1", NULL};
2394 int retcode = 0;
2395 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2396 sh_video->vfilter,
2397 "ass", vf_arg,
2398 &retcode);
2399 if (vf_ass)
2400 sh_video->vfilter = vf_ass;
2401 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2402 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2403 else
2404 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2407 #endif
2409 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2411 #ifdef CONFIG_ASS
2412 if (opts->ass_enabled)
2413 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2414 #endif
2416 current_module="init_video_codec";
2418 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2419 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2420 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2422 if(!sh_video->initialized){
2423 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2424 goto err_out;
2427 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2429 if (sh_video->codec)
2430 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2432 sh_video->last_pts = MP_NOPTS_VALUE;
2433 sh_video->num_buffered_pts = 0;
2434 sh_video->next_frame_time = 0;
2436 if (opts->auto_quality > 0) {
2437 // Auto quality option enabled
2438 output_quality=get_video_quality_max(sh_video);
2439 if (opts->auto_quality > output_quality)
2440 opts->auto_quality = output_quality;
2441 else
2442 output_quality = opts->auto_quality;
2443 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2444 set_video_quality(sh_video,output_quality);
2447 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2449 current_module="init_vo";
2451 return 1;
2453 err_out:
2454 mpctx->sh_video = mpctx->d_video->sh = NULL;
2455 return 0;
2458 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2460 struct sh_video *sh_video = mpctx->sh_video;
2461 double frame_time = 0;
2462 struct vo *video_out = mpctx->video_out;
2463 while (!video_out->frame_loaded) {
2464 current_module = "filter_video";
2465 // In nocorrect-pts mode there is no way to properly time these frames
2466 if (vo_get_buffered_frame(video_out, 0) >= 0)
2467 break;
2468 if (vf_output_queued_frame(sh_video->vfilter))
2469 continue;
2470 unsigned char *packet = NULL;
2471 frame_time = sh_video->next_frame_time;
2472 if (mpctx->restart_playback)
2473 frame_time = 0;
2474 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2475 &packet, force_fps);
2476 if (in_size < 0) {
2477 #ifdef CONFIG_DVDNAV
2478 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2479 if (mp_dvdnav_is_eof(mpctx->stream))
2480 return -1;
2481 if (mpctx->d_video)
2482 mpctx->d_video->eof = 0;
2483 if (mpctx->d_audio)
2484 mpctx->d_audio->eof = 0;
2485 mpctx->stream->eof = 0;
2486 } else
2487 #endif
2488 return -1;
2490 if (in_size > max_framesize)
2491 max_framesize = in_size;
2492 sh_video->timer += frame_time;
2493 if (mpctx->sh_audio)
2494 mpctx->delay -= frame_time;
2495 // video_read_frame can change fps (e.g. for ASF video)
2496 vo_fps = sh_video->fps;
2497 int framedrop_type = check_framedrop(mpctx, frame_time);
2498 current_module = "decode video";
2500 void *decoded_frame;
2501 #ifdef CONFIG_DVDNAV
2502 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2503 if (in_size >= 0 && !decoded_frame)
2504 #endif
2505 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2506 sh_video->pts);
2507 #ifdef CONFIG_DVDNAV
2508 // Save last still frame for future display
2509 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2510 #endif
2511 if (decoded_frame) {
2512 current_module = "filter video";
2513 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2514 if (!video_out->config_ok)
2515 break;
2518 return frame_time;
2521 static void determine_frame_pts(struct MPContext *mpctx)
2523 struct sh_video *sh_video = mpctx->sh_video;
2524 struct MPOpts *opts = &mpctx->opts;
2526 if (opts->user_pts_assoc_mode) {
2527 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2528 } else if (sh_video->pts_assoc_mode == 0) {
2529 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2530 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2531 sh_video->pts_assoc_mode = 1;
2532 else
2533 sh_video->pts_assoc_mode = 2;
2534 } else {
2535 int probcount1 = sh_video->num_reordered_pts_problems;
2536 int probcount2 = sh_video->num_sorted_pts_problems;
2537 if (sh_video->pts_assoc_mode == 2) {
2538 int tmp = probcount1;
2539 probcount1 = probcount2;
2540 probcount2 = tmp;
2542 if (probcount1 >= probcount2 * 1.5 + 2) {
2543 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2544 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2545 "%d.\n", sh_video->pts_assoc_mode);
2548 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2549 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2552 static double update_video(struct MPContext *mpctx)
2554 struct sh_video *sh_video = mpctx->sh_video;
2555 struct vo *video_out = mpctx->video_out;
2556 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2557 mpctx->osd); // hack for vf_expand
2558 if (!mpctx->opts.correct_pts)
2559 return update_video_nocorrect_pts(mpctx);
2561 double pts;
2563 bool hit_eof = false;
2564 while (!video_out->frame_loaded) {
2565 current_module = "filter_video";
2566 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2567 break;
2568 // XXX Time used in this call is not counted in any performance
2569 // timer now, OSD time is not updated correctly for filter-added frames
2570 if (vf_output_queued_frame(sh_video->vfilter))
2571 continue;
2572 if (hit_eof)
2573 return -1;
2574 unsigned char *packet = NULL;
2575 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2576 if (pts != MP_NOPTS_VALUE)
2577 pts += mpctx->video_offset;
2578 if (in_size < 0) {
2579 // try to extract last frames in case of decoder lag
2580 in_size = 0;
2581 pts = MP_NOPTS_VALUE;
2582 hit_eof = true;
2584 if (in_size > max_framesize)
2585 max_framesize = in_size;
2586 current_module = "decode video";
2587 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2588 void *decoded_frame = decode_video(sh_video, packet, in_size,
2589 framedrop_type, pts);
2590 if (decoded_frame) {
2591 determine_frame_pts(mpctx);
2592 current_module = "filter video";
2593 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2594 if (!video_out->config_ok)
2595 break; // We'd likely hang in this loop otherwise
2599 pts = video_out->next_pts;
2600 if (pts == MP_NOPTS_VALUE) {
2601 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2602 // Try to use decoder pts from before filters
2603 pts = sh_video->pts;
2604 if (pts == MP_NOPTS_VALUE)
2605 pts = sh_video->last_pts;
2607 sh_video->pts = pts;
2608 if (sh_video->last_pts == MP_NOPTS_VALUE)
2609 sh_video->last_pts = sh_video->pts;
2610 else if (sh_video->last_pts > sh_video->pts) {
2611 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2612 sh_video->pts, sh_video->last_pts);
2613 /* If the difference in pts is small treat it as jitter around the
2614 * right value (possibly caused by incorrect timestamp ordering) and
2615 * just show this frame immediately after the last one.
2616 * Treat bigger differences as timestamp resets and start counting
2617 * timing of later frames from the position of this one. */
2618 if (sh_video->last_pts - sh_video->pts > 0.5)
2619 sh_video->last_pts = sh_video->pts;
2620 else
2621 sh_video->pts = sh_video->last_pts;
2623 double frame_time = sh_video->pts - sh_video->last_pts;
2624 sh_video->last_pts = sh_video->pts;
2625 sh_video->timer += frame_time;
2626 if (mpctx->sh_audio)
2627 mpctx->delay -= frame_time;
2628 return frame_time;
2631 void pause_player(struct MPContext *mpctx)
2633 if (mpctx->paused)
2634 return;
2635 mpctx->paused = 1;
2636 mpctx->step_frames = 0;
2637 mpctx->time_frame -= get_relative_time(mpctx);
2639 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2640 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2642 if (mpctx->audio_out && mpctx->sh_audio)
2643 mpctx->audio_out->pause(); // pause audio, keep data if possible
2646 void unpause_player(struct MPContext *mpctx)
2648 if (!mpctx->paused)
2649 return;
2650 mpctx->paused = 0;
2652 if (mpctx->audio_out && mpctx->sh_audio)
2653 mpctx->audio_out->resume(); // resume audio
2654 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2655 && !mpctx->step_frames)
2656 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2657 (void)get_relative_time(mpctx); // ignore time that passed during pause
2660 void add_step_frame(struct MPContext *mpctx)
2662 mpctx->step_frames++;
2663 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2664 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2665 unpause_player(mpctx);
2668 static void pause_loop(struct MPContext *mpctx)
2670 struct MPOpts *opts = &mpctx->opts;
2671 mp_cmd_t* cmd;
2672 if (!opts->quiet) {
2673 // Small hack to display the pause message on the OSD line.
2674 // The pause string is: "\n == PAUSE == \r" so we need to
2675 // take the first and the last char out
2676 if (opts->term_osd && !mpctx->sh_video) {
2677 char msg[128] = _("\n ===== PAUSE =====\r");
2678 int mlen = strlen(msg);
2679 msg[mlen-1] = '\0';
2680 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2681 update_osd_msg(mpctx);
2682 } else
2683 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2684 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2687 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2688 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2689 if (cmd) {
2690 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2691 run_command(mpctx, cmd);
2692 mp_cmd_free(cmd);
2693 continue;
2695 if (mpctx->sh_video && mpctx->video_out)
2696 vo_check_events(mpctx->video_out);
2697 #ifdef CONFIG_MENU
2698 if (vf_menu)
2699 vf_menu_pause_update(vf_menu);
2700 #endif
2701 usec_sleep(20000);
2702 update_osd_msg(mpctx);
2703 int hack = vo_osd_changed(0);
2704 vo_osd_changed(hack);
2705 if (hack)
2706 break;
2711 // Find the right mute status and record position for new file position
2712 static void edl_seek_reset(MPContext *mpctx)
2714 mpctx->edl_muted = 0;
2715 next_edl_record = edl_records;
2717 while (next_edl_record) {
2718 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2719 break;
2721 if (next_edl_record->action == EDL_MUTE)
2722 mpctx->edl_muted = !mpctx->edl_muted;
2723 next_edl_record = next_edl_record->next;
2725 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2726 mixer_mute(&mpctx->mixer);
2730 // Execute EDL command for the current position if one exists
2731 static void edl_update(MPContext *mpctx)
2733 if (!next_edl_record)
2734 return;
2736 if (!mpctx->sh_video) {
2737 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2738 free_edl(edl_records);
2739 next_edl_record = NULL;
2740 edl_records = NULL;
2741 return;
2744 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2745 if (next_edl_record->action == EDL_SKIP) {
2746 mpctx->osd_function = OSD_FFW;
2747 mpctx->abs_seek_pos = 0;
2748 mpctx->rel_seek_secs = next_edl_record->length_sec;
2749 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2750 "[%f], length [%f]\n", next_edl_record->start_sec,
2751 next_edl_record->stop_sec, next_edl_record->length_sec);
2753 else if (next_edl_record->action == EDL_MUTE) {
2754 mpctx->edl_muted = !mpctx->edl_muted;
2755 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2756 mixer_mute(&mpctx->mixer);
2757 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2758 next_edl_record->start_sec );
2760 next_edl_record = next_edl_record->next;
2764 static void reinit_decoders(struct MPContext *mpctx)
2766 reinit_video_chain(mpctx);
2767 reinit_audio_chain(mpctx);
2768 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2771 static void seek_reset(struct MPContext *mpctx)
2773 if (mpctx->sh_video) {
2774 current_module = "seek_video_reset";
2775 resync_video_stream(mpctx->sh_video);
2776 mpctx->sh_video->timer = 0;
2777 vo_seek_reset(mpctx->video_out);
2778 mpctx->sh_video->timer = 0;
2779 mpctx->sh_video->num_buffered_pts = 0;
2780 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2781 mpctx->delay = 0;
2782 mpctx->time_frame = 0;
2783 mpctx->restart_playback = true;
2784 // Not all demuxers set d_video->pts during seek, so this value
2785 // (which is used by at least vobsub and edl code below) may
2786 // be completely wrong (probably 0).
2787 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2788 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2789 mpctx->sh_video->pts, mpctx->video_offset,
2790 mpctx->d_sub, 1);
2791 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2794 if (mpctx->sh_audio) {
2795 current_module = "seek_audio_reset";
2796 resync_audio_stream(mpctx->sh_audio);
2797 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2798 mpctx->sh_audio->a_buffer_len = 0;
2799 mpctx->sh_audio->a_out_buffer_len = 0;
2800 if (!mpctx->sh_video)
2801 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2802 mpctx->video_offset, mpctx->d_sub, 1);
2805 if (vo_vobsub && mpctx->sh_video) {
2806 current_module = "seek_vobsub_reset";
2807 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2810 edl_seek_reset(mpctx);
2812 mpctx->total_avsync_change = 0;
2813 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2814 drop_frame_cnt = 0;
2816 current_module = NULL;
2819 static bool timeline_set_part(struct MPContext *mpctx, int i)
2821 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2822 struct timeline_part *n = mpctx->timeline + i;
2823 mpctx->timeline_part = i;
2824 mpctx->video_offset = n->start - n->source_start;
2825 if (n->source == p->source)
2826 return false;
2827 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2828 mpctx->demuxer = n->source->demuxer;
2829 mpctx->d_video = mpctx->demuxer->video;
2830 mpctx->d_audio = mpctx->demuxer->audio;
2831 mpctx->d_sub = mpctx->demuxer->sub;
2832 mpctx->sh_video = mpctx->d_video->sh;
2833 mpctx->sh_audio = mpctx->d_audio->sh;
2834 return true;
2837 // Given pts, switch playback to the corresponding part.
2838 // Return offset within that part.
2839 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2840 bool *need_reset)
2842 if (pts < 0)
2843 pts = 0;
2844 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2845 struct timeline_part *p = mpctx->timeline + i;
2846 if (pts < (p+1)->start) {
2847 *need_reset = timeline_set_part(mpctx, i);
2848 return pts - p->start + p->source_start;
2851 return -1;
2855 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2856 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2857 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2858 static int seek(MPContext *mpctx, double amount, int style)
2860 current_module = "seek";
2861 if (mpctx->stop_play == AT_END_OF_FILE)
2862 mpctx->stop_play = KEEP_PLAYING;
2863 if (style & SEEK_FACTOR
2864 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2865 || amount < 0)
2866 mpctx->last_chapter_seek = -1;
2867 if (mpctx->timeline && style & SEEK_FACTOR) {
2868 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2869 style &= ~SEEK_FACTOR;
2871 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2872 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2873 style |= SEEK_ABSOLUTE;
2874 if (amount > 0)
2875 style |= SEEK_FORWARD;
2876 else
2877 style |= SEEK_BACKWARD;
2878 amount += mpctx->sh_video->pts;
2881 /* At least the liba52 decoder wants to read from the input stream
2882 * during initialization, so reinit must be done after the demux_seek()
2883 * call that clears possible stream EOF. */
2884 bool need_reset = false;
2885 if (mpctx->timeline) {
2886 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2887 if (amount == -1) {
2888 mpctx->stop_play = AT_END_OF_FILE;
2889 // Clear audio from current position
2890 if (mpctx->sh_audio) {
2891 mpctx->audio_out->reset();
2892 mpctx->sh_audio->a_buffer_len = 0;
2893 mpctx->sh_audio->a_out_buffer_len = 0;
2895 return -1;
2898 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2899 if (need_reset)
2900 reinit_decoders(mpctx);
2901 if (seekresult == 0)
2902 return -1;
2904 seek_reset(mpctx);
2905 return 0;
2909 double get_time_length(struct MPContext *mpctx)
2911 if (mpctx->timeline)
2912 return mpctx->timeline[mpctx->num_timeline_parts].start;
2914 struct demuxer *demuxer = mpctx->demuxer;
2915 double get_time_ans;
2916 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
2917 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
2918 (void *) &get_time_ans) > 0)
2919 return get_time_ans;
2921 struct sh_video *sh_video = mpctx->d_video->sh;
2922 struct sh_audio *sh_audio = mpctx->d_audio->sh;
2923 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
2924 return (double) (demuxer->movi_end - demuxer->movi_start) /
2925 (sh_video->i_bps + sh_audio->i_bps);
2926 if (sh_video && sh_video->i_bps)
2927 return (double) (demuxer->movi_end - demuxer->movi_start) /
2928 sh_video->i_bps;
2929 if (sh_audio && sh_audio->i_bps)
2930 return (double) (demuxer->movi_end - demuxer->movi_start) /
2931 sh_audio->i_bps;
2932 return 0;
2935 /* If there are timestamps from stream level then use those (for example
2936 * DVDs can have consistent times there while the MPEG-level timestamps
2937 * reset). */
2938 double get_current_time(struct MPContext *mpctx)
2940 struct demuxer *demuxer = mpctx->demuxer;
2941 if (demuxer->stream_pts != MP_NOPTS_VALUE)
2942 return demuxer->stream_pts;
2943 struct sh_video *sh_video = demuxer->video->sh;
2944 if (sh_video)
2945 return sh_video->pts;
2946 return playing_audio_pts(mpctx);
2949 int get_percent_pos(struct MPContext *mpctx)
2951 struct demuxer *demuxer = mpctx->demuxer;
2952 int ans = 0;
2953 if (mpctx->timeline)
2954 ans = get_current_time(mpctx) * 100 /
2955 mpctx->timeline[mpctx->num_timeline_parts].start;
2956 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
2958 else {
2959 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
2960 off_t pos = demuxer->filepos > 0 ?
2961 demuxer->filepos : stream_tell(demuxer->stream);
2962 if (len > 0)
2963 ans = (pos - demuxer->movi_start) / len;
2964 else
2965 ans = 0;
2967 if (ans < 0)
2968 ans = 0;
2969 if (ans > 100)
2970 ans = 100;
2971 return ans;
2974 // -2 is no chapters, -1 is before first chapter
2975 int get_current_chapter(struct MPContext *mpctx)
2977 double current_pts = get_current_time(mpctx);
2978 if (!mpctx->chapters)
2979 return FFMAX(mpctx->last_chapter_seek,
2980 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
2982 int i;
2983 for (i = 1; i < mpctx->num_chapters; i++)
2984 if (current_pts < mpctx->chapters[i].start)
2985 break;
2986 return FFMAX(mpctx->last_chapter_seek, i - 1);
2989 // currently returns a string allocated with malloc, not talloc
2990 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2992 if (!mpctx->chapters || !mpctx->sh_video)
2993 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2994 return strdup(mpctx->chapters[chapter].name);
2997 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2998 char **chapter_name)
3000 mpctx->last_chapter_seek = -1;
3001 if (!mpctx->chapters || !mpctx->sh_video) {
3002 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3003 chapter_name);
3004 if (res >= 0) {
3005 if (*seek_pts == -1)
3006 seek_reset(mpctx);
3007 else {
3008 mpctx->last_chapter_seek = res;
3009 mpctx->last_chapter_pts = *seek_pts;
3012 return res;
3015 if (chapter >= mpctx->num_chapters)
3016 return -1;
3017 if (chapter < 0)
3018 chapter = 0;
3019 *seek_pts = mpctx->chapters[chapter].start;
3020 mpctx->last_chapter_seek = chapter;
3021 mpctx->last_chapter_pts = *seek_pts;
3022 if (chapter_name)
3023 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3024 return chapter;
3027 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3028 struct content_source *sources,
3029 int num_sources,
3030 unsigned char uid_map[][16])
3032 int num_filenames = 0;
3033 char **filenames = NULL;
3034 if (num_sources > 1) {
3035 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3036 "other sources.\n");
3037 if (mpctx->stream->type != STREAMTYPE_FILE) {
3038 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3039 "normal disk file. Will not search for related files.\n");
3040 } else {
3041 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3042 "same directory to find referenced sources.\n");
3043 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3044 &num_filenames);
3048 int num_left = num_sources - 1;
3049 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3050 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3051 filename_recode(filenames[i]));
3052 int format;
3053 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3054 if (!s)
3055 continue;
3056 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3057 mpctx->opts.audio_id,
3058 mpctx->opts.video_id,
3059 mpctx->opts.sub_id, filenames[i]);
3060 if (!d) {
3061 free_stream(s);
3062 continue;
3064 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3065 for (int i = 1; i < num_sources; i++) {
3066 if (sources[i].demuxer)
3067 continue;
3068 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3069 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3070 i, filename_recode(d->filename));
3071 sources[i].stream = s;
3072 sources[i].demuxer = d;
3073 num_left--;
3074 goto match;
3078 free_demuxer(d);
3079 free_stream(s);
3080 continue;
3081 match:
3084 talloc_free(filenames);
3085 if (num_left) {
3086 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3087 "There will be parts MISSING from the video!\n");
3088 for (int i = 1, j = 1; i < num_sources; i++)
3089 if (sources[i].demuxer) {
3090 sources[j] = sources[i];
3091 memcpy(uid_map[j], uid_map[i], 16);
3092 j++;
3095 return num_sources - num_left;
3098 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3100 struct MPOpts *opts = &mpctx->opts;
3102 if (!opts->ordered_chapters) {
3103 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3104 "you have disabled support for them. Ignoring.\n");
3105 return;
3108 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3109 "edit timeline.\n");
3111 struct demuxer *demuxer = mpctx->demuxer;
3112 struct matroska_data *m = &demuxer->matroska_data;
3114 // +1 because sources/uid_map[0] is original file even if all chapters
3115 // actually use other sources and need separate entries
3116 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3117 m->num_ordered_chapters+1);
3118 sources[0].stream = mpctx->stream;
3119 sources[0].demuxer = mpctx->demuxer;
3120 unsigned char uid_map[m->num_ordered_chapters+1][16];
3121 int num_sources = 1;
3122 memcpy(uid_map[0], m->segment_uid, 16);
3124 for (int i = 0; i < m->num_ordered_chapters; i++) {
3125 struct matroska_chapter *c = m->ordered_chapters + i;
3126 if (!c->has_segment_uid)
3127 memcpy(c->segment_uid, m->segment_uid, 16);
3129 for (int j = 0; j < num_sources; j++)
3130 if (!memcmp(c->segment_uid, uid_map[j], 16))
3131 goto found1;
3132 memcpy(uid_map[num_sources], c->segment_uid, 16);
3133 sources[num_sources] = (struct content_source){};
3134 num_sources++;
3135 found1:
3139 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3140 uid_map);
3143 // +1 for terminating chapter with start time marking end of last real one
3144 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3145 m->num_ordered_chapters + 1);
3146 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3147 m->num_ordered_chapters);
3148 uint64_t starttime = 0;
3149 uint64_t missing_time = 0;
3150 int part_count = 0;
3151 int num_chapters = 0;
3152 uint64_t prev_part_offset = 0;
3153 for (int i = 0; i < m->num_ordered_chapters; i++) {
3154 struct matroska_chapter *c = m->ordered_chapters + i;
3156 int j;
3157 for (j = 0; j < num_sources; j++) {
3158 if (!memcmp(c->segment_uid, uid_map[j], 16))
3159 goto found2;
3161 missing_time += c->end - c->start;
3162 continue;
3163 found2:;
3164 /* Only add a separate part if the time or file actually changes.
3165 * Matroska files have chapter divisions that are redundant from
3166 * timeline point of view because the same chapter structure is used
3167 * both to specify the timeline and for normal chapter information.
3168 * Removing a missing inserted external chapter can also cause this.
3169 * We allow for a configurable fudge factor because of files which
3170 * specify chapter end times that are one frame too early;
3171 * we don't want to try seeking over a one frame gap. */
3172 int64_t join_diff = c->start - starttime - prev_part_offset;
3173 if (part_count == 0 || FFABS(join_diff) > opts->chapter_merge_threshold
3174 || sources + j != timeline[part_count - 1].source) {
3175 timeline[part_count].source = sources + j;
3176 timeline[part_count].start = starttime / 1000.;
3177 timeline[part_count].source_start = c->start / 1000.;
3178 prev_part_offset = c->start - starttime;
3179 part_count++;
3180 } else if (part_count > 0 && join_diff) {
3181 /* Chapter was merged at an inexact boundary;
3182 * adjust timestamps to match. */
3183 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3184 "offset %d ms.\n", i, (int) join_diff);
3185 starttime += join_diff;
3187 chapters[num_chapters].start = starttime / 1000.;
3188 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3189 starttime += c->end - c->start;
3190 num_chapters++;
3192 timeline[part_count].start = starttime / 1000.;
3194 if (!part_count) {
3195 // None of the parts come from the file itself???
3196 talloc_free(sources);
3197 talloc_free(timeline);
3198 talloc_free(chapters);
3199 return;
3202 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3203 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3204 timeline[part_count].start);
3205 if (missing_time)
3206 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3207 "from the timeline!\n", missing_time / 1000.);
3208 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3209 for (int i = 0; i < num_sources; i++)
3210 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3211 filename_recode(sources[i].demuxer->filename));
3212 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3213 "source_start, source):\n");
3214 for (int i = 0; i < part_count; i++) {
3215 struct timeline_part *p = timeline + i;
3216 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3217 p->source_start, p->source - sources);
3219 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3220 mpctx->sources = sources;
3221 mpctx->num_sources = num_sources;
3222 mpctx->timeline = timeline;
3223 mpctx->num_timeline_parts = part_count;
3224 mpctx->num_chapters = num_chapters;
3225 mpctx->chapters = chapters;
3227 mpctx->timeline_part = 0;
3228 mpctx->demuxer = timeline[0].source->demuxer;
3232 static int read_keys(void *ctx, int fd)
3234 getch2(ctx);
3235 return mplayer_get_key(ctx, 0);
3239 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3240 * file for some tools to link against. */
3241 #ifndef DISABLE_MAIN
3242 int main(int argc,char* argv[]){
3245 char * mem_ptr;
3247 // movie info:
3249 /* Flag indicating whether MPlayer should exit without playing anything. */
3250 int opt_exit = 0;
3251 int i;
3253 struct MPContext *mpctx = &(struct MPContext){
3254 .osd_function = OSD_PLAY,
3255 .begin_skip = MP_NOPTS_VALUE,
3256 .play_tree_step = 1,
3257 .global_sub_pos = -1,
3258 .set_of_sub_pos = -1,
3259 .file_format = DEMUXER_TYPE_UNKNOWN,
3260 .last_dvb_step = 1,
3263 InitTimer();
3264 srand(GetTimerMS());
3266 mp_msg_init();
3267 set_av_log_callback();
3269 #ifdef CONFIG_X11
3270 mpctx->x11_state = vo_x11_init_state();
3271 #endif
3272 struct MPOpts *opts = &mpctx->opts;
3273 set_default_mplayer_options(opts);
3274 // Create the config context and register the options
3275 mpctx->mconfig = m_config_new(opts, cfg_include);
3276 m_config_register_options(mpctx->mconfig,mplayer_opts);
3277 m_config_register_options(mpctx->mconfig, common_opts);
3278 mp_input_register_options(mpctx->mconfig);
3280 // Preparse the command line
3281 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3283 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3284 set_path_env();
3285 #endif
3287 #ifdef CONFIG_TV
3288 stream_tv_defaults.immediate = 1;
3289 #endif
3291 parse_cfgfiles(mpctx, mpctx->mconfig);
3293 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3294 if(mpctx->playtree == NULL)
3295 opt_exit = 1;
3296 else {
3297 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3298 if(mpctx->playtree) {
3299 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3300 if(mpctx->playtree_iter) {
3301 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3302 play_tree_iter_free(mpctx->playtree_iter);
3303 mpctx->playtree_iter = NULL;
3305 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3309 mpctx->key_fifo = mp_fifo_create(opts);
3311 print_version("MPlayer");
3313 #if defined(__MINGW32__) || defined(__CYGWIN__)
3315 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3316 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3317 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3318 if (kernel32) {
3319 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3320 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3322 if (setDEP) setDEP(3);
3323 if (setDllDir) setDllDir("");
3325 // stop Windows from showing all kinds of annoying error dialogs
3326 SetErrorMode(0x8003);
3327 // request 1ms timer resolution
3328 timeBeginPeriod(1);
3329 #endif
3331 #ifdef CONFIG_PRIORITY
3332 set_priority();
3333 #endif
3335 if (codec_path)
3336 set_codec_path(codec_path);
3338 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3339 list_video_out();
3340 opt_exit = 1;
3343 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3344 list_audio_out();
3345 opt_exit = 1;
3348 /* Check codecs.conf. */
3349 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3350 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3351 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3352 if(!parse_codec_cfg(NULL)){
3353 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3355 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3358 free( mem_ptr ); // release the buffer created by get_path()
3361 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3362 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3363 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3364 list_codecs(1);
3365 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3366 opt_exit = 1;
3368 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3369 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3370 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3371 list_codecs(0);
3372 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3373 opt_exit = 1;
3375 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3376 vfm_help();
3377 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3378 opt_exit = 1;
3380 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3381 afm_help();
3382 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3383 opt_exit = 1;
3385 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3386 af_help();
3387 printf("\n");
3388 opt_exit = 1;
3390 #ifdef CONFIG_X11
3391 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3392 fstype_help();
3393 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3394 opt_exit = 1;
3396 #endif
3397 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3398 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3399 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3400 demuxer_help();
3401 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3402 opt_exit = 1;
3404 if (opts->list_properties) {
3405 property_print_help();
3406 opt_exit = 1;
3409 if(opt_exit)
3410 exit_player(mpctx, EXIT_NONE);
3412 if (!mpctx->filename && !opts->player_idle_mode) {
3413 // no file/vcd/dvd -> show HELP:
3414 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3415 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3418 /* Display what configure line was used */
3419 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3421 // Many users forget to include command line in bugreports...
3422 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3423 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3424 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3425 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3428 //------ load global data first ------
3430 mpctx->osd = osd_create();
3432 // check font
3433 #ifdef CONFIG_FREETYPE
3434 init_freetype();
3435 #endif
3436 #ifdef CONFIG_FONTCONFIG
3437 if(font_fontconfig <= 0)
3439 #endif
3440 #ifdef CONFIG_BITMAP_FONT
3441 if(font_name){
3442 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3443 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3444 filename_recode(font_name));
3445 } else {
3446 // try default:
3447 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3448 free(mem_ptr); // release the buffer created by get_path()
3449 if(!vo_font)
3450 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3452 if (sub_font_name)
3453 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3454 else
3455 mpctx->osd->sub_font = vo_font;
3456 #endif
3457 #ifdef CONFIG_FONTCONFIG
3459 #endif
3461 #ifdef CONFIG_ASS
3462 ass_library = ass_init();
3463 #endif
3465 #ifdef HAVE_RTC
3466 if(opts->rtc)
3468 char *rtc_device = opts->rtc_device;
3469 // seteuid(0); /* Can't hurt to try to get root here */
3470 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3471 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3472 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3473 else {
3474 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3476 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3477 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3478 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3479 close (rtc_fd);
3480 rtc_fd = -1;
3481 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3482 /* variable only by the root */
3483 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3484 close (rtc_fd);
3485 rtc_fd = -1;
3486 } else
3487 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3490 if(rtc_fd<0)
3491 #endif /* HAVE_RTC */
3492 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3493 opts->softsleep ? "software" : timer_name);
3495 #ifdef HAVE_TERMCAP
3496 load_termcap(NULL); // load key-codes
3497 #endif
3499 // ========== Init keyboard FIFO (connection to libvo) ============
3501 // Init input system
3502 current_module = "init_input";
3503 mpctx->input = mp_input_init(&opts->input);
3504 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3505 if(slave_mode)
3506 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3507 else if (opts->consolecontrols)
3508 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3509 // Set the libstream interrupt callback
3510 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3512 #ifdef CONFIG_MENU
3513 if(use_menu) {
3514 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3515 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3516 else {
3517 menu_cfg = get_path("menu.conf");
3518 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3519 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3520 else {
3521 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3522 MPLAYER_CONFDIR "/menu.conf"))
3523 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3524 else {
3525 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3526 use_menu = 0;
3531 #endif
3533 current_module = NULL;
3535 /// Catch signals
3536 #ifndef __MINGW32__
3537 signal(SIGCHLD,child_sighandler);
3538 #endif
3540 #ifdef CONFIG_CRASH_DEBUG
3541 prog_path = argv[0];
3542 #endif
3543 //========= Catch terminate signals: ================
3544 // terminate requests:
3545 signal(SIGTERM,exit_sighandler); // kill
3546 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3548 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3550 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3551 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3552 #ifdef CONFIG_SIGHANDLER
3553 // fatal errors:
3554 signal(SIGBUS,exit_sighandler); // bus error
3555 signal(SIGSEGV,exit_sighandler); // segfault
3556 signal(SIGILL,exit_sighandler); // illegal instruction
3557 signal(SIGFPE,exit_sighandler); // floating point exc.
3558 signal(SIGABRT,exit_sighandler); // abort()
3559 #ifdef CONFIG_CRASH_DEBUG
3560 if (crash_debug)
3561 signal(SIGTRAP,exit_sighandler);
3562 #endif
3563 #endif
3565 // ******************* Now, let's see the per-file stuff ********************
3567 play_next_file:
3569 // init global sub numbers
3570 mpctx->global_sub_size = 0;
3571 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3573 if (mpctx->filename) {
3574 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3575 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3576 load_per_file_config (mpctx->mconfig, mpctx->filename);
3579 if (opts->video_driver_list)
3580 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3581 if (opts->audio_driver_list)
3582 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3584 // We must enable getch2 here to be able to interrupt network connection
3585 // or cache filling
3586 if (opts->consolecontrols && !slave_mode) {
3587 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3588 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3589 else
3590 getch2_enable(); // prepare stdin for hotkeys...
3591 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3592 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3595 // =================== GUI idle loop (STOP state) ===========================
3596 while (opts->player_idle_mode && !mpctx->filename) {
3597 play_tree_t * entry = NULL;
3598 mp_cmd_t * cmd;
3599 if (mpctx->video_out && mpctx->video_out->config_ok)
3600 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3601 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3602 if (mpctx->video_out)
3603 vo_check_events(mpctx->video_out);
3604 usec_sleep(20000);
3606 switch (cmd->id) {
3607 case MP_CMD_LOADFILE:
3608 // prepare a tree entry with the new filename
3609 entry = play_tree_new();
3610 play_tree_add_file(entry, cmd->args[0].v.s);
3611 // The entry is added to the main playtree after the switch().
3612 break;
3613 case MP_CMD_LOADLIST:
3614 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3615 break;
3616 case MP_CMD_QUIT:
3617 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3618 break;
3619 case MP_CMD_VO_FULLSCREEN:
3620 case MP_CMD_GET_PROPERTY:
3621 case MP_CMD_SET_PROPERTY:
3622 case MP_CMD_STEP_PROPERTY:
3623 run_command(mpctx, cmd);
3624 break;
3627 mp_cmd_free(cmd);
3629 if (entry) { // user entered a command that gave a valid entry
3630 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3631 play_tree_free_list(mpctx->playtree->child, 1);
3632 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3634 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3636 play_tree_set_child(mpctx->playtree, entry);
3638 /* Make iterator start at the top the of tree. */
3639 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3640 if (!mpctx->playtree_iter) continue;
3642 // find the first real item in the tree
3643 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3644 // no items!
3645 play_tree_iter_free(mpctx->playtree_iter);
3646 mpctx->playtree_iter = NULL;
3647 continue; // wait for next command
3649 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3652 //---------------------------------------------------------------------------
3654 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3655 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3657 if (mpctx->filename) {
3658 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3659 filename_recode(mpctx->filename));
3660 if(use_filename_title && opts->vo_wintitle == NULL)
3661 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
3664 if (edl_filename) {
3665 if (edl_records) free_edl(edl_records);
3666 next_edl_record = edl_records = edl_parse_file();
3668 if (edl_output_filename) {
3669 if (edl_fd) fclose(edl_fd);
3670 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3672 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3673 filename_recode(edl_output_filename));
3677 //==================== Open VOB-Sub ============================
3679 current_module="vobsub";
3680 if (vobsub_name){
3681 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3682 if(vo_vobsub==NULL)
3683 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3684 filename_recode(vobsub_name));
3685 } else if (sub_auto && mpctx->filename){
3686 /* try to autodetect vobsub from movie filename ::atmos */
3687 char *buf = strdup(mpctx->filename), *psub;
3688 char *pdot = strrchr(buf, '.');
3689 char *pslash = strrchr(buf, '/');
3690 #if defined(__MINGW32__) || defined(__CYGWIN__)
3691 if (!pslash) pslash = strrchr(buf, '\\');
3692 #endif
3693 if (pdot && (!pslash || pdot > pslash))
3694 *pdot = '\0';
3695 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3696 /* try from ~/.mplayer/sub */
3697 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3698 char *bname;
3699 int l;
3700 bname = strrchr(buf,'/');
3701 #if defined(__MINGW32__) || defined(__CYGWIN__)
3702 if(!bname) bname = strrchr(buf,'\\');
3703 #endif
3704 if(bname) bname++;
3705 else bname = buf;
3706 l = strlen(psub) + strlen(bname) + 1;
3707 psub = realloc(psub,l);
3708 strcat(psub,bname);
3709 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3710 free(psub);
3712 free(buf);
3714 if(vo_vobsub){
3715 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3716 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3717 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3719 // setup global sub numbering
3720 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3723 //============ Open & Sync STREAM --- fork cache2 ====================
3725 mpctx->stream=NULL;
3726 mpctx->demuxer=NULL;
3727 if (mpctx->d_audio) {
3728 //free_demuxer_stream(mpctx->d_audio);
3729 mpctx->d_audio=NULL;
3731 if (mpctx->d_video) {
3732 //free_demuxer_stream(d_video);
3733 mpctx->d_video=NULL;
3735 mpctx->sh_audio=NULL;
3736 mpctx->sh_video=NULL;
3738 current_module="open_stream";
3739 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3740 if(!mpctx->stream) { // error...
3741 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3742 goto goto_next_file;
3744 mpctx->initialized_flags|=INITIALIZED_STREAM;
3746 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3747 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3748 "playlist support will not be used automatically.\n"
3749 "MPlayer's playlist code is unsafe and should only be used with "
3750 "trusted sources.\nPlayback will probably fail.\n\n");
3751 #if 0
3752 play_tree_t* entry;
3753 // Handle playlist
3754 current_module="handle_playlist";
3755 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3756 filename_recode(mpctx->filename));
3757 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3758 mpctx->eof=playtree_add_playlist(mpctx, entry);
3759 goto goto_next_file;
3760 #endif
3762 mpctx->stream->start_pos+=seek_to_byte;
3764 if(stream_dump_type==5){
3765 unsigned char buf[4096];
3766 int len;
3767 FILE *f;
3768 current_module="dumpstream";
3769 stream_reset(mpctx->stream);
3770 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3771 f=fopen(opts->stream_dump_name,"wb");
3772 if(!f){
3773 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3774 exit_player(mpctx, EXIT_ERROR);
3776 if (opts->chapterrange[0] > 1) {
3777 int chapter = opts->chapterrange[0] - 1;
3778 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3780 while(!mpctx->stream->eof && !async_quit_request){
3781 len=stream_read(mpctx->stream,buf,4096);
3782 if(len>0) {
3783 if(fwrite(buf,len,1,f) != 1) {
3784 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3785 exit_player(mpctx, EXIT_ERROR);
3788 if (opts->chapterrange[1] > 0) {
3789 int chapter = -1;
3790 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3791 &chapter) == STREAM_OK
3792 && chapter + 1 > opts->chapterrange[1])
3793 break;
3796 if(fclose(f)) {
3797 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3798 exit_player(mpctx, EXIT_ERROR);
3800 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3801 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3804 #ifdef CONFIG_DVDREAD
3805 if(mpctx->stream->type==STREAMTYPE_DVD){
3806 current_module="dvd lang->id";
3807 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3808 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3809 // setup global sub numbering
3810 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3811 current_module=NULL;
3813 #endif
3815 #ifdef CONFIG_DVDNAV
3816 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3817 current_module="dvdnav lang->id";
3818 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3819 dvdsub_lang_id = -3;
3820 if(opts->sub_lang && opts->sub_id==-1)
3821 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3822 // setup global sub numbering
3823 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3824 current_module=NULL;
3826 #endif
3828 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3829 goto_enable_cache:
3830 if(stream_cache_size>0){
3831 int res;
3832 float stream_cache_min_percent = opts->stream_cache_min_percent;
3833 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
3834 current_module="enable_cache";
3835 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3836 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3837 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3838 if(res == 0)
3839 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3842 //============ Open DEMUXERS --- DETECT file type =======================
3843 current_module="demux_open";
3845 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3847 // HACK to get MOV Reference Files working
3849 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3851 unsigned char* playlist_entry;
3852 play_tree_t *list = NULL, *entry = NULL;
3854 current_module="handle_demux_playlist";
3855 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3857 char *temp;
3858 const char *bname;
3860 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3861 filename_recode(playlist_entry));
3863 bname=mp_basename(playlist_entry);
3864 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3865 continue;
3867 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3868 continue;
3870 entry = play_tree_new();
3872 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3874 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3875 if (temp)
3877 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3878 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3879 strcat(temp, playlist_entry);
3880 if (!strcmp(temp, mpctx->filename)) {
3881 free(temp);
3882 continue;
3884 play_tree_add_file(entry,temp);
3885 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3886 free(temp);
3889 else
3890 play_tree_add_file(entry,playlist_entry);
3892 if(!list)
3893 list = entry;
3894 else
3895 play_tree_append_entry(list,entry);
3897 free_demuxer(mpctx->demuxer);
3898 mpctx->demuxer = NULL;
3900 if (list)
3902 entry = play_tree_new();
3903 play_tree_set_child(entry,list);
3904 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3905 goto goto_next_file;
3909 if(!mpctx->demuxer) {
3910 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
3911 goto goto_next_file;
3914 if (mpctx->demuxer->matroska_data.ordered_chapters)
3915 build_ordered_chapter_timeline(mpctx);
3917 if (!mpctx->sources) {
3918 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3919 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3920 .demuxer = mpctx->demuxer};
3921 mpctx->num_sources = 1;
3924 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3926 #ifdef CONFIG_ASS
3927 if (opts->ass_enabled && ass_library) {
3928 for (int j = 0; j < mpctx->num_sources; j++) {
3929 struct demuxer *d = mpctx->sources[j].demuxer;
3930 for (int i = 0; i < d->num_attachments; i++) {
3931 struct demux_attachment *att = d->attachments + i;
3932 if (use_embedded_fonts && attachment_is_font(att))
3933 ass_add_font(ass_library, att->name, att->data, att->data_size);
3937 #endif
3939 current_module="demux_open2";
3941 mpctx->d_audio=mpctx->demuxer->audio;
3942 mpctx->d_video=mpctx->demuxer->video;
3943 mpctx->d_sub=mpctx->demuxer->sub;
3945 if (ts_prog) {
3946 int tmp = ts_prog;
3947 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3949 // select audio stream
3950 if (mpctx->num_sources)
3951 for (int i = 0; i < mpctx->num_sources; i++)
3952 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3953 opts->audio_lang);
3954 else
3955 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
3957 // DUMP STREAMS:
3958 if((stream_dump_type)&&(stream_dump_type<4)){
3959 FILE *f;
3960 demux_stream_t *ds=NULL;
3961 current_module="dump";
3962 // select stream to dump
3963 switch(stream_dump_type){
3964 case 1: ds=mpctx->d_audio;break;
3965 case 2: ds=mpctx->d_video;break;
3966 case 3: ds=mpctx->d_sub;break;
3968 if(!ds){
3969 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3970 exit_player(mpctx, EXIT_ERROR);
3972 // disable other streams:
3973 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3974 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3975 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3976 // let's dump it!
3977 f=fopen(opts->stream_dump_name,"wb");
3978 if(!f){
3979 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3980 exit_player(mpctx, EXIT_ERROR);
3982 while(!ds->eof){
3983 unsigned char* start;
3984 int in_size=ds_get_packet(ds,&start);
3985 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3986 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3987 if(in_size>0) fwrite(start,in_size,1,f);
3988 if (opts->chapterrange[1] > 0) {
3989 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
3990 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3991 break;
3994 fclose(f);
3995 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3996 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3999 mpctx->sh_audio=mpctx->d_audio->sh;
4000 mpctx->sh_video=mpctx->d_video->sh;
4002 if(mpctx->sh_video){
4004 current_module="video_read_properties";
4005 if(!video_read_properties(mpctx->sh_video)) {
4006 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4007 mpctx->sh_video=mpctx->d_video->sh=NULL;
4008 } else {
4009 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4010 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4011 mpctx->sh_video->fps,mpctx->sh_video->frametime
4014 /* need to set fps here for output encoders to pick it up in their init */
4015 if(force_fps){
4016 mpctx->sh_video->fps=force_fps;
4017 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4019 vo_fps = mpctx->sh_video->fps;
4021 if(!mpctx->sh_video->fps && !force_fps){
4022 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4023 mpctx->opts.correct_pts = 1;
4029 if(!mpctx->sh_video && !mpctx->sh_audio){
4030 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4031 #ifdef CONFIG_DVBIN
4032 if(mpctx->stream->type == STREAMTYPE_DVB)
4034 int dir;
4035 int v = mpctx->last_dvb_step;
4036 if(v > 0)
4037 dir = DVB_CHANNEL_HIGHER;
4038 else
4039 dir = DVB_CHANNEL_LOWER;
4041 if(dvb_step_channel(mpctx->stream, dir)) {
4042 mpctx->stop_play = PT_NEXT_ENTRY;
4043 mpctx->dvbin_reopen = 1;
4046 #endif
4047 goto goto_next_file; // exit_player(_("Fatal error"));
4050 /* display clip info */
4051 demux_info_print(mpctx->demuxer);
4053 //================== Read SUBTITLES (DVD & TEXT) ==========================
4054 if(vo_spudec==NULL &&
4055 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4056 init_vo_spudec(mpctx);
4059 // after reading video params we should load subtitles because
4060 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4061 // check .sub
4062 current_module="read_subtitles_file";
4063 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4064 if(sub_name){
4065 for (i = 0; sub_name[i] != NULL; ++i)
4066 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4068 if(sub_auto) { // auto load sub file ...
4069 char *psub = get_path( "sub/" );
4070 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4071 int i = 0;
4072 free(psub); // release the buffer created by get_path() above
4073 while (tmp[i]) {
4074 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4075 free(tmp[i++]);
4077 free(tmp);
4079 if (mpctx->set_of_sub_size > 0)
4080 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4082 if (select_subtitle(mpctx)) {
4083 if(subdata)
4084 switch (stream_dump_type) {
4085 case 3: list_sub_file(subdata); break;
4086 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
4087 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
4088 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
4089 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
4090 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
4094 print_file_properties(mpctx, mpctx->filename);
4096 if(!mpctx->sh_video) goto main; // audio-only
4098 if(!reinit_video_chain(mpctx)) {
4099 if(!mpctx->sh_video){
4100 if(!mpctx->sh_audio) goto goto_next_file;
4101 goto main; // exit_player(_("Fatal error"));
4105 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4106 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4108 #ifdef CONFIG_FREETYPE
4109 force_load_font = 1;
4110 #endif
4112 //================== MAIN: ==========================
4113 main:
4114 current_module="main";
4116 if (opts->playing_msg) {
4117 char* msg = property_expand_string(mpctx, opts->playing_msg);
4118 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4119 free(msg);
4123 // Disable the term OSD in verbose mode
4124 if (verbose)
4125 opts->term_osd = 0;
4128 int frame_time_remaining=0; // flag
4129 int blit_frame=0;
4131 // Make sure old OSD does not stay around,
4132 // e.g. with -fixed-vo and same-resolution files
4133 clear_osd_msgs();
4134 update_osd_msg(mpctx);
4136 //================ SETUP AUDIO ==========================
4138 if(mpctx->sh_audio){
4139 reinit_audio_chain(mpctx);
4140 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4141 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4144 current_module="av_init";
4146 if(mpctx->sh_video){
4147 mpctx->sh_video->timer=0;
4148 if (! ignore_start)
4149 audio_delay += mpctx->sh_video->stream_delay;
4151 if(mpctx->sh_audio){
4152 if (start_volume >= 0)
4153 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4154 if (! ignore_start)
4155 audio_delay -= mpctx->sh_audio->stream_delay;
4156 mpctx->delay=-audio_delay;
4159 if(!mpctx->sh_audio){
4160 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4161 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4162 ds_free_packs(mpctx->d_audio); // free buffered chunks
4163 //mpctx->d_audio->id=-2; // do not read audio chunks
4164 //uninit_player(mpctx, INITIALIZED_AO); // close device
4166 if(!mpctx->sh_video){
4167 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4168 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4169 ds_free_packs(mpctx->d_video);
4170 mpctx->d_video->id=-2;
4171 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4174 if (!mpctx->sh_video && !mpctx->sh_audio)
4175 goto goto_next_file;
4177 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4178 if(force_fps && mpctx->sh_video){
4179 vo_fps = mpctx->sh_video->fps=force_fps;
4180 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4181 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4184 mp_input_set_section(mpctx->input, NULL);
4185 //TODO: add desired (stream-based) sections here
4186 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4187 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4189 //==================== START PLAYING =======================
4191 if(opts->loop_times>1) opts->loop_times--; else
4192 if(opts->loop_times==1) opts->loop_times = -1;
4194 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4196 total_time_usage_start=GetTimer();
4197 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4198 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4199 play_n_frames=play_n_frames_mf;
4201 if(play_n_frames==0){
4202 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4205 // If there's a timeline force an absolute seek to initialize state
4206 if (seek_to_sec || mpctx->timeline) {
4207 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4208 end_at.pos += seek_to_sec;
4210 if (opts->chapterrange[0] > 0) {
4211 double pts;
4212 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4213 && pts > -1.0)
4214 seek(mpctx, pts, SEEK_ABSOLUTE);
4217 if (end_at.type == END_AT_SIZE) {
4218 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4219 end_at.type = END_AT_NONE;
4222 #ifdef CONFIG_DVDNAV
4223 mp_dvdnav_context_free(mpctx);
4224 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4225 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4226 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4228 #endif
4230 get_relative_time(mpctx); // reset current delta
4231 mpctx->time_frame = 0;
4232 mpctx->drop_message_shown = 0;
4233 mpctx->restart_playback = true;
4234 mpctx->total_avsync_change = 0;
4235 mpctx->last_chapter_seek = -1;
4236 // Make sure VO knows current pause state
4237 if (mpctx->sh_video)
4238 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4239 NULL);
4241 while(!mpctx->stop_play){
4242 float aq_sleep_time=0;
4244 if (opts->chapterrange[1] > 0) {
4245 int cur_chapter = get_current_chapter(mpctx);
4246 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4247 goto goto_next_file;
4250 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4251 mpctx->sh_audio = mpctx->d_audio->sh;
4252 mpctx->sh_audio->ds = mpctx->d_audio;
4253 reinit_audio_chain(mpctx);
4256 /*========================== PLAY AUDIO ============================*/
4258 if (mpctx->sh_audio && !mpctx->paused
4259 && (!mpctx->restart_playback || !mpctx->sh_video))
4260 if (!fill_audio_out_buffers(mpctx))
4261 // at eof, all audio at least written to ao
4262 if (!mpctx->sh_video)
4263 mpctx->stop_play = AT_END_OF_FILE;
4266 if(!mpctx->sh_video) {
4267 // handle audio-only case:
4268 double a_pos=0;
4269 // sh_audio can be NULL due to video stream switching
4270 // TODO: handle this better
4271 if (mpctx->sh_audio)
4272 a_pos = playing_audio_pts(mpctx);
4274 print_status(mpctx, a_pos, false);
4276 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4277 mpctx->stop_play = PT_NEXT_ENTRY;
4278 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4279 mpctx->d_sub, 0);
4280 update_osd_msg(mpctx);
4282 } else {
4284 /*========================== PLAY VIDEO ============================*/
4286 vo_pts=mpctx->sh_video->timer*90000.0;
4287 vo_fps=mpctx->sh_video->fps;
4289 blit_frame = mpctx->video_out->frame_loaded;
4290 if (!blit_frame) {
4291 double frame_time = update_video(mpctx);
4292 blit_frame = mpctx->video_out->frame_loaded;
4293 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4294 if (mpctx->sh_video->vf_initialized < 0) {
4295 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4296 mpctx->stop_play = PT_NEXT_ENTRY;
4297 goto goto_next_file;
4299 if (blit_frame) {
4300 struct sh_video *sh_video = mpctx->sh_video;
4301 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4302 mpctx->video_offset, mpctx->d_sub, 0);
4303 update_teletext(sh_video, mpctx->demuxer, 0);
4304 update_osd_msg(mpctx);
4305 struct vf_instance *vf = mpctx->sh_video->vfilter;
4306 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4307 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4308 vo_osd_changed(0);
4310 if (frame_time < 0)
4311 mpctx->stop_play = AT_END_OF_FILE;
4312 else if (!mpctx->restart_playback) {
4313 mpctx->time_frame += frame_time / opts->playback_speed;
4314 adjust_sync(mpctx, frame_time);
4317 if (mpctx->timeline) {
4318 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4319 if (mpctx->sh_video->pts >= next->start
4320 || mpctx->stop_play == AT_END_OF_FILE
4321 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4322 seek(mpctx, next->start, SEEK_ABSOLUTE);
4323 continue;
4327 // ==========================================================================
4329 // current_module="draw_osd";
4330 // if(vo_config_count) mpctx->video_out->draw_osd();
4332 current_module="vo_check_events";
4333 vo_check_events(mpctx->video_out);
4335 #ifdef CONFIG_X11
4336 if (stop_xscreensaver) {
4337 current_module = "stop_xscreensaver";
4338 xscreensaver_heartbeat(mpctx->x11_state);
4340 #endif
4341 if (heartbeat_cmd) {
4342 static unsigned last_heartbeat;
4343 unsigned now = GetTimerMS();
4344 if (now - last_heartbeat > 30000) {
4345 last_heartbeat = now;
4346 system(heartbeat_cmd);
4350 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4352 //====================== FLIP PAGE (VIDEO BLT): =========================
4354 current_module="flip_page";
4355 if (!frame_time_remaining && blit_frame) {
4356 unsigned int t2=GetTimer();
4357 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4358 int duration = -1;
4359 double pts2 = mpctx->video_out->next_pts2;
4360 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
4361 && !mpctx->restart_playback) {
4362 // expected A/V sync correction is ignored
4363 double diff = (pts2 - mpctx->sh_video->pts);
4364 diff /= opts->playback_speed;
4365 if (mpctx->time_frame < 0)
4366 diff += mpctx->time_frame;
4367 if (diff < 0)
4368 diff = 0;
4369 if (diff > 10)
4370 diff = 10;
4371 duration = diff * 1e6;
4373 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4375 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4376 vout_time_usage += mpctx->last_vo_flip_duration;
4377 if (mpctx->video_out->driver->flip_page_timed) {
4378 // No need to adjust sync based on flip speed
4379 mpctx->last_vo_flip_duration = 0;
4380 // For print_status - VO call finishing early is OK for sync
4381 mpctx->time_frame -= get_relative_time(mpctx);
4383 if (mpctx->restart_playback) {
4384 mpctx->syncing_audio = true;
4385 if (mpctx->sh_audio && !mpctx->paused)
4386 fill_audio_out_buffers(mpctx);
4387 mpctx->restart_playback = false;
4388 mpctx->time_frame = 0;
4389 get_relative_time(mpctx);
4391 print_status(mpctx, MP_NOPTS_VALUE, true);
4393 else
4394 print_status(mpctx, MP_NOPTS_VALUE, false);
4396 //============================ Auto QUALITY ============================
4398 /*Output quality adjustments:*/
4399 if (opts->auto_quality > 0) {
4400 current_module="autoq";
4401 // float total=0.000001f * (GetTimer()-aq_total_time);
4402 // if (output_quality < opts->auto_quality && aq_sleep_time > 0.05f * total)
4403 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
4404 ++output_quality;
4405 else
4406 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4407 if(output_quality>1 && aq_sleep_time<0)
4408 --output_quality;
4409 else
4410 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4411 output_quality=0;
4412 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4413 set_video_quality(mpctx->sh_video,output_quality);
4416 if (!frame_time_remaining && blit_frame) {
4417 if (play_n_frames >= 0) {
4418 --play_n_frames;
4419 if (play_n_frames <= 0)
4420 mpctx->stop_play = PT_NEXT_ENTRY;
4422 if (mpctx->step_frames > 0) {
4423 mpctx->step_frames--;
4424 if (mpctx->step_frames == 0)
4425 pause_player(mpctx);
4430 // FIXME: add size based support for -endpos
4431 if (end_at.type == END_AT_TIME &&
4432 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4433 mpctx->stop_play = PT_NEXT_ENTRY;
4435 } // end if(mpctx->sh_video)
4437 #ifdef CONFIG_DVDNAV
4438 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4439 nav_highlight_t hl;
4440 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4441 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4442 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4443 vo_osd_changed (OSDTYPE_DVDNAV);
4444 } else {
4445 osd_set_nav_box(0, 0, 0, 0);
4446 vo_osd_changed(OSDTYPE_DVDNAV);
4447 vo_osd_changed(OSDTYPE_SPU);
4450 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4451 double ar = -1.0;
4452 if (mpctx->sh_video &&
4453 stream_control (mpctx->demuxer->stream,
4454 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4455 != STREAM_UNSUPPORTED)
4456 mpctx->sh_video->stream_aspect = ar;
4459 #endif
4461 //================= Keyboard events, SEEKing ====================
4463 current_module="key_events";
4466 while (1) {
4467 mp_cmd_t* cmd;
4468 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4469 run_command(mpctx, cmd);
4470 mp_cmd_free(cmd);
4471 if (mpctx->stop_play)
4472 break;
4473 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4474 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4475 /* Allow seek commands to be combined, but execute the real seek
4476 * before processing other commands */
4477 if (!cmd || cmd->id != MP_CMD_SEEK)
4478 break;
4481 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4482 || mpctx->abs_seek_pos)
4483 break;
4484 if (mpctx->sh_video) {
4485 update_osd_msg(mpctx);
4486 int hack = vo_osd_changed(0);
4487 vo_osd_changed(hack);
4488 if (hack) {
4489 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4490 add_step_frame(mpctx);
4491 break;
4493 else
4494 vo_osd_changed(0);
4497 pause_loop(mpctx);
4501 // handle -sstep
4502 if (step_sec > 0 && !mpctx->paused) {
4503 mpctx->osd_function=OSD_FFW;
4504 mpctx->rel_seek_secs+=step_sec;
4507 edl_update(mpctx);
4509 /* Looping. */
4510 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4511 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4513 if(opts->loop_times>1) opts->loop_times--; else
4514 if(opts->loop_times==1) opts->loop_times=-1;
4515 play_n_frames=play_n_frames_mf;
4516 mpctx->stop_play=0;
4517 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4520 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4521 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4523 mpctx->rel_seek_secs=0;
4524 mpctx->abs_seek_pos=0;
4527 } // while(!mpctx->stop_play)
4529 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4531 #ifdef CONFIG_DVBIN
4532 if(mpctx->dvbin_reopen)
4534 mpctx->stop_play = 0;
4535 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4536 cache_uninit(mpctx->stream);
4537 mpctx->dvbin_reopen = 0;
4538 goto goto_enable_cache;
4540 #endif
4543 goto_next_file: // don't jump here after ao/vo/getch initialization!
4545 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4547 if (opts->benchmark) {
4548 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4549 double total_time_usage;
4550 total_time_usage_start=GetTimer()-total_time_usage_start;
4551 total_time_usage = (float)total_time_usage_start*0.000001;
4552 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4553 video_time_usage,vout_time_usage,audio_time_usage,
4554 total_time_usage-tot,total_time_usage);
4555 if(total_time_usage>0.0)
4556 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4557 100.0*video_time_usage/total_time_usage,
4558 100.0*vout_time_usage/total_time_usage,
4559 100.0*audio_time_usage/total_time_usage,
4560 100.0*(total_time_usage-tot)/total_time_usage,
4561 100.0);
4562 if(total_frame_cnt && frame_dropping)
4563 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4564 total_frame_cnt-drop_frame_cnt,
4565 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4566 drop_frame_cnt,
4567 100*drop_frame_cnt/total_frame_cnt,
4568 total_frame_cnt,
4569 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4572 // time to uninit all, except global stuff:
4573 int uninitialize_parts = INITIALIZED_ALL;
4574 if (opts->fixed_vo)
4575 uninitialize_parts -= INITIALIZED_VO;
4576 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4577 uninitialize_parts -= INITIALIZED_AO;
4578 uninit_player(mpctx, uninitialize_parts);
4580 if(mpctx->set_of_sub_size > 0) {
4581 current_module="sub_free";
4582 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4583 sub_free(mpctx->set_of_subtitles[i]);
4584 #ifdef CONFIG_ASS
4585 if(mpctx->set_of_ass_tracks[i])
4586 ass_free_track( mpctx->set_of_ass_tracks[i] );
4587 #endif
4589 mpctx->set_of_sub_size = 0;
4591 vo_sub_last = vo_sub=NULL;
4592 subdata=NULL;
4593 #ifdef CONFIG_ASS
4594 ass_track = NULL;
4595 if(ass_library)
4596 ass_clear_fonts(ass_library);
4597 #endif
4599 if (!mpctx->stop_play) // In case some goto jumped here...
4600 mpctx->stop_play = PT_NEXT_ENTRY;
4602 int playtree_direction = 1;
4604 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4605 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4606 play_tree_iter_free(mpctx->playtree_iter);
4607 mpctx->playtree_iter = NULL;
4609 mpctx->play_tree_step = 1;
4610 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4611 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4612 if(mpctx->playtree_iter) {
4613 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4614 play_tree_iter_free(mpctx->playtree_iter);
4615 mpctx->playtree_iter = NULL;
4618 } else if (mpctx->stop_play == PT_STOP) {
4619 play_tree_iter_free(mpctx->playtree_iter);
4620 mpctx->playtree_iter = NULL;
4621 } else { // NEXT PREV SRC
4622 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4625 while(mpctx->playtree_iter != NULL) {
4626 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4627 if(mpctx->filename == NULL) {
4628 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4629 play_tree_iter_free(mpctx->playtree_iter);
4630 mpctx->playtree_iter = NULL;
4632 } else
4633 break;
4636 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4637 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4638 mpctx->stop_play = 0;
4639 goto play_next_file;
4643 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4645 return 1;
4647 #endif /* DISABLE_MAIN */