OSD: support displaying fractional part of current position
[mplayer/greg.git] / mplayer.c
blob7ced98e965da01d35b12d7c53bc17000f172d655
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 #ifdef HAVE_RTC
116 #ifdef __linux__
117 #include <linux/rtc.h>
118 #else
119 #include <rtc.h>
120 #define RTC_IRQP_SET RTCIO_IRQP_SET
121 #define RTC_PIE_ON RTCIO_PIE_ON
122 #endif /* __linux__ */
123 #endif /* HAVE_RTC */
125 #include "stream/tv.h"
126 #include "stream/stream_radio.h"
127 #ifdef CONFIG_DVBIN
128 #include "stream/dvbin.h"
129 #endif
130 #include "stream/cache2.h"
132 //**************************************************************************//
133 // Playtree
134 //**************************************************************************//
135 #include "playtree.h"
136 #include "playtreeparser.h"
138 //**************************************************************************//
139 // Config
140 //**************************************************************************//
141 #include "parser-cfg.h"
142 #include "parser-mpcmd.h"
144 //**************************************************************************//
145 // Config file
146 //**************************************************************************//
148 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
150 #include "path.h"
152 //**************************************************************************//
153 //**************************************************************************//
154 // Input media streaming & demultiplexer:
155 //**************************************************************************//
157 static int max_framesize=0;
159 #include "stream/stream.h"
160 #include "libmpdemux/demuxer.h"
161 #include "libmpdemux/stheader.h"
163 #ifdef CONFIG_DVDREAD
164 #include "stream/stream_dvd.h"
165 #endif
166 #include "stream/stream_dvdnav.h"
168 #include "libmpcodecs/dec_audio.h"
169 #include "libmpcodecs/dec_video.h"
170 #include "libmpcodecs/mp_image.h"
171 #include "libmpcodecs/vf.h"
172 #include "libmpcodecs/vd.h"
174 #include "mixer.h"
176 #include "mp_core.h"
177 #include "options.h"
178 #include "defaultopts.h"
180 static const char help_text[]=_(
181 "Usage: mplayer [options] [url|path/]filename\n"
182 "\n"
183 "Basic options: (complete list in the man page)\n"
184 " -vo <drv> select video output driver ('-vo help' for a list)\n"
185 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
186 #ifdef CONFIG_VCD
187 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
188 #endif
189 #ifdef CONFIG_DVDREAD
190 " dvd://<titleno> play DVD title from device instead of plain file\n"
191 #endif
192 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
193 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
194 " -nosound do not play sound\n"
195 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
196 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
197 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
198 " -playlist <file> specify playlist file\n"
199 " -vid x -aid y select video (x) and audio (y) stream to play\n"
200 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
201 " -pp <quality> enable postprocessing filter (details in the man page)\n"
202 " -framedrop enable frame dropping (for slow machines)\n"
203 "\n"
204 "Basic keys: (complete list in the man page, also check input.conf)\n"
205 " <- or -> seek backward/forward 10 seconds\n"
206 " down or up seek backward/forward 1 minute\n"
207 " pgdown or pgup seek backward/forward 10 minutes\n"
208 " < or > step backward/forward in playlist\n"
209 " p or SPACE pause movie (press any key to continue)\n"
210 " q or ESC stop playing and quit program\n"
211 " + or - adjust audio delay by +/- 0.1 second\n"
212 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
213 " * or / increase or decrease PCM volume\n"
214 " x or z adjust subtitle delay by +/- 0.1 second\n"
215 " r or t adjust subtitle position up/down, also see -vf expand\n"
216 "\n"
217 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
218 "\n");
221 #define Exit_SIGILL_RTCpuSel _(\
222 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
223 " It may be a bug in our new runtime CPU-detection code...\n"\
224 " Please read DOCS/HTML/en/bugreports.html.\n")
226 #define Exit_SIGILL _(\
227 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
228 " It usually happens when you run it on a CPU different than the one it was\n"\
229 " compiled/optimized for.\n"\
230 " Verify this!\n")
232 #define Exit_SIGSEGV_SIGFPE _(\
233 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
234 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
235 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
237 #define Exit_SIGCRASH _(\
238 "- MPlayer crashed. This shouldn't happen.\n"\
239 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
240 " gcc version. If you think it's MPlayer's fault, please read\n"\
241 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
242 " won't help unless you provide this information when reporting a possible bug.\n")
244 #define SystemTooSlow _("\n\n"\
245 " ************************************************\n"\
246 " **** Your system is too SLOW to play this! ****\n"\
247 " ************************************************\n\n"\
248 "Possible reasons, problems, workarounds:\n"\
249 "- Most common: broken/buggy _audio_ driver\n"\
250 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
251 " - Experiment with different values for -autosync, 30 is a good start.\n"\
252 "- Slow video output\n"\
253 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
254 "- Slow CPU\n"\
255 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
256 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
257 "- Broken file\n"\
258 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
259 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
260 " - Try -cache 8192.\n"\
261 "- Are you using -cache to play a non-interleaved AVI file?\n"\
262 " - Try -nocache.\n"\
263 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
264 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
267 //**************************************************************************//
268 //**************************************************************************//
270 #include "mp_fifo.h"
272 // benchmark:
273 double video_time_usage=0;
274 double vout_time_usage=0;
275 static double audio_time_usage=0;
276 static int total_time_usage_start=0;
277 static int total_frame_cnt=0;
278 static int drop_frame_cnt=0; // total number of dropped frames
280 // options:
281 static int output_quality=0;
283 // seek:
284 static double seek_to_sec;
285 static off_t seek_to_byte=0;
286 static off_t step_sec=0;
288 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
290 // codecs:
291 char **audio_codec_list=NULL; // override audio codec
292 char **video_codec_list=NULL; // override video codec
293 char **audio_fm_list=NULL; // override audio codec family
294 char **video_fm_list=NULL; // override video codec family
296 // this dvdsub_id was selected via slang
297 // use this to allow dvdnav to follow -slang across stream resets,
298 // in particular the subtitle ID for a language changes
299 int dvdsub_lang_id;
300 int vobsub_id=-1;
301 static char* spudec_ifo=NULL;
302 int forced_subs_only=0;
303 int file_filter=1;
305 // cache2:
306 int stream_cache_size=-1;
308 // dump:
309 int stream_dump_type=0;
311 // A-V sync:
312 static float default_max_pts_correction=-1;//0.01f;
313 float audio_delay=0;
314 static int ignore_start=0;
316 double force_fps=0;
317 static int force_srate=0;
318 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
319 static int play_n_frames=-1;
320 static int play_n_frames_mf=-1;
322 // sub:
323 char *font_name=NULL;
324 char *sub_font_name=NULL;
325 extern int font_fontconfig;
326 float font_factor=0.75;
327 char **sub_name=NULL;
328 float sub_delay=0;
329 float sub_fps=0;
330 int sub_auto = 1;
331 char *vobsub_name=NULL;
332 int subcc_enabled=0;
333 int suboverlap_enabled = 1;
335 #include "sub/ass_mp.h"
337 char* current_module=NULL; // for debugging
340 // ---
342 #ifdef CONFIG_MENU
343 #include "m_struct.h"
344 #include "libmenu/menu.h"
345 static const vf_info_t* const libmenu_vfs[] = {
346 &vf_info_menu,
347 NULL
349 static vf_instance_t* vf_menu = NULL;
350 int use_menu = 0;
351 static char* menu_cfg = NULL;
352 static char* menu_root = "main";
353 #endif
356 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
357 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
358 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
359 int use_filedir_conf;
360 int use_filename_title;
362 #include "mpcommon.h"
363 #include "command.h"
365 #include "metadata.h"
367 const void *mpctx_get_video_out(MPContext *mpctx)
369 return mpctx->video_out;
372 const void *mpctx_get_audio_out(MPContext *mpctx)
374 return mpctx->audio_out;
377 void *mpctx_get_demuxer(MPContext *mpctx)
379 return mpctx->demuxer;
382 void *mpctx_get_playtree_iter(MPContext *mpctx)
384 return mpctx->playtree_iter;
387 void *mpctx_get_mixer(MPContext *mpctx)
389 return &mpctx->mixer;
392 int mpctx_get_global_sub_size(MPContext *mpctx)
394 return mpctx->global_sub_size;
397 int mpctx_get_osd_function(MPContext *mpctx)
399 return mpctx->osd_function;
402 static float get_relative_time(struct MPContext *mpctx)
404 unsigned int new_time = GetTimer();
405 unsigned int delta = new_time - mpctx->last_time;
406 mpctx->last_time = new_time;
407 return delta * 0.000001;
410 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
411 switch (type)
413 /* check for valid video stream */
414 case META_VIDEO_CODEC:
415 case META_VIDEO_BITRATE:
416 case META_VIDEO_RESOLUTION:
418 if (!mpctx->sh_video)
419 return 0;
420 break;
423 /* check for valid audio stream */
424 case META_AUDIO_CODEC:
425 case META_AUDIO_BITRATE:
426 case META_AUDIO_SAMPLES:
428 if (!mpctx->sh_audio)
429 return 0;
430 break;
433 /* check for valid demuxer */
434 case META_INFO_TITLE:
435 case META_INFO_ARTIST:
436 case META_INFO_ALBUM:
437 case META_INFO_YEAR:
438 case META_INFO_COMMENT:
439 case META_INFO_TRACK:
440 case META_INFO_GENRE:
442 if (!mpctx->demuxer)
443 return 0;
444 break;
447 default:
448 break;
451 return 1;
454 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
455 char **info = mpctx->demuxer->info;
456 int n;
458 if (!info || !tag)
459 return talloc_strdup(NULL, "");
461 for (n = 0; info[2*n] != NULL ; n++)
462 if (!strcasecmp (info[2*n], tag))
463 break;
465 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
468 char *get_metadata(struct MPContext *mpctx, metadata_t type)
470 sh_audio_t * const sh_audio = mpctx->sh_audio;
471 sh_video_t * const sh_video = mpctx->sh_video;
473 if (!is_valid_metadata_type(mpctx, type))
474 return NULL;
476 switch (type) {
477 case META_NAME:
478 return talloc_strdup(NULL, mp_basename(mpctx->filename));
479 case META_VIDEO_CODEC:
480 if (sh_video->format == 0x10000001)
481 return talloc_strdup(NULL, "mpeg1");
482 else if (sh_video->format == 0x10000002)
483 return talloc_strdup(NULL, "mpeg2");
484 else if (sh_video->format == 0x10000004)
485 return talloc_strdup(NULL, "mpeg4");
486 else if (sh_video->format == 0x10000005)
487 return talloc_strdup(NULL, "h264");
488 else if (sh_video->format >= 0x20202020)
489 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
490 else
491 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
492 case META_VIDEO_BITRATE:
493 return talloc_asprintf(NULL, "%d kbps",
494 (int) (sh_video->i_bps * 8 / 1024));
495 case META_VIDEO_RESOLUTION:
496 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
497 sh_video->disp_h);
498 case META_AUDIO_CODEC:
499 if (sh_audio->codec && sh_audio->codec->name)
500 return talloc_strdup(NULL, sh_audio->codec->name);
501 return talloc_strdup(NULL, "");
502 case META_AUDIO_BITRATE:
503 return talloc_asprintf(NULL, "%d kbps",
504 (int) (sh_audio->i_bps * 8/1000));
505 case META_AUDIO_SAMPLES:
506 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
507 sh_audio->channels);
509 /* check for valid demuxer */
510 case META_INFO_TITLE:
511 return get_demuxer_info(mpctx, "Title");
513 case META_INFO_ARTIST:
514 return get_demuxer_info(mpctx, "Artist");
516 case META_INFO_ALBUM:
517 return get_demuxer_info(mpctx, "Album");
519 case META_INFO_YEAR:
520 return get_demuxer_info(mpctx, "Year");
522 case META_INFO_COMMENT:
523 return get_demuxer_info(mpctx, "Comment");
525 case META_INFO_TRACK:
526 return get_demuxer_info(mpctx, "Track");
528 case META_INFO_GENRE:
529 return get_demuxer_info(mpctx, "Genre");
531 default:
532 break;
535 return talloc_strdup(NULL, "");
538 static void print_file_properties(struct MPContext *mpctx, const char *filename)
540 double start_pts = MP_NOPTS_VALUE;
541 double video_start_pts = MP_NOPTS_VALUE;
542 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
543 filename_recode(filename));
544 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
545 if (mpctx->sh_video) {
546 /* Assume FOURCC if all bytes >= 0x20 (' ') */
547 if (mpctx->sh_video->format >= 0x20202020)
548 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
549 else
550 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
551 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
552 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
553 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
554 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
555 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
556 video_start_pts = ds_get_next_pts(mpctx->d_video);
558 if (mpctx->sh_audio) {
559 /* Assume FOURCC if all bytes >= 0x20 (' ') */
560 if (mpctx->sh_audio->format >= 0x20202020)
561 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
562 else
563 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
564 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
565 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
566 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
567 start_pts = ds_get_next_pts(mpctx->d_audio);
569 if (video_start_pts != MP_NOPTS_VALUE) {
570 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
571 (mpctx->sh_video && video_start_pts < start_pts))
572 start_pts = video_start_pts;
574 if (start_pts != MP_NOPTS_VALUE)
575 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
576 else
577 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
578 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
579 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
580 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
581 if (mpctx->demuxer) {
582 if (mpctx->demuxer->num_chapters == 0)
583 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
584 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
588 /// step size of mixer changes
589 int volstep = 3;
591 #ifdef CONFIG_DVDNAV
592 static void mp_dvdnav_context_free(MPContext *ctx){
593 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
594 ctx->nav_smpi = NULL;
595 free(ctx->nav_buffer);
596 ctx->nav_buffer = NULL;
597 ctx->nav_start = NULL;
598 ctx->nav_in_size = 0;
600 #endif
602 static void uninit_subs(struct demuxer *demuxer)
604 for (int i = 0; i < MAX_S_STREAMS; i++) {
605 struct sh_sub *sh = demuxer->s_streams[i];
606 if (sh && sh->initialized)
607 sub_uninit(sh);
611 void uninit_player(struct MPContext *mpctx, unsigned int mask){
612 mask &= mpctx->initialized_flags;
614 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
616 if(mask&INITIALIZED_ACODEC){
617 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
618 current_module="uninit_acodec";
619 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
620 mpctx->sh_audio=NULL;
621 mpctx->mixer.afilter = NULL;
624 if (mask & INITIALIZED_SUB) {
625 mpctx->initialized_flags &= ~INITIALIZED_SUB;
626 if (mpctx->d_sub->sh)
627 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
630 if(mask&INITIALIZED_VCODEC){
631 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
632 current_module="uninit_vcodec";
633 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
634 mpctx->sh_video=NULL;
635 #ifdef CONFIG_MENU
636 vf_menu=NULL;
637 #endif
640 if(mask&INITIALIZED_DEMUXER){
641 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
642 current_module="free_demuxer";
643 if (mpctx->num_sources) {
644 mpctx->demuxer = mpctx->sources[0].demuxer;
645 for (int i = 1; i < mpctx->num_sources; i++) {
646 uninit_subs(mpctx->sources[i].demuxer);
647 free_stream(mpctx->sources[i].stream);
648 free_demuxer(mpctx->sources[i].demuxer);
651 talloc_free(mpctx->sources);
652 mpctx->sources = NULL;
653 mpctx->num_sources = 0;
654 talloc_free(mpctx->timeline);
655 mpctx->timeline = NULL;
656 mpctx->num_timeline_parts = 0;
657 talloc_free(mpctx->chapters);
658 mpctx->chapters = NULL;
659 mpctx->num_chapters = 0;
660 mpctx->video_offset = 0;
661 if(mpctx->demuxer){
662 mpctx->stream=mpctx->demuxer->stream;
663 uninit_subs(mpctx->demuxer);
664 free_demuxer(mpctx->demuxer);
666 mpctx->demuxer=NULL;
669 // kill the cache process:
670 if(mask&INITIALIZED_STREAM){
671 mpctx->initialized_flags&=~INITIALIZED_STREAM;
672 current_module="uninit_stream";
673 if(mpctx->stream) free_stream(mpctx->stream);
674 mpctx->stream=NULL;
677 if(mask&INITIALIZED_VO){
678 mpctx->initialized_flags&=~INITIALIZED_VO;
679 current_module="uninit_vo";
680 vo_destroy(mpctx->video_out);
681 mpctx->video_out=NULL;
682 #ifdef CONFIG_DVDNAV
683 mp_dvdnav_context_free(mpctx);
684 #endif
687 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
688 if(mask&INITIALIZED_GETCH2){
689 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
690 current_module="uninit_getch2";
691 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
692 // restore terminal:
693 getch2_disable();
696 if(mask&INITIALIZED_VOBSUB){
697 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
698 current_module="uninit_vobsub";
699 if(vo_vobsub) vobsub_close(vo_vobsub);
700 vo_vobsub=NULL;
703 if (mask&INITIALIZED_SPUDEC){
704 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
705 current_module="uninit_spudec";
706 spudec_free(vo_spudec);
707 vo_spudec=NULL;
710 if(mask&INITIALIZED_AO){
711 mpctx->initialized_flags&=~INITIALIZED_AO;
712 current_module="uninit_ao";
713 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
714 if (mpctx->audio_out)
715 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
716 mpctx->audio_out=NULL;
719 current_module=NULL;
722 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
724 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
725 uninit_player(mpctx, INITIALIZED_ALL);
726 #if defined(__MINGW32__) || defined(__CYGWIN__)
727 timeEndPeriod(1);
728 #endif
729 #ifdef CONFIG_X11
730 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
731 #endif
733 current_module="uninit_input";
734 mp_input_uninit(mpctx->input);
735 #ifdef CONFIG_MENU
736 if (use_menu)
737 menu_uninit();
738 #endif
740 #ifdef CONFIG_FREETYPE
741 current_module="uninit_font";
742 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
743 free_font_desc(mpctx->osd->sub_font);
744 free_font_desc(vo_font);
745 vo_font = NULL;
746 done_freetype();
747 #endif
748 osd_free(mpctx->osd);
750 #ifdef CONFIG_ASS
751 ass_library_done(ass_library);
752 ass_library = NULL;
753 #endif
755 current_module="exit_player";
757 // free mplayer config
758 if(mpctx->mconfig)
759 m_config_free(mpctx->mconfig);
760 mpctx->mconfig = NULL;
762 if(mpctx->playtree_iter)
763 play_tree_iter_free(mpctx->playtree_iter);
764 mpctx->playtree_iter = NULL;
765 if(mpctx->playtree)
766 play_tree_free(mpctx->playtree, 1);
767 mpctx->playtree = NULL;
769 talloc_free(mpctx->key_fifo);
771 free(edl_records); // free mem allocated for EDL
772 edl_records = NULL;
773 switch(how) {
774 case EXIT_QUIT:
775 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
776 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
777 break;
778 case EXIT_EOF:
779 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
780 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
781 break;
782 case EXIT_ERROR:
783 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
784 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
785 break;
786 default:
787 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
789 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
791 exit(rc);
794 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
796 exit_player_with_rc(mpctx, how, 1);
799 #ifndef __MINGW32__
800 static void child_sighandler(int x){
801 pid_t pid;
802 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
804 #endif
806 #ifdef CONFIG_CRASH_DEBUG
807 static char *prog_path;
808 static int crash_debug = 0;
809 #endif
811 static void exit_sighandler(int x){
812 static int sig_count=0;
813 #ifdef CONFIG_CRASH_DEBUG
814 if (!crash_debug || x != SIGTRAP)
815 #endif
816 ++sig_count;
817 if(sig_count==5)
819 /* We're crashing bad and can't uninit cleanly :(
820 * by popular request, we make one last (dirty)
821 * effort to restore the user's
822 * terminal. */
823 getch2_disable();
824 exit(1);
826 if(sig_count==6) exit(1);
827 if(sig_count>6){
828 // can't stop :(
829 #ifndef __MINGW32__
830 kill(getpid(),SIGKILL);
831 #endif
833 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
834 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
835 "\nMPlayer interrupted by signal %d in module: %s\n", x,
836 current_module ? current_module : "unknown");
837 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
838 if(sig_count<=1)
839 switch(x){
840 case SIGINT:
841 case SIGPIPE:
842 case SIGQUIT:
843 case SIGTERM:
844 case SIGKILL:
845 async_quit_request = 1;
846 return; // killed from keyboard (^C) or killed [-9]
847 case SIGILL:
848 #if CONFIG_RUNTIME_CPUDETECT
849 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
850 #else
851 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
852 #endif
853 case SIGFPE:
854 case SIGSEGV:
855 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
856 default:
857 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
858 #ifdef CONFIG_CRASH_DEBUG
859 if (crash_debug) {
860 int gdb_pid;
861 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
862 gdb_pid = fork();
863 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
864 if (gdb_pid == 0) { // We are the child
865 char spid[20];
866 snprintf(spid, sizeof(spid), "%i", getppid());
867 getch2_disable(); // allow terminal to work properly with gdb
868 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
869 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
870 } else if (gdb_pid < 0)
871 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
872 else {
873 waitpid(gdb_pid, NULL, 0);
875 if (x == SIGTRAP) return;
877 #endif
879 getch2_disable();
880 exit(1);
883 #include "cfg-mplayer.h"
885 static int cfg_include(m_option_t *conf, char *filename)
887 return m_config_parse_config_file(conf->priv, filename);
890 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
892 struct MPOpts *opts = &mpctx->opts;
893 char *conffile;
894 int conffile_fd;
895 if (!(opts->noconfig & 2) &&
896 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
897 exit_player(mpctx, EXIT_NONE);
898 if ((conffile = get_path("")) == NULL) {
899 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
900 } else {
901 #ifdef __MINGW32__
902 mkdir(conffile);
903 #else
904 mkdir(conffile, 0777);
905 #endif
906 free(conffile);
907 if ((conffile = get_path("config")) == NULL) {
908 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
909 } else {
910 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
911 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
912 write(conffile_fd, default_config, strlen(default_config));
913 close(conffile_fd);
915 if (!(opts->noconfig & 1) &&
916 m_config_parse_config_file(conf, conffile) < 0)
917 exit_player(mpctx, EXIT_NONE);
918 free(conffile);
923 #define PROFILE_CFG_PROTOCOL "protocol."
925 static void load_per_protocol_config (m_config_t* conf, const char *const file)
927 char *str;
928 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
929 m_profile_t *p;
931 /* does filename actually uses a protocol ? */
932 str = strstr (file, "://");
933 if (!str)
934 return;
936 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
937 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
938 p = m_config_get_profile (conf, protocol);
939 if (p)
941 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
942 m_config_set_profile(conf,p);
946 #define PROFILE_CFG_EXTENSION "extension."
948 static void load_per_extension_config (m_config_t* conf, const char *const file)
950 char *str;
951 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
952 m_profile_t *p;
954 /* does filename actually have an extension ? */
955 str = strrchr (file, '.');
956 if (!str)
957 return;
959 sprintf (extension, PROFILE_CFG_EXTENSION);
960 strncat (extension, ++str, 7);
961 p = m_config_get_profile (conf, extension);
962 if (p)
964 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
965 m_config_set_profile(conf,p);
969 #define PROFILE_CFG_VO "vo."
970 #define PROFILE_CFG_AO "ao."
972 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
974 char profile[strlen (cfg) + strlen (out) + 1];
975 m_profile_t *p;
977 sprintf (profile, "%s%s", cfg, out);
978 p = m_config_get_profile (conf, profile);
979 if (p)
981 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
982 m_config_set_profile(conf,p);
987 * Tries to load a config file
988 * @return 0 if file was not found, 1 otherwise
990 static int try_load_config(m_config_t *conf, const char *file)
992 struct stat st;
993 if (stat(file, &st))
994 return 0;
995 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
996 m_config_parse_config_file (conf, file);
997 return 1;
1000 static void load_per_file_config (m_config_t* conf, const char *const file)
1002 char *confpath;
1003 char cfg[PATH_MAX];
1004 const char *name;
1006 if (strlen(file) > PATH_MAX - 14) {
1007 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1008 return;
1010 sprintf (cfg, "%s.conf", file);
1012 name = mp_basename(cfg);
1013 if (use_filedir_conf) {
1014 char dircfg[PATH_MAX];
1015 strcpy(dircfg, cfg);
1016 strcpy(dircfg + (name - cfg), "mplayer.conf");
1017 try_load_config(conf, dircfg);
1019 if (try_load_config(conf, cfg))
1020 return;
1023 if ((confpath = get_path (name)) != NULL)
1025 try_load_config(conf, confpath);
1027 free (confpath);
1031 /* When libmpdemux performs a blocking operation (network connection or
1032 * cache filling) if the operation fails we use this function to check
1033 * if it was interrupted by the user.
1034 * The function returns a new value for eof. */
1035 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1037 mp_cmd_t* cmd;
1038 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1039 switch(cmd->id) {
1040 case MP_CMD_QUIT:
1041 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1042 case MP_CMD_PLAY_TREE_STEP: {
1043 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1044 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1045 } break;
1046 case MP_CMD_PLAY_TREE_UP_STEP: {
1047 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1048 } break;
1049 case MP_CMD_PLAY_ALT_SRC_STEP: {
1050 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1051 } break;
1053 mp_cmd_free(cmd);
1055 return stop_play;
1058 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1060 play_tree_add_bpf(entry,mpctx->filename);
1063 if(!entry) {
1064 entry = mpctx->playtree_iter->tree;
1065 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1066 return PT_NEXT_ENTRY;
1068 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1069 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1070 return PT_NEXT_ENTRY;
1073 play_tree_remove(entry,1,1);
1074 return PT_NEXT_SRC;
1076 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1077 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1078 entry = mpctx->playtree_iter->tree;
1079 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1080 return PT_NEXT_ENTRY;
1082 play_tree_remove(entry,1,1);
1084 return PT_NEXT_SRC;
1087 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1089 struct MPOpts *opts = &mpctx->opts;
1090 sub_data *subd = NULL;
1091 struct ass_track *asst = NULL;
1092 bool is_native_ass = false;
1094 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1095 return;
1097 #ifdef CONFIG_ASS
1098 if (opts->ass_enabled) {
1099 #ifdef CONFIG_ICONV
1100 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1101 #else
1102 asst = mp_ass_read_stream(ass_library, filename, 0);
1103 #endif
1104 is_native_ass = asst;
1105 if (!asst) {
1106 subd = sub_read_file(filename, fps, &mpctx->opts);
1107 if (subd) {
1108 asst = mp_ass_read_subdata(ass_library, subd, fps);
1109 sub_free(subd);
1110 subd = NULL;
1113 } else
1114 #endif
1115 subd = sub_read_file(filename, fps, &mpctx->opts);
1118 if (!asst && !subd) {
1119 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1120 "Cannot load subtitles: %s\n", filename_recode(filename));
1121 return;
1124 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1125 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1126 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1127 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1128 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1129 filename_recode(filename));
1130 ++mpctx->set_of_sub_size;
1131 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1132 filename_recode(filename));
1135 void init_vo_spudec(struct MPContext *mpctx)
1137 spudec_free(vo_spudec);
1138 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1139 vo_spudec = NULL;
1141 // we currently can't work without video stream
1142 if (!mpctx->sh_video)
1143 return;
1145 if (spudec_ifo) {
1146 unsigned int palette[16], width, height;
1147 current_module="spudec_init_vobsub";
1148 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1149 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1152 #ifdef CONFIG_DVDREAD
1153 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1154 current_module="spudec_init_dvdread";
1155 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1156 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1157 NULL, 0);
1159 #endif
1161 #ifdef CONFIG_DVDNAV
1162 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1163 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1164 current_module="spudec_init_dvdnav";
1165 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1167 #endif
1169 if (vo_spudec==NULL) {
1170 sh_sub_t *sh = mpctx->d_sub->sh;
1171 current_module="spudec_init_normal";
1172 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1173 spudec_set_font_factor(vo_spudec,font_factor);
1176 if (vo_spudec!=NULL) {
1177 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1178 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1183 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1184 * make it all work is to use the builtin SDL-bootstrap code, which
1185 * will be done automatically by replacing our main() if we include SDL.h.
1187 #if defined(__APPLE__) && defined(CONFIG_SDL)
1188 #ifdef CONFIG_SDL_SDL_H
1189 #include <SDL/SDL.h>
1190 #else
1191 #include <SDL.h>
1192 #endif
1193 #endif
1196 * \brief append a formatted string
1197 * \param buf buffer to print into
1198 * \param pos position of terminating 0 in buf
1199 * \param len maximum number of characters in buf, not including terminating 0
1200 * \param format printf format string
1202 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1204 va_list va;
1205 va_start(va, format);
1206 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1207 va_end(va);
1208 if (*pos >= len ) {
1209 buf[len] = 0;
1210 *pos = len;
1215 * \brief append time in the hh:mm:ss.f format
1216 * \param buf buffer to print into
1217 * \param pos position of terminating 0 in buf
1218 * \param len maximum number of characters in buf, not including terminating 0
1219 * \param time time value to convert/append
1221 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1222 int64_t tenths = 10 * time;
1223 int f1 = tenths % 10;
1224 int ss = (tenths / 10) % 60;
1225 int mm = (tenths / 600) % 60;
1226 int hh = tenths / 36000;
1227 if (time <= 0) {
1228 saddf(buf, pos, len, "unknown");
1229 return;
1231 if (hh > 0)
1232 saddf(buf, pos, len, "%2d:", hh);
1233 if (hh > 0 || mm > 0)
1234 saddf(buf, pos, len, "%02d:", mm);
1235 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1238 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1240 struct MPOpts *opts = &mpctx->opts;
1241 sh_video_t * const sh_video = mpctx->sh_video;
1243 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1244 a_pos = playing_audio_pts(mpctx);
1245 if (mpctx->sh_audio && sh_video && at_frame) {
1246 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1247 if (mpctx->time_frame > 0)
1248 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1249 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1250 && !mpctx->drop_message_shown) {
1251 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1252 mpctx->drop_message_shown = true;
1255 if (opts->quiet)
1256 return;
1259 int width;
1260 char *line;
1261 unsigned pos = 0;
1262 get_screen_size();
1263 if (screen_width > 0)
1264 width = screen_width;
1265 else
1266 width = 80;
1267 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1268 /* Windows command line is broken (MinGW's rxvt works, but we
1269 * should not depend on that). */
1270 width--;
1271 #endif
1272 line = malloc(width + 1); // one additional char for the terminating null
1274 // Audio time
1275 if (mpctx->sh_audio) {
1276 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1277 if (!sh_video) {
1278 float len = get_time_length(mpctx);
1279 saddf(line, &pos, width, "(");
1280 sadd_hhmmssf(line, &pos, width, a_pos);
1281 saddf(line, &pos, width, ") of %.1f (", len);
1282 sadd_hhmmssf(line, &pos, width, len);
1283 saddf(line, &pos, width, ") ");
1287 // Video time
1288 if (sh_video)
1289 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1291 // A-V sync
1292 if (mpctx->sh_audio && sh_video)
1293 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1294 mpctx->last_av_difference, mpctx->total_avsync_change);
1296 // Video stats
1297 if (sh_video)
1298 saddf(line, &pos, width, "%3d/%3d ",
1299 (int)sh_video->num_frames,
1300 (int)sh_video->num_frames_decoded);
1302 // CPU usage
1303 if (sh_video) {
1304 if (sh_video->timer > 0.5)
1305 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1306 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1307 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1308 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1309 else
1310 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1311 } else if (mpctx->sh_audio) {
1312 if (mpctx->delay > 0.5)
1313 saddf(line, &pos, width, "%4.1f%% ",
1314 100.0*audio_time_usage/(double)mpctx->delay);
1315 else
1316 saddf(line, &pos, width, "??,?%% ");
1319 // VO stats
1320 if (sh_video)
1321 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1323 #ifdef CONFIG_STREAM_CACHE
1324 // cache stats
1325 if (stream_cache_size > 0)
1326 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1327 #endif
1329 // other
1330 if (opts->playback_speed != 1)
1331 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1333 // end
1334 if (erase_to_end_of_line) {
1335 line[pos] = 0;
1336 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1337 } else {
1338 memset(&line[pos], ' ', width - pos);
1339 line[width] = 0;
1340 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1342 free(line);
1346 * \brief build a chain of audio filters that converts the input format
1347 * to the ao's format, taking into account the current playback_speed.
1348 * \param sh_audio describes the requested input format of the chain.
1349 * \param ao_data describes the requested output format of the chain.
1351 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1352 ao_data_t *ao_data)
1354 struct MPOpts *opts = &mpctx->opts;
1355 int new_srate;
1356 int result;
1357 if (!sh_audio)
1359 mpctx->mixer.afilter = NULL;
1360 return 0;
1362 if(af_control_any_rev(sh_audio->afilter,
1363 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1364 &opts->playback_speed)) {
1365 new_srate = sh_audio->samplerate;
1366 } else {
1367 new_srate = sh_audio->samplerate * opts->playback_speed;
1368 if (new_srate != ao_data->samplerate) {
1369 // limits are taken from libaf/af_resample.c
1370 if (new_srate < 8000)
1371 new_srate = 8000;
1372 if (new_srate > 192000)
1373 new_srate = 192000;
1374 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1377 result = init_audio_filters(sh_audio, new_srate,
1378 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1379 mpctx->mixer.afilter = sh_audio->afilter;
1380 return result;
1384 typedef struct mp_osd_msg mp_osd_msg_t;
1385 struct mp_osd_msg {
1386 /// Previous message on the stack.
1387 mp_osd_msg_t* prev;
1388 /// Message text.
1389 char msg[128];
1390 int id,level,started;
1391 /// Display duration in ms.
1392 unsigned time;
1395 /// OSD message stack.
1396 static mp_osd_msg_t* osd_msg_stack = NULL;
1399 * \brief Add a message on the OSD message stack
1401 * If a message with the same id is already present in the stack
1402 * it is pulled on top of the stack, otherwise a new message is created.
1405 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1406 va_list ap)
1408 mp_osd_msg_t *msg,*last=NULL;
1409 int r;
1411 // look if the id is already in the stack
1412 for(msg = osd_msg_stack ; msg && msg->id != id ;
1413 last = msg, msg = msg->prev);
1414 // not found: alloc it
1415 if(!msg) {
1416 msg = calloc(1,sizeof(mp_osd_msg_t));
1417 msg->prev = osd_msg_stack;
1418 osd_msg_stack = msg;
1419 } else if(last) { // found, but it's not on top of the stack
1420 last->prev = msg->prev;
1421 msg->prev = osd_msg_stack;
1422 osd_msg_stack = msg;
1424 // write the msg
1425 r = vsnprintf(msg->msg, 128, fmt, ap);
1426 if(r >= 128) msg->msg[127] = 0;
1427 // set id and time
1428 msg->id = id;
1429 msg->level = level;
1430 msg->time = time;
1434 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1436 va_list ap;
1437 va_start(ap, fmt);
1438 set_osd_msg_va(id, level, time, fmt, ap);
1439 va_end(ap);
1442 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1444 va_list ap;
1445 va_start(ap, fmt);
1446 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1447 va_end(ap);
1452 * \brief Remove a message from the OSD stack
1454 * This function can be used to get rid of a message right away.
1458 void rm_osd_msg(int id) {
1459 mp_osd_msg_t *msg,*last=NULL;
1461 // Search for the msg
1462 for(msg = osd_msg_stack ; msg && msg->id != id ;
1463 last = msg, msg = msg->prev);
1464 if(!msg) return;
1466 // Detach it from the stack and free it
1467 if(last)
1468 last->prev = msg->prev;
1469 else
1470 osd_msg_stack = msg->prev;
1471 free(msg);
1475 * \brief Remove all messages from the OSD stack
1479 static void clear_osd_msgs(void) {
1480 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1481 while(msg) {
1482 prev = msg->prev;
1483 free(msg);
1484 msg = prev;
1486 osd_msg_stack = NULL;
1490 * \brief Get the current message from the OSD stack.
1492 * This function decrements the message timer and destroys the old ones.
1493 * The message that should be displayed is returned (if any).
1497 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1499 struct MPOpts *opts = &mpctx->opts;
1500 mp_osd_msg_t *msg,*prev,*last = NULL;
1501 static unsigned last_update = 0;
1502 unsigned now = GetTimerMS();
1503 unsigned diff;
1504 char hidden_dec_done = 0;
1506 if (mpctx->osd_visible) {
1507 // 36000000 means max timed visibility is 1 hour into the future, if
1508 // the difference is greater assume it's wrapped around from below 0
1509 if (mpctx->osd_visible - now > 36000000) {
1510 mpctx->osd_visible = 0;
1511 vo_osd_progbar_type = -1; // disable
1512 vo_osd_changed(OSDTYPE_PROGBAR);
1513 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1516 if (mpctx->osd_show_percentage_until - now > 36000000)
1517 mpctx->osd_show_percentage_until = 0;
1519 if(!last_update) last_update = now;
1520 diff = now >= last_update ? now - last_update : 0;
1522 last_update = now;
1524 // Look for the first message in the stack with high enough level.
1525 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1526 prev = msg->prev;
1527 if (msg->level > opts->osd_level && hidden_dec_done)
1528 continue;
1529 // The message has a high enough level or it is the first hidden one
1530 // in both cases we decrement the timer or kill it.
1531 if(!msg->started || msg->time > diff) {
1532 if(msg->started) msg->time -= diff;
1533 else msg->started = 1;
1534 // display it
1535 if (msg->level <= opts->osd_level)
1536 return msg;
1537 hidden_dec_done = 1;
1538 continue;
1540 // kill the message
1541 free(msg);
1542 if(last) {
1543 last->prev = prev;
1544 msg = last;
1545 } else {
1546 osd_msg_stack = prev;
1547 msg = NULL;
1550 // Nothing found
1551 return NULL;
1555 * \brief Display the OSD bar.
1557 * Display the OSD bar or fall back on a simple message.
1561 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1562 struct MPOpts *opts = &mpctx->opts;
1563 if (opts->osd_level < 1)
1564 return;
1566 if(mpctx->sh_video) {
1567 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1568 vo_osd_progbar_type = type;
1569 vo_osd_progbar_value = 256*(val-min)/(max-min);
1570 vo_osd_changed(OSDTYPE_PROGBAR);
1571 return;
1574 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1575 name, ROUND(100*(val-min)/(max-min)));
1579 * \brief Display text subtitles on the OSD
1581 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1583 int i;
1584 vo_sub = subs;
1585 vo_osd_changed(OSDTYPE_SUBTITLE);
1586 if (!mpctx->sh_video) {
1587 // reverse order, since newest set_osd_msg is displayed first
1588 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1589 if (!subs || i >= subs->lines || !subs->text[i])
1590 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1591 else {
1592 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1593 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1594 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1601 * \brief Update the OSD message line.
1603 * This function displays the current message on the vo OSD or on the term.
1604 * If the stack is empty and the OSD level is high enough the timer
1605 * is displayed (only on the vo OSD).
1609 static void update_osd_msg(struct MPContext *mpctx)
1611 struct MPOpts *opts = &mpctx->opts;
1612 mp_osd_msg_t *msg;
1613 struct osd_state *osd = mpctx->osd;
1614 char osd_text_timer[128];
1616 if (mpctx->add_osd_seek_info) {
1617 double percentage = get_percent_pos(mpctx);
1618 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1619 if (mpctx->sh_video)
1620 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1621 mpctx->add_osd_seek_info = false;
1624 // Look if we have a msg
1625 if((msg = get_osd_msg(mpctx))) {
1626 if (strcmp(osd->osd_text, msg->msg)) {
1627 strncpy(osd->osd_text, msg->msg, 127);
1628 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1629 if(opts->term_osd)
1630 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1631 msg->msg);
1633 return;
1636 if(mpctx->sh_video) {
1637 // fallback on the timer
1638 if (opts->osd_level >= 2) {
1639 int len = get_time_length(mpctx);
1640 int percentage = -1;
1641 char percentage_text[10];
1642 char fractions_text[4];
1643 double fpts = get_current_time(mpctx);
1644 int pts = fpts;
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_fractions == 1) {
1655 //print fractions as sub-second timestamp
1656 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1657 (int)((fpts - pts) * 100));
1658 } else if (opts->osd_fractions == 2) {
1659 /* Print fractions by estimating the frame count within the
1660 * second.
1662 * Rounding or cutting off numbers after the decimal point
1663 * causes problems because of float's precision and movies
1664 * whose first frame is not exactly at timestamp 0. Therefore,
1665 * we add 0.2 and cut off at the decimal point, which proved
1666 * to be good heuristic.
1668 double fps = mpctx->sh_video->fps;
1669 if (fps <= 1 || fps > 99)
1670 strcpy(fractions_text, ".??");
1671 else
1672 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1673 (int) ( (fpts - pts) * fps + 0.2 ) );
1674 } else {
1675 //do not print fractions
1676 fractions_text[0] = 0;
1679 if (opts->osd_level == 3)
1680 snprintf(osd_text_timer, 63,
1681 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1682 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1683 fractions_text, len/3600, (len/60)%60, len%60,
1684 percentage_text);
1685 else
1686 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s%s",
1687 mpctx->osd_function,pts/3600,(pts/60)%60,
1688 pts%60, fractions_text, percentage_text);
1689 } else
1690 osd_text_timer[0]=0;
1692 if (strcmp(osd->osd_text, osd_text_timer)) {
1693 strncpy(osd->osd_text, osd_text_timer, 63);
1694 vo_osd_changed(OSDTYPE_OSD);
1696 return;
1699 // Clear the term osd line
1700 if (opts->term_osd && osd->osd_text[0]) {
1701 osd->osd_text[0] = 0;
1702 printf("%s\n", opts->term_osd_esc);
1706 ///@}
1707 // OSDMsgStack
1710 void reinit_audio_chain(struct MPContext *mpctx)
1712 struct MPOpts *opts = &mpctx->opts;
1713 if (!mpctx->sh_audio)
1714 return;
1715 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1716 current_module="init_audio_codec";
1717 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1718 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1719 goto init_error;
1721 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1722 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1726 current_module="af_preinit";
1727 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1728 ao_data.samplerate=force_srate;
1729 ao_data.channels=0;
1730 ao_data.format = opts->audio_output_format;
1732 // first init to detect best values
1733 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1734 // input:
1735 mpctx->sh_audio->samplerate,
1736 // output:
1737 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1738 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1739 "pre-init!\n");
1740 exit_player(mpctx, EXIT_ERROR);
1742 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1743 current_module="ao2_init";
1744 ao_data.buffersize = opts->ao_buffersize;
1745 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1746 0, // plugin flag
1747 ao_data.samplerate,
1748 ao_data.channels,
1749 ao_data.format, 0);
1750 if(!mpctx->audio_out){
1751 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1752 goto init_error;
1754 mpctx->initialized_flags|=INITIALIZED_AO;
1755 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1756 mpctx->audio_out->info->short_name,
1757 ao_data.samplerate, ao_data.channels,
1758 af_fmt2str_short(ao_data.format),
1759 af_fmt2bits(ao_data.format)/8 );
1760 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1761 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1762 if(strlen(mpctx->audio_out->info->comment) > 0)
1763 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1766 // init audio filters:
1767 current_module="af_init";
1768 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1769 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1770 goto init_error;
1772 mpctx->mixer.audio_out = mpctx->audio_out;
1773 mpctx->mixer.volstep = volstep;
1774 mpctx->syncing_audio = true;
1775 return;
1777 init_error:
1778 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1779 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1780 mpctx->d_audio->id = -2;
1784 ///@}
1785 // Command2Property
1788 // Return pts value corresponding to the end point of audio written to the
1789 // ao so far.
1790 static double written_audio_pts(struct MPContext *mpctx)
1792 sh_audio_t *sh_audio = mpctx->sh_audio;
1793 demux_stream_t *d_audio = mpctx->d_audio;
1794 double buffered_output;
1795 // first calculate the end pts of audio that has been output by decoder
1796 double a_pts = sh_audio->pts;
1797 if (a_pts != MP_NOPTS_VALUE)
1798 // Good, decoder supports new way of calculating audio pts.
1799 // sh_audio->pts is the timestamp of the latest input packet with
1800 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1801 // the amount of bytes the decoder has written after that timestamp.
1802 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1803 else {
1804 // Decoder doesn't support new way of calculating pts (or we're
1805 // being called before it has decoded anything with known timestamp).
1806 // Use the old method of audio pts calculation: take the timestamp
1807 // of last packet with known pts the decoder has read data from,
1808 // and add amount of bytes read after the beginning of that packet
1809 // divided by input bps. This will be inaccurate if the input/output
1810 // ratio is not constant for every audio packet or if it is constant
1811 // but not accurately known in sh_audio->i_bps.
1813 a_pts = d_audio->pts;
1814 // ds_tell_pts returns bytes read after last timestamp from
1815 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1816 // it has read but not decoded
1817 if (sh_audio->i_bps)
1818 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1819 (double)sh_audio->i_bps;
1821 // Now a_pts hopefully holds the pts for end of audio from decoder.
1822 // Substract data in buffers between decoder and audio out.
1824 // Decoded but not filtered
1825 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1827 // Data buffered in audio filters, measured in bytes of "missing" output
1828 buffered_output = af_calc_delay(sh_audio->afilter);
1830 // Data that was ready for ao but was buffered because ao didn't fully
1831 // accept everything to internal buffers yet
1832 buffered_output += sh_audio->a_out_buffer_len;
1834 // Filters divide audio length by playback_speed, so multiply by it
1835 // to get the length in original units without speedup or slowdown
1836 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1838 return a_pts + mpctx->video_offset;
1841 // Return pts value corresponding to currently playing audio.
1842 double playing_audio_pts(struct MPContext *mpctx)
1844 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1845 mpctx->audio_out->get_delay();
1848 static bool is_av_sub(int type)
1850 return type == 'b' || type == 'p' || type == 'x';
1853 void update_subtitles(struct MPContext *mpctx, double refpts,
1854 double sub_offset, bool reset)
1856 struct MPOpts *opts = &mpctx->opts;
1857 struct sh_video *sh_video = mpctx->sh_video;
1858 struct demux_stream *d_sub = mpctx->d_sub;
1859 double curpts = refpts + sub_delay;
1860 unsigned char *packet=NULL;
1861 int len;
1862 struct sh_sub *sh_sub = d_sub->sh;
1863 int type = sh_sub ? sh_sub->type : 'v';
1864 static subtitle subs;
1865 if (reset) {
1866 if (sh_sub)
1867 sub_reset(sh_sub, mpctx->osd);
1868 sub_clear_text(&subs, MP_NOPTS_VALUE);
1869 if (vo_sub)
1870 set_osd_subtitle(mpctx, NULL);
1871 if (vo_spudec) {
1872 spudec_reset(vo_spudec);
1873 vo_osd_changed(OSDTYPE_SPU);
1875 #ifdef CONFIG_FFMPEG
1876 if (is_av_sub(type))
1877 reset_avsub(sh_sub);
1878 #endif
1879 return;
1881 // find sub
1882 if (mpctx->subdata) {
1883 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1884 current_module = "find_sub";
1885 find_sub(mpctx, mpctx->subdata, curpts *
1886 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1887 if (vo_sub)
1888 mpctx->vo_sub_last = vo_sub;
1891 // DVD sub:
1892 if (vobsub_id >= 0 || type == 'v') {
1893 int timestamp;
1894 current_module = "spudec";
1895 /* Get a sub packet from the DVD or a vobsub */
1896 while(1) {
1897 // Vobsub
1898 len = 0;
1899 if (vo_vobsub) {
1900 if (curpts >= 0) {
1901 len = vobsub_get_packet(vo_vobsub, curpts,
1902 (void**)&packet, &timestamp);
1903 if (len > 0) {
1904 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);
1907 } else {
1908 // DVD sub
1909 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1910 if (len > 0) {
1911 // XXX This is wrong, sh_video->pts can be arbitrarily
1912 // much behind demuxing position. Unfortunately using
1913 // d_video->pts which would have been the simplest
1914 // improvement doesn't work because mpeg specific hacks
1915 // in video.c set d_video->pts to 0.
1916 float x = d_sub->pts - refpts;
1917 if (x > -20 && x < 20) // prevent missing subs on pts reset
1918 timestamp = 90000*d_sub->pts;
1919 else timestamp = 90000*curpts;
1920 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1921 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1922 refpts, d_sub->pts, timestamp);
1925 if (len<=0 || !packet) break;
1926 // create it only here, since with some broken demuxers we might
1927 // type = v but no DVD sub and we currently do not change the
1928 // "original frame size" ever after init, leading to wrong-sized
1929 // PGS subtitles.
1930 if (!vo_spudec)
1931 vo_spudec = spudec_new(NULL);
1932 if (vo_vobsub || timestamp >= 0)
1933 spudec_assemble(vo_spudec, packet, len, timestamp);
1935 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1936 if (type == 'd' && !d_sub->demuxer->teletext) {
1937 tt_stream_props tsp = {0};
1938 void *ptr = &tsp;
1939 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1940 d_sub->demuxer->teletext = ptr;
1942 if (d_sub->non_interleaved)
1943 ds_get_next_pts(d_sub);
1945 while (d_sub->first) {
1946 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1947 if (subpts > curpts) {
1948 // Libass handled subs can be fed to it in advance
1949 if (!opts->ass_enabled || !is_text_sub(type))
1950 break;
1951 // Try to avoid demuxing whole file at once
1952 if (d_sub->non_interleaved && subpts > curpts + 1)
1953 break;
1955 double duration = d_sub->first->duration;
1956 len = ds_get_packet_sub(d_sub, &packet);
1957 if (is_av_sub(type)) {
1958 #ifdef CONFIG_FFMPEG
1959 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
1960 if (ret < 0)
1961 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
1962 "subtitle\n");
1963 #endif
1964 continue;
1966 if (type == 'm') {
1967 if (len < 2) continue;
1968 len = FFMIN(len - 2, AV_RB16(packet));
1969 packet += 2;
1971 if (type == 'd') {
1972 if (d_sub->demuxer->teletext) {
1973 uint8_t *p = packet;
1974 p++;
1975 len--;
1976 while (len >= 46) {
1977 int sublen = p[1];
1978 if (p[0] == 2 || p[0] == 3)
1979 teletext_control(d_sub->demuxer->teletext,
1980 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1981 p += sublen + 2;
1982 len -= sublen + 2;
1985 continue;
1987 if (sh_sub && sh_sub->active) {
1988 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
1989 continue;
1991 if (subpts != MP_NOPTS_VALUE) {
1992 if (duration < 0)
1993 sub_clear_text(&subs, MP_NOPTS_VALUE);
1994 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1995 int i;
1996 unsigned char* p = packet;
1997 for (i=0; i < 8 && *p != '\0'; p++)
1998 if (*p == ',')
1999 i++;
2000 if (*p == '\0') /* Broken line? */
2001 continue;
2002 len -= p - packet;
2003 packet = p;
2005 double endpts = MP_NOPTS_VALUE;
2006 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2007 endpts = subpts + duration;
2008 sub_add_text(&subs, packet, len, endpts);
2009 set_osd_subtitle(mpctx, &subs);
2011 if (d_sub->non_interleaved)
2012 ds_get_next_pts(d_sub);
2014 if (!opts->ass_enabled)
2015 if (sub_clear_text(&subs, curpts))
2016 set_osd_subtitle(mpctx, &subs);
2018 if (vo_spudec) {
2019 spudec_heartbeat(vo_spudec, 90000*curpts);
2020 if (spudec_changed(vo_spudec))
2021 vo_osd_changed(OSDTYPE_SPU);
2024 current_module=NULL;
2027 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2029 int page_changed;
2031 if (!demuxer->teletext)
2032 return;
2034 //Also forcing page update when such ioctl is not supported or call error occured
2035 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2036 page_changed=1;
2038 if(!page_changed)
2039 return;
2041 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2042 vo_osd_teletext_page=NULL;
2043 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2044 vo_osd_teletext_half=0;
2045 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2046 vo_osd_teletext_mode=0;
2047 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2048 vo_osd_teletext_format=0;
2049 vo_osd_changed(OSDTYPE_TELETEXT);
2051 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2054 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2055 struct MPOpts *opts = &mpctx->opts;
2056 // check for frame-drop:
2057 current_module = "check_framedrop";
2058 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2059 static int dropped_frames;
2060 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
2061 float d = delay-mpctx->delay;
2062 ++total_frame_cnt;
2063 // we should avoid dropping too many frames in sequence unless we
2064 // are too late. and we allow 100ms A-V delay here:
2065 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2066 && !mpctx->restart_playback) {
2067 ++drop_frame_cnt;
2068 ++dropped_frames;
2069 return frame_dropping;
2070 } else
2071 dropped_frames = 0;
2073 return 0;
2077 #ifdef HAVE_RTC
2078 int rtc_fd = -1;
2079 #endif
2081 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2083 #ifdef HAVE_RTC
2084 if (rtc_fd >= 0){
2085 // -------- RTC -----------
2086 current_module="sleep_rtc";
2087 while (time_frame > 0.000) {
2088 unsigned long rtc_ts;
2089 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2090 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2091 time_frame -= get_relative_time(mpctx);
2093 } else
2094 #endif
2096 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2097 // unnecessarily high CPU usage
2098 struct MPOpts *opts = &mpctx->opts;
2099 float margin = opts->softsleep ? 0.011 : 0;
2100 current_module = "sleep_timer";
2101 while (time_frame > margin) {
2102 usec_sleep(1000000 * (time_frame - margin));
2103 time_frame -= get_relative_time(mpctx);
2105 if (opts->softsleep){
2106 current_module = "sleep_soft";
2107 if (time_frame < 0)
2108 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2109 while (time_frame > 0)
2110 time_frame -= get_relative_time(mpctx); // burn the CPU
2113 return time_frame;
2116 static int select_subtitle(MPContext *mpctx)
2118 struct MPOpts *opts = &mpctx->opts;
2119 // find the best sub to use
2120 int id;
2121 int found = 0;
2122 mpctx->global_sub_pos = -1; // no subs by default
2123 if (vobsub_id >= 0) {
2124 // if user asks for a vobsub id, use that first.
2125 id = vobsub_id;
2126 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2129 if (!found && opts->sub_id >= 0) {
2130 // if user asks for a dvd sub id, use that next.
2131 id = opts->sub_id;
2132 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2135 if (!found) {
2136 // if there are text subs to use, use those. (autosubs come last here)
2137 id = 0;
2138 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2141 if (!found && opts->sub_id == -1) {
2142 // finally select subs by language and container hints
2143 if (opts->sub_id == -1)
2144 opts->sub_id =
2145 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2146 opts->sub_lang);
2147 if (opts->sub_id >= 0) {
2148 id = opts->sub_id;
2149 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2152 return found;
2155 #ifdef CONFIG_DVDNAV
2156 #ifndef FF_B_TYPE
2157 #define FF_B_TYPE 3
2158 #endif
2159 /// store decoded video image
2160 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2161 mp_image_t *from_mpi) {
2162 mp_image_t *mpi;
2164 /// Do not store B-frames
2165 if (from_mpi->pict_type == FF_B_TYPE)
2166 return to_mpi;
2168 if (to_mpi &&
2169 to_mpi->w == from_mpi->w &&
2170 to_mpi->h == from_mpi->h &&
2171 to_mpi->imgfmt == from_mpi->imgfmt)
2172 mpi = to_mpi;
2173 else {
2174 if (to_mpi)
2175 free_mp_image(to_mpi);
2176 if (from_mpi->w == 0 || from_mpi->h == 0)
2177 return NULL;
2178 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2181 copy_mpi(mpi,from_mpi);
2182 return mpi;
2185 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2186 struct MPOpts *opts = &ctx->opts;
2187 if (ctx->sh_video) {
2188 /// clear video pts
2189 ctx->d_video->pts = 0.0f;
2190 ctx->sh_video->pts = 0.0f;
2191 ctx->sh_video->i_pts = 0.0f;
2192 ctx->sh_video->last_pts = 0.0f;
2193 ctx->sh_video->num_buffered_pts = 0;
2194 ctx->sh_video->num_frames = 0;
2195 ctx->sh_video->num_frames_decoded = 0;
2196 ctx->sh_video->timer = 0.0f;
2197 ctx->sh_video->stream_delay = 0.0f;
2198 ctx->sh_video->timer = 0;
2199 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2202 if (ctx->sh_audio) {
2203 /// free audio packets and reset
2204 ds_free_packs(ctx->d_audio);
2205 audio_delay -= ctx->sh_audio->stream_delay;
2206 ctx->delay =- audio_delay;
2207 ctx->audio_out->reset();
2208 resync_audio_stream(ctx->sh_audio);
2211 audio_delay = 0.0f;
2212 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2213 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2214 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2215 if (dvdsub_lang_id != opts->sub_id) {
2216 opts->sub_id = dvdsub_lang_id;
2217 select_subtitle(ctx);
2221 /// clear all EOF related flags
2222 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2225 /// Restore last decoded DVDNAV (still frame)
2226 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2227 int *in_size,
2228 unsigned char **start,
2229 mp_image_t *decoded_frame)
2231 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2232 return decoded_frame;
2234 /// a change occured in dvdnav stream
2235 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2236 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2237 mp_dvdnav_context_free(mpctx);
2238 mp_dvdnav_reset_stream(mpctx);
2239 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2240 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2243 if (*in_size < 0) {
2244 float len;
2246 /// Display still frame, if any
2247 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2248 decoded_frame = mpctx->nav_smpi;
2250 /// increment video frame : continue playing after still frame
2251 len = get_time_length(mpctx);
2252 if (mpctx->sh_video->pts >= len &&
2253 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2254 mp_dvdnav_skip_still(mpctx->stream);
2255 mp_dvdnav_skip_wait(mpctx->stream);
2257 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2259 if (mpctx->nav_buffer) {
2260 *start = mpctx->nav_start;
2261 *in_size = mpctx->nav_in_size;
2262 if (mpctx->nav_start)
2263 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2267 return decoded_frame;
2270 /// Save last decoded DVDNAV (still frame)
2271 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2272 unsigned char *start,
2273 mp_image_t *decoded_frame)
2275 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2276 return;
2278 free(mpctx->nav_buffer);
2280 mpctx->nav_buffer = malloc(in_size);
2281 mpctx->nav_start = start;
2282 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2283 if (mpctx->nav_buffer)
2284 memcpy(mpctx->nav_buffer,start,in_size);
2286 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2287 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2289 #endif /* CONFIG_DVDNAV */
2291 /* Modify video timing to match the audio timeline. There are two main
2292 * reasons this is needed. First, video and audio can start from different
2293 * positions at beginning of file or after a seek (MPlayer starts both
2294 * immediately even if they have different pts). Second, the file can have
2295 * audio timestamps that are inconsistent with the duration of the audio
2296 * packets, for example two consecutive timestamp values differing by
2297 * one second but only a packet with enough samples for half a second
2298 * of playback between them.
2300 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2302 current_module = "av_sync";
2304 if (!mpctx->sh_audio || mpctx->syncing_audio)
2305 return;
2307 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2308 double v_pts = mpctx->sh_video->pts;
2309 double av_delay = a_pts - v_pts;
2310 // Try to sync vo_flip() so it will *finish* at given time
2311 av_delay += mpctx->last_vo_flip_duration;
2312 av_delay -= audio_delay; // This much pts difference is desired
2314 double change = av_delay * 0.1;
2315 double max_change = default_max_pts_correction >= 0 ?
2316 default_max_pts_correction : frame_time * 0.1;
2317 if (change < -max_change)
2318 change = -max_change;
2319 else if (change > max_change)
2320 change = max_change;
2321 mpctx->delay += change;
2322 mpctx->total_avsync_change += change;
2325 #define ASYNC_PLAY_DONE -3
2326 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2328 struct MPOpts *opts = &mpctx->opts;
2329 sh_audio_t * const sh_audio = mpctx->sh_audio;
2330 int res;
2332 // Timing info may not be set without
2333 res = decode_audio(sh_audio, 1);
2334 if (res < 0)
2335 return res;
2337 int bytes;
2338 bool did_retry = false;
2339 while (1) {
2340 double written_pts = written_audio_pts(mpctx);
2341 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2342 - audio_delay;
2343 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2344 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2346 // ogg demuxers give packets without timing
2347 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2348 if (!did_retry) {
2349 // Try to read more data to see packets that have pts
2350 int res = decode_audio(sh_audio, ao_data.bps);
2351 if (res < 0)
2352 return res;
2353 did_retry = true;
2354 continue;
2356 bytes = 0;
2359 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2360 bytes = 0;
2362 if (bytes > 0)
2363 break;
2365 mpctx->syncing_audio = false;
2366 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2367 int res = decode_audio(sh_audio, a);
2368 bytes += sh_audio->a_out_buffer_len;
2369 if (bytes >= 0) {
2370 memmove(sh_audio->a_out_buffer,
2371 sh_audio->a_out_buffer +
2372 sh_audio->a_out_buffer_len - bytes,
2373 bytes);
2374 sh_audio->a_out_buffer_len = bytes;
2375 if (res < 0)
2376 return res;
2377 return decode_audio(sh_audio, playsize);
2379 sh_audio->a_out_buffer_len = 0;
2380 if (res < 0)
2381 return res;
2383 int fillbyte = 0;
2384 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2385 fillbyte = 0x80;
2386 if (bytes >= playsize) {
2387 /* This case could fall back to the one below with
2388 * bytes = playsize, but then silence would keep accumulating
2389 * in a_out_buffer if the AO accepts less data than it asks for
2390 * in playsize. */
2391 char *p = malloc(playsize);
2392 memset(p, fillbyte, playsize);
2393 playsize = mpctx->audio_out->play(p, playsize, 0);
2394 free(p);
2395 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2396 return ASYNC_PLAY_DONE;
2398 mpctx->syncing_audio = false;
2399 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2400 return decode_audio(sh_audio, playsize);
2403 static int fill_audio_out_buffers(struct MPContext *mpctx)
2405 struct MPOpts *opts = &mpctx->opts;
2406 unsigned int t;
2407 double tt;
2408 int playsize;
2409 int playflags=0;
2410 int audio_eof=0;
2411 bool format_change = false;
2412 sh_audio_t * const sh_audio = mpctx->sh_audio;
2414 current_module="play_audio";
2416 while (1) {
2417 int sleep_time;
2418 // all the current uses of ao_data.pts seem to be in aos that handle
2419 // sync completely wrong; there should be no need to use ao_data.pts
2420 // in get_space()
2421 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2422 playsize = mpctx->audio_out->get_space();
2423 if (mpctx->sh_video || playsize >= ao_data.outburst)
2424 break;
2426 // handle audio-only case:
2427 // this is where mplayer sleeps during audio-only playback
2428 // to avoid 100% CPU use
2429 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2430 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2431 usec_sleep(sleep_time * 1000);
2434 // Fill buffer if needed:
2435 current_module="decode_audio";
2436 t = GetTimer();
2438 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2439 mpctx->syncing_audio = false;
2441 int res;
2442 if (mpctx->syncing_audio && mpctx->sh_video)
2443 res = audio_start_sync(mpctx, playsize);
2444 else
2445 res = decode_audio(sh_audio, playsize);
2446 if (res < 0) { // EOF, error or format change
2447 if (res == -2)
2448 format_change = true;
2449 else if (res == ASYNC_PLAY_DONE)
2450 return 1;
2451 else if (mpctx->d_audio->eof) {
2452 audio_eof = 1;
2453 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2454 if (sh_audio->a_out_buffer_len < unitsize)
2455 return 0;
2458 t = GetTimer() - t;
2459 tt = t*0.000001f; audio_time_usage+=tt;
2460 if (playsize > sh_audio->a_out_buffer_len) {
2461 playsize = sh_audio->a_out_buffer_len;
2462 if (audio_eof)
2463 playflags |= AOPLAY_FINAL_CHUNK;
2465 if (!playsize)
2466 return 1;
2468 // play audio:
2469 current_module="play_audio";
2471 // Is this pts value actually useful for the aos that access it?
2472 // They're obviously badly broken in the way they handle av sync;
2473 // would not having access to this make them more broken?
2474 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2475 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2477 if (playsize > 0) {
2478 sh_audio->a_out_buffer_len -= playsize;
2479 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2480 sh_audio->a_out_buffer_len);
2481 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2482 } else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2483 // Sanity check to avoid hanging in case current ao doesn't output
2484 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2485 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2486 sh_audio->a_out_buffer_len = 0;
2489 /* The format change isn't handled too gracefully. A more precise
2490 * implementation would require draining buffered old-format audio
2491 * while displaying video, then doing the output format switch.
2493 if (format_change) {
2494 uninit_player(mpctx, INITIALIZED_AO);
2495 reinit_audio_chain(mpctx);
2498 return 1;
2501 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2502 float *aq_sleep_time)
2504 struct MPOpts *opts = &mpctx->opts;
2505 double audio_limit = 2;
2506 current_module="calc_sleep_time";
2508 if (mpctx->restart_playback)
2509 return 0;
2511 *time_frame -= get_relative_time(mpctx); // reset timer
2513 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2514 float delay = mpctx->audio_out->get_delay();
2515 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2517 if (opts->autosync) {
2519 * Adjust this raw delay value by calculating the expected
2520 * delay for this frame and generating a new value which is
2521 * weighted between the two. The higher autosync is, the
2522 * closer to the delay value gets to that which "-nosound"
2523 * would have used, and the longer it will take for A/V
2524 * sync to settle at the right value (but it eventually will.)
2525 * This settling time is very short for values below 100.
2527 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2528 float difference = delay - predicted;
2529 delay = predicted + difference / (float)opts->autosync;
2532 *time_frame = delay - mpctx->delay / opts->playback_speed;
2534 // delay = amount of audio buffered in soundcard/driver
2535 delay = FFMIN(delay, 0.5);
2536 delay = FFMAX(delay, 0.1);
2537 audio_limit = delay;
2538 } else {
2539 // If we're lagging more than 200 ms behind the right playback rate,
2540 // don't try to "catch up".
2541 // If benchmark is set always output frames as fast as possible
2542 // without sleeping.
2543 if (*time_frame < -0.2 || opts->benchmark)
2544 *time_frame = 0;
2547 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2549 if (t <= 0.05)
2550 return 0;
2552 t -= 0.05;
2553 if (t > audio_limit * 0.6)
2554 t = audio_limit * 0.5;
2555 *aq_sleep_time += t;
2556 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2557 return 1;
2560 int reinit_video_chain(struct MPContext *mpctx)
2562 struct MPOpts *opts = &mpctx->opts;
2563 sh_video_t * const sh_video = mpctx->sh_video;
2564 double ar=-1.0;
2565 //================== Init VIDEO (codec & libvo) ==========================
2566 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2567 current_module="preinit_libvo";
2569 //shouldn't we set dvideo->id=-2 when we fail?
2570 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2571 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2572 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2573 goto err_out;
2575 mpctx->initialized_flags|=INITIALIZED_VO;
2578 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2579 mpctx->sh_video->stream_aspect = ar;
2580 current_module="init_video_filters";
2582 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2583 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2585 #ifdef CONFIG_MENU
2586 if(use_menu) {
2587 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2588 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2589 if(!vf_menu) {
2590 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2591 use_menu = 0;
2594 if(vf_menu)
2595 sh_video->vfilter = vf_menu;
2596 #endif
2598 #ifdef CONFIG_ASS
2599 if(opts->ass_enabled) {
2600 int i;
2601 int insert = 1;
2602 if (opts->vf_settings)
2603 for (i = 0; opts->vf_settings[i].name; ++i)
2604 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2605 insert = 0;
2606 break;
2608 if (insert) {
2609 extern vf_info_t vf_info_ass;
2610 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2611 char* vf_arg[] = {"auto", "1", NULL};
2612 int retcode = 0;
2613 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2614 sh_video->vfilter,
2615 "ass", vf_arg,
2616 &retcode);
2617 if (vf_ass)
2618 sh_video->vfilter = vf_ass;
2619 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2620 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2621 else
2622 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2625 #endif
2627 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2629 #ifdef CONFIG_ASS
2630 if (opts->ass_enabled)
2631 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2632 #endif
2634 current_module="init_video_codec";
2636 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2637 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2638 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2640 if(!sh_video->initialized){
2641 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2642 goto err_out;
2645 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2647 if (sh_video->codec)
2648 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2650 sh_video->last_pts = MP_NOPTS_VALUE;
2651 sh_video->num_buffered_pts = 0;
2652 sh_video->next_frame_time = 0;
2654 if (opts->auto_quality > 0) {
2655 // Auto quality option enabled
2656 output_quality=get_video_quality_max(sh_video);
2657 if (opts->auto_quality > output_quality)
2658 opts->auto_quality = output_quality;
2659 else
2660 output_quality = opts->auto_quality;
2661 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2662 set_video_quality(sh_video,output_quality);
2665 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2667 current_module="init_vo";
2669 return 1;
2671 err_out:
2672 mpctx->sh_video = mpctx->d_video->sh = NULL;
2673 return 0;
2676 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2678 struct sh_video *sh_video = mpctx->sh_video;
2679 double frame_time = 0;
2680 struct vo *video_out = mpctx->video_out;
2681 while (1) {
2682 current_module = "filter_video";
2683 // In nocorrect-pts mode there is no way to properly time these frames
2684 if (vo_get_buffered_frame(video_out, 0) >= 0)
2685 break;
2686 if (vf_output_queued_frame(sh_video->vfilter))
2687 break;
2688 unsigned char *packet = NULL;
2689 frame_time = sh_video->next_frame_time;
2690 if (mpctx->restart_playback)
2691 frame_time = 0;
2692 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2693 &packet, force_fps);
2694 if (in_size < 0) {
2695 #ifdef CONFIG_DVDNAV
2696 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2697 if (mp_dvdnav_is_eof(mpctx->stream))
2698 return -1;
2699 if (mpctx->d_video)
2700 mpctx->d_video->eof = 0;
2701 if (mpctx->d_audio)
2702 mpctx->d_audio->eof = 0;
2703 mpctx->stream->eof = 0;
2704 } else
2705 #endif
2706 return -1;
2708 if (in_size > max_framesize)
2709 max_framesize = in_size;
2710 sh_video->timer += frame_time;
2711 if (mpctx->sh_audio)
2712 mpctx->delay -= frame_time;
2713 // video_read_frame can change fps (e.g. for ASF video)
2714 vo_fps = sh_video->fps;
2715 int framedrop_type = check_framedrop(mpctx, frame_time);
2716 current_module = "decode video";
2718 void *decoded_frame;
2719 #ifdef CONFIG_DVDNAV
2720 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2721 if (in_size >= 0 && !decoded_frame)
2722 #endif
2723 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2724 sh_video->pts);
2725 #ifdef CONFIG_DVDNAV
2726 // Save last still frame for future display
2727 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2728 #endif
2729 if (decoded_frame) {
2730 current_module = "filter video";
2731 filter_video(sh_video, decoded_frame, sh_video->pts);
2733 break;
2735 return frame_time;
2738 static void determine_frame_pts(struct MPContext *mpctx)
2740 struct sh_video *sh_video = mpctx->sh_video;
2741 struct MPOpts *opts = &mpctx->opts;
2743 if (opts->user_pts_assoc_mode) {
2744 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2745 } else if (sh_video->pts_assoc_mode == 0) {
2746 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2747 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2748 sh_video->pts_assoc_mode = 1;
2749 else
2750 sh_video->pts_assoc_mode = 2;
2751 } else {
2752 int probcount1 = sh_video->num_reordered_pts_problems;
2753 int probcount2 = sh_video->num_sorted_pts_problems;
2754 if (sh_video->pts_assoc_mode == 2) {
2755 int tmp = probcount1;
2756 probcount1 = probcount2;
2757 probcount2 = tmp;
2759 if (probcount1 >= probcount2 * 1.5 + 2) {
2760 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2761 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2762 "%d.\n", sh_video->pts_assoc_mode);
2765 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2766 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2769 static double update_video(struct MPContext *mpctx)
2771 struct sh_video *sh_video = mpctx->sh_video;
2772 struct vo *video_out = mpctx->video_out;
2773 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2774 mpctx->osd); // hack for vf_expand
2775 if (!mpctx->opts.correct_pts)
2776 return update_video_nocorrect_pts(mpctx);
2778 double pts;
2780 while (1) {
2781 current_module = "filter_video";
2782 if (!mpctx->hrseek_active
2783 && vo_get_buffered_frame(video_out, false) >= 0)
2784 break;
2785 // XXX Time used in this call is not counted in any performance
2786 // timer now
2787 if (vf_output_queued_frame(sh_video->vfilter))
2788 break;
2789 unsigned char *packet = NULL;
2790 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2791 if (pts != MP_NOPTS_VALUE)
2792 pts += mpctx->video_offset;
2793 bool hit_eof = false;
2794 if (in_size < 0) {
2795 // try to extract last frames in case of decoder lag
2796 in_size = 0;
2797 pts = MP_NOPTS_VALUE;
2798 hit_eof = true;
2800 if (in_size > max_framesize)
2801 max_framesize = in_size;
2802 current_module = "decode video";
2803 if (pts >= mpctx->hrseek_pts - .005)
2804 mpctx->hrseek_framedrop = false;
2805 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2806 check_framedrop(mpctx, sh_video->frametime);
2807 void *decoded_frame = decode_video(sh_video, packet, in_size,
2808 framedrop_type, pts);
2809 if (decoded_frame) {
2810 determine_frame_pts(mpctx);
2811 current_module = "filter video";
2812 filter_video(sh_video, decoded_frame, sh_video->pts);
2813 } else if (hit_eof) {
2814 if (vo_get_buffered_frame(video_out, true) < 0)
2815 return -1;
2817 break;
2820 if (!video_out->frame_loaded)
2821 return 0;
2823 pts = video_out->next_pts;
2824 if (pts == MP_NOPTS_VALUE) {
2825 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2826 // Try to use decoder pts from before filters
2827 pts = sh_video->pts;
2828 if (pts == MP_NOPTS_VALUE)
2829 pts = sh_video->last_pts;
2831 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2832 vo_skip_frame(video_out);
2833 return 0;
2835 mpctx->hrseek_active = false;
2836 sh_video->pts = pts;
2837 if (sh_video->last_pts == MP_NOPTS_VALUE)
2838 sh_video->last_pts = sh_video->pts;
2839 else if (sh_video->last_pts > sh_video->pts) {
2840 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2841 sh_video->pts, sh_video->last_pts);
2842 /* If the difference in pts is small treat it as jitter around the
2843 * right value (possibly caused by incorrect timestamp ordering) and
2844 * just show this frame immediately after the last one.
2845 * Treat bigger differences as timestamp resets and start counting
2846 * timing of later frames from the position of this one. */
2847 if (sh_video->last_pts - sh_video->pts > 0.5)
2848 sh_video->last_pts = sh_video->pts;
2849 else
2850 sh_video->pts = sh_video->last_pts;
2852 double frame_time = sh_video->pts - sh_video->last_pts;
2853 sh_video->last_pts = sh_video->pts;
2854 sh_video->timer += frame_time;
2855 if (mpctx->sh_audio)
2856 mpctx->delay -= frame_time;
2857 return frame_time;
2860 void pause_player(struct MPContext *mpctx)
2862 if (mpctx->paused)
2863 return;
2864 mpctx->paused = 1;
2865 mpctx->step_frames = 0;
2866 mpctx->time_frame -= get_relative_time(mpctx);
2868 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2869 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2871 if (mpctx->audio_out && mpctx->sh_audio)
2872 mpctx->audio_out->pause(); // pause audio, keep data if possible
2875 void unpause_player(struct MPContext *mpctx)
2877 if (!mpctx->paused)
2878 return;
2879 mpctx->paused = 0;
2881 if (mpctx->audio_out && mpctx->sh_audio)
2882 mpctx->audio_out->resume(); // resume audio
2883 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2884 && !mpctx->step_frames)
2885 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2886 (void)get_relative_time(mpctx); // ignore time that passed during pause
2889 void add_step_frame(struct MPContext *mpctx)
2891 mpctx->step_frames++;
2892 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2893 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2894 unpause_player(mpctx);
2897 static void pause_loop(struct MPContext *mpctx)
2899 struct MPOpts *opts = &mpctx->opts;
2900 mp_cmd_t* cmd;
2901 #ifdef CONFIG_STREAM_CACHE
2902 int old_cache_fill = stream_cache_size > 0 ?
2903 cache_fill_status(mpctx->stream) : 0;
2904 #endif
2905 if (!opts->quiet) {
2906 if (opts->term_osd && !mpctx->sh_video) {
2907 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
2908 update_osd_msg(mpctx);
2909 } else
2910 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
2911 mp_gtext(" ===== PAUSE ====="));
2912 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2915 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2916 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2917 if (cmd) {
2918 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2919 run_command(mpctx, cmd);
2920 mp_cmd_free(cmd);
2921 continue;
2923 if (mpctx->sh_video && mpctx->video_out)
2924 vo_check_events(mpctx->video_out);
2925 #ifdef CONFIG_MENU
2926 if (vf_menu)
2927 vf_menu_pause_update(vf_menu);
2928 #endif
2929 usec_sleep(20000);
2930 update_osd_msg(mpctx);
2931 int hack = vo_osd_changed(0);
2932 vo_osd_changed(hack);
2933 if (hack)
2934 break;
2935 #ifdef CONFIG_STREAM_CACHE
2936 if (!opts->quiet && stream_cache_size > 0) {
2937 int new_cache_fill = cache_fill_status(mpctx->stream);
2938 if (new_cache_fill != old_cache_fill) {
2939 if (opts->term_osd && !mpctx->sh_video) {
2940 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
2941 mp_gtext(" ===== PAUSE ====="),
2942 new_cache_fill);
2943 update_osd_msg(mpctx);
2944 } else
2945 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
2946 mp_gtext(" ===== PAUSE ====="),
2947 new_cache_fill);
2948 old_cache_fill = new_cache_fill;
2951 #endif
2956 // Find the right mute status and record position for new file position
2957 static void edl_seek_reset(MPContext *mpctx)
2959 mpctx->edl_muted = 0;
2960 next_edl_record = edl_records;
2962 while (next_edl_record) {
2963 if (next_edl_record->start_sec >= get_current_time(mpctx))
2964 break;
2966 if (next_edl_record->action == EDL_MUTE)
2967 mpctx->edl_muted = !mpctx->edl_muted;
2968 next_edl_record = next_edl_record->next;
2970 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2971 mixer_mute(&mpctx->mixer);
2975 // Execute EDL command for the current position if one exists
2976 static void edl_update(MPContext *mpctx)
2978 if (!next_edl_record)
2979 return;
2981 if (!mpctx->sh_video) {
2982 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2983 free_edl(edl_records);
2984 next_edl_record = NULL;
2985 edl_records = NULL;
2986 return;
2989 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2990 if (next_edl_record->action == EDL_SKIP) {
2991 mpctx->osd_function = OSD_FFW;
2992 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2993 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2994 "[%f], length [%f]\n", next_edl_record->start_sec,
2995 next_edl_record->stop_sec, next_edl_record->length_sec);
2997 else if (next_edl_record->action == EDL_MUTE) {
2998 mpctx->edl_muted = !mpctx->edl_muted;
2999 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3000 mixer_mute(&mpctx->mixer);
3001 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3002 next_edl_record->start_sec );
3004 next_edl_record = next_edl_record->next;
3008 static void reinit_decoders(struct MPContext *mpctx)
3010 reinit_video_chain(mpctx);
3011 reinit_audio_chain(mpctx);
3012 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3015 static void seek_reset(struct MPContext *mpctx)
3017 if (mpctx->sh_video) {
3018 current_module = "seek_video_reset";
3019 resync_video_stream(mpctx->sh_video);
3020 mpctx->sh_video->timer = 0;
3021 vo_seek_reset(mpctx->video_out);
3022 mpctx->sh_video->timer = 0;
3023 mpctx->sh_video->num_buffered_pts = 0;
3024 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3025 mpctx->delay = 0;
3026 mpctx->time_frame = 0;
3027 mpctx->restart_playback = true;
3028 // Not all demuxers set d_video->pts during seek, so this value
3029 // (which is used by at least vobsub and edl code below) may
3030 // be completely wrong (probably 0).
3031 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3032 mpctx->video_pts = mpctx->sh_video->pts;
3033 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3034 true);
3035 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3038 if (mpctx->sh_audio) {
3039 current_module = "seek_audio_reset";
3040 resync_audio_stream(mpctx->sh_audio);
3041 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
3042 mpctx->sh_audio->a_buffer_len = 0;
3043 mpctx->sh_audio->a_out_buffer_len = 0;
3044 if (!mpctx->sh_video)
3045 update_subtitles(mpctx, mpctx->sh_audio->pts,
3046 mpctx->video_offset, true);
3049 if (vo_vobsub && mpctx->sh_video) {
3050 current_module = "seek_vobsub_reset";
3051 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3054 edl_seek_reset(mpctx);
3056 mpctx->hrseek_active = false;
3057 mpctx->hrseek_framedrop = false;
3058 mpctx->total_avsync_change = 0;
3059 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3060 drop_frame_cnt = 0;
3062 current_module = NULL;
3065 static bool timeline_set_part(struct MPContext *mpctx, int i)
3067 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3068 struct timeline_part *n = mpctx->timeline + i;
3069 mpctx->timeline_part = i;
3070 mpctx->video_offset = n->start - n->source_start;
3071 if (n->source == p->source)
3072 return false;
3073 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC | INITIALIZED_SUB);
3074 mpctx->demuxer = n->source->demuxer;
3075 mpctx->d_video = mpctx->demuxer->video;
3076 mpctx->d_audio = mpctx->demuxer->audio;
3077 mpctx->d_sub = mpctx->demuxer->sub;
3078 mpctx->sh_video = mpctx->d_video->sh;
3079 mpctx->sh_audio = mpctx->d_audio->sh;
3080 return true;
3083 // Given pts, switch playback to the corresponding part.
3084 // Return offset within that part.
3085 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3086 bool *need_reset)
3088 if (pts < 0)
3089 pts = 0;
3090 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3091 struct timeline_part *p = mpctx->timeline + i;
3092 if (pts < (p+1)->start) {
3093 *need_reset = timeline_set_part(mpctx, i);
3094 return pts - p->start + p->source_start;
3097 return -1;
3101 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3102 static int seek(MPContext *mpctx, struct seek_params seek)
3104 struct MPOpts *opts = &mpctx->opts;
3106 current_module = "seek";
3107 if (mpctx->stop_play == AT_END_OF_FILE)
3108 mpctx->stop_play = KEEP_PLAYING;
3109 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3110 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3111 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3112 || opts->hr_seek > 0 || seek.exact > 0;
3113 if (seek.type == MPSEEK_FACTOR
3114 || seek.type == MPSEEK_ABSOLUTE
3115 && seek.amount < mpctx->last_chapter_pts
3116 || seek.amount < 0)
3117 mpctx->last_chapter_seek = -1;
3118 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3119 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3120 seek.type = MPSEEK_ABSOLUTE;
3122 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3123 && seek.type == MPSEEK_RELATIVE) {
3124 seek.type = MPSEEK_ABSOLUTE;
3125 seek.direction = seek.amount > 0 ? 1 : -1;
3126 seek.amount += get_current_time(mpctx);
3129 /* At least the liba52 decoder wants to read from the input stream
3130 * during initialization, so reinit must be done after the demux_seek()
3131 * call that clears possible stream EOF. */
3132 bool need_reset = false;
3133 double demuxer_amount = seek.amount;
3134 if (mpctx->timeline) {
3135 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3136 &need_reset);
3137 if (demuxer_amount == -1) {
3138 mpctx->stop_play = AT_END_OF_FILE;
3139 // Clear audio from current position
3140 if (mpctx->sh_audio) {
3141 mpctx->audio_out->reset();
3142 mpctx->sh_audio->a_buffer_len = 0;
3143 mpctx->sh_audio->a_out_buffer_len = 0;
3145 return -1;
3148 int demuxer_style = 0;
3149 switch (seek.type) {
3150 case MPSEEK_FACTOR:
3151 demuxer_style |= SEEK_FACTOR; // fallthrough
3152 case MPSEEK_ABSOLUTE:
3153 demuxer_style |= SEEK_ABSOLUTE;
3155 if (hr_seek || seek.direction < 0)
3156 demuxer_style |= SEEK_BACKWARD;
3157 else if (seek.direction > 0)
3158 demuxer_style |= SEEK_FORWARD;
3160 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3161 demuxer_style);
3162 if (need_reset)
3163 reinit_decoders(mpctx);
3164 if (seekresult == 0)
3165 return -1;
3167 seek_reset(mpctx);
3169 /* Use the target time as "current position" for further relative
3170 * seeks etc until a new video frame has been decoded */
3171 if (seek.type == MPSEEK_ABSOLUTE)
3172 mpctx->video_pts = seek.amount;
3174 if (hr_seek) {
3175 mpctx->hrseek_active = true;
3176 mpctx->hrseek_framedrop = true;
3177 mpctx->hrseek_pts = seek.amount;
3180 mpctx->start_timestamp = GetTimerMS();
3182 return 0;
3185 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3186 int exact)
3188 struct seek_params *seek = &mpctx->seek;
3189 switch (type) {
3190 case MPSEEK_RELATIVE:
3191 if (seek->type == MPSEEK_FACTOR)
3192 return; // Well... not common enough to bother doing better
3193 seek->amount += amount;
3194 seek->exact = FFMAX(seek->exact, exact);
3195 if (seek->type == MPSEEK_NONE)
3196 seek->exact = exact;
3197 if (seek->type == MPSEEK_ABSOLUTE)
3198 return;
3199 if (seek->amount == 0) {
3200 *seek = (struct seek_params){0};
3201 return;
3203 seek->type = MPSEEK_RELATIVE;
3204 return;
3205 case MPSEEK_ABSOLUTE:
3206 case MPSEEK_FACTOR:
3207 *seek = (struct seek_params) {
3208 .type = type,
3209 .amount = amount,
3210 .exact = exact,
3212 return;
3213 case MPSEEK_NONE:
3214 *seek = (struct seek_params){0};
3215 return;
3217 abort();
3221 double get_time_length(struct MPContext *mpctx)
3223 if (mpctx->timeline)
3224 return mpctx->timeline[mpctx->num_timeline_parts].start;
3226 struct demuxer *demuxer = mpctx->demuxer;
3227 double get_time_ans;
3228 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3229 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3230 (void *) &get_time_ans) > 0)
3231 return get_time_ans;
3233 struct sh_video *sh_video = mpctx->d_video->sh;
3234 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3235 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3236 return (double) (demuxer->movi_end - demuxer->movi_start) /
3237 (sh_video->i_bps + sh_audio->i_bps);
3238 if (sh_video && sh_video->i_bps)
3239 return (double) (demuxer->movi_end - demuxer->movi_start) /
3240 sh_video->i_bps;
3241 if (sh_audio && sh_audio->i_bps)
3242 return (double) (demuxer->movi_end - demuxer->movi_start) /
3243 sh_audio->i_bps;
3244 return 0;
3247 /* If there are timestamps from stream level then use those (for example
3248 * DVDs can have consistent times there while the MPEG-level timestamps
3249 * reset). */
3250 double get_current_time(struct MPContext *mpctx)
3252 struct demuxer *demuxer = mpctx->demuxer;
3253 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3254 return demuxer->stream_pts;
3255 struct sh_video *sh_video = demuxer->video->sh;
3256 if (sh_video)
3257 return mpctx->video_pts;
3258 return playing_audio_pts(mpctx);
3261 int get_percent_pos(struct MPContext *mpctx)
3263 struct demuxer *demuxer = mpctx->demuxer;
3264 int ans = 0;
3265 if (mpctx->timeline)
3266 ans = get_current_time(mpctx) * 100 /
3267 mpctx->timeline[mpctx->num_timeline_parts].start;
3268 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3270 else {
3271 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3272 off_t pos = demuxer->filepos > 0 ?
3273 demuxer->filepos : stream_tell(demuxer->stream);
3274 if (len > 0)
3275 ans = (pos - demuxer->movi_start) / len;
3276 else
3277 ans = 0;
3279 if (ans < 0)
3280 ans = 0;
3281 if (ans > 100)
3282 ans = 100;
3283 return ans;
3286 // -2 is no chapters, -1 is before first chapter
3287 int get_current_chapter(struct MPContext *mpctx)
3289 double current_pts = get_current_time(mpctx);
3290 if (!mpctx->chapters)
3291 return FFMAX(mpctx->last_chapter_seek,
3292 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3294 int i;
3295 for (i = 1; i < mpctx->num_chapters; i++)
3296 if (current_pts < mpctx->chapters[i].start)
3297 break;
3298 return FFMAX(mpctx->last_chapter_seek, i - 1);
3301 // currently returns a string allocated with malloc, not talloc
3302 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3304 if (!mpctx->chapters || !mpctx->sh_video)
3305 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3306 return strdup(mpctx->chapters[chapter].name);
3309 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3310 char **chapter_name)
3312 mpctx->last_chapter_seek = -1;
3313 if (!mpctx->chapters || !mpctx->sh_video) {
3314 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3315 chapter_name);
3316 if (res >= 0) {
3317 if (*seek_pts == -1)
3318 seek_reset(mpctx);
3319 else {
3320 mpctx->last_chapter_seek = res;
3321 mpctx->last_chapter_pts = *seek_pts;
3324 return res;
3327 if (chapter >= mpctx->num_chapters)
3328 return -1;
3329 if (chapter < 0)
3330 chapter = 0;
3331 *seek_pts = mpctx->chapters[chapter].start;
3332 mpctx->last_chapter_seek = chapter;
3333 mpctx->last_chapter_pts = *seek_pts;
3334 if (chapter_name)
3335 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3336 return chapter;
3340 static void run_playloop(struct MPContext *mpctx)
3342 struct MPOpts *opts = &mpctx->opts;
3343 float aq_sleep_time = 0;
3345 if (opts->chapterrange[1] > 0) {
3346 int cur_chapter = get_current_chapter(mpctx);
3347 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3348 mpctx->stop_play = PT_NEXT_ENTRY;
3351 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3352 mpctx->sh_audio = mpctx->d_audio->sh;
3353 mpctx->sh_audio->ds = mpctx->d_audio;
3354 reinit_audio_chain(mpctx);
3357 /*========================== PLAY AUDIO ============================*/
3359 if (mpctx->sh_audio && !mpctx->paused
3360 && (!mpctx->restart_playback || !mpctx->sh_video))
3361 if (!fill_audio_out_buffers(mpctx))
3362 // at eof, all audio at least written to ao
3363 if (!mpctx->sh_video)
3364 mpctx->stop_play = AT_END_OF_FILE;
3367 if (!mpctx->sh_video) {
3368 mpctx->restart_playback = false;
3369 if (mpctx->step_frames) {
3370 mpctx->step_frames = 0;
3371 pause_player(mpctx);
3373 // handle audio-only case:
3374 double a_pos = 0;
3375 // sh_audio can be NULL due to video stream switching
3376 // TODO: handle this better
3377 if (mpctx->sh_audio)
3378 a_pos = playing_audio_pts(mpctx);
3380 print_status(mpctx, a_pos, false);
3382 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3383 mpctx->stop_play = PT_NEXT_ENTRY;
3384 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3385 update_osd_msg(mpctx);
3386 } else {
3388 /*========================== PLAY VIDEO ============================*/
3390 vo_pts = mpctx->sh_video->timer * 90000.0;
3391 vo_fps = mpctx->sh_video->fps;
3393 bool blit_frame = mpctx->video_out->frame_loaded;
3394 if (!blit_frame || mpctx->hrseek_active) {
3395 double frame_time = update_video(mpctx);
3396 blit_frame = mpctx->video_out->frame_loaded;
3397 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3398 if (mpctx->sh_video->vf_initialized < 0) {
3399 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3400 "\nFATAL: Could not initialize video filters (-vf) "
3401 "or video output (-vo).\n");
3402 mpctx->stop_play = PT_NEXT_ENTRY;
3403 return;
3405 if (frame_time < 0)
3406 mpctx->stop_play = AT_END_OF_FILE;
3407 else if (!mpctx->restart_playback) {
3408 mpctx->time_frame += frame_time / opts->playback_speed;
3409 adjust_sync(mpctx, frame_time);
3412 if (mpctx->timeline) {
3413 struct timeline_part *next =
3414 mpctx->timeline + mpctx->timeline_part + 1;
3415 if (mpctx->sh_video->pts >= next->start
3416 || mpctx->stop_play == AT_END_OF_FILE
3417 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3418 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3419 .amount = next->start });
3420 return;
3424 // ==========================================================================
3426 current_module = "vo_check_events";
3427 vo_check_events(mpctx->video_out);
3429 #ifdef CONFIG_X11
3430 if (stop_xscreensaver) {
3431 current_module = "stop_xscreensaver";
3432 xscreensaver_heartbeat(mpctx->x11_state);
3434 #endif
3435 if (heartbeat_cmd) {
3436 static unsigned last_heartbeat;
3437 unsigned now = GetTimerMS();
3438 if (now - last_heartbeat > 30000) {
3439 last_heartbeat = now;
3440 system(heartbeat_cmd);
3444 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3445 &mpctx->time_frame,
3446 &aq_sleep_time);
3448 //====================== FLIP PAGE (VIDEO BLT): =========================
3450 current_module = "flip_page";
3451 if (!frame_time_remaining && blit_frame) {
3452 struct sh_video *sh_video = mpctx->sh_video;
3453 mpctx->video_pts = sh_video->pts;
3454 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3455 update_teletext(sh_video, mpctx->demuxer, 0);
3456 update_osd_msg(mpctx);
3457 struct vf_instance *vf = sh_video->vfilter;
3458 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3459 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3460 vo_osd_changed(0);
3462 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3463 aq_sleep_time += mpctx->time_frame;
3464 // flag 256 means: libvo driver does its timing (dvb card)
3465 if (mpctx->time_frame > 0.001
3466 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3467 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3468 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3470 unsigned int t2 = GetTimer();
3471 /* Playing with playback speed it's possible to get pathological
3472 * cases with mpctx->time_frame negative enough to cause an
3473 * overflow in pts_us calculation, thus the FFMAX. */
3474 double time_frame = FFMAX(mpctx->time_frame, -1);
3475 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3476 int duration = -1;
3477 double pts2 = mpctx->video_out->next_pts2;
3478 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3479 && !mpctx->restart_playback) {
3480 // expected A/V sync correction is ignored
3481 double diff = (pts2 - mpctx->video_pts);
3482 diff /= opts->playback_speed;
3483 if (mpctx->time_frame < 0)
3484 diff += mpctx->time_frame;
3485 if (diff < 0)
3486 diff = 0;
3487 if (diff > 10)
3488 diff = 10;
3489 duration = diff * 1e6;
3491 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3493 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3494 vout_time_usage += mpctx->last_vo_flip_duration;
3495 if (mpctx->video_out->driver->flip_page_timed) {
3496 // No need to adjust sync based on flip speed
3497 mpctx->last_vo_flip_duration = 0;
3498 // For print_status - VO call finishing early is OK for sync
3499 mpctx->time_frame -= get_relative_time(mpctx);
3501 if (mpctx->restart_playback) {
3502 mpctx->syncing_audio = true;
3503 if (mpctx->sh_audio && !mpctx->paused)
3504 fill_audio_out_buffers(mpctx);
3505 mpctx->restart_playback = false;
3506 mpctx->time_frame = 0;
3507 get_relative_time(mpctx);
3509 print_status(mpctx, MP_NOPTS_VALUE, true);
3510 } else
3511 print_status(mpctx, MP_NOPTS_VALUE, false);
3513 //============================ Auto QUALITY ============================
3515 /*Output quality adjustments:*/
3516 if (opts->auto_quality > 0) {
3517 current_module = "autoq";
3518 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3519 ++output_quality;
3520 else
3521 if (output_quality>1 && aq_sleep_time<0)
3522 --output_quality;
3523 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3524 output_quality = 0;
3525 set_video_quality(mpctx->sh_video, output_quality);
3528 if (!frame_time_remaining && blit_frame) {
3529 if (play_n_frames >= 0) {
3530 --play_n_frames;
3531 if (play_n_frames <= 0)
3532 mpctx->stop_play = PT_NEXT_ENTRY;
3534 if (mpctx->step_frames > 0) {
3535 mpctx->step_frames--;
3536 if (mpctx->step_frames == 0)
3537 pause_player(mpctx);
3541 // FIXME: add size based support for -endpos
3542 if (end_at.type == END_AT_TIME &&
3543 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3544 mpctx->stop_play = PT_NEXT_ENTRY;
3546 } // end if(mpctx->sh_video)
3548 #ifdef CONFIG_DVDNAV
3549 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3550 nav_highlight_t hl;
3551 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3552 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3553 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3554 vo_osd_changed(OSDTYPE_DVDNAV);
3555 } else {
3556 osd_set_nav_box(0, 0, 0, 0);
3557 vo_osd_changed(OSDTYPE_DVDNAV);
3558 vo_osd_changed(OSDTYPE_SPU);
3561 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3562 double ar = -1.0;
3563 if (mpctx->sh_video &&
3564 stream_control(mpctx->demuxer->stream,
3565 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3566 != STREAM_UNSUPPORTED)
3567 mpctx->sh_video->stream_aspect = ar;
3570 #endif
3572 //================= Keyboard events, SEEKing ====================
3574 current_module = "key_events";
3576 while (1) {
3577 mp_cmd_t *cmd;
3578 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3579 /* Allow running consecutive seek commands to combine them,
3580 * but execute the seek before running other commands.
3581 * If the user seeks continuously (keeps arrow key down)
3582 * try to finish showing a frame from one location before doing
3583 * another seek (which could lead to unchanging display). */
3584 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3585 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3586 && GetTimerMS() - mpctx->start_timestamp < 300)
3587 break;
3588 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3589 run_command(mpctx, cmd);
3590 mp_cmd_free(cmd);
3591 if (mpctx->stop_play)
3592 break;
3594 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3595 || mpctx->restart_playback)
3596 break;
3597 if (mpctx->sh_video) {
3598 update_osd_msg(mpctx);
3599 int hack = vo_osd_changed(0);
3600 vo_osd_changed(hack);
3601 if (hack) {
3602 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3603 add_step_frame(mpctx);
3604 break;
3605 } else
3606 vo_osd_changed(0);
3609 pause_loop(mpctx);
3612 // handle -sstep
3613 if (step_sec > 0 && !mpctx->paused) {
3614 mpctx->osd_function = OSD_FFW;
3615 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3618 edl_update(mpctx);
3620 /* Looping. */
3621 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3622 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3624 if (opts->loop_times>1)
3625 opts->loop_times--;
3626 else if (opts->loop_times==1)
3627 opts->loop_times = -1;
3628 play_n_frames = play_n_frames_mf;
3629 mpctx->stop_play = 0;
3630 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3633 if (mpctx->seek.type) {
3634 seek(mpctx, mpctx->seek);
3635 mpctx->seek = (struct seek_params){0};
3640 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3641 struct content_source *sources,
3642 int num_sources,
3643 unsigned char uid_map[][16])
3645 int num_filenames = 0;
3646 char **filenames = NULL;
3647 if (num_sources > 1) {
3648 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3649 "other sources.\n");
3650 if (mpctx->stream->type != STREAMTYPE_FILE) {
3651 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3652 "normal disk file. Will not search for related files.\n");
3653 } else {
3654 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3655 "same directory to find referenced sources.\n");
3656 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3657 &num_filenames);
3661 int num_left = num_sources - 1;
3662 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3663 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3664 filename_recode(filenames[i]));
3665 int format;
3666 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3667 if (!s)
3668 continue;
3669 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3670 mpctx->opts.audio_id,
3671 mpctx->opts.video_id,
3672 mpctx->opts.sub_id, filenames[i]);
3673 if (!d) {
3674 free_stream(s);
3675 continue;
3677 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3678 for (int i = 1; i < num_sources; i++) {
3679 if (sources[i].demuxer)
3680 continue;
3681 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3682 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3683 i, filename_recode(d->filename));
3684 sources[i].stream = s;
3685 sources[i].demuxer = d;
3686 num_left--;
3687 goto match;
3691 free_demuxer(d);
3692 free_stream(s);
3693 continue;
3694 match:
3697 talloc_free(filenames);
3698 if (num_left) {
3699 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3700 "There will be parts MISSING from the video!\n");
3701 for (int i = 1, j = 1; i < num_sources; i++)
3702 if (sources[i].demuxer) {
3703 sources[j] = sources[i];
3704 memcpy(uid_map[j], uid_map[i], 16);
3705 j++;
3708 return num_sources - num_left;
3711 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3713 struct MPOpts *opts = &mpctx->opts;
3715 if (!opts->ordered_chapters) {
3716 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3717 "you have disabled support for them. Ignoring.\n");
3718 return;
3721 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3722 "edit timeline.\n");
3724 struct demuxer *demuxer = mpctx->demuxer;
3725 struct matroska_data *m = &demuxer->matroska_data;
3727 // +1 because sources/uid_map[0] is original file even if all chapters
3728 // actually use other sources and need separate entries
3729 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3730 m->num_ordered_chapters+1);
3731 sources[0].stream = mpctx->stream;
3732 sources[0].demuxer = mpctx->demuxer;
3733 unsigned char uid_map[m->num_ordered_chapters+1][16];
3734 int num_sources = 1;
3735 memcpy(uid_map[0], m->segment_uid, 16);
3737 for (int i = 0; i < m->num_ordered_chapters; i++) {
3738 struct matroska_chapter *c = m->ordered_chapters + i;
3739 if (!c->has_segment_uid)
3740 memcpy(c->segment_uid, m->segment_uid, 16);
3742 for (int j = 0; j < num_sources; j++)
3743 if (!memcmp(c->segment_uid, uid_map[j], 16))
3744 goto found1;
3745 memcpy(uid_map[num_sources], c->segment_uid, 16);
3746 sources[num_sources] = (struct content_source){};
3747 num_sources++;
3748 found1:
3752 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3753 uid_map);
3756 // +1 for terminating chapter with start time marking end of last real one
3757 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3758 m->num_ordered_chapters + 1);
3759 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3760 m->num_ordered_chapters);
3761 uint64_t starttime = 0;
3762 uint64_t missing_time = 0;
3763 int part_count = 0;
3764 int num_chapters = 0;
3765 uint64_t prev_part_offset = 0;
3766 for (int i = 0; i < m->num_ordered_chapters; i++) {
3767 struct matroska_chapter *c = m->ordered_chapters + i;
3769 int j;
3770 for (j = 0; j < num_sources; j++) {
3771 if (!memcmp(c->segment_uid, uid_map[j], 16))
3772 goto found2;
3774 missing_time += c->end - c->start;
3775 continue;
3776 found2:;
3777 /* Only add a separate part if the time or file actually changes.
3778 * Matroska files have chapter divisions that are redundant from
3779 * timeline point of view because the same chapter structure is used
3780 * both to specify the timeline and for normal chapter information.
3781 * Removing a missing inserted external chapter can also cause this.
3782 * We allow for a configurable fudge factor because of files which
3783 * specify chapter end times that are one frame too early;
3784 * we don't want to try seeking over a one frame gap. */
3785 int64_t join_diff = c->start - starttime - prev_part_offset;
3786 if (part_count == 0
3787 || FFABS(join_diff) > opts->chapter_merge_threshold * 1000000
3788 || sources + j != timeline[part_count - 1].source) {
3789 timeline[part_count].source = sources + j;
3790 timeline[part_count].start = starttime / 1e9;
3791 timeline[part_count].source_start = c->start / 1e9;
3792 prev_part_offset = c->start - starttime;
3793 part_count++;
3794 } else if (part_count > 0 && join_diff) {
3795 /* Chapter was merged at an inexact boundary;
3796 * adjust timestamps to match. */
3797 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3798 "offset %d ms.\n", i, (int) join_diff);
3799 starttime += join_diff;
3801 chapters[num_chapters].start = starttime / 1e9;
3802 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3803 starttime += c->end - c->start;
3804 num_chapters++;
3806 timeline[part_count].start = starttime / 1e9;
3808 if (!part_count) {
3809 // None of the parts come from the file itself???
3810 talloc_free(sources);
3811 talloc_free(timeline);
3812 talloc_free(chapters);
3813 return;
3816 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3817 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3818 timeline[part_count].start);
3819 if (missing_time)
3820 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3821 "from the timeline!\n", missing_time / 1e9);
3822 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3823 for (int i = 0; i < num_sources; i++)
3824 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3825 filename_recode(sources[i].demuxer->filename));
3826 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3827 "source_start, source):\n");
3828 for (int i = 0; i < part_count; i++) {
3829 struct timeline_part *p = timeline + i;
3830 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3831 p->source_start, p->source - sources);
3833 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3834 mpctx->sources = sources;
3835 mpctx->num_sources = num_sources;
3836 mpctx->timeline = timeline;
3837 mpctx->num_timeline_parts = part_count;
3838 mpctx->num_chapters = num_chapters;
3839 mpctx->chapters = chapters;
3841 mpctx->timeline_part = 0;
3842 mpctx->demuxer = timeline[0].source->demuxer;
3846 static int read_keys(void *ctx, int fd)
3848 getch2(ctx);
3849 return mplayer_get_key(ctx, 0);
3852 static bool attachment_is_font(struct demux_attachment *att)
3854 if (!att->name || !att->type || !att->data || !att->data_size)
3855 return false;
3856 // match against MIME types
3857 if (strcmp(att->type, "application/x-truetype-font") == 0
3858 || strcmp(att->type, "application/x-font") == 0)
3859 return true;
3860 // fallback: match against file extension
3861 if (strlen(att->name) > 4) {
3862 char *ext = att->name + strlen(att->name) - 4;
3863 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3864 || strcasecmp(ext, ".otf") == 0)
3865 return true;
3867 return false;
3870 static int select_audio(demuxer_t *demuxer, int audio_id, char *audio_lang)
3872 if (audio_id == -1)
3873 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3874 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3875 demuxer_switch_audio(demuxer, audio_id);
3876 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3877 demuxer->audio->id = -2;
3878 demuxer->audio->sh = NULL;
3880 return demuxer->audio->id;
3883 static void print_version(const char* name)
3885 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3887 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3888 GetCpuCaps(&gCpuCaps);
3889 #if ARCH_X86
3890 mp_msg(MSGT_CPLAYER, MSGL_V,
3891 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3892 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3893 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3894 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3895 #if CONFIG_RUNTIME_CPUDETECT
3896 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3897 #else
3898 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3899 if (HAVE_MMX)
3900 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3901 if (HAVE_MMX2)
3902 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3903 if (HAVE_AMD3DNOW)
3904 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3905 if (HAVE_AMD3DNOWEXT)
3906 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3907 if (HAVE_SSE)
3908 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3909 if (HAVE_SSE2)
3910 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3911 if (HAVE_SSSE3)
3912 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3913 if (HAVE_CMOV)
3914 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3915 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3916 #endif /* CONFIG_RUNTIME_CPUDETECT */
3917 #endif /* ARCH_X86 */
3920 #ifdef PTW32_STATIC_LIB
3921 static void detach_ptw32(void)
3923 pthread_win32_thread_detach_np();
3924 pthread_win32_process_detach_np();
3926 #endif
3928 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3929 * file for some tools to link against. */
3930 #ifndef DISABLE_MAIN
3931 int main(int argc,char* argv[]){
3932 #ifdef PTW32_STATIC_LIB
3933 pthread_win32_process_attach_np();
3934 pthread_win32_thread_attach_np();
3935 atexit(detach_ptw32);
3936 #endif
3937 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3938 talloc_enable_leak_report();
3940 char * mem_ptr;
3942 // movie info:
3944 /* Flag indicating whether MPlayer should exit without playing anything. */
3945 int opt_exit = 0;
3946 int i;
3948 struct MPContext *mpctx = &(struct MPContext){
3949 .osd_function = OSD_PLAY,
3950 .begin_skip = MP_NOPTS_VALUE,
3951 .play_tree_step = 1,
3952 .global_sub_pos = -1,
3953 .set_of_sub_pos = -1,
3954 .file_format = DEMUXER_TYPE_UNKNOWN,
3955 .last_dvb_step = 1,
3958 InitTimer();
3959 srand(GetTimerMS());
3961 mp_msg_init();
3962 set_av_log_callback();
3964 #ifdef CONFIG_X11
3965 mpctx->x11_state = vo_x11_init_state();
3966 #endif
3967 struct MPOpts *opts = &mpctx->opts;
3968 set_default_mplayer_options(opts);
3969 // Create the config context and register the options
3970 mpctx->mconfig = m_config_new(opts, cfg_include);
3971 m_config_register_options(mpctx->mconfig,mplayer_opts);
3972 m_config_register_options(mpctx->mconfig, common_opts);
3973 mp_input_register_options(mpctx->mconfig);
3975 // Preparse the command line
3976 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3978 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3979 set_path_env();
3980 #endif
3982 #ifdef CONFIG_TV
3983 stream_tv_defaults.immediate = 1;
3984 #endif
3986 parse_cfgfiles(mpctx, mpctx->mconfig);
3988 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3989 if(mpctx->playtree == NULL)
3990 opt_exit = 1;
3991 else {
3992 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3993 if(mpctx->playtree) {
3994 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3995 if(mpctx->playtree_iter) {
3996 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3997 play_tree_iter_free(mpctx->playtree_iter);
3998 mpctx->playtree_iter = NULL;
4000 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
4004 mpctx->key_fifo = mp_fifo_create(opts);
4006 print_version("MPlayer2");
4008 #if defined(__MINGW32__) || defined(__CYGWIN__)
4010 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
4011 BOOL WINAPI (*setDEP)(DWORD) = NULL;
4012 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
4013 if (kernel32) {
4014 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
4015 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
4017 if (setDEP) setDEP(3);
4018 if (setDllDir) setDllDir("");
4020 // stop Windows from showing all kinds of annoying error dialogs
4021 SetErrorMode(0x8003);
4022 // request 1ms timer resolution
4023 timeBeginPeriod(1);
4024 #endif
4026 #ifdef CONFIG_PRIORITY
4027 set_priority();
4028 #endif
4030 if (codec_path)
4031 set_codec_path(codec_path);
4033 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
4034 list_video_out();
4035 opt_exit = 1;
4038 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
4039 list_audio_out();
4040 opt_exit = 1;
4043 /* Check codecs.conf. */
4044 if(!codecs_file || !parse_codec_cfg(codecs_file)){
4045 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
4046 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
4047 if(!parse_codec_cfg(NULL)){
4048 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4050 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
4053 free( mem_ptr ); // release the buffer created by get_path()
4056 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
4057 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4058 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4059 list_codecs(1);
4060 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4061 opt_exit = 1;
4063 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
4064 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4065 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4066 list_codecs(0);
4067 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4068 opt_exit = 1;
4070 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
4071 vfm_help();
4072 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4073 opt_exit = 1;
4075 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
4076 afm_help();
4077 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4078 opt_exit = 1;
4080 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
4081 af_help();
4082 printf("\n");
4083 opt_exit = 1;
4085 #ifdef CONFIG_X11
4086 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
4087 fstype_help();
4088 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4089 opt_exit = 1;
4091 #endif
4092 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
4093 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
4094 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
4095 demuxer_help();
4096 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4097 opt_exit = 1;
4099 if (opts->list_properties) {
4100 property_print_help();
4101 opt_exit = 1;
4104 if(opt_exit)
4105 exit_player(mpctx, EXIT_NONE);
4107 if (!mpctx->filename && !opts->player_idle_mode) {
4108 // no file/vcd/dvd -> show HELP:
4109 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4110 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4113 /* Display what configure line was used */
4114 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4116 // Many users forget to include command line in bugreports...
4117 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
4118 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4119 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
4120 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4123 //------ load global data first ------
4125 mpctx->osd = osd_create();
4127 // check font
4128 #ifdef CONFIG_FREETYPE
4129 init_freetype();
4130 #endif
4131 #ifdef CONFIG_FONTCONFIG
4132 if(font_fontconfig <= 0)
4134 #endif
4135 #ifdef CONFIG_BITMAP_FONT
4136 if(font_name){
4137 vo_font=read_font_desc(font_name,font_factor,verbose>1);
4138 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
4139 filename_recode(font_name));
4140 } else {
4141 // try default:
4142 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
4143 free(mem_ptr); // release the buffer created by get_path()
4144 if(!vo_font)
4145 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
4147 if (sub_font_name)
4148 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
4149 else
4150 mpctx->osd->sub_font = vo_font;
4151 #endif
4152 #ifdef CONFIG_FONTCONFIG
4154 #endif
4156 #ifdef CONFIG_ASS
4157 ass_library = mp_ass_init();
4158 #endif
4160 #ifdef HAVE_RTC
4161 if(opts->rtc)
4163 char *rtc_device = opts->rtc_device;
4164 // seteuid(0); /* Can't hurt to try to get root here */
4165 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4166 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4167 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4168 else {
4169 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4171 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4172 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4173 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4174 close (rtc_fd);
4175 rtc_fd = -1;
4176 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4177 /* variable only by the root */
4178 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4179 close (rtc_fd);
4180 rtc_fd = -1;
4181 } else
4182 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4185 if(rtc_fd<0)
4186 #endif /* HAVE_RTC */
4187 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4188 opts->softsleep ? "software" : timer_name);
4190 #ifdef HAVE_TERMCAP
4191 load_termcap(NULL); // load key-codes
4192 #endif
4194 // ========== Init keyboard FIFO (connection to libvo) ============
4196 // Init input system
4197 current_module = "init_input";
4198 mpctx->input = mp_input_init(&opts->input);
4199 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4200 if(slave_mode)
4201 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4202 else if (opts->consolecontrols)
4203 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4204 // Set the libstream interrupt callback
4205 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4207 #ifdef CONFIG_MENU
4208 if(use_menu) {
4209 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4210 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4211 else {
4212 menu_cfg = get_path("menu.conf");
4213 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4214 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4215 else {
4216 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4217 MPLAYER_CONFDIR "/menu.conf"))
4218 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4219 else {
4220 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4221 use_menu = 0;
4226 #endif
4228 current_module = NULL;
4230 /// Catch signals
4231 #ifndef __MINGW32__
4232 signal(SIGCHLD,child_sighandler);
4233 #endif
4235 #ifdef CONFIG_CRASH_DEBUG
4236 prog_path = argv[0];
4237 #endif
4238 //========= Catch terminate signals: ================
4239 // terminate requests:
4240 signal(SIGTERM,exit_sighandler); // kill
4241 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4243 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4245 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4246 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4247 #ifdef CONFIG_SIGHANDLER
4248 // fatal errors:
4249 signal(SIGBUS,exit_sighandler); // bus error
4250 signal(SIGSEGV,exit_sighandler); // segfault
4251 signal(SIGILL,exit_sighandler); // illegal instruction
4252 signal(SIGFPE,exit_sighandler); // floating point exc.
4253 signal(SIGABRT,exit_sighandler); // abort()
4254 #ifdef CONFIG_CRASH_DEBUG
4255 if (crash_debug)
4256 signal(SIGTRAP,exit_sighandler);
4257 #endif
4258 #endif
4260 // ******************* Now, let's see the per-file stuff ********************
4262 play_next_file:
4264 // init global sub numbers
4265 mpctx->global_sub_size = 0;
4266 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4268 if (mpctx->filename) {
4269 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4270 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4271 load_per_file_config (mpctx->mconfig, mpctx->filename);
4274 if (opts->video_driver_list)
4275 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4276 if (opts->audio_driver_list)
4277 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4279 // We must enable getch2 here to be able to interrupt network connection
4280 // or cache filling
4281 if (opts->consolecontrols && !slave_mode) {
4282 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4283 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4284 else
4285 getch2_enable(); // prepare stdin for hotkeys...
4286 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4287 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4290 // =================== GUI idle loop (STOP state) ===========================
4291 while (opts->player_idle_mode && !mpctx->filename) {
4292 play_tree_t * entry = NULL;
4293 mp_cmd_t * cmd;
4294 if (mpctx->video_out && mpctx->video_out->config_ok)
4295 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4296 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4297 if (mpctx->video_out)
4298 vo_check_events(mpctx->video_out);
4299 usec_sleep(20000);
4301 switch (cmd->id) {
4302 case MP_CMD_LOADFILE:
4303 // prepare a tree entry with the new filename
4304 entry = play_tree_new();
4305 play_tree_add_file(entry, cmd->args[0].v.s);
4306 // The entry is added to the main playtree after the switch().
4307 break;
4308 case MP_CMD_LOADLIST:
4309 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4310 break;
4311 case MP_CMD_QUIT:
4312 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4313 break;
4314 case MP_CMD_VO_FULLSCREEN:
4315 case MP_CMD_GET_PROPERTY:
4316 case MP_CMD_SET_PROPERTY:
4317 case MP_CMD_STEP_PROPERTY:
4318 run_command(mpctx, cmd);
4319 break;
4322 mp_cmd_free(cmd);
4324 if (entry) { // user entered a command that gave a valid entry
4325 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4326 play_tree_free_list(mpctx->playtree->child, 1);
4327 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4329 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4331 play_tree_set_child(mpctx->playtree, entry);
4333 /* Make iterator start at the top the of tree. */
4334 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4335 if (!mpctx->playtree_iter) continue;
4337 // find the first real item in the tree
4338 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4339 // no items!
4340 play_tree_iter_free(mpctx->playtree_iter);
4341 mpctx->playtree_iter = NULL;
4342 continue; // wait for next command
4344 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4347 //---------------------------------------------------------------------------
4349 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4350 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4352 if (mpctx->filename) {
4353 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4354 filename_recode(mpctx->filename));
4355 if(use_filename_title && opts->vo_wintitle == NULL)
4356 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4359 if (edl_filename) {
4360 if (edl_records) free_edl(edl_records);
4361 next_edl_record = edl_records = edl_parse_file();
4363 if (edl_output_filename) {
4364 if (edl_fd) fclose(edl_fd);
4365 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4367 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4368 filename_recode(edl_output_filename));
4372 //==================== Open VOB-Sub ============================
4374 current_module="vobsub";
4375 if (vobsub_name){
4376 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
4377 if(vo_vobsub==NULL)
4378 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4379 filename_recode(vobsub_name));
4380 } else if (sub_auto && mpctx->filename){
4381 /* try to autodetect vobsub from movie filename ::atmos */
4382 char *buf = strdup(mpctx->filename), *psub;
4383 char *pdot = strrchr(buf, '.');
4384 char *pslash = strrchr(buf, '/');
4385 #if defined(__MINGW32__) || defined(__CYGWIN__)
4386 if (!pslash) pslash = strrchr(buf, '\\');
4387 #endif
4388 if (pdot && (!pslash || pdot > pslash))
4389 *pdot = '\0';
4390 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4391 /* try from ~/.mplayer/sub */
4392 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4393 const char *bname = mp_basename(buf);
4394 int l;
4395 l = strlen(psub) + strlen(bname) + 1;
4396 psub = realloc(psub,l);
4397 strcat(psub,bname);
4398 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4399 free(psub);
4401 free(buf);
4403 if(vo_vobsub){
4404 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4405 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4406 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4408 // setup global sub numbering
4409 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4412 //============ Open & Sync STREAM --- fork cache2 ====================
4414 mpctx->stream=NULL;
4415 mpctx->demuxer=NULL;
4416 if (mpctx->d_audio) {
4417 //free_demuxer_stream(mpctx->d_audio);
4418 mpctx->d_audio=NULL;
4420 if (mpctx->d_video) {
4421 //free_demuxer_stream(d_video);
4422 mpctx->d_video=NULL;
4424 mpctx->sh_audio=NULL;
4425 mpctx->sh_video=NULL;
4427 current_module="open_stream";
4428 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4429 if(!mpctx->stream) { // error...
4430 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4431 goto goto_next_file;
4433 mpctx->initialized_flags|=INITIALIZED_STREAM;
4435 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4436 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4437 "playlist support will not be used automatically.\n"
4438 "MPlayer's playlist code is unsafe and should only be used with "
4439 "trusted sources.\nPlayback will probably fail.\n\n");
4440 #if 0
4441 play_tree_t* entry;
4442 // Handle playlist
4443 current_module="handle_playlist";
4444 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4445 filename_recode(mpctx->filename));
4446 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4447 mpctx->eof=playtree_add_playlist(mpctx, entry);
4448 goto goto_next_file;
4449 #endif
4451 mpctx->stream->start_pos+=seek_to_byte;
4453 if(stream_dump_type==5){
4454 unsigned char buf[4096];
4455 int len;
4456 FILE *f;
4457 current_module="dumpstream";
4458 stream_reset(mpctx->stream);
4459 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4460 f=fopen(opts->stream_dump_name,"wb");
4461 if(!f){
4462 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4463 exit_player(mpctx, EXIT_ERROR);
4465 if (opts->chapterrange[0] > 1) {
4466 int chapter = opts->chapterrange[0] - 1;
4467 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4469 while(!mpctx->stream->eof && !async_quit_request){
4470 len=stream_read(mpctx->stream,buf,4096);
4471 if(len>0) {
4472 if(fwrite(buf,len,1,f) != 1) {
4473 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4474 exit_player(mpctx, EXIT_ERROR);
4477 if (opts->chapterrange[1] > 0) {
4478 int chapter = -1;
4479 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4480 &chapter) == STREAM_OK
4481 && chapter + 1 > opts->chapterrange[1])
4482 break;
4485 if(fclose(f)) {
4486 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4487 exit_player(mpctx, EXIT_ERROR);
4489 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4490 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4493 #ifdef CONFIG_DVDREAD
4494 if(mpctx->stream->type==STREAMTYPE_DVD){
4495 current_module="dvd lang->id";
4496 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4497 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4498 // setup global sub numbering
4499 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4500 current_module=NULL;
4502 #endif
4504 #ifdef CONFIG_DVDNAV
4505 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4506 current_module="dvdnav lang->id";
4507 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4508 dvdsub_lang_id = -3;
4509 if(opts->sub_lang && opts->sub_id==-1)
4510 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4511 // setup global sub numbering
4512 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4513 current_module=NULL;
4515 #endif
4517 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4518 goto_enable_cache:
4519 if(stream_cache_size>0){
4520 int res;
4521 float stream_cache_min_percent = opts->stream_cache_min_percent;
4522 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4523 current_module="enable_cache";
4524 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4525 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4526 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4527 if(res == 0)
4528 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4531 //============ Open DEMUXERS --- DETECT file type =======================
4532 current_module="demux_open";
4534 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4536 // HACK to get MOV Reference Files working
4538 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4540 unsigned char* playlist_entry;
4541 play_tree_t *list = NULL, *entry = NULL;
4543 current_module="handle_demux_playlist";
4544 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4546 char *temp;
4547 const char *bname;
4549 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4550 filename_recode(playlist_entry));
4552 bname=mp_basename(playlist_entry);
4553 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4554 continue;
4556 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4557 continue;
4559 entry = play_tree_new();
4561 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4563 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4564 if (temp)
4566 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4567 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4568 strcat(temp, playlist_entry);
4569 if (!strcmp(temp, mpctx->filename)) {
4570 free(temp);
4571 continue;
4573 play_tree_add_file(entry,temp);
4574 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4575 free(temp);
4578 else
4579 play_tree_add_file(entry,playlist_entry);
4581 if(!list)
4582 list = entry;
4583 else
4584 play_tree_append_entry(list,entry);
4586 free_demuxer(mpctx->demuxer);
4587 mpctx->demuxer = NULL;
4589 if (list)
4591 entry = play_tree_new();
4592 play_tree_set_child(entry,list);
4593 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4594 goto goto_next_file;
4598 if(!mpctx->demuxer) {
4599 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4600 goto goto_next_file;
4603 if (mpctx->demuxer->matroska_data.ordered_chapters)
4604 build_ordered_chapter_timeline(mpctx);
4606 if (!mpctx->sources) {
4607 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4608 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4609 .demuxer = mpctx->demuxer};
4610 mpctx->num_sources = 1;
4613 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4615 #ifdef CONFIG_ASS
4616 if (opts->ass_enabled && ass_library) {
4617 for (int j = 0; j < mpctx->num_sources; j++) {
4618 struct demuxer *d = mpctx->sources[j].demuxer;
4619 for (int i = 0; i < d->num_attachments; i++) {
4620 struct demux_attachment *att = d->attachments + i;
4621 if (use_embedded_fonts && attachment_is_font(att))
4622 ass_add_font(ass_library, att->name, att->data, att->data_size);
4626 #endif
4628 current_module="demux_open2";
4630 mpctx->d_audio=mpctx->demuxer->audio;
4631 mpctx->d_video=mpctx->demuxer->video;
4632 mpctx->d_sub=mpctx->demuxer->sub;
4634 if (ts_prog) {
4635 int tmp = ts_prog;
4636 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4638 // select audio stream
4639 for (int i = 0; i < mpctx->num_sources; i++)
4640 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4641 opts->audio_lang);
4643 // DUMP STREAMS:
4644 if((stream_dump_type)&&(stream_dump_type<4)){
4645 FILE *f;
4646 demux_stream_t *ds=NULL;
4647 current_module="dump";
4648 // select stream to dump
4649 switch(stream_dump_type){
4650 case 1: ds=mpctx->d_audio;break;
4651 case 2: ds=mpctx->d_video;break;
4652 case 3: ds=mpctx->d_sub;break;
4654 if(!ds){
4655 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4656 exit_player(mpctx, EXIT_ERROR);
4658 // disable other streams:
4659 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4660 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4661 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4662 // let's dump it!
4663 f=fopen(opts->stream_dump_name,"wb");
4664 if(!f){
4665 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4666 exit_player(mpctx, EXIT_ERROR);
4668 while(!ds->eof){
4669 unsigned char* start;
4670 int in_size=ds_get_packet(ds,&start);
4671 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4672 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4673 if(in_size>0) fwrite(start,in_size,1,f);
4674 if (opts->chapterrange[1] > 0) {
4675 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4676 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4677 break;
4680 fclose(f);
4681 mp_tmsg(MSGT_CPLAYER ,MSGL_INFO, "Stream dump complete.\n");
4682 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4685 mpctx->sh_audio=mpctx->d_audio->sh;
4686 mpctx->sh_video=mpctx->d_video->sh;
4688 if(mpctx->sh_video){
4690 current_module="video_read_properties";
4691 if(!video_read_properties(mpctx->sh_video)) {
4692 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4693 mpctx->sh_video=mpctx->d_video->sh=NULL;
4694 } else {
4695 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4696 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4697 mpctx->sh_video->fps,mpctx->sh_video->frametime
4700 /* need to set fps here for output encoders to pick it up in their init */
4701 if(force_fps){
4702 mpctx->sh_video->fps=force_fps;
4703 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4705 vo_fps = mpctx->sh_video->fps;
4707 if(!mpctx->sh_video->fps && !force_fps){
4708 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4709 mpctx->opts.correct_pts = 1;
4715 if(!mpctx->sh_video && !mpctx->sh_audio){
4716 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4717 #ifdef CONFIG_DVBIN
4718 if(mpctx->stream->type == STREAMTYPE_DVB)
4720 int dir;
4721 int v = mpctx->last_dvb_step;
4722 if(v > 0)
4723 dir = DVB_CHANNEL_HIGHER;
4724 else
4725 dir = DVB_CHANNEL_LOWER;
4727 if(dvb_step_channel(mpctx->stream, dir)) {
4728 mpctx->stop_play = PT_NEXT_ENTRY;
4729 mpctx->dvbin_reopen = 1;
4732 #endif
4733 goto goto_next_file; // exit_player(_("Fatal error"));
4736 /* display clip info */
4737 demux_info_print(mpctx->demuxer);
4739 //================== Read SUBTITLES (DVD & TEXT) ==========================
4740 if(vo_spudec==NULL &&
4741 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4742 init_vo_spudec(mpctx);
4745 // after reading video params we should load subtitles because
4746 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4747 // check .sub
4748 current_module="read_subtitles_file";
4749 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4750 if(sub_name){
4751 for (i = 0; sub_name[i] != NULL; ++i)
4752 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4754 if(sub_auto) { // auto load sub file ...
4755 char *psub = get_path( "sub/" );
4756 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4757 int i = 0;
4758 free(psub); // release the buffer created by get_path() above
4759 while (tmp[i]) {
4760 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4761 free(tmp[i++]);
4763 free(tmp);
4765 if (mpctx->set_of_sub_size > 0)
4766 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4768 if (select_subtitle(mpctx)) {
4769 if(mpctx->subdata)
4770 switch (stream_dump_type) {
4771 case 3: list_sub_file(mpctx->subdata); break;
4772 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4773 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4774 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4775 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4776 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4780 print_file_properties(mpctx, mpctx->filename);
4782 if (mpctx->sh_video)
4783 reinit_video_chain(mpctx);
4784 if (mpctx->sh_video) {
4785 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4786 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4787 #ifdef CONFIG_FREETYPE
4788 force_load_font = 1;
4789 #endif
4790 } else if (!mpctx->sh_audio)
4791 goto goto_next_file;
4793 //================== MAIN: ==========================
4794 current_module="main";
4796 if (opts->playing_msg) {
4797 char* msg = property_expand_string(mpctx, opts->playing_msg);
4798 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4799 free(msg);
4803 // Disable the term OSD in verbose mode
4804 if (verbose)
4805 opts->term_osd = 0;
4809 // Make sure old OSD does not stay around,
4810 // e.g. with -fixed-vo and same-resolution files
4811 clear_osd_msgs();
4812 update_osd_msg(mpctx);
4814 //================ SETUP AUDIO ==========================
4816 if(mpctx->sh_audio){
4817 reinit_audio_chain(mpctx);
4818 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4819 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4822 current_module="av_init";
4824 if(mpctx->sh_video){
4825 mpctx->sh_video->timer=0;
4826 if (! ignore_start)
4827 audio_delay += mpctx->sh_video->stream_delay;
4829 if(mpctx->sh_audio){
4830 if (start_volume >= 0)
4831 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4832 if (! ignore_start)
4833 audio_delay -= mpctx->sh_audio->stream_delay;
4834 mpctx->delay=-audio_delay;
4837 if(!mpctx->sh_audio){
4838 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4839 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4840 ds_free_packs(mpctx->d_audio); // free buffered chunks
4841 //mpctx->d_audio->id=-2; // do not read audio chunks
4842 //uninit_player(mpctx, INITIALIZED_AO); // close device
4844 if(!mpctx->sh_video){
4845 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4846 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4847 ds_free_packs(mpctx->d_video);
4848 mpctx->d_video->id=-2;
4849 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4852 if (!mpctx->sh_video && !mpctx->sh_audio)
4853 goto goto_next_file;
4855 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4856 if(force_fps && mpctx->sh_video){
4857 vo_fps = mpctx->sh_video->fps=force_fps;
4858 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4859 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4862 mp_input_set_section(mpctx->input, NULL);
4863 //TODO: add desired (stream-based) sections here
4864 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4865 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4867 //==================== START PLAYING =======================
4869 if(opts->loop_times>1) opts->loop_times--; else
4870 if(opts->loop_times==1) opts->loop_times = -1;
4872 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4874 total_time_usage_start=GetTimer();
4875 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4876 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4877 play_n_frames=play_n_frames_mf;
4879 if(play_n_frames==0){
4880 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4883 mpctx->time_frame = 0;
4884 mpctx->drop_message_shown = 0;
4885 mpctx->restart_playback = true;
4886 mpctx->video_pts = 0;
4887 mpctx->hrseek_active = false;
4888 mpctx->hrseek_framedrop = false;
4889 mpctx->step_frames = 0;
4890 mpctx->total_avsync_change = 0;
4891 mpctx->last_chapter_seek = -1;
4893 // If there's a timeline force an absolute seek to initialize state
4894 if (seek_to_sec || mpctx->timeline) {
4895 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4896 seek(mpctx, mpctx->seek);
4897 end_at.pos += seek_to_sec;
4899 if (opts->chapterrange[0] > 0) {
4900 double pts;
4901 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4902 && pts > -1.0) {
4903 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4904 seek(mpctx, mpctx->seek);
4908 if (end_at.type == END_AT_SIZE) {
4909 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4910 end_at.type = END_AT_NONE;
4913 #ifdef CONFIG_DVDNAV
4914 mp_dvdnav_context_free(mpctx);
4915 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4916 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4917 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4919 #endif
4921 mpctx->seek = (struct seek_params){0};
4922 get_relative_time(mpctx); // reset current delta
4923 // Make sure VO knows current pause state
4924 if (mpctx->sh_video)
4925 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4926 NULL);
4928 while (!mpctx->stop_play)
4929 run_playloop(mpctx);
4931 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4933 #ifdef CONFIG_DVBIN
4934 if(mpctx->dvbin_reopen)
4936 mpctx->stop_play = 0;
4937 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4938 cache_uninit(mpctx->stream);
4939 mpctx->dvbin_reopen = 0;
4940 goto goto_enable_cache;
4942 #endif
4945 goto_next_file: // don't jump here after ao/vo/getch initialization!
4947 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4949 if (opts->benchmark) {
4950 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4951 double total_time_usage;
4952 total_time_usage_start=GetTimer()-total_time_usage_start;
4953 total_time_usage = (float)total_time_usage_start*0.000001;
4954 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4955 video_time_usage,vout_time_usage,audio_time_usage,
4956 total_time_usage-tot,total_time_usage);
4957 if(total_time_usage>0.0)
4958 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4959 100.0*video_time_usage/total_time_usage,
4960 100.0*vout_time_usage/total_time_usage,
4961 100.0*audio_time_usage/total_time_usage,
4962 100.0*(total_time_usage-tot)/total_time_usage,
4963 100.0);
4964 if(total_frame_cnt && frame_dropping)
4965 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4966 total_frame_cnt-drop_frame_cnt,
4967 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4968 drop_frame_cnt,
4969 100*drop_frame_cnt/total_frame_cnt,
4970 total_frame_cnt,
4971 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4974 // time to uninit all, except global stuff:
4975 int uninitialize_parts = INITIALIZED_ALL;
4976 if (opts->fixed_vo)
4977 uninitialize_parts -= INITIALIZED_VO;
4978 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4979 uninitialize_parts -= INITIALIZED_AO;
4980 uninit_player(mpctx, uninitialize_parts);
4982 if(mpctx->set_of_sub_size > 0) {
4983 current_module="sub_free";
4984 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4985 sub_free(mpctx->set_of_subtitles[i]);
4986 #ifdef CONFIG_ASS
4987 if(mpctx->set_of_ass_tracks[i])
4988 ass_free_track( mpctx->set_of_ass_tracks[i] );
4989 #endif
4991 mpctx->set_of_sub_size = 0;
4993 mpctx->vo_sub_last = vo_sub=NULL;
4994 mpctx->subdata=NULL;
4995 #ifdef CONFIG_ASS
4996 mpctx->osd->ass_track = NULL;
4997 if(ass_library)
4998 ass_clear_fonts(ass_library);
4999 #endif
5001 if (!mpctx->stop_play) // In case some goto jumped here...
5002 mpctx->stop_play = PT_NEXT_ENTRY;
5004 int playtree_direction = 1;
5006 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
5007 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
5008 play_tree_iter_free(mpctx->playtree_iter);
5009 mpctx->playtree_iter = NULL;
5011 mpctx->play_tree_step = 1;
5012 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
5013 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5014 if(mpctx->playtree_iter) {
5015 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
5016 play_tree_iter_free(mpctx->playtree_iter);
5017 mpctx->playtree_iter = NULL;
5020 } else if (mpctx->stop_play == PT_STOP) {
5021 play_tree_iter_free(mpctx->playtree_iter);
5022 mpctx->playtree_iter = NULL;
5023 } else { // NEXT PREV SRC
5024 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5027 while(mpctx->playtree_iter != NULL) {
5028 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
5029 if(mpctx->filename == NULL) {
5030 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
5031 play_tree_iter_free(mpctx->playtree_iter);
5032 mpctx->playtree_iter = NULL;
5034 } else
5035 break;
5038 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5039 if(!mpctx->playtree_iter) mpctx->filename = NULL;
5040 mpctx->stop_play = 0;
5041 goto play_next_file;
5045 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5047 return 1;
5049 #endif /* DISABLE_MAIN */