vo_glamo: sub.h was moved to sub directory in c9026cb3210205b07e2e068467a18ee40f9259a3
[mplayer/glamo.git] / mplayer.c
blob03067ad9b037ba100900156a7aabbc6924733a8b
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 "sub/subreader.h"
75 #include "sub/dec_sub.h"
77 #include "mp_osd.h"
78 #include "libvo/video_out.h"
80 #include "sub/font_load.h"
81 #include "sub/sub.h"
82 #include "ffmpeg_files/intreadwrite.h"
83 #include "sub/av_sub.h"
84 #include "libmpcodecs/dec_teletext.h"
85 #include "cpudetect.h"
86 #include "version.h"
88 #ifdef CONFIG_X11
89 #include "libvo/x11_common.h"
90 #endif
92 #include "libao2/audio_out.h"
94 #include "codec-cfg.h"
96 #include "edl.h"
98 #include "sub/spudec.h"
99 #include "sub/vobsub.h"
101 #include "osdep/getch2.h"
102 #include "osdep/timer.h"
103 #include "osdep/findfiles.h"
105 #include "input/input.h"
107 int slave_mode=0;
108 int enable_mouse_movements=0;
109 float start_volume = -1;
111 #include "osdep/priority.h"
113 char *heartbeat_cmd;
115 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
117 #ifdef HAVE_RTC
118 #ifdef __linux__
119 #include <linux/rtc.h>
120 #else
121 #include <rtc.h>
122 #define RTC_IRQP_SET RTCIO_IRQP_SET
123 #define RTC_PIE_ON RTCIO_PIE_ON
124 #endif /* __linux__ */
125 #endif /* HAVE_RTC */
127 #include "stream/tv.h"
128 #include "stream/stream_radio.h"
129 #ifdef CONFIG_DVBIN
130 #include "stream/dvbin.h"
131 #endif
132 #include "stream/cache2.h"
134 //**************************************************************************//
135 // Playtree
136 //**************************************************************************//
137 #include "playtree.h"
138 #include "playtreeparser.h"
140 //**************************************************************************//
141 // Config
142 //**************************************************************************//
143 #include "parser-cfg.h"
144 #include "parser-mpcmd.h"
146 //**************************************************************************//
147 // Config file
148 //**************************************************************************//
150 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
152 #include "path.h"
154 //**************************************************************************//
155 //**************************************************************************//
156 // Input media streaming & demultiplexer:
157 //**************************************************************************//
159 static int max_framesize=0;
161 #include "stream/stream.h"
162 #include "libmpdemux/demuxer.h"
163 #include "libmpdemux/stheader.h"
165 #ifdef CONFIG_DVDREAD
166 #include "stream/stream_dvd.h"
167 #endif
168 #include "stream/stream_dvdnav.h"
170 #include "libmpcodecs/dec_audio.h"
171 #include "libmpcodecs/dec_video.h"
172 #include "libmpcodecs/mp_image.h"
173 #include "libmpcodecs/vf.h"
174 #include "libmpcodecs/vd.h"
176 #include "mixer.h"
178 #include "mp_core.h"
179 #include "options.h"
180 #include "defaultopts.h"
182 static const char help_text[]=_(
183 "Usage: mplayer [options] [url|path/]filename\n"
184 "\n"
185 "Basic options: (complete list in the man page)\n"
186 " -vo <drv> select video output driver ('-vo help' for a list)\n"
187 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
188 #ifdef CONFIG_VCD
189 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
190 #endif
191 #ifdef CONFIG_DVDREAD
192 " dvd://<titleno> play DVD title from device instead of plain file\n"
193 #endif
194 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
195 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
196 " -nosound do not play sound\n"
197 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
198 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
199 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
200 " -playlist <file> specify playlist file\n"
201 " -vid x -aid y select video (x) and audio (y) stream to play\n"
202 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
203 " -pp <quality> enable postprocessing filter (details in the man page)\n"
204 " -framedrop enable frame dropping (for slow machines)\n"
205 "\n"
206 "Basic keys: (complete list in the man page, also check input.conf)\n"
207 " <- or -> seek backward/forward 10 seconds\n"
208 " down or up seek backward/forward 1 minute\n"
209 " pgdown or pgup seek backward/forward 10 minutes\n"
210 " < or > step backward/forward in playlist\n"
211 " p or SPACE pause movie (press any key to continue)\n"
212 " q or ESC stop playing and quit program\n"
213 " + or - adjust audio delay by +/- 0.1 second\n"
214 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
215 " * or / increase or decrease PCM volume\n"
216 " x or z adjust subtitle delay by +/- 0.1 second\n"
217 " r or t adjust subtitle position up/down, also see -vf expand\n"
218 "\n"
219 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
220 "\n");
223 #define Exit_SIGILL_RTCpuSel _(\
224 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
225 " It may be a bug in our new runtime CPU-detection code...\n"\
226 " Please read DOCS/HTML/en/bugreports.html.\n")
228 #define Exit_SIGILL _(\
229 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
230 " It usually happens when you run it on a CPU different than the one it was\n"\
231 " compiled/optimized for.\n"\
232 " Verify this!\n")
234 #define Exit_SIGSEGV_SIGFPE _(\
235 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
236 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
237 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
239 #define Exit_SIGCRASH _(\
240 "- MPlayer crashed. This shouldn't happen.\n"\
241 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
242 " gcc version. If you think it's MPlayer's fault, please read\n"\
243 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
244 " won't help unless you provide this information when reporting a possible bug.\n")
246 #define SystemTooSlow _("\n\n"\
247 " ************************************************\n"\
248 " **** Your system is too SLOW to play this! ****\n"\
249 " ************************************************\n\n"\
250 "Possible reasons, problems, workarounds:\n"\
251 "- Most common: broken/buggy _audio_ driver\n"\
252 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
253 " - Experiment with different values for -autosync, 30 is a good start.\n"\
254 "- Slow video output\n"\
255 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
256 "- Slow CPU\n"\
257 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
258 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
259 "- Broken file\n"\
260 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
261 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
262 " - Try -cache 8192.\n"\
263 "- Are you using -cache to play a non-interleaved AVI file?\n"\
264 " - Try -nocache.\n"\
265 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
266 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
269 //**************************************************************************//
270 //**************************************************************************//
272 #include "mp_fifo.h"
274 // benchmark:
275 double video_time_usage=0;
276 double vout_time_usage=0;
277 static double audio_time_usage=0;
278 static int total_time_usage_start=0;
279 static int total_frame_cnt=0;
280 static int drop_frame_cnt=0; // total number of dropped frames
282 // options:
283 static int output_quality=0;
285 // seek:
286 static double seek_to_sec;
287 static off_t seek_to_byte=0;
288 static off_t step_sec=0;
290 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
292 // codecs:
293 char **audio_codec_list=NULL; // override audio codec
294 char **video_codec_list=NULL; // override video codec
295 char **audio_fm_list=NULL; // override audio codec family
296 char **video_fm_list=NULL; // override video codec family
298 // this dvdsub_id was selected via slang
299 // use this to allow dvdnav to follow -slang across stream resets,
300 // in particular the subtitle ID for a language changes
301 int dvdsub_lang_id;
302 int vobsub_id=-1;
303 static char* spudec_ifo=NULL;
304 int forced_subs_only=0;
305 int file_filter=1;
307 // cache2:
308 int stream_cache_size=-1;
310 // dump:
311 int stream_dump_type=0;
313 // A-V sync:
314 static float default_max_pts_correction=-1;//0.01f;
315 float audio_delay=0;
316 static int ignore_start=0;
318 double force_fps=0;
319 static int force_srate=0;
320 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
321 static int play_n_frames=-1;
322 static int play_n_frames_mf=-1;
324 // sub:
325 char *font_name=NULL;
326 char *sub_font_name=NULL;
327 extern int font_fontconfig;
328 float font_factor=0.75;
329 char **sub_name=NULL;
330 float sub_delay=0;
331 float sub_fps=0;
332 int sub_auto = 1;
333 char *vobsub_name=NULL;
334 int subcc_enabled=0;
335 int suboverlap_enabled = 1;
337 #include "sub/ass_mp.h"
339 char* current_module=NULL; // for debugging
342 // ---
344 #ifdef CONFIG_MENU
345 #include "m_struct.h"
346 #include "libmenu/menu.h"
347 static const vf_info_t* const libmenu_vfs[] = {
348 &vf_info_menu,
349 NULL
351 static vf_instance_t* vf_menu = NULL;
352 int use_menu = 0;
353 static char* menu_cfg = NULL;
354 static char* menu_root = "main";
355 #endif
358 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
359 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
360 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
361 int use_filedir_conf;
362 int use_filename_title;
364 #include "mpcommon.h"
365 #include "command.h"
367 #include "metadata.h"
369 const void *mpctx_get_video_out(MPContext *mpctx)
371 return mpctx->video_out;
374 const void *mpctx_get_audio_out(MPContext *mpctx)
376 return mpctx->audio_out;
379 void *mpctx_get_demuxer(MPContext *mpctx)
381 return mpctx->demuxer;
384 void *mpctx_get_playtree_iter(MPContext *mpctx)
386 return mpctx->playtree_iter;
389 void *mpctx_get_mixer(MPContext *mpctx)
391 return &mpctx->mixer;
394 int mpctx_get_global_sub_size(MPContext *mpctx)
396 return mpctx->global_sub_size;
399 int mpctx_get_osd_function(MPContext *mpctx)
401 return mpctx->osd_function;
404 static float get_relative_time(struct MPContext *mpctx)
406 unsigned int new_time = GetTimer();
407 unsigned int delta = new_time - mpctx->last_time;
408 mpctx->last_time = new_time;
409 return delta * 0.000001;
412 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
413 switch (type)
415 /* check for valid video stream */
416 case META_VIDEO_CODEC:
417 case META_VIDEO_BITRATE:
418 case META_VIDEO_RESOLUTION:
420 if (!mpctx->sh_video)
421 return 0;
422 break;
425 /* check for valid audio stream */
426 case META_AUDIO_CODEC:
427 case META_AUDIO_BITRATE:
428 case META_AUDIO_SAMPLES:
430 if (!mpctx->sh_audio)
431 return 0;
432 break;
435 /* check for valid demuxer */
436 case META_INFO_TITLE:
437 case META_INFO_ARTIST:
438 case META_INFO_ALBUM:
439 case META_INFO_YEAR:
440 case META_INFO_COMMENT:
441 case META_INFO_TRACK:
442 case META_INFO_GENRE:
444 if (!mpctx->demuxer)
445 return 0;
446 break;
449 default:
450 break;
453 return 1;
456 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
457 char **info = mpctx->demuxer->info;
458 int n;
460 if (!info || !tag)
461 return talloc_strdup(NULL, "");
463 for (n = 0; info[2*n] != NULL ; n++)
464 if (!strcasecmp (info[2*n], tag))
465 break;
467 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
470 char *get_metadata(struct MPContext *mpctx, metadata_t type)
472 sh_audio_t * const sh_audio = mpctx->sh_audio;
473 sh_video_t * const sh_video = mpctx->sh_video;
475 if (!is_valid_metadata_type(mpctx, type))
476 return NULL;
478 switch (type) {
479 case META_NAME:
480 return talloc_strdup(NULL, mp_basename(mpctx->filename));
481 case META_VIDEO_CODEC:
482 if (sh_video->format == 0x10000001)
483 return talloc_strdup(NULL, "mpeg1");
484 else if (sh_video->format == 0x10000002)
485 return talloc_strdup(NULL, "mpeg2");
486 else if (sh_video->format == 0x10000004)
487 return talloc_strdup(NULL, "mpeg4");
488 else if (sh_video->format == 0x10000005)
489 return talloc_strdup(NULL, "h264");
490 else if (sh_video->format >= 0x20202020)
491 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
492 else
493 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
494 case META_VIDEO_BITRATE:
495 return talloc_asprintf(NULL, "%d kbps",
496 (int) (sh_video->i_bps * 8 / 1024));
497 case META_VIDEO_RESOLUTION:
498 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
499 sh_video->disp_h);
500 case META_AUDIO_CODEC:
501 if (sh_audio->codec && sh_audio->codec->name)
502 return talloc_strdup(NULL, sh_audio->codec->name);
503 return talloc_strdup(NULL, "");
504 case META_AUDIO_BITRATE:
505 return talloc_asprintf(NULL, "%d kbps",
506 (int) (sh_audio->i_bps * 8/1000));
507 case META_AUDIO_SAMPLES:
508 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
509 sh_audio->channels);
511 /* check for valid demuxer */
512 case META_INFO_TITLE:
513 return get_demuxer_info(mpctx, "Title");
515 case META_INFO_ARTIST:
516 return get_demuxer_info(mpctx, "Artist");
518 case META_INFO_ALBUM:
519 return get_demuxer_info(mpctx, "Album");
521 case META_INFO_YEAR:
522 return get_demuxer_info(mpctx, "Year");
524 case META_INFO_COMMENT:
525 return get_demuxer_info(mpctx, "Comment");
527 case META_INFO_TRACK:
528 return get_demuxer_info(mpctx, "Track");
530 case META_INFO_GENRE:
531 return get_demuxer_info(mpctx, "Genre");
533 default:
534 break;
537 return talloc_strdup(NULL, "");
540 static void print_file_properties(struct MPContext *mpctx, const char *filename)
542 double start_pts = MP_NOPTS_VALUE;
543 double video_start_pts = MP_NOPTS_VALUE;
544 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
545 filename_recode(filename));
546 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
547 if (mpctx->sh_video) {
548 /* Assume FOURCC if all bytes >= 0x20 (' ') */
549 if (mpctx->sh_video->format >= 0x20202020)
550 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
551 else
552 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
553 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
554 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
555 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
556 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
557 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
558 video_start_pts = ds_get_next_pts(mpctx->d_video);
560 if (mpctx->sh_audio) {
561 /* Assume FOURCC if all bytes >= 0x20 (' ') */
562 if (mpctx->sh_audio->format >= 0x20202020)
563 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
564 else
565 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
566 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
567 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
568 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
569 start_pts = ds_get_next_pts(mpctx->d_audio);
571 if (video_start_pts != MP_NOPTS_VALUE) {
572 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
573 (mpctx->sh_video && video_start_pts < start_pts))
574 start_pts = video_start_pts;
576 if (start_pts != MP_NOPTS_VALUE)
577 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
578 else
579 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
580 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
581 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
582 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
583 if (mpctx->demuxer) {
584 if (mpctx->demuxer->num_chapters == 0)
585 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
586 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
590 /// step size of mixer changes
591 int volstep = 3;
593 #ifdef CONFIG_DVDNAV
594 static void mp_dvdnav_context_free(MPContext *ctx){
595 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
596 ctx->nav_smpi = NULL;
597 free(ctx->nav_buffer);
598 ctx->nav_buffer = NULL;
599 ctx->nav_start = NULL;
600 ctx->nav_in_size = 0;
602 #endif
604 static void uninit_subs(struct demuxer *demuxer)
606 for (int i = 0; i < MAX_S_STREAMS; i++) {
607 struct sh_sub *sh = demuxer->s_streams[i];
608 if (sh && sh->initialized)
609 sub_uninit(sh);
613 void uninit_player(struct MPContext *mpctx, unsigned int mask){
614 mask &= mpctx->initialized_flags;
616 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
618 if(mask&INITIALIZED_ACODEC){
619 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
620 current_module="uninit_acodec";
621 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
622 mpctx->sh_audio=NULL;
623 mpctx->mixer.afilter = NULL;
626 if (mask & INITIALIZED_SUB) {
627 mpctx->initialized_flags &= ~INITIALIZED_SUB;
628 if (mpctx->d_sub->sh)
629 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
632 if(mask&INITIALIZED_VCODEC){
633 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
634 current_module="uninit_vcodec";
635 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
636 mpctx->sh_video=NULL;
637 #ifdef CONFIG_MENU
638 vf_menu=NULL;
639 #endif
642 if(mask&INITIALIZED_DEMUXER){
643 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
644 current_module="free_demuxer";
645 if (mpctx->num_sources) {
646 mpctx->demuxer = mpctx->sources[0].demuxer;
647 for (int i = 1; i < mpctx->num_sources; i++) {
648 uninit_subs(mpctx->sources[i].demuxer);
649 free_stream(mpctx->sources[i].stream);
650 free_demuxer(mpctx->sources[i].demuxer);
653 talloc_free(mpctx->sources);
654 mpctx->sources = NULL;
655 mpctx->num_sources = 0;
656 talloc_free(mpctx->timeline);
657 mpctx->timeline = NULL;
658 mpctx->num_timeline_parts = 0;
659 talloc_free(mpctx->chapters);
660 mpctx->chapters = NULL;
661 mpctx->num_chapters = 0;
662 mpctx->video_offset = 0;
663 if(mpctx->demuxer){
664 mpctx->stream=mpctx->demuxer->stream;
665 uninit_subs(mpctx->demuxer);
666 free_demuxer(mpctx->demuxer);
668 mpctx->demuxer=NULL;
671 // kill the cache process:
672 if(mask&INITIALIZED_STREAM){
673 mpctx->initialized_flags&=~INITIALIZED_STREAM;
674 current_module="uninit_stream";
675 if(mpctx->stream) free_stream(mpctx->stream);
676 mpctx->stream=NULL;
679 if(mask&INITIALIZED_VO){
680 mpctx->initialized_flags&=~INITIALIZED_VO;
681 current_module="uninit_vo";
682 vo_destroy(mpctx->video_out);
683 mpctx->video_out=NULL;
684 #ifdef CONFIG_DVDNAV
685 mp_dvdnav_context_free(mpctx);
686 #endif
689 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
690 if(mask&INITIALIZED_GETCH2){
691 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
692 current_module="uninit_getch2";
693 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
694 // restore terminal:
695 getch2_disable();
698 if(mask&INITIALIZED_VOBSUB){
699 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
700 current_module="uninit_vobsub";
701 if(vo_vobsub) vobsub_close(vo_vobsub);
702 vo_vobsub=NULL;
705 if (mask&INITIALIZED_SPUDEC){
706 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
707 current_module="uninit_spudec";
708 spudec_free(vo_spudec);
709 vo_spudec=NULL;
712 if(mask&INITIALIZED_AO){
713 mpctx->initialized_flags&=~INITIALIZED_AO;
714 current_module="uninit_ao";
715 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
716 if (mpctx->audio_out)
717 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
718 mpctx->audio_out=NULL;
721 current_module=NULL;
724 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
726 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
727 uninit_player(mpctx, INITIALIZED_ALL);
728 #if defined(__MINGW32__) || defined(__CYGWIN__)
729 timeEndPeriod(1);
730 #endif
731 #ifdef CONFIG_X11
732 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
733 #endif
735 current_module="uninit_input";
736 mp_input_uninit(mpctx->input);
737 #ifdef CONFIG_MENU
738 if (use_menu)
739 menu_uninit();
740 #endif
742 #ifdef CONFIG_FREETYPE
743 current_module="uninit_font";
744 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
745 free_font_desc(mpctx->osd->sub_font);
746 free_font_desc(vo_font);
747 vo_font = NULL;
748 done_freetype();
749 #endif
750 osd_free(mpctx->osd);
752 #ifdef CONFIG_ASS
753 ass_library_done(ass_library);
754 ass_library = NULL;
755 #endif
757 current_module="exit_player";
759 // free mplayer config
760 if(mpctx->mconfig)
761 m_config_free(mpctx->mconfig);
762 mpctx->mconfig = NULL;
764 if(mpctx->playtree_iter)
765 play_tree_iter_free(mpctx->playtree_iter);
766 mpctx->playtree_iter = NULL;
767 if(mpctx->playtree)
768 play_tree_free(mpctx->playtree, 1);
769 mpctx->playtree = NULL;
771 talloc_free(mpctx->key_fifo);
773 free(edl_records); // free mem allocated for EDL
774 edl_records = NULL;
775 switch(how) {
776 case EXIT_QUIT:
777 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
778 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
779 break;
780 case EXIT_EOF:
781 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
782 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
783 break;
784 case EXIT_ERROR:
785 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
786 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
787 break;
788 default:
789 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
791 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
793 exit(rc);
796 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
798 exit_player_with_rc(mpctx, how, 1);
801 #ifndef __MINGW32__
802 static void child_sighandler(int x){
803 pid_t pid;
804 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
806 #endif
808 #ifdef CONFIG_CRASH_DEBUG
809 static char *prog_path;
810 static int crash_debug = 0;
811 #endif
813 static void exit_sighandler(int x){
814 static int sig_count=0;
815 #ifdef CONFIG_CRASH_DEBUG
816 if (!crash_debug || x != SIGTRAP)
817 #endif
818 ++sig_count;
819 if(sig_count==5)
821 /* We're crashing bad and can't uninit cleanly :(
822 * by popular request, we make one last (dirty)
823 * effort to restore the user's
824 * terminal. */
825 getch2_disable();
826 exit(1);
828 if(sig_count==6) exit(1);
829 if(sig_count>6){
830 // can't stop :(
831 #ifndef __MINGW32__
832 kill(getpid(),SIGKILL);
833 #endif
835 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
836 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
837 "\nMPlayer interrupted by signal %d in module: %s\n", x,
838 current_module ? current_module : "unknown");
839 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
840 if(sig_count<=1)
841 switch(x){
842 case SIGINT:
843 case SIGPIPE:
844 case SIGQUIT:
845 case SIGTERM:
846 case SIGKILL:
847 async_quit_request = 1;
848 return; // killed from keyboard (^C) or killed [-9]
849 case SIGILL:
850 #if CONFIG_RUNTIME_CPUDETECT
851 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
852 #else
853 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
854 #endif
855 case SIGFPE:
856 case SIGSEGV:
857 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
858 default:
859 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
860 #ifdef CONFIG_CRASH_DEBUG
861 if (crash_debug) {
862 int gdb_pid;
863 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
864 gdb_pid = fork();
865 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
866 if (gdb_pid == 0) { // We are the child
867 char spid[20];
868 snprintf(spid, sizeof(spid), "%i", getppid());
869 getch2_disable(); // allow terminal to work properly with gdb
870 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
871 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
872 } else if (gdb_pid < 0)
873 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
874 else {
875 waitpid(gdb_pid, NULL, 0);
877 if (x == SIGTRAP) return;
879 #endif
881 getch2_disable();
882 exit(1);
885 #include "cfg-mplayer.h"
887 static int cfg_include(m_option_t *conf, char *filename)
889 return m_config_parse_config_file(conf->priv, filename);
892 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
894 struct MPOpts *opts = &mpctx->opts;
895 char *conffile;
896 int conffile_fd;
897 if (!(opts->noconfig & 2) &&
898 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
899 exit_player(mpctx, EXIT_NONE);
900 if ((conffile = get_path("")) == NULL) {
901 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
902 } else {
903 #ifdef __MINGW32__
904 mkdir(conffile);
905 #else
906 mkdir(conffile, 0777);
907 #endif
908 free(conffile);
909 if ((conffile = get_path("config")) == NULL) {
910 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
911 } else {
912 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
913 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
914 write(conffile_fd, default_config, strlen(default_config));
915 close(conffile_fd);
917 if (!(opts->noconfig & 1) &&
918 m_config_parse_config_file(conf, conffile) < 0)
919 exit_player(mpctx, EXIT_NONE);
920 free(conffile);
925 #define PROFILE_CFG_PROTOCOL "protocol."
927 static void load_per_protocol_config (m_config_t* conf, const char *const file)
929 char *str;
930 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
931 m_profile_t *p;
933 /* does filename actually uses a protocol ? */
934 str = strstr (file, "://");
935 if (!str)
936 return;
938 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
939 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
940 p = m_config_get_profile (conf, protocol);
941 if (p)
943 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
944 m_config_set_profile(conf,p);
948 #define PROFILE_CFG_EXTENSION "extension."
950 static void load_per_extension_config (m_config_t* conf, const char *const file)
952 char *str;
953 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
954 m_profile_t *p;
956 /* does filename actually have an extension ? */
957 str = strrchr (file, '.');
958 if (!str)
959 return;
961 sprintf (extension, PROFILE_CFG_EXTENSION);
962 strncat (extension, ++str, 7);
963 p = m_config_get_profile (conf, extension);
964 if (p)
966 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
967 m_config_set_profile(conf,p);
971 #define PROFILE_CFG_VO "vo."
972 #define PROFILE_CFG_AO "ao."
974 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
976 char profile[strlen (cfg) + strlen (out) + 1];
977 m_profile_t *p;
979 sprintf (profile, "%s%s", cfg, out);
980 p = m_config_get_profile (conf, profile);
981 if (p)
983 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
984 m_config_set_profile(conf,p);
989 * Tries to load a config file
990 * @return 0 if file was not found, 1 otherwise
992 static int try_load_config(m_config_t *conf, const char *file)
994 struct stat st;
995 if (stat(file, &st))
996 return 0;
997 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
998 m_config_parse_config_file (conf, file);
999 return 1;
1002 static void load_per_file_config (m_config_t* conf, const char *const file)
1004 char *confpath;
1005 char cfg[PATH_MAX];
1006 const char *name;
1008 if (strlen(file) > PATH_MAX - 14) {
1009 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1010 return;
1012 sprintf (cfg, "%s.conf", file);
1014 name = mp_basename(cfg);
1015 if (use_filedir_conf) {
1016 char dircfg[PATH_MAX];
1017 strcpy(dircfg, cfg);
1018 strcpy(dircfg + (name - cfg), "mplayer.conf");
1019 try_load_config(conf, dircfg);
1021 if (try_load_config(conf, cfg))
1022 return;
1025 if ((confpath = get_path (name)) != NULL)
1027 try_load_config(conf, confpath);
1029 free (confpath);
1033 /* When libmpdemux performs a blocking operation (network connection or
1034 * cache filling) if the operation fails we use this function to check
1035 * if it was interrupted by the user.
1036 * The function returns a new value for eof. */
1037 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1039 mp_cmd_t* cmd;
1040 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1041 switch(cmd->id) {
1042 case MP_CMD_QUIT:
1043 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1044 case MP_CMD_PLAY_TREE_STEP: {
1045 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1046 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1047 } break;
1048 case MP_CMD_PLAY_TREE_UP_STEP: {
1049 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1050 } break;
1051 case MP_CMD_PLAY_ALT_SRC_STEP: {
1052 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1053 } break;
1055 mp_cmd_free(cmd);
1057 return stop_play;
1060 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1062 play_tree_add_bpf(entry,mpctx->filename);
1065 if(!entry) {
1066 entry = mpctx->playtree_iter->tree;
1067 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1068 return PT_NEXT_ENTRY;
1070 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1071 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1072 return PT_NEXT_ENTRY;
1075 play_tree_remove(entry,1,1);
1076 return PT_NEXT_SRC;
1078 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1079 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1080 entry = mpctx->playtree_iter->tree;
1081 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1082 return PT_NEXT_ENTRY;
1084 play_tree_remove(entry,1,1);
1086 return PT_NEXT_SRC;
1089 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1091 struct MPOpts *opts = &mpctx->opts;
1092 sub_data *subd = NULL;
1093 struct ass_track *asst = NULL;
1094 bool is_native_ass = false;
1096 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1097 return;
1099 #ifdef CONFIG_ASS
1100 if (opts->ass_enabled) {
1101 #ifdef CONFIG_ICONV
1102 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1103 #else
1104 asst = mp_ass_read_stream(ass_library, filename, 0);
1105 #endif
1106 is_native_ass = asst;
1107 if (!asst) {
1108 subd = sub_read_file(filename, fps, &mpctx->opts);
1109 if (subd) {
1110 asst = mp_ass_read_subdata(ass_library, subd, fps);
1111 sub_free(subd);
1112 subd = NULL;
1115 } else
1116 #endif
1117 subd = sub_read_file(filename, fps, &mpctx->opts);
1120 if (!asst && !subd) {
1121 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1122 "Cannot load subtitles: %s\n", filename_recode(filename));
1123 return;
1126 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1127 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1128 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1129 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1130 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1131 filename_recode(filename));
1132 ++mpctx->set_of_sub_size;
1133 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1134 filename_recode(filename));
1137 void init_vo_spudec(struct MPContext *mpctx)
1139 spudec_free(vo_spudec);
1140 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1141 vo_spudec = NULL;
1143 // we currently can't work without video stream
1144 if (!mpctx->sh_video)
1145 return;
1147 if (spudec_ifo) {
1148 unsigned int palette[16], width, height;
1149 current_module="spudec_init_vobsub";
1150 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1151 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1154 #ifdef CONFIG_DVDREAD
1155 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1156 current_module="spudec_init_dvdread";
1157 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1158 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1159 NULL, 0);
1161 #endif
1163 #ifdef CONFIG_DVDNAV
1164 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1165 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1166 current_module="spudec_init_dvdnav";
1167 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1169 #endif
1171 if (vo_spudec==NULL) {
1172 sh_sub_t *sh = mpctx->d_sub->sh;
1173 current_module="spudec_init_normal";
1174 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1175 spudec_set_font_factor(vo_spudec,font_factor);
1178 if (vo_spudec!=NULL) {
1179 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1180 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1185 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1186 * make it all work is to use the builtin SDL-bootstrap code, which
1187 * will be done automatically by replacing our main() if we include SDL.h.
1189 #if defined(__APPLE__) && defined(CONFIG_SDL)
1190 #ifdef CONFIG_SDL_SDL_H
1191 #include <SDL/SDL.h>
1192 #else
1193 #include <SDL.h>
1194 #endif
1195 #endif
1198 * \brief append a formatted string
1199 * \param buf buffer to print into
1200 * \param pos position of terminating 0 in buf
1201 * \param len maximum number of characters in buf, not including terminating 0
1202 * \param format printf format string
1204 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1206 va_list va;
1207 va_start(va, format);
1208 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1209 va_end(va);
1210 if (*pos >= len ) {
1211 buf[len] = 0;
1212 *pos = len;
1217 * \brief append time in the hh:mm:ss.f format
1218 * \param buf buffer to print into
1219 * \param pos position of terminating 0 in buf
1220 * \param len maximum number of characters in buf, not including terminating 0
1221 * \param time time value to convert/append
1223 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1224 int64_t tenths = 10 * time;
1225 int f1 = tenths % 10;
1226 int ss = (tenths / 10) % 60;
1227 int mm = (tenths / 600) % 60;
1228 int hh = tenths / 36000;
1229 if (time <= 0) {
1230 saddf(buf, pos, len, "unknown");
1231 return;
1233 if (hh > 0)
1234 saddf(buf, pos, len, "%2d:", hh);
1235 if (hh > 0 || mm > 0)
1236 saddf(buf, pos, len, "%02d:", mm);
1237 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1240 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1242 struct MPOpts *opts = &mpctx->opts;
1243 sh_video_t * const sh_video = mpctx->sh_video;
1245 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1246 a_pos = playing_audio_pts(mpctx);
1247 if (mpctx->sh_audio && sh_video && at_frame) {
1248 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1249 if (mpctx->time_frame > 0)
1250 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1251 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1252 && !mpctx->drop_message_shown) {
1253 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1254 mpctx->drop_message_shown = true;
1257 if (opts->quiet)
1258 return;
1261 int width;
1262 char *line;
1263 unsigned pos = 0;
1264 get_screen_size();
1265 if (screen_width > 0)
1266 width = screen_width;
1267 else
1268 width = 80;
1269 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1270 /* Windows command line is broken (MinGW's rxvt works, but we
1271 * should not depend on that). */
1272 width--;
1273 #endif
1274 line = malloc(width + 1); // one additional char for the terminating null
1276 // Audio time
1277 if (mpctx->sh_audio) {
1278 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1279 if (!sh_video) {
1280 float len = get_time_length(mpctx);
1281 saddf(line, &pos, width, "(");
1282 sadd_hhmmssf(line, &pos, width, a_pos);
1283 saddf(line, &pos, width, ") of %.1f (", len);
1284 sadd_hhmmssf(line, &pos, width, len);
1285 saddf(line, &pos, width, ") ");
1289 // Video time
1290 if (sh_video)
1291 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1293 // A-V sync
1294 if (mpctx->sh_audio && sh_video)
1295 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1296 mpctx->last_av_difference, mpctx->total_avsync_change);
1298 // Video stats
1299 if (sh_video)
1300 saddf(line, &pos, width, "%3d/%3d ",
1301 (int)sh_video->num_frames,
1302 (int)sh_video->num_frames_decoded);
1304 // CPU usage
1305 if (sh_video) {
1306 if (sh_video->timer > 0.5)
1307 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1308 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1309 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1310 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1311 else
1312 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1313 } else if (mpctx->sh_audio) {
1314 if (mpctx->delay > 0.5)
1315 saddf(line, &pos, width, "%4.1f%% ",
1316 100.0*audio_time_usage/(double)mpctx->delay);
1317 else
1318 saddf(line, &pos, width, "??,?%% ");
1321 // VO stats
1322 if (sh_video)
1323 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1325 #ifdef CONFIG_STREAM_CACHE
1326 // cache stats
1327 if (stream_cache_size > 0)
1328 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1329 #endif
1331 // other
1332 if (opts->playback_speed != 1)
1333 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1335 // end
1336 if (erase_to_end_of_line) {
1337 line[pos] = 0;
1338 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1339 } else {
1340 memset(&line[pos], ' ', width - pos);
1341 line[width] = 0;
1342 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1344 free(line);
1348 * \brief build a chain of audio filters that converts the input format
1349 * to the ao's format, taking into account the current playback_speed.
1350 * \param sh_audio describes the requested input format of the chain.
1351 * \param ao_data describes the requested output format of the chain.
1353 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1354 ao_data_t *ao_data)
1356 struct MPOpts *opts = &mpctx->opts;
1357 int new_srate;
1358 int result;
1359 if (!sh_audio)
1361 mpctx->mixer.afilter = NULL;
1362 return 0;
1364 if(af_control_any_rev(sh_audio->afilter,
1365 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1366 &opts->playback_speed)) {
1367 new_srate = sh_audio->samplerate;
1368 } else {
1369 new_srate = sh_audio->samplerate * opts->playback_speed;
1370 if (new_srate != ao_data->samplerate) {
1371 // limits are taken from libaf/af_resample.c
1372 if (new_srate < 8000)
1373 new_srate = 8000;
1374 if (new_srate > 192000)
1375 new_srate = 192000;
1376 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1379 result = init_audio_filters(sh_audio, new_srate,
1380 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1381 mpctx->mixer.afilter = sh_audio->afilter;
1382 return result;
1386 typedef struct mp_osd_msg mp_osd_msg_t;
1387 struct mp_osd_msg {
1388 /// Previous message on the stack.
1389 mp_osd_msg_t* prev;
1390 /// Message text.
1391 char msg[128];
1392 int id,level,started;
1393 /// Display duration in ms.
1394 unsigned time;
1397 /// OSD message stack.
1398 static mp_osd_msg_t* osd_msg_stack = NULL;
1401 * \brief Add a message on the OSD message stack
1403 * If a message with the same id is already present in the stack
1404 * it is pulled on top of the stack, otherwise a new message is created.
1407 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1408 va_list ap)
1410 mp_osd_msg_t *msg,*last=NULL;
1411 int r;
1413 // look if the id is already in the stack
1414 for(msg = osd_msg_stack ; msg && msg->id != id ;
1415 last = msg, msg = msg->prev);
1416 // not found: alloc it
1417 if(!msg) {
1418 msg = calloc(1,sizeof(mp_osd_msg_t));
1419 msg->prev = osd_msg_stack;
1420 osd_msg_stack = msg;
1421 } else if(last) { // found, but it's not on top of the stack
1422 last->prev = msg->prev;
1423 msg->prev = osd_msg_stack;
1424 osd_msg_stack = msg;
1426 // write the msg
1427 r = vsnprintf(msg->msg, 128, fmt, ap);
1428 if(r >= 128) msg->msg[127] = 0;
1429 // set id and time
1430 msg->id = id;
1431 msg->level = level;
1432 msg->time = time;
1436 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1438 va_list ap;
1439 va_start(ap, fmt);
1440 set_osd_msg_va(id, level, time, fmt, ap);
1441 va_end(ap);
1444 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1446 va_list ap;
1447 va_start(ap, fmt);
1448 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1449 va_end(ap);
1454 * \brief Remove a message from the OSD stack
1456 * This function can be used to get rid of a message right away.
1460 void rm_osd_msg(int id) {
1461 mp_osd_msg_t *msg,*last=NULL;
1463 // Search for the msg
1464 for(msg = osd_msg_stack ; msg && msg->id != id ;
1465 last = msg, msg = msg->prev);
1466 if(!msg) return;
1468 // Detach it from the stack and free it
1469 if(last)
1470 last->prev = msg->prev;
1471 else
1472 osd_msg_stack = msg->prev;
1473 free(msg);
1477 * \brief Remove all messages from the OSD stack
1481 static void clear_osd_msgs(void) {
1482 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1483 while(msg) {
1484 prev = msg->prev;
1485 free(msg);
1486 msg = prev;
1488 osd_msg_stack = NULL;
1492 * \brief Get the current message from the OSD stack.
1494 * This function decrements the message timer and destroys the old ones.
1495 * The message that should be displayed is returned (if any).
1499 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1501 struct MPOpts *opts = &mpctx->opts;
1502 mp_osd_msg_t *msg,*prev,*last = NULL;
1503 static unsigned last_update = 0;
1504 unsigned now = GetTimerMS();
1505 unsigned diff;
1506 char hidden_dec_done = 0;
1508 if (mpctx->osd_visible) {
1509 // 36000000 means max timed visibility is 1 hour into the future, if
1510 // the difference is greater assume it's wrapped around from below 0
1511 if (mpctx->osd_visible - now > 36000000) {
1512 mpctx->osd_visible = 0;
1513 vo_osd_progbar_type = -1; // disable
1514 vo_osd_changed(OSDTYPE_PROGBAR);
1515 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1518 if (mpctx->osd_show_percentage_until - now > 36000000)
1519 mpctx->osd_show_percentage_until = 0;
1521 if(!last_update) last_update = now;
1522 diff = now >= last_update ? now - last_update : 0;
1524 last_update = now;
1526 // Look for the first message in the stack with high enough level.
1527 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1528 prev = msg->prev;
1529 if (msg->level > opts->osd_level && hidden_dec_done)
1530 continue;
1531 // The message has a high enough level or it is the first hidden one
1532 // in both cases we decrement the timer or kill it.
1533 if(!msg->started || msg->time > diff) {
1534 if(msg->started) msg->time -= diff;
1535 else msg->started = 1;
1536 // display it
1537 if (msg->level <= opts->osd_level)
1538 return msg;
1539 hidden_dec_done = 1;
1540 continue;
1542 // kill the message
1543 free(msg);
1544 if(last) {
1545 last->prev = prev;
1546 msg = last;
1547 } else {
1548 osd_msg_stack = prev;
1549 msg = NULL;
1552 // Nothing found
1553 return NULL;
1557 * \brief Display the OSD bar.
1559 * Display the OSD bar or fall back on a simple message.
1563 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1564 struct MPOpts *opts = &mpctx->opts;
1565 if (opts->osd_level < 1)
1566 return;
1568 if(mpctx->sh_video) {
1569 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1570 vo_osd_progbar_type = type;
1571 vo_osd_progbar_value = 256*(val-min)/(max-min);
1572 vo_osd_changed(OSDTYPE_PROGBAR);
1573 return;
1576 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1577 name, ROUND(100*(val-min)/(max-min)));
1581 * \brief Display text subtitles on the OSD
1583 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1585 int i;
1586 vo_sub = subs;
1587 vo_osd_changed(OSDTYPE_SUBTITLE);
1588 if (!mpctx->sh_video) {
1589 // reverse order, since newest set_osd_msg is displayed first
1590 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1591 if (!subs || i >= subs->lines || !subs->text[i])
1592 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1593 else {
1594 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1595 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1596 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1603 * \brief Update the OSD message line.
1605 * This function displays the current message on the vo OSD or on the term.
1606 * If the stack is empty and the OSD level is high enough the timer
1607 * is displayed (only on the vo OSD).
1611 static void update_osd_msg(struct MPContext *mpctx)
1613 struct MPOpts *opts = &mpctx->opts;
1614 mp_osd_msg_t *msg;
1615 struct osd_state *osd = mpctx->osd;
1616 char osd_text_timer[128];
1618 if (mpctx->add_osd_seek_info) {
1619 double percentage = get_percent_pos(mpctx);
1620 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1621 if (mpctx->sh_video)
1622 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1623 mpctx->add_osd_seek_info = false;
1626 // Look if we have a msg
1627 if((msg = get_osd_msg(mpctx))) {
1628 if (strcmp(osd->osd_text, msg->msg)) {
1629 strncpy(osd->osd_text, msg->msg, 127);
1630 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1631 if(opts->term_osd)
1632 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1633 msg->msg);
1635 return;
1638 if(mpctx->sh_video) {
1639 // fallback on the timer
1640 if (opts->osd_level >= 2) {
1641 int len = get_time_length(mpctx);
1642 int percentage = -1;
1643 char percentage_text[10];
1644 int pts = get_current_time(mpctx);
1646 if (mpctx->osd_show_percentage_until)
1647 percentage = get_percent_pos(mpctx);
1649 if (percentage >= 0)
1650 snprintf(percentage_text, 9, " (%d%%)", percentage);
1651 else
1652 percentage_text[0] = 0;
1654 if (opts->osd_level == 3)
1655 snprintf(osd_text_timer, 63,
1656 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1657 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1658 len/3600,(len/60)%60,len%60,percentage_text);
1659 else
1660 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1661 mpctx->osd_function,pts/3600,(pts/60)%60,
1662 pts%60,percentage_text);
1663 } else
1664 osd_text_timer[0]=0;
1666 if (strcmp(osd->osd_text, osd_text_timer)) {
1667 strncpy(osd->osd_text, osd_text_timer, 63);
1668 vo_osd_changed(OSDTYPE_OSD);
1670 return;
1673 // Clear the term osd line
1674 if (opts->term_osd && osd->osd_text[0]) {
1675 osd->osd_text[0] = 0;
1676 printf("%s\n", opts->term_osd_esc);
1680 ///@}
1681 // OSDMsgStack
1684 void reinit_audio_chain(struct MPContext *mpctx)
1686 struct MPOpts *opts = &mpctx->opts;
1687 if (!mpctx->sh_audio)
1688 return;
1689 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1690 current_module="init_audio_codec";
1691 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1692 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1693 goto init_error;
1695 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1696 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1700 current_module="af_preinit";
1701 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1702 ao_data.samplerate=force_srate;
1703 ao_data.channels=0;
1704 ao_data.format = opts->audio_output_format;
1706 // first init to detect best values
1707 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1708 // input:
1709 mpctx->sh_audio->samplerate,
1710 // output:
1711 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1712 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1713 "pre-init!\n");
1714 exit_player(mpctx, EXIT_ERROR);
1716 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1717 current_module="ao2_init";
1718 ao_data.buffersize = opts->ao_buffersize;
1719 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1720 0, // plugin flag
1721 ao_data.samplerate,
1722 ao_data.channels,
1723 ao_data.format, 0);
1724 if(!mpctx->audio_out){
1725 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1726 goto init_error;
1728 mpctx->initialized_flags|=INITIALIZED_AO;
1729 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1730 mpctx->audio_out->info->short_name,
1731 ao_data.samplerate, ao_data.channels,
1732 af_fmt2str_short(ao_data.format),
1733 af_fmt2bits(ao_data.format)/8 );
1734 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1735 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1736 if(strlen(mpctx->audio_out->info->comment) > 0)
1737 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1740 // init audio filters:
1741 current_module="af_init";
1742 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1743 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1744 goto init_error;
1746 mpctx->mixer.audio_out = mpctx->audio_out;
1747 mpctx->mixer.volstep = volstep;
1748 mpctx->syncing_audio = true;
1749 return;
1751 init_error:
1752 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1753 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1754 mpctx->d_audio->id = -2;
1758 ///@}
1759 // Command2Property
1762 // Return pts value corresponding to the end point of audio written to the
1763 // ao so far.
1764 static double written_audio_pts(struct MPContext *mpctx)
1766 sh_audio_t *sh_audio = mpctx->sh_audio;
1767 demux_stream_t *d_audio = mpctx->d_audio;
1768 double buffered_output;
1769 // first calculate the end pts of audio that has been output by decoder
1770 double a_pts = sh_audio->pts;
1771 if (a_pts != MP_NOPTS_VALUE)
1772 // Good, decoder supports new way of calculating audio pts.
1773 // sh_audio->pts is the timestamp of the latest input packet with
1774 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1775 // the amount of bytes the decoder has written after that timestamp.
1776 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1777 else {
1778 // Decoder doesn't support new way of calculating pts (or we're
1779 // being called before it has decoded anything with known timestamp).
1780 // Use the old method of audio pts calculation: take the timestamp
1781 // of last packet with known pts the decoder has read data from,
1782 // and add amount of bytes read after the beginning of that packet
1783 // divided by input bps. This will be inaccurate if the input/output
1784 // ratio is not constant for every audio packet or if it is constant
1785 // but not accurately known in sh_audio->i_bps.
1787 a_pts = d_audio->pts;
1788 // ds_tell_pts returns bytes read after last timestamp from
1789 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1790 // it has read but not decoded
1791 if (sh_audio->i_bps)
1792 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1793 (double)sh_audio->i_bps;
1795 // Now a_pts hopefully holds the pts for end of audio from decoder.
1796 // Substract data in buffers between decoder and audio out.
1798 // Decoded but not filtered
1799 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1801 // Data buffered in audio filters, measured in bytes of "missing" output
1802 buffered_output = af_calc_delay(sh_audio->afilter);
1804 // Data that was ready for ao but was buffered because ao didn't fully
1805 // accept everything to internal buffers yet
1806 buffered_output += sh_audio->a_out_buffer_len;
1808 // Filters divide audio length by playback_speed, so multiply by it
1809 // to get the length in original units without speedup or slowdown
1810 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1812 return a_pts + mpctx->video_offset;
1815 // Return pts value corresponding to currently playing audio.
1816 double playing_audio_pts(struct MPContext *mpctx)
1818 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1819 mpctx->audio_out->get_delay();
1822 static bool is_av_sub(int type)
1824 return type == 'b' || type == 'p' || type == 'x';
1827 void update_subtitles(struct MPContext *mpctx, double refpts,
1828 double sub_offset, bool reset)
1830 struct MPOpts *opts = &mpctx->opts;
1831 struct sh_video *sh_video = mpctx->sh_video;
1832 struct demux_stream *d_sub = mpctx->d_sub;
1833 double curpts = refpts + sub_delay;
1834 unsigned char *packet=NULL;
1835 int len;
1836 struct sh_sub *sh_sub = d_sub->sh;
1837 int type = sh_sub ? sh_sub->type : 'v';
1838 static subtitle subs;
1839 if (reset) {
1840 if (sh_sub)
1841 sub_reset(sh_sub, mpctx->osd);
1842 sub_clear_text(&subs, MP_NOPTS_VALUE);
1843 if (vo_sub)
1844 set_osd_subtitle(mpctx, NULL);
1845 if (vo_spudec) {
1846 spudec_reset(vo_spudec);
1847 vo_osd_changed(OSDTYPE_SPU);
1849 #ifdef CONFIG_FFMPEG
1850 if (is_av_sub(type))
1851 reset_avsub(sh_sub);
1852 #endif
1853 return;
1855 // find sub
1856 if (mpctx->subdata) {
1857 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1858 current_module = "find_sub";
1859 find_sub(mpctx, mpctx->subdata, curpts *
1860 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1861 if (vo_sub)
1862 mpctx->vo_sub_last = vo_sub;
1865 // DVD sub:
1866 if (vobsub_id >= 0 || type == 'v') {
1867 int timestamp;
1868 current_module = "spudec";
1869 /* Get a sub packet from the DVD or a vobsub */
1870 while(1) {
1871 // Vobsub
1872 len = 0;
1873 if (vo_vobsub) {
1874 if (curpts >= 0) {
1875 len = vobsub_get_packet(vo_vobsub, curpts,
1876 (void**)&packet, &timestamp);
1877 if (len > 0) {
1878 mp_dbg(MSGT_CPLAYER,MSGL_V,"\rVOB sub: len=%d v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",len,refpts,sh_video->timer,timestamp / 90000.0,timestamp);
1881 } else {
1882 // DVD sub
1883 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1884 if (len > 0) {
1885 // XXX This is wrong, sh_video->pts can be arbitrarily
1886 // much behind demuxing position. Unfortunately using
1887 // d_video->pts which would have been the simplest
1888 // improvement doesn't work because mpeg specific hacks
1889 // in video.c set d_video->pts to 0.
1890 float x = d_sub->pts - refpts;
1891 if (x > -20 && x < 20) // prevent missing subs on pts reset
1892 timestamp = 90000*d_sub->pts;
1893 else timestamp = 90000*curpts;
1894 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1895 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1896 refpts, d_sub->pts, timestamp);
1899 if (len<=0 || !packet) break;
1900 // create it only here, since with some broken demuxers we might
1901 // type = v but no DVD sub and we currently do not change the
1902 // "original frame size" ever after init, leading to wrong-sized
1903 // PGS subtitles.
1904 if (!vo_spudec)
1905 vo_spudec = spudec_new(NULL);
1906 if (vo_vobsub || timestamp >= 0)
1907 spudec_assemble(vo_spudec, packet, len, timestamp);
1909 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1910 if (type == 'd' && !d_sub->demuxer->teletext) {
1911 tt_stream_props tsp = {0};
1912 void *ptr = &tsp;
1913 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1914 d_sub->demuxer->teletext = ptr;
1916 if (d_sub->non_interleaved)
1917 ds_get_next_pts(d_sub);
1919 while (d_sub->first) {
1920 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1921 if (subpts > curpts) {
1922 // Libass handled subs can be fed to it in advance
1923 if (!opts->ass_enabled || !is_text_sub(type))
1924 break;
1925 // Try to avoid demuxing whole file at once
1926 if (d_sub->non_interleaved && subpts > curpts + 1)
1927 break;
1929 double duration = d_sub->first->duration;
1930 len = ds_get_packet_sub(d_sub, &packet);
1931 if (is_av_sub(type)) {
1932 #ifdef CONFIG_FFMPEG
1933 decode_avsub(sh_sub, packet, len, subpts, duration);
1934 #endif
1935 continue;
1937 if (type == 'm') {
1938 if (len < 2) continue;
1939 len = FFMIN(len - 2, AV_RB16(packet));
1940 packet += 2;
1942 if (type == 'd') {
1943 if (d_sub->demuxer->teletext) {
1944 uint8_t *p = packet;
1945 p++;
1946 len--;
1947 while (len >= 46) {
1948 int sublen = p[1];
1949 if (p[0] == 2 || p[0] == 3)
1950 teletext_control(d_sub->demuxer->teletext,
1951 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1952 p += sublen + 2;
1953 len -= sublen + 2;
1956 continue;
1958 if (sh_sub && sh_sub->active) {
1959 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
1960 continue;
1962 if (subpts != MP_NOPTS_VALUE) {
1963 if (duration < 0)
1964 sub_clear_text(&subs, MP_NOPTS_VALUE);
1965 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1966 int i;
1967 unsigned char* p = packet;
1968 for (i=0; i < 8 && *p != '\0'; p++)
1969 if (*p == ',')
1970 i++;
1971 if (*p == '\0') /* Broken line? */
1972 continue;
1973 len -= p - packet;
1974 packet = p;
1976 double endpts = MP_NOPTS_VALUE;
1977 if (subpts != MP_NOPTS_VALUE && duration >= 0)
1978 endpts = subpts + duration;
1979 sub_add_text(&subs, packet, len, endpts);
1980 set_osd_subtitle(mpctx, &subs);
1982 if (d_sub->non_interleaved)
1983 ds_get_next_pts(d_sub);
1985 if (!opts->ass_enabled)
1986 if (sub_clear_text(&subs, curpts))
1987 set_osd_subtitle(mpctx, &subs);
1989 if (vo_spudec) {
1990 spudec_heartbeat(vo_spudec, 90000*curpts);
1991 if (spudec_changed(vo_spudec))
1992 vo_osd_changed(OSDTYPE_SPU);
1995 current_module=NULL;
1998 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2000 int page_changed;
2002 if (!demuxer->teletext)
2003 return;
2005 //Also forcing page update when such ioctl is not supported or call error occured
2006 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2007 page_changed=1;
2009 if(!page_changed)
2010 return;
2012 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2013 vo_osd_teletext_page=NULL;
2014 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2015 vo_osd_teletext_half=0;
2016 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2017 vo_osd_teletext_mode=0;
2018 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2019 vo_osd_teletext_format=0;
2020 vo_osd_changed(OSDTYPE_TELETEXT);
2022 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2025 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2026 struct MPOpts *opts = &mpctx->opts;
2027 // check for frame-drop:
2028 current_module = "check_framedrop";
2029 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2030 static int dropped_frames;
2031 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
2032 float d = delay-mpctx->delay;
2033 ++total_frame_cnt;
2034 // we should avoid dropping too many frames in sequence unless we
2035 // are too late. and we allow 100ms A-V delay here:
2036 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2037 && !mpctx->restart_playback) {
2038 ++drop_frame_cnt;
2039 ++dropped_frames;
2040 return frame_dropping;
2041 } else
2042 dropped_frames = 0;
2044 return 0;
2048 #ifdef HAVE_RTC
2049 int rtc_fd = -1;
2050 #endif
2052 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2054 #ifdef HAVE_RTC
2055 if (rtc_fd >= 0){
2056 // -------- RTC -----------
2057 current_module="sleep_rtc";
2058 while (time_frame > 0.000) {
2059 unsigned long rtc_ts;
2060 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2061 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2062 time_frame -= get_relative_time(mpctx);
2064 } else
2065 #endif
2067 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2068 // unnecessarily high CPU usage
2069 struct MPOpts *opts = &mpctx->opts;
2070 float margin = opts->softsleep ? 0.011 : 0;
2071 current_module = "sleep_timer";
2072 while (time_frame > margin) {
2073 usec_sleep(1000000 * (time_frame - margin));
2074 time_frame -= get_relative_time(mpctx);
2076 if (opts->softsleep){
2077 current_module = "sleep_soft";
2078 if (time_frame < 0)
2079 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2080 while (time_frame > 0)
2081 time_frame -= get_relative_time(mpctx); // burn the CPU
2084 return time_frame;
2087 static int select_subtitle(MPContext *mpctx)
2089 struct MPOpts *opts = &mpctx->opts;
2090 // find the best sub to use
2091 int id;
2092 int found = 0;
2093 mpctx->global_sub_pos = -1; // no subs by default
2094 if (vobsub_id >= 0) {
2095 // if user asks for a vobsub id, use that first.
2096 id = vobsub_id;
2097 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2100 if (!found && opts->sub_id >= 0) {
2101 // if user asks for a dvd sub id, use that next.
2102 id = opts->sub_id;
2103 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2106 if (!found) {
2107 // if there are text subs to use, use those. (autosubs come last here)
2108 id = 0;
2109 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2112 if (!found && opts->sub_id == -1) {
2113 // finally select subs by language and container hints
2114 if (opts->sub_id == -1)
2115 opts->sub_id =
2116 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2117 opts->sub_lang);
2118 if (opts->sub_id >= 0) {
2119 id = opts->sub_id;
2120 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2123 return found;
2126 #ifdef CONFIG_DVDNAV
2127 #ifndef FF_B_TYPE
2128 #define FF_B_TYPE 3
2129 #endif
2130 /// store decoded video image
2131 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2132 mp_image_t *from_mpi) {
2133 mp_image_t *mpi;
2135 /// Do not store B-frames
2136 if (from_mpi->pict_type == FF_B_TYPE)
2137 return to_mpi;
2139 if (to_mpi &&
2140 to_mpi->w == from_mpi->w &&
2141 to_mpi->h == from_mpi->h &&
2142 to_mpi->imgfmt == from_mpi->imgfmt)
2143 mpi = to_mpi;
2144 else {
2145 if (to_mpi)
2146 free_mp_image(to_mpi);
2147 if (from_mpi->w == 0 || from_mpi->h == 0)
2148 return NULL;
2149 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2152 copy_mpi(mpi,from_mpi);
2153 return mpi;
2156 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2157 struct MPOpts *opts = &ctx->opts;
2158 if (ctx->sh_video) {
2159 /// clear video pts
2160 ctx->d_video->pts = 0.0f;
2161 ctx->sh_video->pts = 0.0f;
2162 ctx->sh_video->i_pts = 0.0f;
2163 ctx->sh_video->last_pts = 0.0f;
2164 ctx->sh_video->num_buffered_pts = 0;
2165 ctx->sh_video->num_frames = 0;
2166 ctx->sh_video->num_frames_decoded = 0;
2167 ctx->sh_video->timer = 0.0f;
2168 ctx->sh_video->stream_delay = 0.0f;
2169 ctx->sh_video->timer = 0;
2170 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2173 if (ctx->sh_audio) {
2174 /// free audio packets and reset
2175 ds_free_packs(ctx->d_audio);
2176 audio_delay -= ctx->sh_audio->stream_delay;
2177 ctx->delay =- audio_delay;
2178 ctx->audio_out->reset();
2179 resync_audio_stream(ctx->sh_audio);
2182 audio_delay = 0.0f;
2183 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2184 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2185 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2186 if (dvdsub_lang_id != opts->sub_id) {
2187 opts->sub_id = dvdsub_lang_id;
2188 select_subtitle(ctx);
2192 /// clear all EOF related flags
2193 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2196 /// Restore last decoded DVDNAV (still frame)
2197 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2198 int *in_size,
2199 unsigned char **start,
2200 mp_image_t *decoded_frame)
2202 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2203 return decoded_frame;
2205 /// a change occured in dvdnav stream
2206 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2207 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2208 mp_dvdnav_context_free(mpctx);
2209 mp_dvdnav_reset_stream(mpctx);
2210 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2211 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2214 if (*in_size < 0) {
2215 float len;
2217 /// Display still frame, if any
2218 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2219 decoded_frame = mpctx->nav_smpi;
2221 /// increment video frame : continue playing after still frame
2222 len = get_time_length(mpctx);
2223 if (mpctx->sh_video->pts >= len &&
2224 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2225 mp_dvdnav_skip_still(mpctx->stream);
2226 mp_dvdnav_skip_wait(mpctx->stream);
2228 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2230 if (mpctx->nav_buffer) {
2231 *start = mpctx->nav_start;
2232 *in_size = mpctx->nav_in_size;
2233 if (mpctx->nav_start)
2234 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2238 return decoded_frame;
2241 /// Save last decoded DVDNAV (still frame)
2242 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2243 unsigned char *start,
2244 mp_image_t *decoded_frame)
2246 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2247 return;
2249 free(mpctx->nav_buffer);
2251 mpctx->nav_buffer = malloc(in_size);
2252 mpctx->nav_start = start;
2253 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2254 if (mpctx->nav_buffer)
2255 memcpy(mpctx->nav_buffer,start,in_size);
2257 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2258 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2260 #endif /* CONFIG_DVDNAV */
2262 /* Modify video timing to match the audio timeline. There are two main
2263 * reasons this is needed. First, video and audio can start from different
2264 * positions at beginning of file or after a seek (MPlayer starts both
2265 * immediately even if they have different pts). Second, the file can have
2266 * audio timestamps that are inconsistent with the duration of the audio
2267 * packets, for example two consecutive timestamp values differing by
2268 * one second but only a packet with enough samples for half a second
2269 * of playback between them.
2271 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2273 current_module = "av_sync";
2275 if (!mpctx->sh_audio || mpctx->syncing_audio)
2276 return;
2278 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2279 double v_pts = mpctx->sh_video->pts;
2280 double av_delay = a_pts - v_pts;
2281 // Try to sync vo_flip() so it will *finish* at given time
2282 av_delay += mpctx->last_vo_flip_duration;
2283 av_delay -= audio_delay; // This much pts difference is desired
2285 double change = av_delay * 0.1;
2286 double max_change = default_max_pts_correction >= 0 ?
2287 default_max_pts_correction : frame_time * 0.1;
2288 if (change < -max_change)
2289 change = -max_change;
2290 else if (change > max_change)
2291 change = max_change;
2292 mpctx->delay += change;
2293 mpctx->total_avsync_change += change;
2296 #define ASYNC_PLAY_DONE -3
2297 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2299 struct MPOpts *opts = &mpctx->opts;
2300 sh_audio_t * const sh_audio = mpctx->sh_audio;
2301 int res;
2303 // Timing info may not be set without
2304 res = decode_audio(sh_audio, 1);
2305 if (res < 0)
2306 return res;
2308 int bytes;
2309 bool did_retry = false;
2310 while (1) {
2311 double written_pts = written_audio_pts(mpctx);
2312 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2313 - audio_delay;
2314 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2315 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2317 // ogg demuxers give packets without timing
2318 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2319 if (!did_retry) {
2320 // Try to read more data to see packets that have pts
2321 int res = decode_audio(sh_audio, ao_data.bps);
2322 if (res < 0)
2323 return res;
2324 did_retry = true;
2325 continue;
2327 bytes = 0;
2330 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2331 bytes = 0;
2333 if (bytes > 0)
2334 break;
2336 mpctx->syncing_audio = false;
2337 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2338 int res = decode_audio(sh_audio, a);
2339 bytes += sh_audio->a_out_buffer_len;
2340 if (bytes >= 0) {
2341 memmove(sh_audio->a_out_buffer,
2342 sh_audio->a_out_buffer +
2343 sh_audio->a_out_buffer_len - bytes,
2344 bytes);
2345 sh_audio->a_out_buffer_len = bytes;
2346 if (res < 0)
2347 return res;
2348 return decode_audio(sh_audio, playsize);
2350 sh_audio->a_out_buffer_len = 0;
2351 if (res < 0)
2352 return res;
2354 int fillbyte = 0;
2355 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2356 fillbyte = 0x80;
2357 if (bytes >= playsize) {
2358 /* This case could fall back to the one below with
2359 * bytes = playsize, but then silence would keep accumulating
2360 * in a_out_buffer if the AO accepts less data than it asks for
2361 * in playsize. */
2362 char *p = malloc(playsize);
2363 memset(p, fillbyte, playsize);
2364 playsize = mpctx->audio_out->play(p, playsize, 0);
2365 free(p);
2366 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2367 return ASYNC_PLAY_DONE;
2369 mpctx->syncing_audio = false;
2370 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2371 return decode_audio(sh_audio, playsize);
2374 static int fill_audio_out_buffers(struct MPContext *mpctx)
2376 struct MPOpts *opts = &mpctx->opts;
2377 unsigned int t;
2378 double tt;
2379 int playsize;
2380 int playflags=0;
2381 int audio_eof=0;
2382 bool format_change = false;
2383 sh_audio_t * const sh_audio = mpctx->sh_audio;
2385 current_module="play_audio";
2387 while (1) {
2388 int sleep_time;
2389 // all the current uses of ao_data.pts seem to be in aos that handle
2390 // sync completely wrong; there should be no need to use ao_data.pts
2391 // in get_space()
2392 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2393 playsize = mpctx->audio_out->get_space();
2394 if (mpctx->sh_video || playsize >= ao_data.outburst)
2395 break;
2397 // handle audio-only case:
2398 // this is where mplayer sleeps during audio-only playback
2399 // to avoid 100% CPU use
2400 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2401 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2402 usec_sleep(sleep_time * 1000);
2405 // Fill buffer if needed:
2406 current_module="decode_audio";
2407 t = GetTimer();
2409 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2410 mpctx->syncing_audio = false;
2412 int res;
2413 if (mpctx->syncing_audio && mpctx->sh_video)
2414 res = audio_start_sync(mpctx, playsize);
2415 else
2416 res = decode_audio(sh_audio, playsize);
2417 if (res < 0) { // EOF, error or format change
2418 if (res == -2)
2419 format_change = true;
2420 else if (res == ASYNC_PLAY_DONE)
2421 return 1;
2422 else if (mpctx->d_audio->eof) {
2423 audio_eof = 1;
2424 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2425 if (sh_audio->a_out_buffer_len < unitsize)
2426 return 0;
2429 t = GetTimer() - t;
2430 tt = t*0.000001f; audio_time_usage+=tt;
2431 if (playsize > sh_audio->a_out_buffer_len) {
2432 playsize = sh_audio->a_out_buffer_len;
2433 if (audio_eof)
2434 playflags |= AOPLAY_FINAL_CHUNK;
2436 if (!playsize)
2437 return 1;
2439 // play audio:
2440 current_module="play_audio";
2442 // Is this pts value actually useful for the aos that access it?
2443 // They're obviously badly broken in the way they handle av sync;
2444 // would not having access to this make them more broken?
2445 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2446 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2448 if (playsize > 0) {
2449 sh_audio->a_out_buffer_len -= playsize;
2450 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2451 sh_audio->a_out_buffer_len);
2452 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2453 } else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2454 // Sanity check to avoid hanging in case current ao doesn't output
2455 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2456 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2457 sh_audio->a_out_buffer_len = 0;
2460 /* The format change isn't handled too gracefully. A more precise
2461 * implementation would require draining buffered old-format audio
2462 * while displaying video, then doing the output format switch.
2464 if (format_change) {
2465 uninit_player(mpctx, INITIALIZED_AO);
2466 reinit_audio_chain(mpctx);
2469 return 1;
2472 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2473 float *aq_sleep_time)
2475 struct MPOpts *opts = &mpctx->opts;
2476 double audio_limit = 2;
2477 current_module="calc_sleep_time";
2479 if (mpctx->restart_playback)
2480 return 0;
2482 *time_frame -= get_relative_time(mpctx); // reset timer
2484 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2485 float delay = mpctx->audio_out->get_delay();
2486 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2488 if (opts->autosync) {
2490 * Adjust this raw delay value by calculating the expected
2491 * delay for this frame and generating a new value which is
2492 * weighted between the two. The higher autosync is, the
2493 * closer to the delay value gets to that which "-nosound"
2494 * would have used, and the longer it will take for A/V
2495 * sync to settle at the right value (but it eventually will.)
2496 * This settling time is very short for values below 100.
2498 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2499 float difference = delay - predicted;
2500 delay = predicted + difference / (float)opts->autosync;
2503 *time_frame = delay - mpctx->delay / opts->playback_speed;
2505 // delay = amount of audio buffered in soundcard/driver
2506 delay = FFMIN(delay, 0.5);
2507 delay = FFMAX(delay, 0.1);
2508 audio_limit = delay;
2509 } else {
2510 // If we're lagging more than 200 ms behind the right playback rate,
2511 // don't try to "catch up".
2512 // If benchmark is set always output frames as fast as possible
2513 // without sleeping.
2514 if (*time_frame < -0.2 || opts->benchmark)
2515 *time_frame = 0;
2518 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2520 if (t <= 0.05)
2521 return 0;
2523 t -= 0.05;
2524 if (t > audio_limit * 0.6)
2525 t = audio_limit * 0.5;
2526 *aq_sleep_time += t;
2527 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2528 return 1;
2531 int reinit_video_chain(struct MPContext *mpctx)
2533 struct MPOpts *opts = &mpctx->opts;
2534 sh_video_t * const sh_video = mpctx->sh_video;
2535 double ar=-1.0;
2536 //================== Init VIDEO (codec & libvo) ==========================
2537 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2538 current_module="preinit_libvo";
2540 //shouldn't we set dvideo->id=-2 when we fail?
2541 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2542 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2543 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2544 goto err_out;
2546 mpctx->initialized_flags|=INITIALIZED_VO;
2549 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2550 mpctx->sh_video->stream_aspect = ar;
2551 current_module="init_video_filters";
2553 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2554 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2556 #ifdef CONFIG_MENU
2557 if(use_menu) {
2558 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2559 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2560 if(!vf_menu) {
2561 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2562 use_menu = 0;
2565 if(vf_menu)
2566 sh_video->vfilter = vf_menu;
2567 #endif
2569 #ifdef CONFIG_ASS
2570 if(opts->ass_enabled) {
2571 int i;
2572 int insert = 1;
2573 if (opts->vf_settings)
2574 for (i = 0; opts->vf_settings[i].name; ++i)
2575 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2576 insert = 0;
2577 break;
2579 if (insert) {
2580 extern vf_info_t vf_info_ass;
2581 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2582 char* vf_arg[] = {"auto", "1", NULL};
2583 int retcode = 0;
2584 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2585 sh_video->vfilter,
2586 "ass", vf_arg,
2587 &retcode);
2588 if (vf_ass)
2589 sh_video->vfilter = vf_ass;
2590 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2591 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2592 else
2593 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2596 #endif
2598 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2600 #ifdef CONFIG_ASS
2601 if (opts->ass_enabled)
2602 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2603 #endif
2605 current_module="init_video_codec";
2607 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2608 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2609 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2611 if(!sh_video->initialized){
2612 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2613 goto err_out;
2616 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2618 if (sh_video->codec)
2619 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2621 sh_video->last_pts = MP_NOPTS_VALUE;
2622 sh_video->num_buffered_pts = 0;
2623 sh_video->next_frame_time = 0;
2625 if (opts->auto_quality > 0) {
2626 // Auto quality option enabled
2627 output_quality=get_video_quality_max(sh_video);
2628 if (opts->auto_quality > output_quality)
2629 opts->auto_quality = output_quality;
2630 else
2631 output_quality = opts->auto_quality;
2632 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2633 set_video_quality(sh_video,output_quality);
2636 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2638 current_module="init_vo";
2640 return 1;
2642 err_out:
2643 mpctx->sh_video = mpctx->d_video->sh = NULL;
2644 return 0;
2647 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2649 struct sh_video *sh_video = mpctx->sh_video;
2650 double frame_time = 0;
2651 struct vo *video_out = mpctx->video_out;
2652 while (1) {
2653 current_module = "filter_video";
2654 // In nocorrect-pts mode there is no way to properly time these frames
2655 if (vo_get_buffered_frame(video_out, 0) >= 0)
2656 break;
2657 if (vf_output_queued_frame(sh_video->vfilter))
2658 break;
2659 unsigned char *packet = NULL;
2660 frame_time = sh_video->next_frame_time;
2661 if (mpctx->restart_playback)
2662 frame_time = 0;
2663 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2664 &packet, force_fps);
2665 if (in_size < 0) {
2666 #ifdef CONFIG_DVDNAV
2667 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2668 if (mp_dvdnav_is_eof(mpctx->stream))
2669 return -1;
2670 if (mpctx->d_video)
2671 mpctx->d_video->eof = 0;
2672 if (mpctx->d_audio)
2673 mpctx->d_audio->eof = 0;
2674 mpctx->stream->eof = 0;
2675 } else
2676 #endif
2677 return -1;
2679 if (in_size > max_framesize)
2680 max_framesize = in_size;
2681 sh_video->timer += frame_time;
2682 if (mpctx->sh_audio)
2683 mpctx->delay -= frame_time;
2684 // video_read_frame can change fps (e.g. for ASF video)
2685 vo_fps = sh_video->fps;
2686 int framedrop_type = check_framedrop(mpctx, frame_time);
2687 current_module = "decode video";
2689 void *decoded_frame;
2690 #ifdef CONFIG_DVDNAV
2691 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2692 if (in_size >= 0 && !decoded_frame)
2693 #endif
2694 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2695 sh_video->pts);
2696 #ifdef CONFIG_DVDNAV
2697 // Save last still frame for future display
2698 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2699 #endif
2700 if (decoded_frame) {
2701 current_module = "filter video";
2702 filter_video(sh_video, decoded_frame, sh_video->pts);
2704 break;
2706 return frame_time;
2709 static void determine_frame_pts(struct MPContext *mpctx)
2711 struct sh_video *sh_video = mpctx->sh_video;
2712 struct MPOpts *opts = &mpctx->opts;
2714 if (opts->user_pts_assoc_mode) {
2715 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2716 } else if (sh_video->pts_assoc_mode == 0) {
2717 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2718 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2719 sh_video->pts_assoc_mode = 1;
2720 else
2721 sh_video->pts_assoc_mode = 2;
2722 } else {
2723 int probcount1 = sh_video->num_reordered_pts_problems;
2724 int probcount2 = sh_video->num_sorted_pts_problems;
2725 if (sh_video->pts_assoc_mode == 2) {
2726 int tmp = probcount1;
2727 probcount1 = probcount2;
2728 probcount2 = tmp;
2730 if (probcount1 >= probcount2 * 1.5 + 2) {
2731 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2732 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2733 "%d.\n", sh_video->pts_assoc_mode);
2736 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2737 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2740 static double update_video(struct MPContext *mpctx)
2742 struct sh_video *sh_video = mpctx->sh_video;
2743 struct vo *video_out = mpctx->video_out;
2744 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2745 mpctx->osd); // hack for vf_expand
2746 if (!mpctx->opts.correct_pts)
2747 return update_video_nocorrect_pts(mpctx);
2749 double pts;
2751 while (1) {
2752 current_module = "filter_video";
2753 if (!mpctx->hrseek_active
2754 && vo_get_buffered_frame(video_out, false) >= 0)
2755 break;
2756 // XXX Time used in this call is not counted in any performance
2757 // timer now
2758 if (vf_output_queued_frame(sh_video->vfilter))
2759 break;
2760 unsigned char *packet = NULL;
2761 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2762 if (pts != MP_NOPTS_VALUE)
2763 pts += mpctx->video_offset;
2764 bool hit_eof = false;
2765 if (in_size < 0) {
2766 // try to extract last frames in case of decoder lag
2767 in_size = 0;
2768 pts = MP_NOPTS_VALUE;
2769 hit_eof = true;
2771 if (in_size > max_framesize)
2772 max_framesize = in_size;
2773 current_module = "decode video";
2774 if (pts >= mpctx->hrseek_pts - .005)
2775 mpctx->hrseek_framedrop = false;
2776 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2777 check_framedrop(mpctx, sh_video->frametime);
2778 void *decoded_frame = decode_video(sh_video, packet, in_size,
2779 framedrop_type, pts);
2780 if (decoded_frame) {
2781 determine_frame_pts(mpctx);
2782 current_module = "filter video";
2783 filter_video(sh_video, decoded_frame, sh_video->pts);
2784 } else if (hit_eof) {
2785 if (vo_get_buffered_frame(video_out, true) < 0)
2786 return -1;
2788 break;
2791 if (!video_out->frame_loaded)
2792 return 0;
2794 pts = video_out->next_pts;
2795 if (pts == MP_NOPTS_VALUE) {
2796 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2797 // Try to use decoder pts from before filters
2798 pts = sh_video->pts;
2799 if (pts == MP_NOPTS_VALUE)
2800 pts = sh_video->last_pts;
2802 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005)
2803 return 0;
2804 mpctx->hrseek_active = false;
2805 sh_video->pts = pts;
2806 if (sh_video->last_pts == MP_NOPTS_VALUE)
2807 sh_video->last_pts = sh_video->pts;
2808 else if (sh_video->last_pts > sh_video->pts) {
2809 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2810 sh_video->pts, sh_video->last_pts);
2811 /* If the difference in pts is small treat it as jitter around the
2812 * right value (possibly caused by incorrect timestamp ordering) and
2813 * just show this frame immediately after the last one.
2814 * Treat bigger differences as timestamp resets and start counting
2815 * timing of later frames from the position of this one. */
2816 if (sh_video->last_pts - sh_video->pts > 0.5)
2817 sh_video->last_pts = sh_video->pts;
2818 else
2819 sh_video->pts = sh_video->last_pts;
2821 double frame_time = sh_video->pts - sh_video->last_pts;
2822 sh_video->last_pts = sh_video->pts;
2823 sh_video->timer += frame_time;
2824 if (mpctx->sh_audio)
2825 mpctx->delay -= frame_time;
2826 return frame_time;
2829 void pause_player(struct MPContext *mpctx)
2831 if (mpctx->paused)
2832 return;
2833 mpctx->paused = 1;
2834 mpctx->step_frames = 0;
2835 mpctx->time_frame -= get_relative_time(mpctx);
2837 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2838 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2840 if (mpctx->audio_out && mpctx->sh_audio)
2841 mpctx->audio_out->pause(); // pause audio, keep data if possible
2844 void unpause_player(struct MPContext *mpctx)
2846 if (!mpctx->paused)
2847 return;
2848 mpctx->paused = 0;
2850 if (mpctx->audio_out && mpctx->sh_audio)
2851 mpctx->audio_out->resume(); // resume audio
2852 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2853 && !mpctx->step_frames)
2854 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2855 (void)get_relative_time(mpctx); // ignore time that passed during pause
2858 void add_step_frame(struct MPContext *mpctx)
2860 mpctx->step_frames++;
2861 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2862 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2863 unpause_player(mpctx);
2866 static void pause_loop(struct MPContext *mpctx)
2868 struct MPOpts *opts = &mpctx->opts;
2869 mp_cmd_t* cmd;
2870 if (!opts->quiet) {
2871 // Small hack to display the pause message on the OSD line.
2872 // The pause string is: "\n == PAUSE == \r" so we need to
2873 // take the first and the last char out
2874 if (opts->term_osd && !mpctx->sh_video) {
2875 char msg[128] = _("\n ===== PAUSE =====\r");
2876 int mlen = strlen(msg);
2877 msg[mlen-1] = '\0';
2878 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2879 update_osd_msg(mpctx);
2880 } else
2881 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2882 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2885 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2886 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2887 if (cmd) {
2888 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2889 run_command(mpctx, cmd);
2890 mp_cmd_free(cmd);
2891 continue;
2893 if (mpctx->sh_video && mpctx->video_out)
2894 vo_check_events(mpctx->video_out);
2895 #ifdef CONFIG_MENU
2896 if (vf_menu)
2897 vf_menu_pause_update(vf_menu);
2898 #endif
2899 usec_sleep(20000);
2900 update_osd_msg(mpctx);
2901 int hack = vo_osd_changed(0);
2902 vo_osd_changed(hack);
2903 if (hack)
2904 break;
2909 // Find the right mute status and record position for new file position
2910 static void edl_seek_reset(MPContext *mpctx)
2912 mpctx->edl_muted = 0;
2913 next_edl_record = edl_records;
2915 while (next_edl_record) {
2916 if (next_edl_record->start_sec >= get_current_time(mpctx))
2917 break;
2919 if (next_edl_record->action == EDL_MUTE)
2920 mpctx->edl_muted = !mpctx->edl_muted;
2921 next_edl_record = next_edl_record->next;
2923 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2924 mixer_mute(&mpctx->mixer);
2928 // Execute EDL command for the current position if one exists
2929 static void edl_update(MPContext *mpctx)
2931 if (!next_edl_record)
2932 return;
2934 if (!mpctx->sh_video) {
2935 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2936 free_edl(edl_records);
2937 next_edl_record = NULL;
2938 edl_records = NULL;
2939 return;
2942 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2943 if (next_edl_record->action == EDL_SKIP) {
2944 mpctx->osd_function = OSD_FFW;
2945 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2946 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2947 "[%f], length [%f]\n", next_edl_record->start_sec,
2948 next_edl_record->stop_sec, next_edl_record->length_sec);
2950 else if (next_edl_record->action == EDL_MUTE) {
2951 mpctx->edl_muted = !mpctx->edl_muted;
2952 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2953 mixer_mute(&mpctx->mixer);
2954 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2955 next_edl_record->start_sec );
2957 next_edl_record = next_edl_record->next;
2961 static void reinit_decoders(struct MPContext *mpctx)
2963 reinit_video_chain(mpctx);
2964 reinit_audio_chain(mpctx);
2965 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
2968 static void seek_reset(struct MPContext *mpctx)
2970 if (mpctx->sh_video) {
2971 current_module = "seek_video_reset";
2972 resync_video_stream(mpctx->sh_video);
2973 mpctx->sh_video->timer = 0;
2974 vo_seek_reset(mpctx->video_out);
2975 mpctx->sh_video->timer = 0;
2976 mpctx->sh_video->num_buffered_pts = 0;
2977 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2978 mpctx->delay = 0;
2979 mpctx->time_frame = 0;
2980 mpctx->restart_playback = true;
2981 // Not all demuxers set d_video->pts during seek, so this value
2982 // (which is used by at least vobsub and edl code below) may
2983 // be completely wrong (probably 0).
2984 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2985 mpctx->video_pts = mpctx->sh_video->pts;
2986 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
2987 true);
2988 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2991 if (mpctx->sh_audio) {
2992 current_module = "seek_audio_reset";
2993 resync_audio_stream(mpctx->sh_audio);
2994 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2995 mpctx->sh_audio->a_buffer_len = 0;
2996 mpctx->sh_audio->a_out_buffer_len = 0;
2997 if (!mpctx->sh_video)
2998 update_subtitles(mpctx, mpctx->sh_audio->pts,
2999 mpctx->video_offset, true);
3002 if (vo_vobsub && mpctx->sh_video) {
3003 current_module = "seek_vobsub_reset";
3004 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3007 edl_seek_reset(mpctx);
3009 mpctx->hrseek_active = false;
3010 mpctx->hrseek_framedrop = false;
3011 mpctx->total_avsync_change = 0;
3012 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3013 drop_frame_cnt = 0;
3015 current_module = NULL;
3018 static bool timeline_set_part(struct MPContext *mpctx, int i)
3020 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3021 struct timeline_part *n = mpctx->timeline + i;
3022 mpctx->timeline_part = i;
3023 mpctx->video_offset = n->start - n->source_start;
3024 if (n->source == p->source)
3025 return false;
3026 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC | INITIALIZED_SUB);
3027 mpctx->demuxer = n->source->demuxer;
3028 mpctx->d_video = mpctx->demuxer->video;
3029 mpctx->d_audio = mpctx->demuxer->audio;
3030 mpctx->d_sub = mpctx->demuxer->sub;
3031 mpctx->sh_video = mpctx->d_video->sh;
3032 mpctx->sh_audio = mpctx->d_audio->sh;
3033 return true;
3036 // Given pts, switch playback to the corresponding part.
3037 // Return offset within that part.
3038 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3039 bool *need_reset)
3041 if (pts < 0)
3042 pts = 0;
3043 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3044 struct timeline_part *p = mpctx->timeline + i;
3045 if (pts < (p+1)->start) {
3046 *need_reset = timeline_set_part(mpctx, i);
3047 return pts - p->start + p->source_start;
3050 return -1;
3054 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3055 static int seek(MPContext *mpctx, struct seek_params seek)
3057 struct MPOpts *opts = &mpctx->opts;
3059 current_module = "seek";
3060 if (mpctx->stop_play == AT_END_OF_FILE)
3061 mpctx->stop_play = KEEP_PLAYING;
3062 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3063 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3064 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3065 || opts->hr_seek > 0 || seek.exact > 0;
3066 if (seek.type == MPSEEK_FACTOR
3067 || seek.type == MPSEEK_ABSOLUTE
3068 && seek.amount < mpctx->last_chapter_pts
3069 || seek.amount < 0)
3070 mpctx->last_chapter_seek = -1;
3071 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3072 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3073 seek.type = MPSEEK_ABSOLUTE;
3075 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3076 && seek.type == MPSEEK_RELATIVE) {
3077 seek.type = MPSEEK_ABSOLUTE;
3078 seek.direction = seek.amount > 0 ? 1 : -1;
3079 seek.amount += get_current_time(mpctx);
3082 /* At least the liba52 decoder wants to read from the input stream
3083 * during initialization, so reinit must be done after the demux_seek()
3084 * call that clears possible stream EOF. */
3085 bool need_reset = false;
3086 double demuxer_amount = seek.amount;
3087 if (mpctx->timeline) {
3088 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3089 &need_reset);
3090 if (demuxer_amount == -1) {
3091 mpctx->stop_play = AT_END_OF_FILE;
3092 // Clear audio from current position
3093 if (mpctx->sh_audio) {
3094 mpctx->audio_out->reset();
3095 mpctx->sh_audio->a_buffer_len = 0;
3096 mpctx->sh_audio->a_out_buffer_len = 0;
3098 return -1;
3101 int demuxer_style = 0;
3102 switch (seek.type) {
3103 case MPSEEK_FACTOR:
3104 demuxer_style |= SEEK_FACTOR; // fallthrough
3105 case MPSEEK_ABSOLUTE:
3106 demuxer_style |= SEEK_ABSOLUTE;
3108 if (hr_seek || seek.direction < 0)
3109 demuxer_style |= SEEK_BACKWARD;
3110 else if (seek.direction > 0)
3111 demuxer_style |= SEEK_FORWARD;
3113 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3114 demuxer_style);
3115 if (need_reset)
3116 reinit_decoders(mpctx);
3117 if (seekresult == 0)
3118 return -1;
3120 seek_reset(mpctx);
3122 /* Use the target time as "current position" for further relative
3123 * seeks etc until a new video frame has been decoded */
3124 if (seek.type == MPSEEK_ABSOLUTE)
3125 mpctx->video_pts = seek.amount;
3127 if (hr_seek) {
3128 mpctx->hrseek_active = true;
3129 mpctx->hrseek_framedrop = true;
3130 mpctx->hrseek_pts = seek.amount;
3133 mpctx->start_timestamp = GetTimerMS();
3135 return 0;
3138 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3139 int exact)
3141 struct seek_params *seek = &mpctx->seek;
3142 switch (type) {
3143 case MPSEEK_RELATIVE:
3144 if (seek->type == MPSEEK_FACTOR)
3145 return; // Well... not common enough to bother doing better
3146 seek->amount += amount;
3147 seek->exact = FFMAX(seek->exact, exact);
3148 if (seek->type == MPSEEK_NONE)
3149 seek->exact = exact;
3150 if (seek->type == MPSEEK_ABSOLUTE)
3151 return;
3152 if (seek->amount == 0) {
3153 *seek = (struct seek_params){0};
3154 return;
3156 seek->type = MPSEEK_RELATIVE;
3157 return;
3158 case MPSEEK_ABSOLUTE:
3159 case MPSEEK_FACTOR:
3160 *seek = (struct seek_params) {
3161 .type = type,
3162 .amount = amount,
3163 .exact = exact,
3165 return;
3166 case MPSEEK_NONE:
3167 *seek = (struct seek_params){0};
3168 return;
3170 abort();
3174 double get_time_length(struct MPContext *mpctx)
3176 if (mpctx->timeline)
3177 return mpctx->timeline[mpctx->num_timeline_parts].start;
3179 struct demuxer *demuxer = mpctx->demuxer;
3180 double get_time_ans;
3181 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3182 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3183 (void *) &get_time_ans) > 0)
3184 return get_time_ans;
3186 struct sh_video *sh_video = mpctx->d_video->sh;
3187 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3188 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3189 return (double) (demuxer->movi_end - demuxer->movi_start) /
3190 (sh_video->i_bps + sh_audio->i_bps);
3191 if (sh_video && sh_video->i_bps)
3192 return (double) (demuxer->movi_end - demuxer->movi_start) /
3193 sh_video->i_bps;
3194 if (sh_audio && sh_audio->i_bps)
3195 return (double) (demuxer->movi_end - demuxer->movi_start) /
3196 sh_audio->i_bps;
3197 return 0;
3200 /* If there are timestamps from stream level then use those (for example
3201 * DVDs can have consistent times there while the MPEG-level timestamps
3202 * reset). */
3203 double get_current_time(struct MPContext *mpctx)
3205 struct demuxer *demuxer = mpctx->demuxer;
3206 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3207 return demuxer->stream_pts;
3208 struct sh_video *sh_video = demuxer->video->sh;
3209 if (sh_video)
3210 return mpctx->video_pts;
3211 return playing_audio_pts(mpctx);
3214 int get_percent_pos(struct MPContext *mpctx)
3216 struct demuxer *demuxer = mpctx->demuxer;
3217 int ans = 0;
3218 if (mpctx->timeline)
3219 ans = get_current_time(mpctx) * 100 /
3220 mpctx->timeline[mpctx->num_timeline_parts].start;
3221 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3223 else {
3224 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3225 off_t pos = demuxer->filepos > 0 ?
3226 demuxer->filepos : stream_tell(demuxer->stream);
3227 if (len > 0)
3228 ans = (pos - demuxer->movi_start) / len;
3229 else
3230 ans = 0;
3232 if (ans < 0)
3233 ans = 0;
3234 if (ans > 100)
3235 ans = 100;
3236 return ans;
3239 // -2 is no chapters, -1 is before first chapter
3240 int get_current_chapter(struct MPContext *mpctx)
3242 double current_pts = get_current_time(mpctx);
3243 if (!mpctx->chapters)
3244 return FFMAX(mpctx->last_chapter_seek,
3245 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3247 int i;
3248 for (i = 1; i < mpctx->num_chapters; i++)
3249 if (current_pts < mpctx->chapters[i].start)
3250 break;
3251 return FFMAX(mpctx->last_chapter_seek, i - 1);
3254 // currently returns a string allocated with malloc, not talloc
3255 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3257 if (!mpctx->chapters || !mpctx->sh_video)
3258 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3259 return strdup(mpctx->chapters[chapter].name);
3262 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3263 char **chapter_name)
3265 mpctx->last_chapter_seek = -1;
3266 if (!mpctx->chapters || !mpctx->sh_video) {
3267 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3268 chapter_name);
3269 if (res >= 0) {
3270 if (*seek_pts == -1)
3271 seek_reset(mpctx);
3272 else {
3273 mpctx->last_chapter_seek = res;
3274 mpctx->last_chapter_pts = *seek_pts;
3277 return res;
3280 if (chapter >= mpctx->num_chapters)
3281 return -1;
3282 if (chapter < 0)
3283 chapter = 0;
3284 *seek_pts = mpctx->chapters[chapter].start;
3285 mpctx->last_chapter_seek = chapter;
3286 mpctx->last_chapter_pts = *seek_pts;
3287 if (chapter_name)
3288 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3289 return chapter;
3293 static void run_playloop(struct MPContext *mpctx)
3295 struct MPOpts *opts = &mpctx->opts;
3296 float aq_sleep_time = 0;
3298 if (opts->chapterrange[1] > 0) {
3299 int cur_chapter = get_current_chapter(mpctx);
3300 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3301 mpctx->stop_play = PT_NEXT_ENTRY;
3304 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3305 mpctx->sh_audio = mpctx->d_audio->sh;
3306 mpctx->sh_audio->ds = mpctx->d_audio;
3307 reinit_audio_chain(mpctx);
3310 /*========================== PLAY AUDIO ============================*/
3312 if (mpctx->sh_audio && !mpctx->paused
3313 && (!mpctx->restart_playback || !mpctx->sh_video))
3314 if (!fill_audio_out_buffers(mpctx))
3315 // at eof, all audio at least written to ao
3316 if (!mpctx->sh_video)
3317 mpctx->stop_play = AT_END_OF_FILE;
3320 if (!mpctx->sh_video) {
3321 mpctx->restart_playback = false;
3322 if (mpctx->step_frames) {
3323 mpctx->step_frames = 0;
3324 pause_player(mpctx);
3326 // handle audio-only case:
3327 double a_pos = 0;
3328 // sh_audio can be NULL due to video stream switching
3329 // TODO: handle this better
3330 if (mpctx->sh_audio)
3331 a_pos = playing_audio_pts(mpctx);
3333 print_status(mpctx, a_pos, false);
3335 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3336 mpctx->stop_play = PT_NEXT_ENTRY;
3337 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3338 update_osd_msg(mpctx);
3339 } else {
3341 /*========================== PLAY VIDEO ============================*/
3343 vo_pts = mpctx->sh_video->timer * 90000.0;
3344 vo_fps = mpctx->sh_video->fps;
3346 bool blit_frame = mpctx->video_out->frame_loaded;
3347 if (!blit_frame || mpctx->hrseek_active) {
3348 double frame_time = update_video(mpctx);
3349 blit_frame = mpctx->video_out->frame_loaded;
3350 blit_frame &= !mpctx->hrseek_active;
3351 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3352 if (mpctx->sh_video->vf_initialized < 0) {
3353 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3354 "\nFATAL: Could not initialize video filters (-vf) "
3355 "or video output (-vo).\n");
3356 mpctx->stop_play = PT_NEXT_ENTRY;
3357 return;
3359 if (frame_time < 0)
3360 mpctx->stop_play = AT_END_OF_FILE;
3361 else if (!mpctx->restart_playback) {
3362 mpctx->time_frame += frame_time / opts->playback_speed;
3363 adjust_sync(mpctx, frame_time);
3366 if (mpctx->timeline) {
3367 struct timeline_part *next =
3368 mpctx->timeline + mpctx->timeline_part + 1;
3369 if (mpctx->sh_video->pts >= next->start
3370 || mpctx->stop_play == AT_END_OF_FILE
3371 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3372 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3373 .amount = next->start });
3374 return;
3378 // ==========================================================================
3380 current_module = "vo_check_events";
3381 vo_check_events(mpctx->video_out);
3383 #ifdef CONFIG_X11
3384 if (stop_xscreensaver) {
3385 current_module = "stop_xscreensaver";
3386 xscreensaver_heartbeat(mpctx->x11_state);
3388 #endif
3389 if (heartbeat_cmd) {
3390 static unsigned last_heartbeat;
3391 unsigned now = GetTimerMS();
3392 if (now - last_heartbeat > 30000) {
3393 last_heartbeat = now;
3394 system(heartbeat_cmd);
3398 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3399 &mpctx->time_frame,
3400 &aq_sleep_time);
3402 //====================== FLIP PAGE (VIDEO BLT): =========================
3404 current_module = "flip_page";
3405 if (!frame_time_remaining && blit_frame) {
3406 struct sh_video *sh_video = mpctx->sh_video;
3407 mpctx->video_pts = sh_video->pts;
3408 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3409 update_teletext(sh_video, mpctx->demuxer, 0);
3410 update_osd_msg(mpctx);
3411 struct vf_instance *vf = sh_video->vfilter;
3412 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3413 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3414 vo_osd_changed(0);
3416 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3417 aq_sleep_time += mpctx->time_frame;
3418 // flag 256 means: libvo driver does its timing (dvb card)
3419 if (mpctx->time_frame > 0.001
3420 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3421 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3422 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3424 unsigned int t2 = GetTimer();
3425 /* Playing with playback speed it's possible to get pathological
3426 * cases with mpctx->time_frame negative enough to cause an
3427 * overflow in pts_us calculation, thus the FFMAX. */
3428 double time_frame = FFMAX(mpctx->time_frame, -1);
3429 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3430 int duration = -1;
3431 double pts2 = mpctx->video_out->next_pts2;
3432 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3433 && !mpctx->restart_playback) {
3434 // expected A/V sync correction is ignored
3435 double diff = (pts2 - mpctx->video_pts);
3436 diff /= opts->playback_speed;
3437 if (mpctx->time_frame < 0)
3438 diff += mpctx->time_frame;
3439 if (diff < 0)
3440 diff = 0;
3441 if (diff > 10)
3442 diff = 10;
3443 duration = diff * 1e6;
3445 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3447 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3448 vout_time_usage += mpctx->last_vo_flip_duration;
3449 if (mpctx->video_out->driver->flip_page_timed) {
3450 // No need to adjust sync based on flip speed
3451 mpctx->last_vo_flip_duration = 0;
3452 // For print_status - VO call finishing early is OK for sync
3453 mpctx->time_frame -= get_relative_time(mpctx);
3455 if (mpctx->restart_playback) {
3456 mpctx->syncing_audio = true;
3457 if (mpctx->sh_audio && !mpctx->paused)
3458 fill_audio_out_buffers(mpctx);
3459 mpctx->restart_playback = false;
3460 mpctx->time_frame = 0;
3461 get_relative_time(mpctx);
3463 print_status(mpctx, MP_NOPTS_VALUE, true);
3464 } else
3465 print_status(mpctx, MP_NOPTS_VALUE, false);
3467 //============================ Auto QUALITY ============================
3469 /*Output quality adjustments:*/
3470 if (opts->auto_quality > 0) {
3471 current_module = "autoq";
3472 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3473 ++output_quality;
3474 else
3475 if (output_quality>1 && aq_sleep_time<0)
3476 --output_quality;
3477 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3478 output_quality = 0;
3479 set_video_quality(mpctx->sh_video, output_quality);
3482 if (!frame_time_remaining && blit_frame) {
3483 if (play_n_frames >= 0) {
3484 --play_n_frames;
3485 if (play_n_frames <= 0)
3486 mpctx->stop_play = PT_NEXT_ENTRY;
3488 if (mpctx->step_frames > 0) {
3489 mpctx->step_frames--;
3490 if (mpctx->step_frames == 0)
3491 pause_player(mpctx);
3495 // FIXME: add size based support for -endpos
3496 if (end_at.type == END_AT_TIME &&
3497 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3498 mpctx->stop_play = PT_NEXT_ENTRY;
3500 } // end if(mpctx->sh_video)
3502 #ifdef CONFIG_DVDNAV
3503 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3504 nav_highlight_t hl;
3505 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3506 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3507 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3508 vo_osd_changed(OSDTYPE_DVDNAV);
3509 } else {
3510 osd_set_nav_box(0, 0, 0, 0);
3511 vo_osd_changed(OSDTYPE_DVDNAV);
3512 vo_osd_changed(OSDTYPE_SPU);
3515 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3516 double ar = -1.0;
3517 if (mpctx->sh_video &&
3518 stream_control(mpctx->demuxer->stream,
3519 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3520 != STREAM_UNSUPPORTED)
3521 mpctx->sh_video->stream_aspect = ar;
3524 #endif
3526 //================= Keyboard events, SEEKing ====================
3528 current_module = "key_events";
3530 while (1) {
3531 mp_cmd_t *cmd;
3532 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3533 /* Allow running consecutive seek commands to combine them,
3534 * but execute the seek before running other commands.
3535 * If the user seeks continuously (keeps arrow key down)
3536 * try to finish showing a frame from one location before doing
3537 * another seek (which could lead to unchanging display). */
3538 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3539 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3540 && GetTimerMS() - mpctx->start_timestamp < 300)
3541 break;
3542 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3543 run_command(mpctx, cmd);
3544 mp_cmd_free(cmd);
3545 if (mpctx->stop_play)
3546 break;
3548 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3549 || mpctx->restart_playback)
3550 break;
3551 if (mpctx->sh_video) {
3552 update_osd_msg(mpctx);
3553 int hack = vo_osd_changed(0);
3554 vo_osd_changed(hack);
3555 if (hack) {
3556 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3557 add_step_frame(mpctx);
3558 break;
3559 } else
3560 vo_osd_changed(0);
3563 pause_loop(mpctx);
3566 // handle -sstep
3567 if (step_sec > 0 && !mpctx->paused) {
3568 mpctx->osd_function = OSD_FFW;
3569 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3572 edl_update(mpctx);
3574 /* Looping. */
3575 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3576 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3578 if (opts->loop_times>1)
3579 opts->loop_times--;
3580 else if (opts->loop_times==1)
3581 opts->loop_times = -1;
3582 play_n_frames = play_n_frames_mf;
3583 mpctx->stop_play = 0;
3584 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3587 if (mpctx->seek.type) {
3588 seek(mpctx, mpctx->seek);
3589 mpctx->seek = (struct seek_params){0};
3594 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3595 struct content_source *sources,
3596 int num_sources,
3597 unsigned char uid_map[][16])
3599 int num_filenames = 0;
3600 char **filenames = NULL;
3601 if (num_sources > 1) {
3602 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3603 "other sources.\n");
3604 if (mpctx->stream->type != STREAMTYPE_FILE) {
3605 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3606 "normal disk file. Will not search for related files.\n");
3607 } else {
3608 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3609 "same directory to find referenced sources.\n");
3610 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3611 &num_filenames);
3615 int num_left = num_sources - 1;
3616 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3617 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3618 filename_recode(filenames[i]));
3619 int format;
3620 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3621 if (!s)
3622 continue;
3623 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3624 mpctx->opts.audio_id,
3625 mpctx->opts.video_id,
3626 mpctx->opts.sub_id, filenames[i]);
3627 if (!d) {
3628 free_stream(s);
3629 continue;
3631 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3632 for (int i = 1; i < num_sources; i++) {
3633 if (sources[i].demuxer)
3634 continue;
3635 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3636 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3637 i, filename_recode(d->filename));
3638 sources[i].stream = s;
3639 sources[i].demuxer = d;
3640 num_left--;
3641 goto match;
3645 free_demuxer(d);
3646 free_stream(s);
3647 continue;
3648 match:
3651 talloc_free(filenames);
3652 if (num_left) {
3653 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3654 "There will be parts MISSING from the video!\n");
3655 for (int i = 1, j = 1; i < num_sources; i++)
3656 if (sources[i].demuxer) {
3657 sources[j] = sources[i];
3658 memcpy(uid_map[j], uid_map[i], 16);
3659 j++;
3662 return num_sources - num_left;
3665 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3667 struct MPOpts *opts = &mpctx->opts;
3669 if (!opts->ordered_chapters) {
3670 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3671 "you have disabled support for them. Ignoring.\n");
3672 return;
3675 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3676 "edit timeline.\n");
3678 struct demuxer *demuxer = mpctx->demuxer;
3679 struct matroska_data *m = &demuxer->matroska_data;
3681 // +1 because sources/uid_map[0] is original file even if all chapters
3682 // actually use other sources and need separate entries
3683 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3684 m->num_ordered_chapters+1);
3685 sources[0].stream = mpctx->stream;
3686 sources[0].demuxer = mpctx->demuxer;
3687 unsigned char uid_map[m->num_ordered_chapters+1][16];
3688 int num_sources = 1;
3689 memcpy(uid_map[0], m->segment_uid, 16);
3691 for (int i = 0; i < m->num_ordered_chapters; i++) {
3692 struct matroska_chapter *c = m->ordered_chapters + i;
3693 if (!c->has_segment_uid)
3694 memcpy(c->segment_uid, m->segment_uid, 16);
3696 for (int j = 0; j < num_sources; j++)
3697 if (!memcmp(c->segment_uid, uid_map[j], 16))
3698 goto found1;
3699 memcpy(uid_map[num_sources], c->segment_uid, 16);
3700 sources[num_sources] = (struct content_source){};
3701 num_sources++;
3702 found1:
3706 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3707 uid_map);
3710 // +1 for terminating chapter with start time marking end of last real one
3711 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3712 m->num_ordered_chapters + 1);
3713 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3714 m->num_ordered_chapters);
3715 uint64_t starttime = 0;
3716 uint64_t missing_time = 0;
3717 int part_count = 0;
3718 int num_chapters = 0;
3719 uint64_t prev_part_offset = 0;
3720 for (int i = 0; i < m->num_ordered_chapters; i++) {
3721 struct matroska_chapter *c = m->ordered_chapters + i;
3723 int j;
3724 for (j = 0; j < num_sources; j++) {
3725 if (!memcmp(c->segment_uid, uid_map[j], 16))
3726 goto found2;
3728 missing_time += c->end - c->start;
3729 continue;
3730 found2:;
3731 /* Only add a separate part if the time or file actually changes.
3732 * Matroska files have chapter divisions that are redundant from
3733 * timeline point of view because the same chapter structure is used
3734 * both to specify the timeline and for normal chapter information.
3735 * Removing a missing inserted external chapter can also cause this.
3736 * We allow for a configurable fudge factor because of files which
3737 * specify chapter end times that are one frame too early;
3738 * we don't want to try seeking over a one frame gap. */
3739 int64_t join_diff = c->start - starttime - prev_part_offset;
3740 if (part_count == 0
3741 || FFABS(join_diff) > opts->chapter_merge_threshold * 1000000
3742 || sources + j != timeline[part_count - 1].source) {
3743 timeline[part_count].source = sources + j;
3744 timeline[part_count].start = starttime / 1e9;
3745 timeline[part_count].source_start = c->start / 1e9;
3746 prev_part_offset = c->start - starttime;
3747 part_count++;
3748 } else if (part_count > 0 && join_diff) {
3749 /* Chapter was merged at an inexact boundary;
3750 * adjust timestamps to match. */
3751 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3752 "offset %d ms.\n", i, (int) join_diff);
3753 starttime += join_diff;
3755 chapters[num_chapters].start = starttime / 1e9;
3756 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3757 starttime += c->end - c->start;
3758 num_chapters++;
3760 timeline[part_count].start = starttime / 1e9;
3762 if (!part_count) {
3763 // None of the parts come from the file itself???
3764 talloc_free(sources);
3765 talloc_free(timeline);
3766 talloc_free(chapters);
3767 return;
3770 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3771 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3772 timeline[part_count].start);
3773 if (missing_time)
3774 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3775 "from the timeline!\n", missing_time / 1e9);
3776 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3777 for (int i = 0; i < num_sources; i++)
3778 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3779 filename_recode(sources[i].demuxer->filename));
3780 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3781 "source_start, source):\n");
3782 for (int i = 0; i < part_count; i++) {
3783 struct timeline_part *p = timeline + i;
3784 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3785 p->source_start, p->source - sources);
3787 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3788 mpctx->sources = sources;
3789 mpctx->num_sources = num_sources;
3790 mpctx->timeline = timeline;
3791 mpctx->num_timeline_parts = part_count;
3792 mpctx->num_chapters = num_chapters;
3793 mpctx->chapters = chapters;
3795 mpctx->timeline_part = 0;
3796 mpctx->demuxer = timeline[0].source->demuxer;
3800 static int read_keys(void *ctx, int fd)
3802 getch2(ctx);
3803 return mplayer_get_key(ctx, 0);
3806 static bool attachment_is_font(struct demux_attachment *att)
3808 if (!att->name || !att->type || !att->data || !att->data_size)
3809 return false;
3810 // match against MIME types
3811 if (strcmp(att->type, "application/x-truetype-font") == 0
3812 || strcmp(att->type, "application/x-font") == 0)
3813 return true;
3814 // fallback: match against file extension
3815 if (strlen(att->name) > 4) {
3816 char *ext = att->name + strlen(att->name) - 4;
3817 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3818 || strcasecmp(ext, ".otf") == 0)
3819 return true;
3821 return false;
3824 static int select_audio(demuxer_t *demuxer, int audio_id, char *audio_lang)
3826 if (audio_id == -1)
3827 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3828 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3829 demuxer_switch_audio(demuxer, audio_id);
3830 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3831 demuxer->audio->id = -2;
3832 demuxer->audio->sh = NULL;
3834 return demuxer->audio->id;
3837 static void print_version(const char* name)
3839 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3841 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3842 GetCpuCaps(&gCpuCaps);
3843 #if ARCH_X86
3844 mp_msg(MSGT_CPLAYER, MSGL_V,
3845 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3846 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3847 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3848 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3849 #if CONFIG_RUNTIME_CPUDETECT
3850 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3851 #else
3852 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3853 if (HAVE_MMX)
3854 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3855 if (HAVE_MMX2)
3856 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3857 if (HAVE_AMD3DNOW)
3858 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3859 if (HAVE_AMD3DNOWEXT)
3860 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3861 if (HAVE_SSE)
3862 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3863 if (HAVE_SSE2)
3864 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3865 if (HAVE_SSSE3)
3866 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3867 if (HAVE_CMOV)
3868 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3869 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3870 #endif /* CONFIG_RUNTIME_CPUDETECT */
3871 #endif /* ARCH_X86 */
3874 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3875 * file for some tools to link against. */
3876 #ifndef DISABLE_MAIN
3877 int main(int argc,char* argv[]){
3878 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3879 talloc_enable_leak_report();
3881 char * mem_ptr;
3883 // movie info:
3885 /* Flag indicating whether MPlayer should exit without playing anything. */
3886 int opt_exit = 0;
3887 int i;
3889 struct MPContext *mpctx = &(struct MPContext){
3890 .osd_function = OSD_PLAY,
3891 .begin_skip = MP_NOPTS_VALUE,
3892 .play_tree_step = 1,
3893 .global_sub_pos = -1,
3894 .set_of_sub_pos = -1,
3895 .file_format = DEMUXER_TYPE_UNKNOWN,
3896 .last_dvb_step = 1,
3899 InitTimer();
3900 srand(GetTimerMS());
3902 mp_msg_init();
3903 set_av_log_callback();
3905 #ifdef CONFIG_X11
3906 mpctx->x11_state = vo_x11_init_state();
3907 #endif
3908 struct MPOpts *opts = &mpctx->opts;
3909 set_default_mplayer_options(opts);
3910 // Create the config context and register the options
3911 mpctx->mconfig = m_config_new(opts, cfg_include);
3912 m_config_register_options(mpctx->mconfig,mplayer_opts);
3913 m_config_register_options(mpctx->mconfig, common_opts);
3914 mp_input_register_options(mpctx->mconfig);
3916 // Preparse the command line
3917 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3919 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3920 set_path_env();
3921 #endif
3923 #ifdef CONFIG_TV
3924 stream_tv_defaults.immediate = 1;
3925 #endif
3927 parse_cfgfiles(mpctx, mpctx->mconfig);
3929 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3930 if(mpctx->playtree == NULL)
3931 opt_exit = 1;
3932 else {
3933 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3934 if(mpctx->playtree) {
3935 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3936 if(mpctx->playtree_iter) {
3937 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3938 play_tree_iter_free(mpctx->playtree_iter);
3939 mpctx->playtree_iter = NULL;
3941 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3945 mpctx->key_fifo = mp_fifo_create(opts);
3947 print_version("MPlayer");
3949 #if defined(__MINGW32__) || defined(__CYGWIN__)
3951 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3952 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3953 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3954 if (kernel32) {
3955 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3956 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3958 if (setDEP) setDEP(3);
3959 if (setDllDir) setDllDir("");
3961 // stop Windows from showing all kinds of annoying error dialogs
3962 SetErrorMode(0x8003);
3963 // request 1ms timer resolution
3964 timeBeginPeriod(1);
3965 #endif
3967 #ifdef CONFIG_PRIORITY
3968 set_priority();
3969 #endif
3971 if (codec_path)
3972 set_codec_path(codec_path);
3974 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3975 list_video_out();
3976 opt_exit = 1;
3979 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3980 list_audio_out();
3981 opt_exit = 1;
3984 /* Check codecs.conf. */
3985 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3986 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3987 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3988 if(!parse_codec_cfg(NULL)){
3989 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3991 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3994 free( mem_ptr ); // release the buffer created by get_path()
3997 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3998 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3999 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4000 list_codecs(1);
4001 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4002 opt_exit = 1;
4004 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
4005 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4006 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4007 list_codecs(0);
4008 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4009 opt_exit = 1;
4011 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
4012 vfm_help();
4013 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4014 opt_exit = 1;
4016 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
4017 afm_help();
4018 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4019 opt_exit = 1;
4021 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
4022 af_help();
4023 printf("\n");
4024 opt_exit = 1;
4026 #ifdef CONFIG_X11
4027 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
4028 fstype_help();
4029 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4030 opt_exit = 1;
4032 #endif
4033 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
4034 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
4035 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
4036 demuxer_help();
4037 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4038 opt_exit = 1;
4040 if (opts->list_properties) {
4041 property_print_help();
4042 opt_exit = 1;
4045 if(opt_exit)
4046 exit_player(mpctx, EXIT_NONE);
4048 if (!mpctx->filename && !opts->player_idle_mode) {
4049 // no file/vcd/dvd -> show HELP:
4050 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4051 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4054 /* Display what configure line was used */
4055 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4057 // Many users forget to include command line in bugreports...
4058 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
4059 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4060 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
4061 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4064 //------ load global data first ------
4066 mpctx->osd = osd_create();
4068 // check font
4069 #ifdef CONFIG_FREETYPE
4070 init_freetype();
4071 #endif
4072 #ifdef CONFIG_FONTCONFIG
4073 if(font_fontconfig <= 0)
4075 #endif
4076 #ifdef CONFIG_BITMAP_FONT
4077 if(font_name){
4078 vo_font=read_font_desc(font_name,font_factor,verbose>1);
4079 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
4080 filename_recode(font_name));
4081 } else {
4082 // try default:
4083 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
4084 free(mem_ptr); // release the buffer created by get_path()
4085 if(!vo_font)
4086 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
4088 if (sub_font_name)
4089 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
4090 else
4091 mpctx->osd->sub_font = vo_font;
4092 #endif
4093 #ifdef CONFIG_FONTCONFIG
4095 #endif
4097 #ifdef CONFIG_ASS
4098 ass_library = mp_ass_init();
4099 #endif
4101 #ifdef HAVE_RTC
4102 if(opts->rtc)
4104 char *rtc_device = opts->rtc_device;
4105 // seteuid(0); /* Can't hurt to try to get root here */
4106 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4107 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4108 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4109 else {
4110 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4112 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4113 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4114 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4115 close (rtc_fd);
4116 rtc_fd = -1;
4117 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4118 /* variable only by the root */
4119 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4120 close (rtc_fd);
4121 rtc_fd = -1;
4122 } else
4123 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4126 if(rtc_fd<0)
4127 #endif /* HAVE_RTC */
4128 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4129 opts->softsleep ? "software" : timer_name);
4131 #ifdef HAVE_TERMCAP
4132 load_termcap(NULL); // load key-codes
4133 #endif
4135 // ========== Init keyboard FIFO (connection to libvo) ============
4137 // Init input system
4138 current_module = "init_input";
4139 mpctx->input = mp_input_init(&opts->input);
4140 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4141 if(slave_mode)
4142 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4143 else if (opts->consolecontrols)
4144 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4145 // Set the libstream interrupt callback
4146 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4148 #ifdef CONFIG_MENU
4149 if(use_menu) {
4150 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4151 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4152 else {
4153 menu_cfg = get_path("menu.conf");
4154 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4155 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4156 else {
4157 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4158 MPLAYER_CONFDIR "/menu.conf"))
4159 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4160 else {
4161 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4162 use_menu = 0;
4167 #endif
4169 current_module = NULL;
4171 /// Catch signals
4172 #ifndef __MINGW32__
4173 signal(SIGCHLD,child_sighandler);
4174 #endif
4176 #ifdef CONFIG_CRASH_DEBUG
4177 prog_path = argv[0];
4178 #endif
4179 //========= Catch terminate signals: ================
4180 // terminate requests:
4181 signal(SIGTERM,exit_sighandler); // kill
4182 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4184 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4186 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4187 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4188 #ifdef CONFIG_SIGHANDLER
4189 // fatal errors:
4190 signal(SIGBUS,exit_sighandler); // bus error
4191 signal(SIGSEGV,exit_sighandler); // segfault
4192 signal(SIGILL,exit_sighandler); // illegal instruction
4193 signal(SIGFPE,exit_sighandler); // floating point exc.
4194 signal(SIGABRT,exit_sighandler); // abort()
4195 #ifdef CONFIG_CRASH_DEBUG
4196 if (crash_debug)
4197 signal(SIGTRAP,exit_sighandler);
4198 #endif
4199 #endif
4201 // ******************* Now, let's see the per-file stuff ********************
4203 play_next_file:
4205 // init global sub numbers
4206 mpctx->global_sub_size = 0;
4207 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4209 if (mpctx->filename) {
4210 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4211 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4212 load_per_file_config (mpctx->mconfig, mpctx->filename);
4215 if (opts->video_driver_list)
4216 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4217 if (opts->audio_driver_list)
4218 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4220 // We must enable getch2 here to be able to interrupt network connection
4221 // or cache filling
4222 if (opts->consolecontrols && !slave_mode) {
4223 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4224 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4225 else
4226 getch2_enable(); // prepare stdin for hotkeys...
4227 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4228 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4231 // =================== GUI idle loop (STOP state) ===========================
4232 while (opts->player_idle_mode && !mpctx->filename) {
4233 play_tree_t * entry = NULL;
4234 mp_cmd_t * cmd;
4235 if (mpctx->video_out && mpctx->video_out->config_ok)
4236 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4237 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4238 if (mpctx->video_out)
4239 vo_check_events(mpctx->video_out);
4240 usec_sleep(20000);
4242 switch (cmd->id) {
4243 case MP_CMD_LOADFILE:
4244 // prepare a tree entry with the new filename
4245 entry = play_tree_new();
4246 play_tree_add_file(entry, cmd->args[0].v.s);
4247 // The entry is added to the main playtree after the switch().
4248 break;
4249 case MP_CMD_LOADLIST:
4250 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4251 break;
4252 case MP_CMD_QUIT:
4253 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4254 break;
4255 case MP_CMD_VO_FULLSCREEN:
4256 case MP_CMD_GET_PROPERTY:
4257 case MP_CMD_SET_PROPERTY:
4258 case MP_CMD_STEP_PROPERTY:
4259 run_command(mpctx, cmd);
4260 break;
4263 mp_cmd_free(cmd);
4265 if (entry) { // user entered a command that gave a valid entry
4266 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4267 play_tree_free_list(mpctx->playtree->child, 1);
4268 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4270 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4272 play_tree_set_child(mpctx->playtree, entry);
4274 /* Make iterator start at the top the of tree. */
4275 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4276 if (!mpctx->playtree_iter) continue;
4278 // find the first real item in the tree
4279 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4280 // no items!
4281 play_tree_iter_free(mpctx->playtree_iter);
4282 mpctx->playtree_iter = NULL;
4283 continue; // wait for next command
4285 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4288 //---------------------------------------------------------------------------
4290 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4291 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4293 if (mpctx->filename) {
4294 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4295 filename_recode(mpctx->filename));
4296 if(use_filename_title && opts->vo_wintitle == NULL)
4297 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4300 if (edl_filename) {
4301 if (edl_records) free_edl(edl_records);
4302 next_edl_record = edl_records = edl_parse_file();
4304 if (edl_output_filename) {
4305 if (edl_fd) fclose(edl_fd);
4306 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4308 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4309 filename_recode(edl_output_filename));
4313 //==================== Open VOB-Sub ============================
4315 current_module="vobsub";
4316 if (vobsub_name){
4317 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
4318 if(vo_vobsub==NULL)
4319 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4320 filename_recode(vobsub_name));
4321 } else if (sub_auto && mpctx->filename){
4322 /* try to autodetect vobsub from movie filename ::atmos */
4323 char *buf = strdup(mpctx->filename), *psub;
4324 char *pdot = strrchr(buf, '.');
4325 char *pslash = strrchr(buf, '/');
4326 #if defined(__MINGW32__) || defined(__CYGWIN__)
4327 if (!pslash) pslash = strrchr(buf, '\\');
4328 #endif
4329 if (pdot && (!pslash || pdot > pslash))
4330 *pdot = '\0';
4331 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4332 /* try from ~/.mplayer/sub */
4333 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4334 const char *bname = mp_basename(buf);
4335 int l;
4336 l = strlen(psub) + strlen(bname) + 1;
4337 psub = realloc(psub,l);
4338 strcat(psub,bname);
4339 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4340 free(psub);
4342 free(buf);
4344 if(vo_vobsub){
4345 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4346 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4347 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4349 // setup global sub numbering
4350 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4353 //============ Open & Sync STREAM --- fork cache2 ====================
4355 mpctx->stream=NULL;
4356 mpctx->demuxer=NULL;
4357 if (mpctx->d_audio) {
4358 //free_demuxer_stream(mpctx->d_audio);
4359 mpctx->d_audio=NULL;
4361 if (mpctx->d_video) {
4362 //free_demuxer_stream(d_video);
4363 mpctx->d_video=NULL;
4365 mpctx->sh_audio=NULL;
4366 mpctx->sh_video=NULL;
4368 current_module="open_stream";
4369 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4370 if(!mpctx->stream) { // error...
4371 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4372 goto goto_next_file;
4374 mpctx->initialized_flags|=INITIALIZED_STREAM;
4376 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4377 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4378 "playlist support will not be used automatically.\n"
4379 "MPlayer's playlist code is unsafe and should only be used with "
4380 "trusted sources.\nPlayback will probably fail.\n\n");
4381 #if 0
4382 play_tree_t* entry;
4383 // Handle playlist
4384 current_module="handle_playlist";
4385 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4386 filename_recode(mpctx->filename));
4387 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4388 mpctx->eof=playtree_add_playlist(mpctx, entry);
4389 goto goto_next_file;
4390 #endif
4392 mpctx->stream->start_pos+=seek_to_byte;
4394 if(stream_dump_type==5){
4395 unsigned char buf[4096];
4396 int len;
4397 FILE *f;
4398 current_module="dumpstream";
4399 stream_reset(mpctx->stream);
4400 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4401 f=fopen(opts->stream_dump_name,"wb");
4402 if(!f){
4403 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4404 exit_player(mpctx, EXIT_ERROR);
4406 if (opts->chapterrange[0] > 1) {
4407 int chapter = opts->chapterrange[0] - 1;
4408 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4410 while(!mpctx->stream->eof && !async_quit_request){
4411 len=stream_read(mpctx->stream,buf,4096);
4412 if(len>0) {
4413 if(fwrite(buf,len,1,f) != 1) {
4414 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4415 exit_player(mpctx, EXIT_ERROR);
4418 if (opts->chapterrange[1] > 0) {
4419 int chapter = -1;
4420 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4421 &chapter) == STREAM_OK
4422 && chapter + 1 > opts->chapterrange[1])
4423 break;
4426 if(fclose(f)) {
4427 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4428 exit_player(mpctx, EXIT_ERROR);
4430 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4431 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4434 #ifdef CONFIG_DVDREAD
4435 if(mpctx->stream->type==STREAMTYPE_DVD){
4436 current_module="dvd lang->id";
4437 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4438 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4439 // setup global sub numbering
4440 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4441 current_module=NULL;
4443 #endif
4445 #ifdef CONFIG_DVDNAV
4446 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4447 current_module="dvdnav lang->id";
4448 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4449 dvdsub_lang_id = -3;
4450 if(opts->sub_lang && opts->sub_id==-1)
4451 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4452 // setup global sub numbering
4453 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4454 current_module=NULL;
4456 #endif
4458 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4459 goto_enable_cache:
4460 if(stream_cache_size>0){
4461 int res;
4462 float stream_cache_min_percent = opts->stream_cache_min_percent;
4463 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4464 current_module="enable_cache";
4465 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4466 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4467 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4468 if(res == 0)
4469 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4472 //============ Open DEMUXERS --- DETECT file type =======================
4473 current_module="demux_open";
4475 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4477 // HACK to get MOV Reference Files working
4479 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4481 unsigned char* playlist_entry;
4482 play_tree_t *list = NULL, *entry = NULL;
4484 current_module="handle_demux_playlist";
4485 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4487 char *temp;
4488 const char *bname;
4490 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4491 filename_recode(playlist_entry));
4493 bname=mp_basename(playlist_entry);
4494 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4495 continue;
4497 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4498 continue;
4500 entry = play_tree_new();
4502 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4504 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4505 if (temp)
4507 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4508 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4509 strcat(temp, playlist_entry);
4510 if (!strcmp(temp, mpctx->filename)) {
4511 free(temp);
4512 continue;
4514 play_tree_add_file(entry,temp);
4515 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4516 free(temp);
4519 else
4520 play_tree_add_file(entry,playlist_entry);
4522 if(!list)
4523 list = entry;
4524 else
4525 play_tree_append_entry(list,entry);
4527 free_demuxer(mpctx->demuxer);
4528 mpctx->demuxer = NULL;
4530 if (list)
4532 entry = play_tree_new();
4533 play_tree_set_child(entry,list);
4534 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4535 goto goto_next_file;
4539 if(!mpctx->demuxer) {
4540 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4541 goto goto_next_file;
4544 if (mpctx->demuxer->matroska_data.ordered_chapters)
4545 build_ordered_chapter_timeline(mpctx);
4547 if (!mpctx->sources) {
4548 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4549 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4550 .demuxer = mpctx->demuxer};
4551 mpctx->num_sources = 1;
4554 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4556 #ifdef CONFIG_ASS
4557 if (opts->ass_enabled && ass_library) {
4558 for (int j = 0; j < mpctx->num_sources; j++) {
4559 struct demuxer *d = mpctx->sources[j].demuxer;
4560 for (int i = 0; i < d->num_attachments; i++) {
4561 struct demux_attachment *att = d->attachments + i;
4562 if (use_embedded_fonts && attachment_is_font(att))
4563 ass_add_font(ass_library, att->name, att->data, att->data_size);
4567 #endif
4569 current_module="demux_open2";
4571 mpctx->d_audio=mpctx->demuxer->audio;
4572 mpctx->d_video=mpctx->demuxer->video;
4573 mpctx->d_sub=mpctx->demuxer->sub;
4575 if (ts_prog) {
4576 int tmp = ts_prog;
4577 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4579 // select audio stream
4580 if (mpctx->num_sources)
4581 for (int i = 0; i < mpctx->num_sources; i++)
4582 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
4583 opts->audio_lang);
4584 else
4585 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
4587 // DUMP STREAMS:
4588 if((stream_dump_type)&&(stream_dump_type<4)){
4589 FILE *f;
4590 demux_stream_t *ds=NULL;
4591 current_module="dump";
4592 // select stream to dump
4593 switch(stream_dump_type){
4594 case 1: ds=mpctx->d_audio;break;
4595 case 2: ds=mpctx->d_video;break;
4596 case 3: ds=mpctx->d_sub;break;
4598 if(!ds){
4599 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4600 exit_player(mpctx, EXIT_ERROR);
4602 // disable other streams:
4603 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4604 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4605 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4606 // let's dump it!
4607 f=fopen(opts->stream_dump_name,"wb");
4608 if(!f){
4609 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4610 exit_player(mpctx, EXIT_ERROR);
4612 while(!ds->eof){
4613 unsigned char* start;
4614 int in_size=ds_get_packet(ds,&start);
4615 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4616 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4617 if(in_size>0) fwrite(start,in_size,1,f);
4618 if (opts->chapterrange[1] > 0) {
4619 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4620 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4621 break;
4624 fclose(f);
4625 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4626 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4629 mpctx->sh_audio=mpctx->d_audio->sh;
4630 mpctx->sh_video=mpctx->d_video->sh;
4632 if(mpctx->sh_video){
4634 current_module="video_read_properties";
4635 if(!video_read_properties(mpctx->sh_video)) {
4636 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4637 mpctx->sh_video=mpctx->d_video->sh=NULL;
4638 } else {
4639 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4640 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4641 mpctx->sh_video->fps,mpctx->sh_video->frametime
4644 /* need to set fps here for output encoders to pick it up in their init */
4645 if(force_fps){
4646 mpctx->sh_video->fps=force_fps;
4647 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4649 vo_fps = mpctx->sh_video->fps;
4651 if(!mpctx->sh_video->fps && !force_fps){
4652 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4653 mpctx->opts.correct_pts = 1;
4659 if(!mpctx->sh_video && !mpctx->sh_audio){
4660 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4661 #ifdef CONFIG_DVBIN
4662 if(mpctx->stream->type == STREAMTYPE_DVB)
4664 int dir;
4665 int v = mpctx->last_dvb_step;
4666 if(v > 0)
4667 dir = DVB_CHANNEL_HIGHER;
4668 else
4669 dir = DVB_CHANNEL_LOWER;
4671 if(dvb_step_channel(mpctx->stream, dir)) {
4672 mpctx->stop_play = PT_NEXT_ENTRY;
4673 mpctx->dvbin_reopen = 1;
4676 #endif
4677 goto goto_next_file; // exit_player(_("Fatal error"));
4680 /* display clip info */
4681 demux_info_print(mpctx->demuxer);
4683 //================== Read SUBTITLES (DVD & TEXT) ==========================
4684 if(vo_spudec==NULL &&
4685 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4686 init_vo_spudec(mpctx);
4689 // after reading video params we should load subtitles because
4690 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4691 // check .sub
4692 current_module="read_subtitles_file";
4693 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4694 if(sub_name){
4695 for (i = 0; sub_name[i] != NULL; ++i)
4696 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4698 if(sub_auto) { // auto load sub file ...
4699 char *psub = get_path( "sub/" );
4700 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4701 int i = 0;
4702 free(psub); // release the buffer created by get_path() above
4703 while (tmp[i]) {
4704 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4705 free(tmp[i++]);
4707 free(tmp);
4709 if (mpctx->set_of_sub_size > 0)
4710 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4712 if (select_subtitle(mpctx)) {
4713 if(mpctx->subdata)
4714 switch (stream_dump_type) {
4715 case 3: list_sub_file(mpctx->subdata); break;
4716 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4717 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4718 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4719 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4720 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4724 print_file_properties(mpctx, mpctx->filename);
4726 if(!mpctx->sh_video) goto main; // audio-only
4728 if(!reinit_video_chain(mpctx)) {
4729 if(!mpctx->sh_video){
4730 if(!mpctx->sh_audio) goto goto_next_file;
4731 goto main; // exit_player(_("Fatal error"));
4735 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4736 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4738 #ifdef CONFIG_FREETYPE
4739 force_load_font = 1;
4740 #endif
4742 //================== MAIN: ==========================
4743 main:
4744 current_module="main";
4746 if (opts->playing_msg) {
4747 char* msg = property_expand_string(mpctx, opts->playing_msg);
4748 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4749 free(msg);
4753 // Disable the term OSD in verbose mode
4754 if (verbose)
4755 opts->term_osd = 0;
4759 // Make sure old OSD does not stay around,
4760 // e.g. with -fixed-vo and same-resolution files
4761 clear_osd_msgs();
4762 update_osd_msg(mpctx);
4764 //================ SETUP AUDIO ==========================
4766 if(mpctx->sh_audio){
4767 reinit_audio_chain(mpctx);
4768 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4769 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4772 current_module="av_init";
4774 if(mpctx->sh_video){
4775 mpctx->sh_video->timer=0;
4776 if (! ignore_start)
4777 audio_delay += mpctx->sh_video->stream_delay;
4779 if(mpctx->sh_audio){
4780 if (start_volume >= 0)
4781 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4782 if (! ignore_start)
4783 audio_delay -= mpctx->sh_audio->stream_delay;
4784 mpctx->delay=-audio_delay;
4787 if(!mpctx->sh_audio){
4788 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4789 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4790 ds_free_packs(mpctx->d_audio); // free buffered chunks
4791 //mpctx->d_audio->id=-2; // do not read audio chunks
4792 //uninit_player(mpctx, INITIALIZED_AO); // close device
4794 if(!mpctx->sh_video){
4795 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4796 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4797 ds_free_packs(mpctx->d_video);
4798 mpctx->d_video->id=-2;
4799 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4802 if (!mpctx->sh_video && !mpctx->sh_audio)
4803 goto goto_next_file;
4805 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4806 if(force_fps && mpctx->sh_video){
4807 vo_fps = mpctx->sh_video->fps=force_fps;
4808 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4809 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4812 mp_input_set_section(mpctx->input, NULL);
4813 //TODO: add desired (stream-based) sections here
4814 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4815 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4817 //==================== START PLAYING =======================
4819 if(opts->loop_times>1) opts->loop_times--; else
4820 if(opts->loop_times==1) opts->loop_times = -1;
4822 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4824 total_time_usage_start=GetTimer();
4825 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4826 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4827 play_n_frames=play_n_frames_mf;
4829 if(play_n_frames==0){
4830 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4833 mpctx->time_frame = 0;
4834 mpctx->drop_message_shown = 0;
4835 mpctx->restart_playback = true;
4836 mpctx->video_pts = 0;
4837 mpctx->hrseek_active = false;
4838 mpctx->hrseek_framedrop = false;
4839 mpctx->step_frames = 0;
4840 mpctx->total_avsync_change = 0;
4841 mpctx->last_chapter_seek = -1;
4843 // If there's a timeline force an absolute seek to initialize state
4844 if (seek_to_sec || mpctx->timeline) {
4845 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4846 seek(mpctx, mpctx->seek);
4847 end_at.pos += seek_to_sec;
4849 if (opts->chapterrange[0] > 0) {
4850 double pts;
4851 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4852 && pts > -1.0) {
4853 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4854 seek(mpctx, mpctx->seek);
4858 if (end_at.type == END_AT_SIZE) {
4859 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4860 end_at.type = END_AT_NONE;
4863 #ifdef CONFIG_DVDNAV
4864 mp_dvdnav_context_free(mpctx);
4865 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4866 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4867 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4869 #endif
4871 mpctx->seek = (struct seek_params){0};
4872 get_relative_time(mpctx); // reset current delta
4873 // Make sure VO knows current pause state
4874 if (mpctx->sh_video)
4875 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4876 NULL);
4878 while (!mpctx->stop_play)
4879 run_playloop(mpctx);
4881 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4883 #ifdef CONFIG_DVBIN
4884 if(mpctx->dvbin_reopen)
4886 mpctx->stop_play = 0;
4887 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4888 cache_uninit(mpctx->stream);
4889 mpctx->dvbin_reopen = 0;
4890 goto goto_enable_cache;
4892 #endif
4895 goto_next_file: // don't jump here after ao/vo/getch initialization!
4897 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4899 if (opts->benchmark) {
4900 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4901 double total_time_usage;
4902 total_time_usage_start=GetTimer()-total_time_usage_start;
4903 total_time_usage = (float)total_time_usage_start*0.000001;
4904 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4905 video_time_usage,vout_time_usage,audio_time_usage,
4906 total_time_usage-tot,total_time_usage);
4907 if(total_time_usage>0.0)
4908 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4909 100.0*video_time_usage/total_time_usage,
4910 100.0*vout_time_usage/total_time_usage,
4911 100.0*audio_time_usage/total_time_usage,
4912 100.0*(total_time_usage-tot)/total_time_usage,
4913 100.0);
4914 if(total_frame_cnt && frame_dropping)
4915 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4916 total_frame_cnt-drop_frame_cnt,
4917 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4918 drop_frame_cnt,
4919 100*drop_frame_cnt/total_frame_cnt,
4920 total_frame_cnt,
4921 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4924 // time to uninit all, except global stuff:
4925 int uninitialize_parts = INITIALIZED_ALL;
4926 if (opts->fixed_vo)
4927 uninitialize_parts -= INITIALIZED_VO;
4928 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4929 uninitialize_parts -= INITIALIZED_AO;
4930 uninit_player(mpctx, uninitialize_parts);
4932 if(mpctx->set_of_sub_size > 0) {
4933 current_module="sub_free";
4934 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4935 sub_free(mpctx->set_of_subtitles[i]);
4936 #ifdef CONFIG_ASS
4937 if(mpctx->set_of_ass_tracks[i])
4938 ass_free_track( mpctx->set_of_ass_tracks[i] );
4939 #endif
4941 mpctx->set_of_sub_size = 0;
4943 mpctx->vo_sub_last = vo_sub=NULL;
4944 mpctx->subdata=NULL;
4945 #ifdef CONFIG_ASS
4946 mpctx->osd->ass_track = NULL;
4947 if(ass_library)
4948 ass_clear_fonts(ass_library);
4949 #endif
4951 if (!mpctx->stop_play) // In case some goto jumped here...
4952 mpctx->stop_play = PT_NEXT_ENTRY;
4954 int playtree_direction = 1;
4956 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4957 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4958 play_tree_iter_free(mpctx->playtree_iter);
4959 mpctx->playtree_iter = NULL;
4961 mpctx->play_tree_step = 1;
4962 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4963 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4964 if(mpctx->playtree_iter) {
4965 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4966 play_tree_iter_free(mpctx->playtree_iter);
4967 mpctx->playtree_iter = NULL;
4970 } else if (mpctx->stop_play == PT_STOP) {
4971 play_tree_iter_free(mpctx->playtree_iter);
4972 mpctx->playtree_iter = NULL;
4973 } else { // NEXT PREV SRC
4974 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4977 while(mpctx->playtree_iter != NULL) {
4978 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4979 if(mpctx->filename == NULL) {
4980 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4981 play_tree_iter_free(mpctx->playtree_iter);
4982 mpctx->playtree_iter = NULL;
4984 } else
4985 break;
4988 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4989 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4990 mpctx->stop_play = 0;
4991 goto play_next_file;
4995 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4997 return 1;
4999 #endif /* DISABLE_MAIN */