subtitles: move global ass_track to struct osd_state
[mplayer/glamo.git] / mplayer.c
blobf36bb2788f7e23b649a33fb13d6986909364f201
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 /// \file
20 /// \ingroup Properties Command2Property OSDMsgStack
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdbool.h>
25 #include <math.h>
27 #include "config.h"
28 #include "talloc.h"
30 #if defined(__MINGW32__) || defined(__CYGWIN__)
31 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
32 #include <windows.h>
33 #endif
34 #include <string.h>
35 #include <unistd.h>
37 // #include <sys/mman.h>
38 #include <sys/types.h>
39 #ifndef __MINGW32__
40 #include <sys/ioctl.h>
41 #include <sys/wait.h>
42 #else
43 #define SIGHUP 1 /* hangup */
44 #define SIGQUIT 3 /* quit */
45 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
46 #define SIGBUS 10 /* bus error */
47 #define SIGPIPE 13 /* broken pipe */
48 #endif
50 #include <sys/time.h>
51 #include <sys/stat.h>
53 #include <signal.h>
54 #include <time.h>
55 #include <fcntl.h>
56 #include <limits.h>
58 #include <errno.h>
60 #include "mp_msg.h"
61 #include "av_log.h"
64 #include "m_option.h"
65 #include "m_config.h"
66 #include "mplayer.h"
67 #include "access_mpcontext.h"
68 #include "m_property.h"
70 #include "cfg-mplayer-def.h"
72 #include "libavutil/avstring.h"
74 #include "subreader.h"
76 #include "mp_osd.h"
77 #include "libvo/video_out.h"
79 #include "libvo/font_load.h"
80 #include "libvo/sub.h"
81 #include "ffmpeg_files/intreadwrite.h"
82 #include "av_sub.h"
83 #include "libmpcodecs/dec_teletext.h"
84 #include "cpudetect.h"
85 #include "version.h"
87 #ifdef CONFIG_X11
88 #include "libvo/x11_common.h"
89 #endif
91 #include "libao2/audio_out.h"
93 #include "codec-cfg.h"
95 #include "edl.h"
97 #include "spudec.h"
98 #include "vobsub.h"
100 #include "osdep/getch2.h"
101 #include "osdep/timer.h"
102 #include "osdep/findfiles.h"
104 #include "input/input.h"
106 const int under_mencoder = 0;
107 int slave_mode=0;
108 int enable_mouse_movements=0;
109 float start_volume = -1;
111 #include "osdep/priority.h"
113 char *heartbeat_cmd;
115 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
117 #ifdef HAVE_RTC
118 #ifdef __linux__
119 #include <linux/rtc.h>
120 #else
121 #include <rtc.h>
122 #define RTC_IRQP_SET RTCIO_IRQP_SET
123 #define RTC_PIE_ON RTCIO_PIE_ON
124 #endif /* __linux__ */
125 #endif /* HAVE_RTC */
127 #include "stream/tv.h"
128 #include "stream/stream_radio.h"
129 #ifdef CONFIG_DVBIN
130 #include "stream/dvbin.h"
131 #endif
132 #include "stream/cache2.h"
134 //**************************************************************************//
135 // Playtree
136 //**************************************************************************//
137 #include "playtree.h"
138 #include "playtreeparser.h"
140 //**************************************************************************//
141 // Config
142 //**************************************************************************//
143 #include "parser-cfg.h"
144 #include "parser-mpcmd.h"
146 //**************************************************************************//
147 // Config file
148 //**************************************************************************//
150 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
152 #include "path.h"
154 //**************************************************************************//
155 //**************************************************************************//
156 // Input media streaming & demultiplexer:
157 //**************************************************************************//
159 static int max_framesize=0;
161 #include "stream/stream.h"
162 #include "libmpdemux/demuxer.h"
163 #include "libmpdemux/stheader.h"
165 #ifdef CONFIG_DVDREAD
166 #include "stream/stream_dvd.h"
167 #endif
168 #include "stream/stream_dvdnav.h"
170 #include "libmpcodecs/dec_audio.h"
171 #include "libmpcodecs/dec_video.h"
172 #include "libmpcodecs/mp_image.h"
173 #include "libmpcodecs/vf.h"
174 #include "libmpcodecs/vd.h"
176 #include "mixer.h"
178 #include "mp_core.h"
179 #include "options.h"
180 #include "defaultopts.h"
182 static const char help_text[]=_(
183 "Usage: mplayer [options] [url|path/]filename\n"
184 "\n"
185 "Basic options: (complete list in the man page)\n"
186 " -vo <drv> select video output driver ('-vo help' for a list)\n"
187 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
188 #ifdef CONFIG_VCD
189 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
190 #endif
191 #ifdef CONFIG_DVDREAD
192 " dvd://<titleno> play DVD title from device instead of plain file\n"
193 #endif
194 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
195 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
196 " -nosound do not play sound\n"
197 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
198 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
199 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
200 " -playlist <file> specify playlist file\n"
201 " -vid x -aid y select video (x) and audio (y) stream to play\n"
202 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
203 " -pp <quality> enable postprocessing filter (details in the man page)\n"
204 " -framedrop enable frame dropping (for slow machines)\n"
205 "\n"
206 "Basic keys: (complete list in the man page, also check input.conf)\n"
207 " <- or -> seek backward/forward 10 seconds\n"
208 " down or up seek backward/forward 1 minute\n"
209 " pgdown or pgup seek backward/forward 10 minutes\n"
210 " < or > step backward/forward in playlist\n"
211 " p or SPACE pause movie (press any key to continue)\n"
212 " q or ESC stop playing and quit program\n"
213 " + or - adjust audio delay by +/- 0.1 second\n"
214 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
215 " * or / increase or decrease PCM volume\n"
216 " x or z adjust subtitle delay by +/- 0.1 second\n"
217 " r or t adjust subtitle position up/down, also see -vf expand\n"
218 "\n"
219 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
220 "\n");
223 #define Exit_SIGILL_RTCpuSel _(\
224 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
225 " It may be a bug in our new runtime CPU-detection code...\n"\
226 " Please read DOCS/HTML/en/bugreports.html.\n")
228 #define Exit_SIGILL _(\
229 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
230 " It usually happens when you run it on a CPU different than the one it was\n"\
231 " compiled/optimized for.\n"\
232 " Verify this!\n")
234 #define Exit_SIGSEGV_SIGFPE _(\
235 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
236 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
237 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
239 #define Exit_SIGCRASH _(\
240 "- MPlayer crashed. This shouldn't happen.\n"\
241 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
242 " gcc version. If you think it's MPlayer's fault, please read\n"\
243 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
244 " won't help unless you provide this information when reporting a possible bug.\n")
246 #define SystemTooSlow _("\n\n"\
247 " ************************************************\n"\
248 " **** Your system is too SLOW to play this! ****\n"\
249 " ************************************************\n\n"\
250 "Possible reasons, problems, workarounds:\n"\
251 "- Most common: broken/buggy _audio_ driver\n"\
252 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
253 " - Experiment with different values for -autosync, 30 is a good start.\n"\
254 "- Slow video output\n"\
255 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
256 "- Slow CPU\n"\
257 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
258 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
259 "- Broken file\n"\
260 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
261 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
262 " - Try -cache 8192.\n"\
263 "- Are you using -cache to play a non-interleaved AVI file?\n"\
264 " - Try -nocache.\n"\
265 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
266 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
269 //**************************************************************************//
270 //**************************************************************************//
272 #include "mp_fifo.h"
274 // benchmark:
275 double video_time_usage=0;
276 double vout_time_usage=0;
277 static double audio_time_usage=0;
278 static int total_time_usage_start=0;
279 static int total_frame_cnt=0;
280 static int drop_frame_cnt=0; // total number of dropped frames
282 // options:
283 static int output_quality=0;
285 // seek:
286 static double seek_to_sec;
287 static off_t seek_to_byte=0;
288 static off_t step_sec=0;
290 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
292 // codecs:
293 char **audio_codec_list=NULL; // override audio codec
294 char **video_codec_list=NULL; // override video codec
295 char **audio_fm_list=NULL; // override audio codec family
296 char **video_fm_list=NULL; // override video codec family
298 // this dvdsub_id was selected via slang
299 // use this to allow dvdnav to follow -slang across stream resets,
300 // in particular the subtitle ID for a language changes
301 int dvdsub_lang_id;
302 int vobsub_id=-1;
303 static char* spudec_ifo=NULL;
304 int forced_subs_only=0;
305 int file_filter=1;
307 // cache2:
308 int stream_cache_size=-1;
310 // dump:
311 int stream_dump_type=0;
313 // A-V sync:
314 static float default_max_pts_correction=-1;//0.01f;
315 float audio_delay=0;
316 static int ignore_start=0;
318 double force_fps=0;
319 static int force_srate=0;
320 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
321 static int play_n_frames=-1;
322 static int play_n_frames_mf=-1;
324 // sub:
325 char *font_name=NULL;
326 char *sub_font_name=NULL;
327 extern int font_fontconfig;
328 float font_factor=0.75;
329 char **sub_name=NULL;
330 float sub_delay=0;
331 float sub_fps=0;
332 int sub_auto = 1;
333 char *vobsub_name=NULL;
334 int subcc_enabled=0;
335 int suboverlap_enabled = 1;
337 #include "ass_mp.h"
339 char* current_module=NULL; // for debugging
342 // ---
344 #ifdef CONFIG_MENU
345 #include "m_struct.h"
346 #include "libmenu/menu.h"
347 static const vf_info_t* const libmenu_vfs[] = {
348 &vf_info_menu,
349 NULL
351 static vf_instance_t* vf_menu = NULL;
352 int use_menu = 0;
353 static char* menu_cfg = NULL;
354 static char* menu_root = "main";
355 #endif
358 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
359 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
360 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
361 int use_filedir_conf;
362 int use_filename_title;
364 #include "mpcommon.h"
365 #include "command.h"
367 #include "metadata.h"
369 const void *mpctx_get_video_out(MPContext *mpctx)
371 return mpctx->video_out;
374 const void *mpctx_get_audio_out(MPContext *mpctx)
376 return mpctx->audio_out;
379 void *mpctx_get_demuxer(MPContext *mpctx)
381 return mpctx->demuxer;
384 void *mpctx_get_playtree_iter(MPContext *mpctx)
386 return mpctx->playtree_iter;
389 void *mpctx_get_mixer(MPContext *mpctx)
391 return &mpctx->mixer;
394 int mpctx_get_global_sub_size(MPContext *mpctx)
396 return mpctx->global_sub_size;
399 int mpctx_get_osd_function(MPContext *mpctx)
401 return mpctx->osd_function;
404 static float get_relative_time(struct MPContext *mpctx)
406 unsigned int new_time = GetTimer();
407 unsigned int delta = new_time - mpctx->last_time;
408 mpctx->last_time = new_time;
409 return delta * 0.000001;
412 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
413 switch (type)
415 /* check for valid video stream */
416 case META_VIDEO_CODEC:
417 case META_VIDEO_BITRATE:
418 case META_VIDEO_RESOLUTION:
420 if (!mpctx->sh_video)
421 return 0;
422 break;
425 /* check for valid audio stream */
426 case META_AUDIO_CODEC:
427 case META_AUDIO_BITRATE:
428 case META_AUDIO_SAMPLES:
430 if (!mpctx->sh_audio)
431 return 0;
432 break;
435 /* check for valid demuxer */
436 case META_INFO_TITLE:
437 case META_INFO_ARTIST:
438 case META_INFO_ALBUM:
439 case META_INFO_YEAR:
440 case META_INFO_COMMENT:
441 case META_INFO_TRACK:
442 case META_INFO_GENRE:
444 if (!mpctx->demuxer)
445 return 0;
446 break;
449 default:
450 break;
453 return 1;
456 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
457 char **info = mpctx->demuxer->info;
458 int n;
460 if (!info || !tag)
461 return talloc_strdup(NULL, "");
463 for (n = 0; info[2*n] != NULL ; n++)
464 if (!strcasecmp (info[2*n], tag))
465 break;
467 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
470 char *get_metadata(struct MPContext *mpctx, metadata_t type)
472 sh_audio_t * const sh_audio = mpctx->sh_audio;
473 sh_video_t * const sh_video = mpctx->sh_video;
475 if (!is_valid_metadata_type(mpctx, type))
476 return NULL;
478 switch (type) {
479 case META_NAME:
480 return talloc_strdup(NULL, mp_basename(mpctx->filename));
481 case META_VIDEO_CODEC:
482 if (sh_video->format == 0x10000001)
483 return talloc_strdup(NULL, "mpeg1");
484 else if (sh_video->format == 0x10000002)
485 return talloc_strdup(NULL, "mpeg2");
486 else if (sh_video->format == 0x10000004)
487 return talloc_strdup(NULL, "mpeg4");
488 else if (sh_video->format == 0x10000005)
489 return talloc_strdup(NULL, "h264");
490 else if (sh_video->format >= 0x20202020)
491 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
492 else
493 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
494 case META_VIDEO_BITRATE:
495 return talloc_asprintf(NULL, "%d kbps",
496 (int) (sh_video->i_bps * 8 / 1024));
497 case META_VIDEO_RESOLUTION:
498 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
499 sh_video->disp_h);
500 case META_AUDIO_CODEC:
501 if (sh_audio->codec && sh_audio->codec->name)
502 return talloc_strdup(NULL, sh_audio->codec->name);
503 return talloc_strdup(NULL, "");
504 case META_AUDIO_BITRATE:
505 return talloc_asprintf(NULL, "%d kbps",
506 (int) (sh_audio->i_bps * 8/1000));
507 case META_AUDIO_SAMPLES:
508 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
509 sh_audio->channels);
511 /* check for valid demuxer */
512 case META_INFO_TITLE:
513 return get_demuxer_info(mpctx, "Title");
515 case META_INFO_ARTIST:
516 return get_demuxer_info(mpctx, "Artist");
518 case META_INFO_ALBUM:
519 return get_demuxer_info(mpctx, "Album");
521 case META_INFO_YEAR:
522 return get_demuxer_info(mpctx, "Year");
524 case META_INFO_COMMENT:
525 return get_demuxer_info(mpctx, "Comment");
527 case META_INFO_TRACK:
528 return get_demuxer_info(mpctx, "Track");
530 case META_INFO_GENRE:
531 return get_demuxer_info(mpctx, "Genre");
533 default:
534 break;
537 return talloc_strdup(NULL, "");
540 static void print_file_properties(struct MPContext *mpctx, const char *filename)
542 double start_pts = MP_NOPTS_VALUE;
543 double video_start_pts = MP_NOPTS_VALUE;
544 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
545 filename_recode(filename));
546 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
547 if (mpctx->sh_video) {
548 /* Assume FOURCC if all bytes >= 0x20 (' ') */
549 if (mpctx->sh_video->format >= 0x20202020)
550 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
551 else
552 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
553 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
554 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
555 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
556 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
557 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
558 video_start_pts = ds_get_next_pts(mpctx->d_video);
560 if (mpctx->sh_audio) {
561 /* Assume FOURCC if all bytes >= 0x20 (' ') */
562 if (mpctx->sh_audio->format >= 0x20202020)
563 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
564 else
565 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
566 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
567 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
568 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
569 start_pts = ds_get_next_pts(mpctx->d_audio);
571 if (video_start_pts != MP_NOPTS_VALUE) {
572 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
573 (mpctx->sh_video && video_start_pts < start_pts))
574 start_pts = video_start_pts;
576 if (start_pts != MP_NOPTS_VALUE)
577 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
578 else
579 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
580 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
581 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
582 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
583 if (mpctx->demuxer) {
584 if (mpctx->demuxer->num_chapters == 0)
585 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
586 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
590 /// step size of mixer changes
591 int volstep = 3;
593 #ifdef CONFIG_DVDNAV
594 static void mp_dvdnav_context_free(MPContext *ctx){
595 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
596 ctx->nav_smpi = NULL;
597 free(ctx->nav_buffer);
598 ctx->nav_buffer = NULL;
599 ctx->nav_start = NULL;
600 ctx->nav_in_size = 0;
602 #endif
604 void uninit_player(struct MPContext *mpctx, unsigned int mask){
605 mask &= mpctx->initialized_flags;
607 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
609 if(mask&INITIALIZED_ACODEC){
610 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
611 current_module="uninit_acodec";
612 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
613 mpctx->sh_audio=NULL;
614 mpctx->mixer.afilter = NULL;
617 if(mask&INITIALIZED_VCODEC){
618 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
619 current_module="uninit_vcodec";
620 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
621 mpctx->sh_video=NULL;
622 #ifdef CONFIG_MENU
623 vf_menu=NULL;
624 #endif
627 if(mask&INITIALIZED_DEMUXER){
628 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
629 current_module="free_demuxer";
630 if (mpctx->num_sources) {
631 mpctx->demuxer = mpctx->sources[0].demuxer;
632 for (int i = 1; i < mpctx->num_sources; i++) {
633 free_stream(mpctx->sources[i].stream);
634 free_demuxer(mpctx->sources[i].demuxer);
637 talloc_free(mpctx->sources);
638 mpctx->sources = NULL;
639 mpctx->num_sources = 0;
640 talloc_free(mpctx->timeline);
641 mpctx->timeline = NULL;
642 mpctx->num_timeline_parts = 0;
643 talloc_free(mpctx->chapters);
644 mpctx->chapters = NULL;
645 mpctx->num_chapters = 0;
646 mpctx->video_offset = 0;
647 if(mpctx->demuxer){
648 mpctx->stream=mpctx->demuxer->stream;
649 free_demuxer(mpctx->demuxer);
651 mpctx->demuxer=NULL;
654 // kill the cache process:
655 if(mask&INITIALIZED_STREAM){
656 mpctx->initialized_flags&=~INITIALIZED_STREAM;
657 current_module="uninit_stream";
658 if(mpctx->stream) free_stream(mpctx->stream);
659 mpctx->stream=NULL;
662 if(mask&INITIALIZED_VO){
663 mpctx->initialized_flags&=~INITIALIZED_VO;
664 current_module="uninit_vo";
665 vo_destroy(mpctx->video_out);
666 mpctx->video_out=NULL;
667 #ifdef CONFIG_DVDNAV
668 mp_dvdnav_context_free(mpctx);
669 #endif
672 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
673 if(mask&INITIALIZED_GETCH2){
674 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
675 current_module="uninit_getch2";
676 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
677 // restore terminal:
678 getch2_disable();
681 if(mask&INITIALIZED_VOBSUB){
682 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
683 current_module="uninit_vobsub";
684 if(vo_vobsub) vobsub_close(vo_vobsub);
685 vo_vobsub=NULL;
688 if (mask&INITIALIZED_SPUDEC){
689 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
690 current_module="uninit_spudec";
691 spudec_free(vo_spudec);
692 vo_spudec=NULL;
695 if(mask&INITIALIZED_AO){
696 mpctx->initialized_flags&=~INITIALIZED_AO;
697 current_module="uninit_ao";
698 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
699 if (mpctx->audio_out)
700 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
701 mpctx->audio_out=NULL;
704 current_module=NULL;
707 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
709 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
710 uninit_player(mpctx, INITIALIZED_ALL);
711 #if defined(__MINGW32__) || defined(__CYGWIN__)
712 timeEndPeriod(1);
713 #endif
714 #ifdef CONFIG_X11
715 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
716 #endif
718 current_module="uninit_input";
719 mp_input_uninit(mpctx->input);
720 #ifdef CONFIG_MENU
721 if (use_menu)
722 menu_uninit();
723 #endif
725 #ifdef CONFIG_FREETYPE
726 current_module="uninit_font";
727 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
728 free_font_desc(mpctx->osd->sub_font);
729 free_font_desc(vo_font);
730 vo_font = NULL;
731 done_freetype();
732 #endif
733 osd_free(mpctx->osd);
735 #ifdef CONFIG_ASS
736 ass_library_done(ass_library);
737 ass_library = NULL;
738 #endif
740 current_module="exit_player";
742 // free mplayer config
743 if(mpctx->mconfig)
744 m_config_free(mpctx->mconfig);
745 mpctx->mconfig = NULL;
747 if(mpctx->playtree_iter)
748 play_tree_iter_free(mpctx->playtree_iter);
749 mpctx->playtree_iter = NULL;
750 if(mpctx->playtree)
751 play_tree_free(mpctx->playtree, 1);
752 mpctx->playtree = NULL;
754 talloc_free(mpctx->key_fifo);
756 free(edl_records); // free mem allocated for EDL
757 edl_records = NULL;
758 switch(how) {
759 case EXIT_QUIT:
760 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
761 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
762 break;
763 case EXIT_EOF:
764 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
765 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
766 break;
767 case EXIT_ERROR:
768 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
769 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
770 break;
771 default:
772 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
774 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
776 exit(rc);
779 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
781 exit_player_with_rc(mpctx, how, 1);
784 #ifndef __MINGW32__
785 static void child_sighandler(int x){
786 pid_t pid;
787 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
789 #endif
791 #ifdef CONFIG_CRASH_DEBUG
792 static char *prog_path;
793 static int crash_debug = 0;
794 #endif
796 static void exit_sighandler(int x){
797 static int sig_count=0;
798 #ifdef CONFIG_CRASH_DEBUG
799 if (!crash_debug || x != SIGTRAP)
800 #endif
801 ++sig_count;
802 if(sig_count==5)
804 /* We're crashing bad and can't uninit cleanly :(
805 * by popular request, we make one last (dirty)
806 * effort to restore the user's
807 * terminal. */
808 getch2_disable();
809 exit(1);
811 if(sig_count==6) exit(1);
812 if(sig_count>6){
813 // can't stop :(
814 #ifndef __MINGW32__
815 kill(getpid(),SIGKILL);
816 #endif
818 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
819 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
820 "\nMPlayer interrupted by signal %d in module: %s\n", x,
821 current_module ? current_module : "unknown");
822 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
823 if(sig_count<=1)
824 switch(x){
825 case SIGINT:
826 case SIGPIPE:
827 case SIGQUIT:
828 case SIGTERM:
829 case SIGKILL:
830 async_quit_request = 1;
831 return; // killed from keyboard (^C) or killed [-9]
832 case SIGILL:
833 #if CONFIG_RUNTIME_CPUDETECT
834 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
835 #else
836 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
837 #endif
838 case SIGFPE:
839 case SIGSEGV:
840 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
841 default:
842 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
843 #ifdef CONFIG_CRASH_DEBUG
844 if (crash_debug) {
845 int gdb_pid;
846 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
847 gdb_pid = fork();
848 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
849 if (gdb_pid == 0) { // We are the child
850 char spid[20];
851 snprintf(spid, sizeof(spid), "%i", getppid());
852 getch2_disable(); // allow terminal to work properly with gdb
853 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
854 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
855 } else if (gdb_pid < 0)
856 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
857 else {
858 waitpid(gdb_pid, NULL, 0);
860 if (x == SIGTRAP) return;
862 #endif
864 getch2_disable();
865 exit(1);
868 #include "cfg-mplayer.h"
870 static int cfg_include(m_option_t *conf, char *filename)
872 return m_config_parse_config_file(conf->priv, filename);
875 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
877 struct MPOpts *opts = &mpctx->opts;
878 char *conffile;
879 int conffile_fd;
880 if (!(opts->noconfig & 2) &&
881 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
882 exit_player(mpctx, EXIT_NONE);
883 if ((conffile = get_path("")) == NULL) {
884 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
885 } else {
886 #ifdef __MINGW32__
887 mkdir(conffile);
888 #else
889 mkdir(conffile, 0777);
890 #endif
891 free(conffile);
892 if ((conffile = get_path("config")) == NULL) {
893 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
894 } else {
895 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
896 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
897 write(conffile_fd, default_config, strlen(default_config));
898 close(conffile_fd);
900 if (!(opts->noconfig & 1) &&
901 m_config_parse_config_file(conf, conffile) < 0)
902 exit_player(mpctx, EXIT_NONE);
903 free(conffile);
908 #define PROFILE_CFG_PROTOCOL "protocol."
910 static void load_per_protocol_config (m_config_t* conf, const char *const file)
912 char *str;
913 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
914 m_profile_t *p;
916 /* does filename actually uses a protocol ? */
917 str = strstr (file, "://");
918 if (!str)
919 return;
921 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
922 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
923 p = m_config_get_profile (conf, protocol);
924 if (p)
926 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
927 m_config_set_profile(conf,p);
931 #define PROFILE_CFG_EXTENSION "extension."
933 static void load_per_extension_config (m_config_t* conf, const char *const file)
935 char *str;
936 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
937 m_profile_t *p;
939 /* does filename actually have an extension ? */
940 str = strrchr (file, '.');
941 if (!str)
942 return;
944 sprintf (extension, PROFILE_CFG_EXTENSION);
945 strncat (extension, ++str, 7);
946 p = m_config_get_profile (conf, extension);
947 if (p)
949 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
950 m_config_set_profile(conf,p);
954 #define PROFILE_CFG_VO "vo."
955 #define PROFILE_CFG_AO "ao."
957 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
959 char profile[strlen (cfg) + strlen (out) + 1];
960 m_profile_t *p;
962 sprintf (profile, "%s%s", cfg, out);
963 p = m_config_get_profile (conf, profile);
964 if (p)
966 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
967 m_config_set_profile(conf,p);
972 * Tries to load a config file
973 * @return 0 if file was not found, 1 otherwise
975 static int try_load_config(m_config_t *conf, const char *file)
977 struct stat st;
978 if (stat(file, &st))
979 return 0;
980 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
981 m_config_parse_config_file (conf, file);
982 return 1;
985 static void load_per_file_config (m_config_t* conf, const char *const file)
987 char *confpath;
988 char cfg[PATH_MAX];
989 const char *name;
991 if (strlen(file) > PATH_MAX - 14) {
992 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
993 return;
995 sprintf (cfg, "%s.conf", file);
997 name = mp_basename(cfg);
998 if (use_filedir_conf) {
999 char dircfg[PATH_MAX];
1000 strcpy(dircfg, cfg);
1001 strcpy(dircfg + (name - cfg), "mplayer.conf");
1002 try_load_config(conf, dircfg);
1004 if (try_load_config(conf, cfg))
1005 return;
1008 if ((confpath = get_path (name)) != NULL)
1010 try_load_config(conf, confpath);
1012 free (confpath);
1016 /* When libmpdemux performs a blocking operation (network connection or
1017 * cache filling) if the operation fails we use this function to check
1018 * if it was interrupted by the user.
1019 * The function returns a new value for eof. */
1020 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1022 mp_cmd_t* cmd;
1023 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1024 switch(cmd->id) {
1025 case MP_CMD_QUIT:
1026 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1027 case MP_CMD_PLAY_TREE_STEP: {
1028 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1029 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1030 } break;
1031 case MP_CMD_PLAY_TREE_UP_STEP: {
1032 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1033 } break;
1034 case MP_CMD_PLAY_ALT_SRC_STEP: {
1035 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1036 } break;
1038 mp_cmd_free(cmd);
1040 return stop_play;
1043 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1045 play_tree_add_bpf(entry,mpctx->filename);
1048 if(!entry) {
1049 entry = mpctx->playtree_iter->tree;
1050 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1051 return PT_NEXT_ENTRY;
1053 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1054 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1055 return PT_NEXT_ENTRY;
1058 play_tree_remove(entry,1,1);
1059 return PT_NEXT_SRC;
1061 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1062 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1063 entry = mpctx->playtree_iter->tree;
1064 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1065 return PT_NEXT_ENTRY;
1067 play_tree_remove(entry,1,1);
1069 return PT_NEXT_SRC;
1072 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1074 struct MPOpts *opts = &mpctx->opts;
1075 sub_data *subd = NULL;
1076 struct ass_track *asst = NULL;
1078 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1079 return;
1082 #ifdef CONFIG_ASS
1083 if (opts->ass_enabled) {
1084 #ifdef CONFIG_ICONV
1085 asst = ass_read_stream(ass_library, filename, sub_cp);
1086 #else
1087 asst = ass_read_stream(ass_library, filename, 0);
1088 #endif
1089 if (!asst) {
1090 subd = sub_read_file(filename, fps);
1091 if (subd) {
1092 asst = ass_read_subdata(ass_library, subd, fps);
1093 if (asst) {
1094 sub_free(subd);
1095 subd = NULL;
1099 } else
1100 #endif
1101 subd = sub_read_file(filename, fps);
1104 if (!asst && !subd) {
1105 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1106 "Cannot load subtitles: %s\n", filename_recode(filename));
1107 return;
1110 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1111 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1112 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1113 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1114 filename_recode(filename));
1115 ++mpctx->set_of_sub_size;
1116 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1117 filename_recode(filename));
1120 void init_vo_spudec(struct MPContext *mpctx)
1122 spudec_free(vo_spudec);
1123 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1124 vo_spudec = NULL;
1126 // we currently can't work without video stream
1127 if (!mpctx->sh_video)
1128 return;
1130 if (spudec_ifo) {
1131 unsigned int palette[16], width, height;
1132 current_module="spudec_init_vobsub";
1133 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1134 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1137 #ifdef CONFIG_DVDREAD
1138 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1139 current_module="spudec_init_dvdread";
1140 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1141 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1142 NULL, 0);
1144 #endif
1146 #ifdef CONFIG_DVDNAV
1147 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1148 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1149 current_module="spudec_init_dvdnav";
1150 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1152 #endif
1154 if (vo_spudec==NULL) {
1155 sh_sub_t *sh = mpctx->d_sub->sh;
1156 current_module="spudec_init_normal";
1157 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1158 spudec_set_font_factor(vo_spudec,font_factor);
1161 if (vo_spudec!=NULL) {
1162 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1163 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1168 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1169 * make it all work is to use the builtin SDL-bootstrap code, which
1170 * will be done automatically by replacing our main() if we include SDL.h.
1172 #if defined(__APPLE__) && defined(CONFIG_SDL)
1173 #ifdef CONFIG_SDL_SDL_H
1174 #include <SDL/SDL.h>
1175 #else
1176 #include <SDL.h>
1177 #endif
1178 #endif
1181 * \brief append a formatted string
1182 * \param buf buffer to print into
1183 * \param pos position of terminating 0 in buf
1184 * \param len maximum number of characters in buf, not including terminating 0
1185 * \param format printf format string
1187 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1189 va_list va;
1190 va_start(va, format);
1191 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1192 va_end(va);
1193 if (*pos >= len ) {
1194 buf[len] = 0;
1195 *pos = len;
1200 * \brief append time in the hh:mm:ss.f format
1201 * \param buf buffer to print into
1202 * \param pos position of terminating 0 in buf
1203 * \param len maximum number of characters in buf, not including terminating 0
1204 * \param time time value to convert/append
1206 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1207 int64_t tenths = 10 * time;
1208 int f1 = tenths % 10;
1209 int ss = (tenths / 10) % 60;
1210 int mm = (tenths / 600) % 60;
1211 int hh = tenths / 36000;
1212 if (time <= 0) {
1213 saddf(buf, pos, len, "unknown");
1214 return;
1216 if (hh > 0)
1217 saddf(buf, pos, len, "%2d:", hh);
1218 if (hh > 0 || mm > 0)
1219 saddf(buf, pos, len, "%02d:", mm);
1220 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1223 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1225 struct MPOpts *opts = &mpctx->opts;
1226 sh_video_t * const sh_video = mpctx->sh_video;
1228 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1229 a_pos = playing_audio_pts(mpctx);
1230 if (mpctx->sh_audio && sh_video && at_frame) {
1231 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1232 if (mpctx->time_frame > 0)
1233 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1234 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1235 && !mpctx->drop_message_shown) {
1236 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1237 mpctx->drop_message_shown = true;
1240 if (opts->quiet)
1241 return;
1244 int width;
1245 char *line;
1246 unsigned pos = 0;
1247 get_screen_size();
1248 if (screen_width > 0)
1249 width = screen_width;
1250 else
1251 width = 80;
1252 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1253 /* Windows command line is broken (MinGW's rxvt works, but we
1254 * should not depend on that). */
1255 width--;
1256 #endif
1257 line = malloc(width + 1); // one additional char for the terminating null
1259 // Audio time
1260 if (mpctx->sh_audio) {
1261 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1262 if (!sh_video) {
1263 float len = get_time_length(mpctx);
1264 saddf(line, &pos, width, "(");
1265 sadd_hhmmssf(line, &pos, width, a_pos);
1266 saddf(line, &pos, width, ") of %.1f (", len);
1267 sadd_hhmmssf(line, &pos, width, len);
1268 saddf(line, &pos, width, ") ");
1272 // Video time
1273 if (sh_video)
1274 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1276 // A-V sync
1277 if (mpctx->sh_audio && sh_video)
1278 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1279 mpctx->last_av_difference, mpctx->total_avsync_change);
1281 // Video stats
1282 if (sh_video)
1283 saddf(line, &pos, width, "%3d/%3d ",
1284 (int)sh_video->num_frames,
1285 (int)sh_video->num_frames_decoded);
1287 // CPU usage
1288 if (sh_video) {
1289 if (sh_video->timer > 0.5)
1290 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1291 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1292 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1293 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1294 else
1295 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1296 } else if (mpctx->sh_audio) {
1297 if (mpctx->delay > 0.5)
1298 saddf(line, &pos, width, "%4.1f%% ",
1299 100.0*audio_time_usage/(double)mpctx->delay);
1300 else
1301 saddf(line, &pos, width, "??,?%% ");
1304 // VO stats
1305 if (sh_video)
1306 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1308 #ifdef CONFIG_STREAM_CACHE
1309 // cache stats
1310 if (stream_cache_size > 0)
1311 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1312 #endif
1314 // other
1315 if (opts->playback_speed != 1)
1316 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1318 // end
1319 if (erase_to_end_of_line) {
1320 line[pos] = 0;
1321 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1322 } else {
1323 memset(&line[pos], ' ', width - pos);
1324 line[width] = 0;
1325 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1327 free(line);
1331 * \brief build a chain of audio filters that converts the input format
1332 * to the ao's format, taking into account the current playback_speed.
1333 * \param sh_audio describes the requested input format of the chain.
1334 * \param ao_data describes the requested output format of the chain.
1336 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1337 ao_data_t *ao_data)
1339 struct MPOpts *opts = &mpctx->opts;
1340 int new_srate;
1341 int result;
1342 if (!sh_audio)
1344 mpctx->mixer.afilter = NULL;
1345 return 0;
1347 if(af_control_any_rev(sh_audio->afilter,
1348 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1349 &opts->playback_speed)) {
1350 new_srate = sh_audio->samplerate;
1351 } else {
1352 new_srate = sh_audio->samplerate * opts->playback_speed;
1353 if (new_srate != ao_data->samplerate) {
1354 // limits are taken from libaf/af_resample.c
1355 if (new_srate < 8000)
1356 new_srate = 8000;
1357 if (new_srate > 192000)
1358 new_srate = 192000;
1359 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1362 result = init_audio_filters(sh_audio, new_srate,
1363 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1364 mpctx->mixer.afilter = sh_audio->afilter;
1365 return result;
1369 typedef struct mp_osd_msg mp_osd_msg_t;
1370 struct mp_osd_msg {
1371 /// Previous message on the stack.
1372 mp_osd_msg_t* prev;
1373 /// Message text.
1374 char msg[128];
1375 int id,level,started;
1376 /// Display duration in ms.
1377 unsigned time;
1380 /// OSD message stack.
1381 static mp_osd_msg_t* osd_msg_stack = NULL;
1384 * \brief Add a message on the OSD message stack
1386 * If a message with the same id is already present in the stack
1387 * it is pulled on top of the stack, otherwise a new message is created.
1390 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1391 va_list ap)
1393 mp_osd_msg_t *msg,*last=NULL;
1394 int r;
1396 // look if the id is already in the stack
1397 for(msg = osd_msg_stack ; msg && msg->id != id ;
1398 last = msg, msg = msg->prev);
1399 // not found: alloc it
1400 if(!msg) {
1401 msg = calloc(1,sizeof(mp_osd_msg_t));
1402 msg->prev = osd_msg_stack;
1403 osd_msg_stack = msg;
1404 } else if(last) { // found, but it's not on top of the stack
1405 last->prev = msg->prev;
1406 msg->prev = osd_msg_stack;
1407 osd_msg_stack = msg;
1409 // write the msg
1410 r = vsnprintf(msg->msg, 128, fmt, ap);
1411 if(r >= 128) msg->msg[127] = 0;
1412 // set id and time
1413 msg->id = id;
1414 msg->level = level;
1415 msg->time = time;
1419 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1421 va_list ap;
1422 va_start(ap, fmt);
1423 set_osd_msg_va(id, level, time, fmt, ap);
1424 va_end(ap);
1427 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1429 va_list ap;
1430 va_start(ap, fmt);
1431 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1432 va_end(ap);
1437 * \brief Remove a message from the OSD stack
1439 * This function can be used to get rid of a message right away.
1443 void rm_osd_msg(int id) {
1444 mp_osd_msg_t *msg,*last=NULL;
1446 // Search for the msg
1447 for(msg = osd_msg_stack ; msg && msg->id != id ;
1448 last = msg, msg = msg->prev);
1449 if(!msg) return;
1451 // Detach it from the stack and free it
1452 if(last)
1453 last->prev = msg->prev;
1454 else
1455 osd_msg_stack = msg->prev;
1456 free(msg);
1460 * \brief Remove all messages from the OSD stack
1464 static void clear_osd_msgs(void) {
1465 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1466 while(msg) {
1467 prev = msg->prev;
1468 free(msg);
1469 msg = prev;
1471 osd_msg_stack = NULL;
1475 * \brief Get the current message from the OSD stack.
1477 * This function decrements the message timer and destroys the old ones.
1478 * The message that should be displayed is returned (if any).
1482 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1484 struct MPOpts *opts = &mpctx->opts;
1485 mp_osd_msg_t *msg,*prev,*last = NULL;
1486 static unsigned last_update = 0;
1487 unsigned now = GetTimerMS();
1488 unsigned diff;
1489 char hidden_dec_done = 0;
1491 if (mpctx->osd_visible) {
1492 // 36000000 means max timed visibility is 1 hour into the future, if
1493 // the difference is greater assume it's wrapped around from below 0
1494 if (mpctx->osd_visible - now > 36000000) {
1495 mpctx->osd_visible = 0;
1496 vo_osd_progbar_type = -1; // disable
1497 vo_osd_changed(OSDTYPE_PROGBAR);
1498 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1501 if (mpctx->osd_show_percentage_until - now > 36000000)
1502 mpctx->osd_show_percentage_until = 0;
1504 if(!last_update) last_update = now;
1505 diff = now >= last_update ? now - last_update : 0;
1507 last_update = now;
1509 // Look for the first message in the stack with high enough level.
1510 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1511 prev = msg->prev;
1512 if (msg->level > opts->osd_level && hidden_dec_done)
1513 continue;
1514 // The message has a high enough level or it is the first hidden one
1515 // in both cases we decrement the timer or kill it.
1516 if(!msg->started || msg->time > diff) {
1517 if(msg->started) msg->time -= diff;
1518 else msg->started = 1;
1519 // display it
1520 if (msg->level <= opts->osd_level)
1521 return msg;
1522 hidden_dec_done = 1;
1523 continue;
1525 // kill the message
1526 free(msg);
1527 if(last) {
1528 last->prev = prev;
1529 msg = last;
1530 } else {
1531 osd_msg_stack = prev;
1532 msg = NULL;
1535 // Nothing found
1536 return NULL;
1540 * \brief Display the OSD bar.
1542 * Display the OSD bar or fall back on a simple message.
1546 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1547 struct MPOpts *opts = &mpctx->opts;
1548 if (opts->osd_level < 1)
1549 return;
1551 if(mpctx->sh_video) {
1552 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1553 vo_osd_progbar_type = type;
1554 vo_osd_progbar_value = 256*(val-min)/(max-min);
1555 vo_osd_changed(OSDTYPE_PROGBAR);
1556 return;
1559 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1560 name, ROUND(100*(val-min)/(max-min)));
1564 * \brief Display text subtitles on the OSD
1566 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1568 int i;
1569 vo_sub = subs;
1570 vo_osd_changed(OSDTYPE_SUBTITLE);
1571 if (!mpctx->sh_video) {
1572 // reverse order, since newest set_osd_msg is displayed first
1573 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1574 if (!subs || i >= subs->lines || !subs->text[i])
1575 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1576 else {
1577 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1578 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1579 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1586 * \brief Update the OSD message line.
1588 * This function displays the current message on the vo OSD or on the term.
1589 * If the stack is empty and the OSD level is high enough the timer
1590 * is displayed (only on the vo OSD).
1594 static void update_osd_msg(struct MPContext *mpctx)
1596 struct MPOpts *opts = &mpctx->opts;
1597 mp_osd_msg_t *msg;
1598 struct osd_state *osd = mpctx->osd;
1599 char osd_text_timer[128];
1601 if (mpctx->add_osd_seek_info) {
1602 double percentage = get_percent_pos(mpctx);
1603 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1604 if (mpctx->sh_video)
1605 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1606 mpctx->add_osd_seek_info = false;
1609 // Look if we have a msg
1610 if((msg = get_osd_msg(mpctx))) {
1611 if (strcmp(osd->osd_text, msg->msg)) {
1612 strncpy(osd->osd_text, msg->msg, 127);
1613 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1614 if(opts->term_osd)
1615 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1616 msg->msg);
1618 return;
1621 if(mpctx->sh_video) {
1622 // fallback on the timer
1623 if (opts->osd_level >= 2) {
1624 int len = get_time_length(mpctx);
1625 int percentage = -1;
1626 char percentage_text[10];
1627 int pts = get_current_time(mpctx);
1629 if (mpctx->osd_show_percentage_until)
1630 percentage = get_percent_pos(mpctx);
1632 if (percentage >= 0)
1633 snprintf(percentage_text, 9, " (%d%%)", percentage);
1634 else
1635 percentage_text[0] = 0;
1637 if (opts->osd_level == 3)
1638 snprintf(osd_text_timer, 63,
1639 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1640 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1641 len/3600,(len/60)%60,len%60,percentage_text);
1642 else
1643 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1644 mpctx->osd_function,pts/3600,(pts/60)%60,
1645 pts%60,percentage_text);
1646 } else
1647 osd_text_timer[0]=0;
1649 if (strcmp(osd->osd_text, osd_text_timer)) {
1650 strncpy(osd->osd_text, osd_text_timer, 63);
1651 vo_osd_changed(OSDTYPE_OSD);
1653 return;
1656 // Clear the term osd line
1657 if (opts->term_osd && osd->osd_text[0]) {
1658 osd->osd_text[0] = 0;
1659 printf("%s\n", opts->term_osd_esc);
1663 ///@}
1664 // OSDMsgStack
1667 void reinit_audio_chain(struct MPContext *mpctx)
1669 struct MPOpts *opts = &mpctx->opts;
1670 if (!mpctx->sh_audio)
1671 return;
1672 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1673 current_module="init_audio_codec";
1674 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1675 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1676 goto init_error;
1678 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1679 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1683 current_module="af_preinit";
1684 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1685 ao_data.samplerate=force_srate;
1686 ao_data.channels=0;
1687 ao_data.format = opts->audio_output_format;
1689 // first init to detect best values
1690 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1691 // input:
1692 mpctx->sh_audio->samplerate,
1693 // output:
1694 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1695 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1696 "pre-init!\n");
1697 exit_player(mpctx, EXIT_ERROR);
1699 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1700 current_module="ao2_init";
1701 ao_data.buffersize = opts->ao_buffersize;
1702 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1703 0, // plugin flag
1704 ao_data.samplerate,
1705 ao_data.channels,
1706 ao_data.format, 0);
1707 if(!mpctx->audio_out){
1708 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1709 goto init_error;
1711 mpctx->initialized_flags|=INITIALIZED_AO;
1712 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1713 mpctx->audio_out->info->short_name,
1714 ao_data.samplerate, ao_data.channels,
1715 af_fmt2str_short(ao_data.format),
1716 af_fmt2bits(ao_data.format)/8 );
1717 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1718 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1719 if(strlen(mpctx->audio_out->info->comment) > 0)
1720 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1723 // init audio filters:
1724 current_module="af_init";
1725 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1726 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1727 goto init_error;
1729 mpctx->mixer.audio_out = mpctx->audio_out;
1730 mpctx->mixer.volstep = volstep;
1731 mpctx->syncing_audio = true;
1732 return;
1734 init_error:
1735 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1736 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1737 mpctx->d_audio->id = -2;
1741 ///@}
1742 // Command2Property
1745 // Return pts value corresponding to the end point of audio written to the
1746 // ao so far.
1747 static double written_audio_pts(struct MPContext *mpctx)
1749 sh_audio_t *sh_audio = mpctx->sh_audio;
1750 demux_stream_t *d_audio = mpctx->d_audio;
1751 double buffered_output;
1752 // first calculate the end pts of audio that has been output by decoder
1753 double a_pts = sh_audio->pts;
1754 if (a_pts != MP_NOPTS_VALUE)
1755 // Good, decoder supports new way of calculating audio pts.
1756 // sh_audio->pts is the timestamp of the latest input packet with
1757 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1758 // the amount of bytes the decoder has written after that timestamp.
1759 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1760 else {
1761 // Decoder doesn't support new way of calculating pts (or we're
1762 // being called before it has decoded anything with known timestamp).
1763 // Use the old method of audio pts calculation: take the timestamp
1764 // of last packet with known pts the decoder has read data from,
1765 // and add amount of bytes read after the beginning of that packet
1766 // divided by input bps. This will be inaccurate if the input/output
1767 // ratio is not constant for every audio packet or if it is constant
1768 // but not accurately known in sh_audio->i_bps.
1770 a_pts = d_audio->pts;
1771 // ds_tell_pts returns bytes read after last timestamp from
1772 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1773 // it has read but not decoded
1774 if (sh_audio->i_bps)
1775 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1776 (double)sh_audio->i_bps;
1778 // Now a_pts hopefully holds the pts for end of audio from decoder.
1779 // Substract data in buffers between decoder and audio out.
1781 // Decoded but not filtered
1782 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1784 // Data buffered in audio filters, measured in bytes of "missing" output
1785 buffered_output = af_calc_delay(sh_audio->afilter);
1787 // Data that was ready for ao but was buffered because ao didn't fully
1788 // accept everything to internal buffers yet
1789 buffered_output += sh_audio->a_out_buffer_len;
1791 // Filters divide audio length by playback_speed, so multiply by it
1792 // to get the length in original units without speedup or slowdown
1793 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1795 return a_pts + mpctx->video_offset;
1798 // Return pts value corresponding to currently playing audio.
1799 double playing_audio_pts(struct MPContext *mpctx)
1801 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1802 mpctx->audio_out->get_delay();
1805 static bool is_text_sub(int type)
1807 return type == 't' || type == 'm' || type == 'a';
1810 static bool is_av_sub(int type)
1812 return type == 'b' || type == 'p' || type == 'x';
1815 void update_subtitles(struct MPContext *mpctx, double refpts,
1816 double sub_offset, bool reset)
1818 struct MPOpts *opts = &mpctx->opts;
1819 struct sh_video *sh_video = mpctx->sh_video;
1820 struct demux_stream *d_sub = mpctx->d_sub;
1821 double curpts = refpts + sub_delay;
1822 unsigned char *packet=NULL;
1823 int len;
1824 int type = d_sub->sh ? ((sh_sub_t *)d_sub->sh)->type : 'v';
1825 static subtitle subs;
1826 if (reset) {
1827 sub_clear_text(&subs, MP_NOPTS_VALUE);
1828 if (vo_sub)
1829 set_osd_subtitle(mpctx, NULL);
1830 if (vo_spudec) {
1831 spudec_reset(vo_spudec);
1832 vo_osd_changed(OSDTYPE_SPU);
1834 #ifdef CONFIG_FFMPEG
1835 if (is_av_sub(type))
1836 reset_avsub(d_sub->sh);
1837 #endif
1838 return;
1840 // find sub
1841 if (mpctx->subdata) {
1842 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1843 current_module = "find_sub";
1844 find_sub(mpctx, mpctx->subdata, curpts *
1845 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1846 if (vo_sub)
1847 mpctx->vo_sub_last = vo_sub;
1850 // DVD sub:
1851 if (vobsub_id >= 0 || type == 'v') {
1852 int timestamp;
1853 current_module = "spudec";
1854 /* Get a sub packet from the DVD or a vobsub */
1855 while(1) {
1856 // Vobsub
1857 len = 0;
1858 if (vo_vobsub) {
1859 if (curpts >= 0) {
1860 len = vobsub_get_packet(vo_vobsub, curpts,
1861 (void**)&packet, &timestamp);
1862 if (len > 0) {
1863 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);
1866 } else {
1867 // DVD sub
1868 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1869 if (len > 0) {
1870 // XXX This is wrong, sh_video->pts can be arbitrarily
1871 // much behind demuxing position. Unfortunately using
1872 // d_video->pts which would have been the simplest
1873 // improvement doesn't work because mpeg specific hacks
1874 // in video.c set d_video->pts to 0.
1875 float x = d_sub->pts - refpts;
1876 if (x > -20 && x < 20) // prevent missing subs on pts reset
1877 timestamp = 90000*d_sub->pts;
1878 else timestamp = 90000*curpts;
1879 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1880 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1881 refpts, d_sub->pts, timestamp);
1884 if (len<=0 || !packet) break;
1885 // create it only here, since with some broken demuxers we might
1886 // type = v but no DVD sub and we currently do not change the
1887 // "original frame size" ever after init, leading to wrong-sized
1888 // PGS subtitles.
1889 if (!vo_spudec)
1890 vo_spudec = spudec_new(NULL);
1891 if (vo_vobsub || timestamp >= 0)
1892 spudec_assemble(vo_spudec, packet, len, timestamp);
1894 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1895 if (type == 'd' && !d_sub->demuxer->teletext) {
1896 tt_stream_props tsp = {0};
1897 void *ptr = &tsp;
1898 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1899 d_sub->demuxer->teletext = ptr;
1901 if (d_sub->non_interleaved)
1902 ds_get_next_pts(d_sub);
1904 int orig_type = type;
1905 while (d_sub->first) {
1906 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1907 type = orig_type;
1908 if (subpts > curpts) {
1909 // Libass handled subs can be fed to it in advance
1910 if (!opts->ass_enabled || !is_text_sub(type))
1911 break;
1912 // Try to avoid demuxing whole file at once
1913 if (d_sub->non_interleaved && subpts > curpts + 1)
1914 break;
1916 double endpts = d_sub->first->endpts + sub_offset;
1917 len = ds_get_packet_sub(d_sub, &packet);
1918 if (is_av_sub(type)) {
1919 #ifdef CONFIG_FFMPEG
1920 type = decode_avsub(d_sub->sh, &packet, &len, &subpts, &endpts);
1921 if (type <= 0)
1922 #endif
1923 continue;
1925 if (type == 'm') {
1926 if (len < 2) continue;
1927 len = FFMIN(len - 2, AV_RB16(packet));
1928 packet += 2;
1930 if (type == 'd') {
1931 if (d_sub->demuxer->teletext) {
1932 uint8_t *p = packet;
1933 p++;
1934 len--;
1935 while (len >= 46) {
1936 int sublen = p[1];
1937 if (p[0] == 2 || p[0] == 3)
1938 teletext_control(d_sub->demuxer->teletext,
1939 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1940 p += sublen + 2;
1941 len -= sublen + 2;
1944 continue;
1946 #ifdef CONFIG_ASS
1947 if (opts->ass_enabled) {
1948 sh_sub_t* sh = d_sub->sh;
1949 mpctx->osd->ass_track = sh ? sh->ass_track : NULL;
1950 if (!mpctx->osd->ass_track) continue;
1951 if (type == 'a') { // ssa/ass subs with libass
1952 ass_process_chunk(mpctx->osd->ass_track, packet, len,
1953 (long long)(subpts*1000 + 0.5),
1954 (long long)((endpts-subpts)*1000 + 0.5));
1955 } else { // plaintext subs with libass
1956 if (subpts != MP_NOPTS_VALUE) {
1957 subtitle tmp_subs = {0};
1958 if (endpts == MP_NOPTS_VALUE) endpts = subpts + 3;
1959 sub_add_text(&tmp_subs, packet, len, endpts);
1960 tmp_subs.start = subpts * 100;
1961 tmp_subs.end = endpts * 100;
1962 ass_process_subtitle(mpctx->osd->ass_track, &tmp_subs);
1963 sub_clear_text(&tmp_subs, MP_NOPTS_VALUE);
1966 continue;
1968 #endif
1969 if (subpts != MP_NOPTS_VALUE) {
1970 if (endpts == MP_NOPTS_VALUE)
1971 sub_clear_text(&subs, MP_NOPTS_VALUE);
1972 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1973 int i;
1974 unsigned char* p = packet;
1975 for (i=0; i < 8 && *p != '\0'; p++)
1976 if (*p == ',')
1977 i++;
1978 if (*p == '\0') /* Broken line? */
1979 continue;
1980 len -= p - packet;
1981 packet = p;
1983 sub_add_text(&subs, packet, len, endpts);
1984 set_osd_subtitle(mpctx, &subs);
1986 if (d_sub->non_interleaved)
1987 ds_get_next_pts(d_sub);
1989 if (!opts->ass_enabled)
1990 if (sub_clear_text(&subs, curpts))
1991 set_osd_subtitle(mpctx, &subs);
1993 if (vo_spudec) {
1994 spudec_heartbeat(vo_spudec, 90000*curpts);
1995 if (spudec_changed(vo_spudec))
1996 vo_osd_changed(OSDTYPE_SPU);
1999 current_module=NULL;
2002 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2004 int page_changed;
2006 if (!demuxer->teletext)
2007 return;
2009 //Also forcing page update when such ioctl is not supported or call error occured
2010 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2011 page_changed=1;
2013 if(!page_changed)
2014 return;
2016 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2017 vo_osd_teletext_page=NULL;
2018 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2019 vo_osd_teletext_half=0;
2020 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2021 vo_osd_teletext_mode=0;
2022 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2023 vo_osd_teletext_format=0;
2024 vo_osd_changed(OSDTYPE_TELETEXT);
2026 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2029 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2030 struct MPOpts *opts = &mpctx->opts;
2031 // check for frame-drop:
2032 current_module = "check_framedrop";
2033 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2034 static int dropped_frames;
2035 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
2036 float d = delay-mpctx->delay;
2037 ++total_frame_cnt;
2038 // we should avoid dropping too many frames in sequence unless we
2039 // are too late. and we allow 100ms A-V delay here:
2040 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2041 && !mpctx->restart_playback) {
2042 ++drop_frame_cnt;
2043 ++dropped_frames;
2044 return frame_dropping;
2045 } else
2046 dropped_frames = 0;
2048 return 0;
2052 #ifdef HAVE_RTC
2053 int rtc_fd = -1;
2054 #endif
2056 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2058 #ifdef HAVE_RTC
2059 if (rtc_fd >= 0){
2060 // -------- RTC -----------
2061 current_module="sleep_rtc";
2062 while (time_frame > 0.000) {
2063 unsigned long rtc_ts;
2064 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2065 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2066 time_frame -= get_relative_time(mpctx);
2068 } else
2069 #endif
2071 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2072 // unnecessarily high CPU usage
2073 struct MPOpts *opts = &mpctx->opts;
2074 float margin = opts->softsleep ? 0.011 : 0;
2075 current_module = "sleep_timer";
2076 while (time_frame > margin) {
2077 usec_sleep(1000000 * (time_frame - margin));
2078 time_frame -= get_relative_time(mpctx);
2080 if (opts->softsleep){
2081 current_module = "sleep_soft";
2082 if (time_frame < 0)
2083 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2084 while (time_frame > 0)
2085 time_frame -= get_relative_time(mpctx); // burn the CPU
2088 return time_frame;
2091 static int select_subtitle(MPContext *mpctx)
2093 struct MPOpts *opts = &mpctx->opts;
2094 // find the best sub to use
2095 int id;
2096 int found = 0;
2097 mpctx->global_sub_pos = -1; // no subs by default
2098 if (vobsub_id >= 0) {
2099 // if user asks for a vobsub id, use that first.
2100 id = vobsub_id;
2101 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2104 if (!found && opts->sub_id >= 0) {
2105 // if user asks for a dvd sub id, use that next.
2106 id = opts->sub_id;
2107 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2110 if (!found) {
2111 // if there are text subs to use, use those. (autosubs come last here)
2112 id = 0;
2113 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2116 if (!found && opts->sub_id == -1) {
2117 // finally select subs by language and container hints
2118 if (opts->sub_id == -1)
2119 opts->sub_id =
2120 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2121 opts->sub_lang);
2122 if (opts->sub_id >= 0) {
2123 id = opts->sub_id;
2124 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2127 return found;
2130 #ifdef CONFIG_DVDNAV
2131 #ifndef FF_B_TYPE
2132 #define FF_B_TYPE 3
2133 #endif
2134 /// store decoded video image
2135 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2136 mp_image_t *from_mpi) {
2137 mp_image_t *mpi;
2139 /// Do not store B-frames
2140 if (from_mpi->pict_type == FF_B_TYPE)
2141 return to_mpi;
2143 if (to_mpi &&
2144 to_mpi->w == from_mpi->w &&
2145 to_mpi->h == from_mpi->h &&
2146 to_mpi->imgfmt == from_mpi->imgfmt)
2147 mpi = to_mpi;
2148 else {
2149 if (to_mpi)
2150 free_mp_image(to_mpi);
2151 if (from_mpi->w == 0 || from_mpi->h == 0)
2152 return NULL;
2153 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2156 copy_mpi(mpi,from_mpi);
2157 return mpi;
2160 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2161 struct MPOpts *opts = &ctx->opts;
2162 if (ctx->sh_video) {
2163 /// clear video pts
2164 ctx->d_video->pts = 0.0f;
2165 ctx->sh_video->pts = 0.0f;
2166 ctx->sh_video->i_pts = 0.0f;
2167 ctx->sh_video->last_pts = 0.0f;
2168 ctx->sh_video->num_buffered_pts = 0;
2169 ctx->sh_video->num_frames = 0;
2170 ctx->sh_video->num_frames_decoded = 0;
2171 ctx->sh_video->timer = 0.0f;
2172 ctx->sh_video->stream_delay = 0.0f;
2173 ctx->sh_video->timer = 0;
2174 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2177 if (ctx->sh_audio) {
2178 /// free audio packets and reset
2179 ds_free_packs(ctx->d_audio);
2180 audio_delay -= ctx->sh_audio->stream_delay;
2181 ctx->delay =- audio_delay;
2182 ctx->audio_out->reset();
2183 resync_audio_stream(ctx->sh_audio);
2186 audio_delay = 0.0f;
2187 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2188 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2189 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2190 if (dvdsub_lang_id != opts->sub_id) {
2191 opts->sub_id = dvdsub_lang_id;
2192 select_subtitle(ctx);
2196 /// clear all EOF related flags
2197 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2200 /// Restore last decoded DVDNAV (still frame)
2201 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2202 int *in_size,
2203 unsigned char **start,
2204 mp_image_t *decoded_frame)
2206 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2207 return decoded_frame;
2209 /// a change occured in dvdnav stream
2210 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2211 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2212 mp_dvdnav_context_free(mpctx);
2213 mp_dvdnav_reset_stream(mpctx);
2214 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2215 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2218 if (*in_size < 0) {
2219 float len;
2221 /// Display still frame, if any
2222 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2223 decoded_frame = mpctx->nav_smpi;
2225 /// increment video frame : continue playing after still frame
2226 len = get_time_length(mpctx);
2227 if (mpctx->sh_video->pts >= len &&
2228 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2229 mp_dvdnav_skip_still(mpctx->stream);
2230 mp_dvdnav_skip_wait(mpctx->stream);
2232 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2234 if (mpctx->nav_buffer) {
2235 *start = mpctx->nav_start;
2236 *in_size = mpctx->nav_in_size;
2237 if (mpctx->nav_start)
2238 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2242 return decoded_frame;
2245 /// Save last decoded DVDNAV (still frame)
2246 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2247 unsigned char *start,
2248 mp_image_t *decoded_frame)
2250 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2251 return;
2253 free(mpctx->nav_buffer);
2255 mpctx->nav_buffer = malloc(in_size);
2256 mpctx->nav_start = start;
2257 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2258 if (mpctx->nav_buffer)
2259 memcpy(mpctx->nav_buffer,start,in_size);
2261 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2262 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2264 #endif /* CONFIG_DVDNAV */
2266 /* Modify video timing to match the audio timeline. There are two main
2267 * reasons this is needed. First, video and audio can start from different
2268 * positions at beginning of file or after a seek (MPlayer starts both
2269 * immediately even if they have different pts). Second, the file can have
2270 * audio timestamps that are inconsistent with the duration of the audio
2271 * packets, for example two consecutive timestamp values differing by
2272 * one second but only a packet with enough samples for half a second
2273 * of playback between them.
2275 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2277 current_module = "av_sync";
2279 if (!mpctx->sh_audio || mpctx->syncing_audio)
2280 return;
2282 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2283 double v_pts = mpctx->sh_video->pts;
2284 double av_delay = a_pts - v_pts;
2285 // Try to sync vo_flip() so it will *finish* at given time
2286 av_delay += mpctx->last_vo_flip_duration;
2287 av_delay -= audio_delay; // This much pts difference is desired
2289 double change = av_delay * 0.1;
2290 double max_change = default_max_pts_correction >= 0 ?
2291 default_max_pts_correction : frame_time * 0.1;
2292 if (change < -max_change)
2293 change = -max_change;
2294 else if (change > max_change)
2295 change = max_change;
2296 mpctx->delay += change;
2297 mpctx->total_avsync_change += change;
2300 #define ASYNC_PLAY_DONE -3
2301 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2303 struct MPOpts *opts = &mpctx->opts;
2304 sh_audio_t * const sh_audio = mpctx->sh_audio;
2305 int res;
2307 // Timing info may not be set without
2308 res = decode_audio(sh_audio, 1);
2309 if (res < 0)
2310 return res;
2312 int bytes;
2313 bool did_retry = false;
2314 while (1) {
2315 double written_pts = written_audio_pts(mpctx);
2316 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2317 - audio_delay;
2318 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2319 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2321 // ogg demuxers give packets without timing
2322 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2323 if (!did_retry) {
2324 // Try to read more data to see packets that have pts
2325 int res = decode_audio(sh_audio, ao_data.bps);
2326 if (res < 0)
2327 return res;
2328 did_retry = true;
2329 continue;
2331 bytes = 0;
2334 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2335 bytes = 0;
2337 if (bytes > 0)
2338 break;
2340 mpctx->syncing_audio = false;
2341 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2342 int res = decode_audio(sh_audio, a);
2343 bytes += sh_audio->a_out_buffer_len;
2344 if (bytes >= 0) {
2345 memmove(sh_audio->a_out_buffer,
2346 sh_audio->a_out_buffer +
2347 sh_audio->a_out_buffer_len - bytes,
2348 bytes);
2349 sh_audio->a_out_buffer_len = bytes;
2350 if (res < 0)
2351 return res;
2352 return decode_audio(sh_audio, playsize);
2354 sh_audio->a_out_buffer_len = 0;
2355 if (res < 0)
2356 return res;
2358 int fillbyte = 0;
2359 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2360 fillbyte = 0x80;
2361 if (bytes >= playsize) {
2362 /* This case could fall back to the one below with
2363 * bytes = playsize, but then silence would keep accumulating
2364 * in a_out_buffer if the AO accepts less data than it asks for
2365 * in playsize. */
2366 char *p = malloc(playsize);
2367 memset(p, fillbyte, playsize);
2368 playsize = mpctx->audio_out->play(p, playsize, 0);
2369 free(p);
2370 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2371 return ASYNC_PLAY_DONE;
2373 mpctx->syncing_audio = false;
2374 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2375 return decode_audio(sh_audio, playsize);
2378 static int fill_audio_out_buffers(struct MPContext *mpctx)
2380 struct MPOpts *opts = &mpctx->opts;
2381 unsigned int t;
2382 double tt;
2383 int playsize;
2384 int playflags=0;
2385 int audio_eof=0;
2386 bool format_change = false;
2387 sh_audio_t * const sh_audio = mpctx->sh_audio;
2389 current_module="play_audio";
2391 while (1) {
2392 int sleep_time;
2393 // all the current uses of ao_data.pts seem to be in aos that handle
2394 // sync completely wrong; there should be no need to use ao_data.pts
2395 // in get_space()
2396 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2397 playsize = mpctx->audio_out->get_space();
2398 if (mpctx->sh_video || playsize >= ao_data.outburst)
2399 break;
2401 // handle audio-only case:
2402 // this is where mplayer sleeps during audio-only playback
2403 // to avoid 100% CPU use
2404 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2405 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2406 usec_sleep(sleep_time * 1000);
2409 // Fill buffer if needed:
2410 current_module="decode_audio";
2411 t = GetTimer();
2413 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2414 mpctx->syncing_audio = false;
2416 int res;
2417 if (mpctx->syncing_audio && mpctx->sh_video)
2418 res = audio_start_sync(mpctx, playsize);
2419 else
2420 res = decode_audio(sh_audio, playsize);
2421 if (res < 0) { // EOF, error or format change
2422 if (res == -2)
2423 format_change = true;
2424 else if (res == ASYNC_PLAY_DONE)
2425 return 1;
2426 else if (mpctx->d_audio->eof) {
2427 audio_eof = 1;
2428 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2429 if (sh_audio->a_out_buffer_len < unitsize)
2430 return 0;
2433 t = GetTimer() - t;
2434 tt = t*0.000001f; audio_time_usage+=tt;
2435 if (playsize > sh_audio->a_out_buffer_len) {
2436 playsize = sh_audio->a_out_buffer_len;
2437 if (audio_eof)
2438 playflags |= AOPLAY_FINAL_CHUNK;
2440 if (!playsize)
2441 return 1;
2443 // play audio:
2444 current_module="play_audio";
2446 // Is this pts value actually useful for the aos that access it?
2447 // They're obviously badly broken in the way they handle av sync;
2448 // would not having access to this make them more broken?
2449 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2450 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2452 if (playsize > 0) {
2453 sh_audio->a_out_buffer_len -= playsize;
2454 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2455 sh_audio->a_out_buffer_len);
2456 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2457 } else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2458 // Sanity check to avoid hanging in case current ao doesn't output
2459 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2460 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2461 sh_audio->a_out_buffer_len = 0;
2464 /* The format change isn't handled too gracefully. A more precise
2465 * implementation would require draining buffered old-format audio
2466 * while displaying video, then doing the output format switch.
2468 if (format_change) {
2469 uninit_player(mpctx, INITIALIZED_AO);
2470 reinit_audio_chain(mpctx);
2473 return 1;
2476 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2477 float *aq_sleep_time)
2479 struct MPOpts *opts = &mpctx->opts;
2480 double audio_limit = 2;
2481 current_module="calc_sleep_time";
2483 if (mpctx->restart_playback)
2484 return 0;
2486 *time_frame -= get_relative_time(mpctx); // reset timer
2488 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2489 float delay = mpctx->audio_out->get_delay();
2490 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2492 if (opts->autosync) {
2494 * Adjust this raw delay value by calculating the expected
2495 * delay for this frame and generating a new value which is
2496 * weighted between the two. The higher autosync is, the
2497 * closer to the delay value gets to that which "-nosound"
2498 * would have used, and the longer it will take for A/V
2499 * sync to settle at the right value (but it eventually will.)
2500 * This settling time is very short for values below 100.
2502 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2503 float difference = delay - predicted;
2504 delay = predicted + difference / (float)opts->autosync;
2507 *time_frame = delay - mpctx->delay / opts->playback_speed;
2509 // delay = amount of audio buffered in soundcard/driver
2510 delay = FFMIN(delay, 0.5);
2511 delay = FFMAX(delay, 0.1);
2512 audio_limit = delay;
2513 } else {
2514 // If we're lagging more than 200 ms behind the right playback rate,
2515 // don't try to "catch up".
2516 // If benchmark is set always output frames as fast as possible
2517 // without sleeping.
2518 if (*time_frame < -0.2 || opts->benchmark)
2519 *time_frame = 0;
2522 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2524 if (t <= 0.05)
2525 return 0;
2527 t -= 0.05;
2528 if (t > audio_limit * 0.6)
2529 t = audio_limit * 0.5;
2530 *aq_sleep_time += t;
2531 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2532 return 1;
2535 int reinit_video_chain(struct MPContext *mpctx)
2537 struct MPOpts *opts = &mpctx->opts;
2538 sh_video_t * const sh_video = mpctx->sh_video;
2539 double ar=-1.0;
2540 //================== Init VIDEO (codec & libvo) ==========================
2541 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2542 current_module="preinit_libvo";
2544 //shouldn't we set dvideo->id=-2 when we fail?
2545 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2546 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2547 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2548 goto err_out;
2550 mpctx->initialized_flags|=INITIALIZED_VO;
2553 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2554 mpctx->sh_video->stream_aspect = ar;
2555 current_module="init_video_filters";
2557 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2558 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2560 #ifdef CONFIG_MENU
2561 if(use_menu) {
2562 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2563 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2564 if(!vf_menu) {
2565 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2566 use_menu = 0;
2569 if(vf_menu)
2570 sh_video->vfilter = vf_menu;
2571 #endif
2573 #ifdef CONFIG_ASS
2574 if(opts->ass_enabled) {
2575 int i;
2576 int insert = 1;
2577 if (opts->vf_settings)
2578 for (i = 0; opts->vf_settings[i].name; ++i)
2579 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2580 insert = 0;
2581 break;
2583 if (insert) {
2584 extern vf_info_t vf_info_ass;
2585 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2586 char* vf_arg[] = {"auto", "1", NULL};
2587 int retcode = 0;
2588 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2589 sh_video->vfilter,
2590 "ass", vf_arg,
2591 &retcode);
2592 if (vf_ass)
2593 sh_video->vfilter = vf_ass;
2594 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2595 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2596 else
2597 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2600 #endif
2602 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2604 #ifdef CONFIG_ASS
2605 if (opts->ass_enabled)
2606 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2607 #endif
2609 current_module="init_video_codec";
2611 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2612 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2613 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2615 if(!sh_video->initialized){
2616 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2617 goto err_out;
2620 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2622 if (sh_video->codec)
2623 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2625 sh_video->last_pts = MP_NOPTS_VALUE;
2626 sh_video->num_buffered_pts = 0;
2627 sh_video->next_frame_time = 0;
2629 if (opts->auto_quality > 0) {
2630 // Auto quality option enabled
2631 output_quality=get_video_quality_max(sh_video);
2632 if (opts->auto_quality > output_quality)
2633 opts->auto_quality = output_quality;
2634 else
2635 output_quality = opts->auto_quality;
2636 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2637 set_video_quality(sh_video,output_quality);
2640 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2642 current_module="init_vo";
2644 return 1;
2646 err_out:
2647 mpctx->sh_video = mpctx->d_video->sh = NULL;
2648 return 0;
2651 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2653 struct sh_video *sh_video = mpctx->sh_video;
2654 double frame_time = 0;
2655 struct vo *video_out = mpctx->video_out;
2656 while (1) {
2657 current_module = "filter_video";
2658 // In nocorrect-pts mode there is no way to properly time these frames
2659 if (vo_get_buffered_frame(video_out, 0) >= 0)
2660 break;
2661 if (vf_output_queued_frame(sh_video->vfilter))
2662 break;
2663 unsigned char *packet = NULL;
2664 frame_time = sh_video->next_frame_time;
2665 if (mpctx->restart_playback)
2666 frame_time = 0;
2667 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2668 &packet, force_fps);
2669 if (in_size < 0) {
2670 #ifdef CONFIG_DVDNAV
2671 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2672 if (mp_dvdnav_is_eof(mpctx->stream))
2673 return -1;
2674 if (mpctx->d_video)
2675 mpctx->d_video->eof = 0;
2676 if (mpctx->d_audio)
2677 mpctx->d_audio->eof = 0;
2678 mpctx->stream->eof = 0;
2679 } else
2680 #endif
2681 return -1;
2683 if (in_size > max_framesize)
2684 max_framesize = in_size;
2685 sh_video->timer += frame_time;
2686 if (mpctx->sh_audio)
2687 mpctx->delay -= frame_time;
2688 // video_read_frame can change fps (e.g. for ASF video)
2689 vo_fps = sh_video->fps;
2690 int framedrop_type = check_framedrop(mpctx, frame_time);
2691 current_module = "decode video";
2693 void *decoded_frame;
2694 #ifdef CONFIG_DVDNAV
2695 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2696 if (in_size >= 0 && !decoded_frame)
2697 #endif
2698 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2699 sh_video->pts);
2700 #ifdef CONFIG_DVDNAV
2701 // Save last still frame for future display
2702 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2703 #endif
2704 if (decoded_frame) {
2705 current_module = "filter video";
2706 filter_video(sh_video, decoded_frame, sh_video->pts);
2708 break;
2710 return frame_time;
2713 static void determine_frame_pts(struct MPContext *mpctx)
2715 struct sh_video *sh_video = mpctx->sh_video;
2716 struct MPOpts *opts = &mpctx->opts;
2718 if (opts->user_pts_assoc_mode) {
2719 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2720 } else if (sh_video->pts_assoc_mode == 0) {
2721 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2722 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2723 sh_video->pts_assoc_mode = 1;
2724 else
2725 sh_video->pts_assoc_mode = 2;
2726 } else {
2727 int probcount1 = sh_video->num_reordered_pts_problems;
2728 int probcount2 = sh_video->num_sorted_pts_problems;
2729 if (sh_video->pts_assoc_mode == 2) {
2730 int tmp = probcount1;
2731 probcount1 = probcount2;
2732 probcount2 = tmp;
2734 if (probcount1 >= probcount2 * 1.5 + 2) {
2735 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2736 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2737 "%d.\n", sh_video->pts_assoc_mode);
2740 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2741 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2744 static double update_video(struct MPContext *mpctx)
2746 struct sh_video *sh_video = mpctx->sh_video;
2747 struct vo *video_out = mpctx->video_out;
2748 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2749 mpctx->osd); // hack for vf_expand
2750 if (!mpctx->opts.correct_pts)
2751 return update_video_nocorrect_pts(mpctx);
2753 double pts;
2755 while (1) {
2756 current_module = "filter_video";
2757 if (!mpctx->hrseek_active
2758 && vo_get_buffered_frame(video_out, false) >= 0)
2759 break;
2760 // XXX Time used in this call is not counted in any performance
2761 // timer now
2762 if (vf_output_queued_frame(sh_video->vfilter))
2763 break;
2764 unsigned char *packet = NULL;
2765 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2766 if (pts != MP_NOPTS_VALUE)
2767 pts += mpctx->video_offset;
2768 bool hit_eof = false;
2769 if (in_size < 0) {
2770 // try to extract last frames in case of decoder lag
2771 in_size = 0;
2772 pts = MP_NOPTS_VALUE;
2773 hit_eof = true;
2775 if (in_size > max_framesize)
2776 max_framesize = in_size;
2777 current_module = "decode video";
2778 if (pts >= mpctx->hrseek_pts - .005)
2779 mpctx->hrseek_framedrop = false;
2780 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2781 check_framedrop(mpctx, sh_video->frametime);
2782 void *decoded_frame = decode_video(sh_video, packet, in_size,
2783 framedrop_type, pts);
2784 if (decoded_frame) {
2785 determine_frame_pts(mpctx);
2786 current_module = "filter video";
2787 filter_video(sh_video, decoded_frame, sh_video->pts);
2788 } else if (hit_eof) {
2789 if (vo_get_buffered_frame(video_out, true) < 0)
2790 return -1;
2792 break;
2795 if (!video_out->frame_loaded)
2796 return 0;
2798 pts = video_out->next_pts;
2799 if (pts == MP_NOPTS_VALUE) {
2800 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2801 // Try to use decoder pts from before filters
2802 pts = sh_video->pts;
2803 if (pts == MP_NOPTS_VALUE)
2804 pts = sh_video->last_pts;
2806 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005)
2807 return 0;
2808 mpctx->hrseek_active = false;
2809 sh_video->pts = pts;
2810 if (sh_video->last_pts == MP_NOPTS_VALUE)
2811 sh_video->last_pts = sh_video->pts;
2812 else if (sh_video->last_pts > sh_video->pts) {
2813 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2814 sh_video->pts, sh_video->last_pts);
2815 /* If the difference in pts is small treat it as jitter around the
2816 * right value (possibly caused by incorrect timestamp ordering) and
2817 * just show this frame immediately after the last one.
2818 * Treat bigger differences as timestamp resets and start counting
2819 * timing of later frames from the position of this one. */
2820 if (sh_video->last_pts - sh_video->pts > 0.5)
2821 sh_video->last_pts = sh_video->pts;
2822 else
2823 sh_video->pts = sh_video->last_pts;
2825 double frame_time = sh_video->pts - sh_video->last_pts;
2826 sh_video->last_pts = sh_video->pts;
2827 sh_video->timer += frame_time;
2828 if (mpctx->sh_audio)
2829 mpctx->delay -= frame_time;
2830 return frame_time;
2833 void pause_player(struct MPContext *mpctx)
2835 if (mpctx->paused)
2836 return;
2837 mpctx->paused = 1;
2838 mpctx->step_frames = 0;
2839 mpctx->time_frame -= get_relative_time(mpctx);
2841 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2842 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2844 if (mpctx->audio_out && mpctx->sh_audio)
2845 mpctx->audio_out->pause(); // pause audio, keep data if possible
2848 void unpause_player(struct MPContext *mpctx)
2850 if (!mpctx->paused)
2851 return;
2852 mpctx->paused = 0;
2854 if (mpctx->audio_out && mpctx->sh_audio)
2855 mpctx->audio_out->resume(); // resume audio
2856 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2857 && !mpctx->step_frames)
2858 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2859 (void)get_relative_time(mpctx); // ignore time that passed during pause
2862 void add_step_frame(struct MPContext *mpctx)
2864 mpctx->step_frames++;
2865 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2866 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2867 unpause_player(mpctx);
2870 static void pause_loop(struct MPContext *mpctx)
2872 struct MPOpts *opts = &mpctx->opts;
2873 mp_cmd_t* cmd;
2874 if (!opts->quiet) {
2875 // Small hack to display the pause message on the OSD line.
2876 // The pause string is: "\n == PAUSE == \r" so we need to
2877 // take the first and the last char out
2878 if (opts->term_osd && !mpctx->sh_video) {
2879 char msg[128] = _("\n ===== PAUSE =====\r");
2880 int mlen = strlen(msg);
2881 msg[mlen-1] = '\0';
2882 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2883 update_osd_msg(mpctx);
2884 } else
2885 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2886 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2889 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2890 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2891 if (cmd) {
2892 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2893 run_command(mpctx, cmd);
2894 mp_cmd_free(cmd);
2895 continue;
2897 if (mpctx->sh_video && mpctx->video_out)
2898 vo_check_events(mpctx->video_out);
2899 #ifdef CONFIG_MENU
2900 if (vf_menu)
2901 vf_menu_pause_update(vf_menu);
2902 #endif
2903 usec_sleep(20000);
2904 update_osd_msg(mpctx);
2905 int hack = vo_osd_changed(0);
2906 vo_osd_changed(hack);
2907 if (hack)
2908 break;
2913 // Find the right mute status and record position for new file position
2914 static void edl_seek_reset(MPContext *mpctx)
2916 mpctx->edl_muted = 0;
2917 next_edl_record = edl_records;
2919 while (next_edl_record) {
2920 if (next_edl_record->start_sec >= get_current_time(mpctx))
2921 break;
2923 if (next_edl_record->action == EDL_MUTE)
2924 mpctx->edl_muted = !mpctx->edl_muted;
2925 next_edl_record = next_edl_record->next;
2927 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2928 mixer_mute(&mpctx->mixer);
2932 // Execute EDL command for the current position if one exists
2933 static void edl_update(MPContext *mpctx)
2935 if (!next_edl_record)
2936 return;
2938 if (!mpctx->sh_video) {
2939 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2940 free_edl(edl_records);
2941 next_edl_record = NULL;
2942 edl_records = NULL;
2943 return;
2946 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2947 if (next_edl_record->action == EDL_SKIP) {
2948 mpctx->osd_function = OSD_FFW;
2949 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2950 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2951 "[%f], length [%f]\n", next_edl_record->start_sec,
2952 next_edl_record->stop_sec, next_edl_record->length_sec);
2954 else if (next_edl_record->action == EDL_MUTE) {
2955 mpctx->edl_muted = !mpctx->edl_muted;
2956 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2957 mixer_mute(&mpctx->mixer);
2958 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2959 next_edl_record->start_sec );
2961 next_edl_record = next_edl_record->next;
2965 static void reinit_decoders(struct MPContext *mpctx)
2967 reinit_video_chain(mpctx);
2968 reinit_audio_chain(mpctx);
2969 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2972 static void seek_reset(struct MPContext *mpctx)
2974 if (mpctx->sh_video) {
2975 current_module = "seek_video_reset";
2976 resync_video_stream(mpctx->sh_video);
2977 mpctx->sh_video->timer = 0;
2978 vo_seek_reset(mpctx->video_out);
2979 mpctx->sh_video->timer = 0;
2980 mpctx->sh_video->num_buffered_pts = 0;
2981 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2982 mpctx->delay = 0;
2983 mpctx->time_frame = 0;
2984 mpctx->restart_playback = true;
2985 // Not all demuxers set d_video->pts during seek, so this value
2986 // (which is used by at least vobsub and edl code below) may
2987 // be completely wrong (probably 0).
2988 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2989 mpctx->video_pts = mpctx->sh_video->pts;
2990 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
2991 true);
2992 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2995 if (mpctx->sh_audio) {
2996 current_module = "seek_audio_reset";
2997 resync_audio_stream(mpctx->sh_audio);
2998 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2999 mpctx->sh_audio->a_buffer_len = 0;
3000 mpctx->sh_audio->a_out_buffer_len = 0;
3001 if (!mpctx->sh_video)
3002 update_subtitles(mpctx, mpctx->sh_audio->pts,
3003 mpctx->video_offset, true);
3006 if (vo_vobsub && mpctx->sh_video) {
3007 current_module = "seek_vobsub_reset";
3008 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3011 edl_seek_reset(mpctx);
3013 mpctx->hrseek_active = false;
3014 mpctx->hrseek_framedrop = false;
3015 mpctx->total_avsync_change = 0;
3016 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3017 drop_frame_cnt = 0;
3019 current_module = NULL;
3022 static bool timeline_set_part(struct MPContext *mpctx, int i)
3024 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3025 struct timeline_part *n = mpctx->timeline + i;
3026 mpctx->timeline_part = i;
3027 mpctx->video_offset = n->start - n->source_start;
3028 if (n->source == p->source)
3029 return false;
3030 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
3031 mpctx->demuxer = n->source->demuxer;
3032 mpctx->d_video = mpctx->demuxer->video;
3033 mpctx->d_audio = mpctx->demuxer->audio;
3034 mpctx->d_sub = mpctx->demuxer->sub;
3035 mpctx->sh_video = mpctx->d_video->sh;
3036 mpctx->sh_audio = mpctx->d_audio->sh;
3037 return true;
3040 // Given pts, switch playback to the corresponding part.
3041 // Return offset within that part.
3042 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3043 bool *need_reset)
3045 if (pts < 0)
3046 pts = 0;
3047 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3048 struct timeline_part *p = mpctx->timeline + i;
3049 if (pts < (p+1)->start) {
3050 *need_reset = timeline_set_part(mpctx, i);
3051 return pts - p->start + p->source_start;
3054 return -1;
3058 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3059 static int seek(MPContext *mpctx, struct seek_params seek)
3061 struct MPOpts *opts = &mpctx->opts;
3063 current_module = "seek";
3064 if (mpctx->stop_play == AT_END_OF_FILE)
3065 mpctx->stop_play = KEEP_PLAYING;
3066 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3067 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3068 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3069 || opts->hr_seek > 0 || seek.exact > 0;
3070 if (seek.type == MPSEEK_FACTOR
3071 || seek.type == MPSEEK_ABSOLUTE
3072 && seek.amount < mpctx->last_chapter_pts
3073 || seek.amount < 0)
3074 mpctx->last_chapter_seek = -1;
3075 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3076 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3077 seek.type = MPSEEK_ABSOLUTE;
3079 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3080 && seek.type == MPSEEK_RELATIVE) {
3081 seek.type = MPSEEK_ABSOLUTE;
3082 seek.direction = seek.amount > 0 ? 1 : -1;
3083 seek.amount += get_current_time(mpctx);
3086 /* At least the liba52 decoder wants to read from the input stream
3087 * during initialization, so reinit must be done after the demux_seek()
3088 * call that clears possible stream EOF. */
3089 bool need_reset = false;
3090 double demuxer_amount = seek.amount;
3091 if (mpctx->timeline) {
3092 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3093 &need_reset);
3094 if (demuxer_amount == -1) {
3095 mpctx->stop_play = AT_END_OF_FILE;
3096 // Clear audio from current position
3097 if (mpctx->sh_audio) {
3098 mpctx->audio_out->reset();
3099 mpctx->sh_audio->a_buffer_len = 0;
3100 mpctx->sh_audio->a_out_buffer_len = 0;
3102 return -1;
3105 int demuxer_style = 0;
3106 switch (seek.type) {
3107 case MPSEEK_FACTOR:
3108 demuxer_style |= SEEK_FACTOR; // fallthrough
3109 case MPSEEK_ABSOLUTE:
3110 demuxer_style |= SEEK_ABSOLUTE;
3112 if (hr_seek || seek.direction < 0)
3113 demuxer_style |= SEEK_BACKWARD;
3114 else if (seek.direction > 0)
3115 demuxer_style |= SEEK_FORWARD;
3117 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3118 demuxer_style);
3119 if (need_reset)
3120 reinit_decoders(mpctx);
3121 if (seekresult == 0)
3122 return -1;
3124 seek_reset(mpctx);
3126 /* Use the target time as "current position" for further relative
3127 * seeks etc until a new video frame has been decoded */
3128 if (seek.type == MPSEEK_ABSOLUTE)
3129 mpctx->video_pts = seek.amount;
3131 if (hr_seek) {
3132 mpctx->hrseek_active = true;
3133 mpctx->hrseek_framedrop = true;
3134 mpctx->hrseek_pts = seek.amount;
3137 mpctx->start_timestamp = GetTimerMS();
3139 return 0;
3142 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3143 int exact)
3145 struct seek_params *seek = &mpctx->seek;
3146 switch (type) {
3147 case MPSEEK_RELATIVE:
3148 if (seek->type == MPSEEK_FACTOR)
3149 return; // Well... not common enough to bother doing better
3150 seek->amount += amount;
3151 seek->exact = FFMAX(seek->exact, exact);
3152 if (seek->type == MPSEEK_NONE)
3153 seek->exact = exact;
3154 if (seek->type == MPSEEK_ABSOLUTE)
3155 return;
3156 if (seek->amount == 0) {
3157 *seek = (struct seek_params){0};
3158 return;
3160 seek->type = MPSEEK_RELATIVE;
3161 return;
3162 case MPSEEK_ABSOLUTE:
3163 case MPSEEK_FACTOR:
3164 *seek = (struct seek_params) {
3165 .type = type,
3166 .amount = amount,
3167 .exact = exact,
3169 return;
3170 case MPSEEK_NONE:
3171 *seek = (struct seek_params){0};
3172 return;
3174 abort();
3178 double get_time_length(struct MPContext *mpctx)
3180 if (mpctx->timeline)
3181 return mpctx->timeline[mpctx->num_timeline_parts].start;
3183 struct demuxer *demuxer = mpctx->demuxer;
3184 double get_time_ans;
3185 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3186 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3187 (void *) &get_time_ans) > 0)
3188 return get_time_ans;
3190 struct sh_video *sh_video = mpctx->d_video->sh;
3191 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3192 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3193 return (double) (demuxer->movi_end - demuxer->movi_start) /
3194 (sh_video->i_bps + sh_audio->i_bps);
3195 if (sh_video && sh_video->i_bps)
3196 return (double) (demuxer->movi_end - demuxer->movi_start) /
3197 sh_video->i_bps;
3198 if (sh_audio && sh_audio->i_bps)
3199 return (double) (demuxer->movi_end - demuxer->movi_start) /
3200 sh_audio->i_bps;
3201 return 0;
3204 /* If there are timestamps from stream level then use those (for example
3205 * DVDs can have consistent times there while the MPEG-level timestamps
3206 * reset). */
3207 double get_current_time(struct MPContext *mpctx)
3209 struct demuxer *demuxer = mpctx->demuxer;
3210 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3211 return demuxer->stream_pts;
3212 struct sh_video *sh_video = demuxer->video->sh;
3213 if (sh_video)
3214 return mpctx->video_pts;
3215 return playing_audio_pts(mpctx);
3218 int get_percent_pos(struct MPContext *mpctx)
3220 struct demuxer *demuxer = mpctx->demuxer;
3221 int ans = 0;
3222 if (mpctx->timeline)
3223 ans = get_current_time(mpctx) * 100 /
3224 mpctx->timeline[mpctx->num_timeline_parts].start;
3225 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3227 else {
3228 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3229 off_t pos = demuxer->filepos > 0 ?
3230 demuxer->filepos : stream_tell(demuxer->stream);
3231 if (len > 0)
3232 ans = (pos - demuxer->movi_start) / len;
3233 else
3234 ans = 0;
3236 if (ans < 0)
3237 ans = 0;
3238 if (ans > 100)
3239 ans = 100;
3240 return ans;
3243 // -2 is no chapters, -1 is before first chapter
3244 int get_current_chapter(struct MPContext *mpctx)
3246 double current_pts = get_current_time(mpctx);
3247 if (!mpctx->chapters)
3248 return FFMAX(mpctx->last_chapter_seek,
3249 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3251 int i;
3252 for (i = 1; i < mpctx->num_chapters; i++)
3253 if (current_pts < mpctx->chapters[i].start)
3254 break;
3255 return FFMAX(mpctx->last_chapter_seek, i - 1);
3258 // currently returns a string allocated with malloc, not talloc
3259 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3261 if (!mpctx->chapters || !mpctx->sh_video)
3262 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3263 return strdup(mpctx->chapters[chapter].name);
3266 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3267 char **chapter_name)
3269 mpctx->last_chapter_seek = -1;
3270 if (!mpctx->chapters || !mpctx->sh_video) {
3271 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3272 chapter_name);
3273 if (res >= 0) {
3274 if (*seek_pts == -1)
3275 seek_reset(mpctx);
3276 else {
3277 mpctx->last_chapter_seek = res;
3278 mpctx->last_chapter_pts = *seek_pts;
3281 return res;
3284 if (chapter >= mpctx->num_chapters)
3285 return -1;
3286 if (chapter < 0)
3287 chapter = 0;
3288 *seek_pts = mpctx->chapters[chapter].start;
3289 mpctx->last_chapter_seek = chapter;
3290 mpctx->last_chapter_pts = *seek_pts;
3291 if (chapter_name)
3292 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3293 return chapter;
3297 static void run_playloop(struct MPContext *mpctx)
3299 struct MPOpts *opts = &mpctx->opts;
3300 float aq_sleep_time = 0;
3302 if (opts->chapterrange[1] > 0) {
3303 int cur_chapter = get_current_chapter(mpctx);
3304 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3305 mpctx->stop_play = PT_NEXT_ENTRY;
3308 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3309 mpctx->sh_audio = mpctx->d_audio->sh;
3310 mpctx->sh_audio->ds = mpctx->d_audio;
3311 reinit_audio_chain(mpctx);
3314 /*========================== PLAY AUDIO ============================*/
3316 if (mpctx->sh_audio && !mpctx->paused
3317 && (!mpctx->restart_playback || !mpctx->sh_video))
3318 if (!fill_audio_out_buffers(mpctx))
3319 // at eof, all audio at least written to ao
3320 if (!mpctx->sh_video)
3321 mpctx->stop_play = AT_END_OF_FILE;
3324 if (!mpctx->sh_video) {
3325 mpctx->restart_playback = false;
3326 if (mpctx->step_frames) {
3327 mpctx->step_frames = 0;
3328 pause_player(mpctx);
3330 // handle audio-only case:
3331 double a_pos = 0;
3332 // sh_audio can be NULL due to video stream switching
3333 // TODO: handle this better
3334 if (mpctx->sh_audio)
3335 a_pos = playing_audio_pts(mpctx);
3337 print_status(mpctx, a_pos, false);
3339 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3340 mpctx->stop_play = PT_NEXT_ENTRY;
3341 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3342 update_osd_msg(mpctx);
3343 } else {
3345 /*========================== PLAY VIDEO ============================*/
3347 vo_pts = mpctx->sh_video->timer * 90000.0;
3348 vo_fps = mpctx->sh_video->fps;
3350 bool blit_frame = mpctx->video_out->frame_loaded;
3351 if (!blit_frame || mpctx->hrseek_active) {
3352 double frame_time = update_video(mpctx);
3353 blit_frame = mpctx->video_out->frame_loaded;
3354 blit_frame &= !mpctx->hrseek_active;
3355 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3356 if (mpctx->sh_video->vf_initialized < 0) {
3357 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3358 "\nFATAL: Could not initialize video filters (-vf) "
3359 "or video output (-vo).\n");
3360 mpctx->stop_play = PT_NEXT_ENTRY;
3361 return;
3363 if (frame_time < 0)
3364 mpctx->stop_play = AT_END_OF_FILE;
3365 else if (!mpctx->restart_playback) {
3366 mpctx->time_frame += frame_time / opts->playback_speed;
3367 adjust_sync(mpctx, frame_time);
3370 if (mpctx->timeline) {
3371 struct timeline_part *next =
3372 mpctx->timeline + mpctx->timeline_part + 1;
3373 if (mpctx->sh_video->pts >= next->start
3374 || mpctx->stop_play == AT_END_OF_FILE
3375 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3376 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3377 .amount = next->start });
3378 return;
3382 // ==========================================================================
3384 current_module = "vo_check_events";
3385 vo_check_events(mpctx->video_out);
3387 #ifdef CONFIG_X11
3388 if (stop_xscreensaver) {
3389 current_module = "stop_xscreensaver";
3390 xscreensaver_heartbeat(mpctx->x11_state);
3392 #endif
3393 if (heartbeat_cmd) {
3394 static unsigned last_heartbeat;
3395 unsigned now = GetTimerMS();
3396 if (now - last_heartbeat > 30000) {
3397 last_heartbeat = now;
3398 system(heartbeat_cmd);
3402 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3403 &mpctx->time_frame,
3404 &aq_sleep_time);
3406 //====================== FLIP PAGE (VIDEO BLT): =========================
3408 current_module = "flip_page";
3409 if (!frame_time_remaining && blit_frame) {
3410 struct sh_video *sh_video = mpctx->sh_video;
3411 mpctx->video_pts = sh_video->pts;
3412 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3413 update_teletext(sh_video, mpctx->demuxer, 0);
3414 update_osd_msg(mpctx);
3415 struct vf_instance *vf = sh_video->vfilter;
3416 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3417 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3418 vo_osd_changed(0);
3420 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3421 aq_sleep_time += mpctx->time_frame;
3422 // flag 256 means: libvo driver does its timing (dvb card)
3423 if (mpctx->time_frame > 0.001
3424 && !(mpctx->sh_video->output_flags&256))
3425 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3426 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3428 unsigned int t2 = GetTimer();
3429 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
3430 int duration = -1;
3431 double pts2 = mpctx->video_out->next_pts2;
3432 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3433 && !mpctx->restart_playback) {
3434 // expected A/V sync correction is ignored
3435 double diff = (pts2 - mpctx->video_pts);
3436 diff /= opts->playback_speed;
3437 if (mpctx->time_frame < 0)
3438 diff += mpctx->time_frame;
3439 if (diff < 0)
3440 diff = 0;
3441 if (diff > 10)
3442 diff = 10;
3443 duration = diff * 1e6;
3445 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3447 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3448 vout_time_usage += mpctx->last_vo_flip_duration;
3449 if (mpctx->video_out->driver->flip_page_timed) {
3450 // No need to adjust sync based on flip speed
3451 mpctx->last_vo_flip_duration = 0;
3452 // For print_status - VO call finishing early is OK for sync
3453 mpctx->time_frame -= get_relative_time(mpctx);
3455 if (mpctx->restart_playback) {
3456 mpctx->syncing_audio = true;
3457 if (mpctx->sh_audio && !mpctx->paused)
3458 fill_audio_out_buffers(mpctx);
3459 mpctx->restart_playback = false;
3460 mpctx->time_frame = 0;
3461 get_relative_time(mpctx);
3463 print_status(mpctx, MP_NOPTS_VALUE, true);
3464 } else
3465 print_status(mpctx, MP_NOPTS_VALUE, false);
3467 //============================ Auto QUALITY ============================
3469 /*Output quality adjustments:*/
3470 if (opts->auto_quality > 0) {
3471 current_module = "autoq";
3472 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3473 ++output_quality;
3474 else
3475 if (output_quality>1 && aq_sleep_time<0)
3476 --output_quality;
3477 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3478 output_quality = 0;
3479 set_video_quality(mpctx->sh_video, output_quality);
3482 if (!frame_time_remaining && blit_frame) {
3483 if (play_n_frames >= 0) {
3484 --play_n_frames;
3485 if (play_n_frames <= 0)
3486 mpctx->stop_play = PT_NEXT_ENTRY;
3488 if (mpctx->step_frames > 0) {
3489 mpctx->step_frames--;
3490 if (mpctx->step_frames == 0)
3491 pause_player(mpctx);
3495 // FIXME: add size based support for -endpos
3496 if (end_at.type == END_AT_TIME &&
3497 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3498 mpctx->stop_play = PT_NEXT_ENTRY;
3500 } // end if(mpctx->sh_video)
3502 #ifdef CONFIG_DVDNAV
3503 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3504 nav_highlight_t hl;
3505 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3506 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3507 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3508 vo_osd_changed(OSDTYPE_DVDNAV);
3509 } else {
3510 osd_set_nav_box(0, 0, 0, 0);
3511 vo_osd_changed(OSDTYPE_DVDNAV);
3512 vo_osd_changed(OSDTYPE_SPU);
3515 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3516 double ar = -1.0;
3517 if (mpctx->sh_video &&
3518 stream_control(mpctx->demuxer->stream,
3519 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3520 != STREAM_UNSUPPORTED)
3521 mpctx->sh_video->stream_aspect = ar;
3524 #endif
3526 //================= Keyboard events, SEEKing ====================
3528 current_module = "key_events";
3530 while (1) {
3531 mp_cmd_t *cmd;
3532 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3533 /* Allow running consecutive seek commands to combine them,
3534 * but execute the seek before running other commands.
3535 * If the user seeks continuously (keeps arrow key down)
3536 * try to finish showing a frame from one location before doing
3537 * another seek (which could lead to unchanging display). */
3538 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3539 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3540 && GetTimerMS() - mpctx->start_timestamp < 300)
3541 break;
3542 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3543 run_command(mpctx, cmd);
3544 mp_cmd_free(cmd);
3545 if (mpctx->stop_play)
3546 break;
3548 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3549 || mpctx->restart_playback)
3550 break;
3551 if (mpctx->sh_video) {
3552 update_osd_msg(mpctx);
3553 int hack = vo_osd_changed(0);
3554 vo_osd_changed(hack);
3555 if (hack) {
3556 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3557 add_step_frame(mpctx);
3558 break;
3559 } else
3560 vo_osd_changed(0);
3563 pause_loop(mpctx);
3566 // handle -sstep
3567 if (step_sec > 0 && !mpctx->paused) {
3568 mpctx->osd_function = OSD_FFW;
3569 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3572 edl_update(mpctx);
3574 /* Looping. */
3575 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3576 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3578 if (opts->loop_times>1)
3579 opts->loop_times--;
3580 else if (opts->loop_times==1)
3581 opts->loop_times = -1;
3582 play_n_frames = play_n_frames_mf;
3583 mpctx->stop_play = 0;
3584 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3587 if (mpctx->seek.type) {
3588 seek(mpctx, mpctx->seek);
3589 mpctx->seek = (struct seek_params){0};
3594 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3595 struct content_source *sources,
3596 int num_sources,
3597 unsigned char uid_map[][16])
3599 int num_filenames = 0;
3600 char **filenames = NULL;
3601 if (num_sources > 1) {
3602 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3603 "other sources.\n");
3604 if (mpctx->stream->type != STREAMTYPE_FILE) {
3605 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3606 "normal disk file. Will not search for related files.\n");
3607 } else {
3608 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3609 "same directory to find referenced sources.\n");
3610 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3611 &num_filenames);
3615 int num_left = num_sources - 1;
3616 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3617 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3618 filename_recode(filenames[i]));
3619 int format;
3620 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3621 if (!s)
3622 continue;
3623 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3624 mpctx->opts.audio_id,
3625 mpctx->opts.video_id,
3626 mpctx->opts.sub_id, filenames[i]);
3627 if (!d) {
3628 free_stream(s);
3629 continue;
3631 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3632 for (int i = 1; i < num_sources; i++) {
3633 if (sources[i].demuxer)
3634 continue;
3635 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3636 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3637 i, filename_recode(d->filename));
3638 sources[i].stream = s;
3639 sources[i].demuxer = d;
3640 num_left--;
3641 goto match;
3645 free_demuxer(d);
3646 free_stream(s);
3647 continue;
3648 match:
3651 talloc_free(filenames);
3652 if (num_left) {
3653 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3654 "There will be parts MISSING from the video!\n");
3655 for (int i = 1, j = 1; i < num_sources; i++)
3656 if (sources[i].demuxer) {
3657 sources[j] = sources[i];
3658 memcpy(uid_map[j], uid_map[i], 16);
3659 j++;
3662 return num_sources - num_left;
3665 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3667 struct MPOpts *opts = &mpctx->opts;
3669 if (!opts->ordered_chapters) {
3670 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3671 "you have disabled support for them. Ignoring.\n");
3672 return;
3675 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3676 "edit timeline.\n");
3678 struct demuxer *demuxer = mpctx->demuxer;
3679 struct matroska_data *m = &demuxer->matroska_data;
3681 // +1 because sources/uid_map[0] is original file even if all chapters
3682 // actually use other sources and need separate entries
3683 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3684 m->num_ordered_chapters+1);
3685 sources[0].stream = mpctx->stream;
3686 sources[0].demuxer = mpctx->demuxer;
3687 unsigned char uid_map[m->num_ordered_chapters+1][16];
3688 int num_sources = 1;
3689 memcpy(uid_map[0], m->segment_uid, 16);
3691 for (int i = 0; i < m->num_ordered_chapters; i++) {
3692 struct matroska_chapter *c = m->ordered_chapters + i;
3693 if (!c->has_segment_uid)
3694 memcpy(c->segment_uid, m->segment_uid, 16);
3696 for (int j = 0; j < num_sources; j++)
3697 if (!memcmp(c->segment_uid, uid_map[j], 16))
3698 goto found1;
3699 memcpy(uid_map[num_sources], c->segment_uid, 16);
3700 sources[num_sources] = (struct content_source){};
3701 num_sources++;
3702 found1:
3706 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3707 uid_map);
3710 // +1 for terminating chapter with start time marking end of last real one
3711 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3712 m->num_ordered_chapters + 1);
3713 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3714 m->num_ordered_chapters);
3715 uint64_t starttime = 0;
3716 uint64_t missing_time = 0;
3717 int part_count = 0;
3718 int num_chapters = 0;
3719 uint64_t prev_part_offset = 0;
3720 for (int i = 0; i < m->num_ordered_chapters; i++) {
3721 struct matroska_chapter *c = m->ordered_chapters + i;
3723 int j;
3724 for (j = 0; j < num_sources; j++) {
3725 if (!memcmp(c->segment_uid, uid_map[j], 16))
3726 goto found2;
3728 missing_time += c->end - c->start;
3729 continue;
3730 found2:;
3731 /* Only add a separate part if the time or file actually changes.
3732 * Matroska files have chapter divisions that are redundant from
3733 * timeline point of view because the same chapter structure is used
3734 * both to specify the timeline and for normal chapter information.
3735 * Removing a missing inserted external chapter can also cause this.
3736 * We allow for a configurable fudge factor because of files which
3737 * specify chapter end times that are one frame too early;
3738 * we don't want to try seeking over a one frame gap. */
3739 int64_t join_diff = c->start - starttime - prev_part_offset;
3740 if (part_count == 0 || FFABS(join_diff) > opts->chapter_merge_threshold
3741 || sources + j != timeline[part_count - 1].source) {
3742 timeline[part_count].source = sources + j;
3743 timeline[part_count].start = starttime / 1000.;
3744 timeline[part_count].source_start = c->start / 1000.;
3745 prev_part_offset = c->start - starttime;
3746 part_count++;
3747 } else if (part_count > 0 && join_diff) {
3748 /* Chapter was merged at an inexact boundary;
3749 * adjust timestamps to match. */
3750 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3751 "offset %d ms.\n", i, (int) join_diff);
3752 starttime += join_diff;
3754 chapters[num_chapters].start = starttime / 1000.;
3755 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3756 starttime += c->end - c->start;
3757 num_chapters++;
3759 timeline[part_count].start = starttime / 1000.;
3761 if (!part_count) {
3762 // None of the parts come from the file itself???
3763 talloc_free(sources);
3764 talloc_free(timeline);
3765 talloc_free(chapters);
3766 return;
3769 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3770 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3771 timeline[part_count].start);
3772 if (missing_time)
3773 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3774 "from the timeline!\n", missing_time / 1000.);
3775 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3776 for (int i = 0; i < num_sources; i++)
3777 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3778 filename_recode(sources[i].demuxer->filename));
3779 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3780 "source_start, source):\n");
3781 for (int i = 0; i < part_count; i++) {
3782 struct timeline_part *p = timeline + i;
3783 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3784 p->source_start, p->source - sources);
3786 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3787 mpctx->sources = sources;
3788 mpctx->num_sources = num_sources;
3789 mpctx->timeline = timeline;
3790 mpctx->num_timeline_parts = part_count;
3791 mpctx->num_chapters = num_chapters;
3792 mpctx->chapters = chapters;
3794 mpctx->timeline_part = 0;
3795 mpctx->demuxer = timeline[0].source->demuxer;
3799 static int read_keys(void *ctx, int fd)
3801 getch2(ctx);
3802 return mplayer_get_key(ctx, 0);
3805 static bool attachment_is_font(struct demux_attachment *att)
3807 if (!att->name || !att->type || !att->data || !att->data_size)
3808 return false;
3809 // match against MIME types
3810 if (strcmp(att->type, "application/x-truetype-font") == 0
3811 || strcmp(att->type, "application/x-font") == 0)
3812 return true;
3813 // fallback: match against file extension
3814 if (strlen(att->name) > 4) {
3815 char *ext = att->name + strlen(att->name) - 4;
3816 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3817 || strcasecmp(ext, ".otf") == 0)
3818 return true;
3820 return false;
3823 static int select_audio(demuxer_t *demuxer, int audio_id, char *audio_lang)
3825 if (audio_id == -1)
3826 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3827 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3828 demuxer_switch_audio(demuxer, audio_id);
3829 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3830 demuxer->audio->id = -2;
3831 demuxer->audio->sh = NULL;
3833 return demuxer->audio->id;
3836 static void print_version(const char* name)
3838 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3840 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3841 GetCpuCaps(&gCpuCaps);
3842 #if ARCH_X86
3843 mp_msg(MSGT_CPLAYER, MSGL_V,
3844 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3845 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3846 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3847 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3848 #if CONFIG_RUNTIME_CPUDETECT
3849 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3850 #else
3851 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3852 if (HAVE_MMX)
3853 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3854 if (HAVE_MMX2)
3855 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3856 if (HAVE_AMD3DNOW)
3857 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3858 if (HAVE_AMD3DNOWEXT)
3859 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3860 if (HAVE_SSE)
3861 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3862 if (HAVE_SSE2)
3863 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3864 if (HAVE_SSSE3)
3865 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3866 if (HAVE_CMOV)
3867 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3868 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3869 #endif /* CONFIG_RUNTIME_CPUDETECT */
3870 #endif /* ARCH_X86 */
3873 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3874 * file for some tools to link against. */
3875 #ifndef DISABLE_MAIN
3876 int main(int argc,char* argv[]){
3879 char * mem_ptr;
3881 // movie info:
3883 /* Flag indicating whether MPlayer should exit without playing anything. */
3884 int opt_exit = 0;
3885 int i;
3887 struct MPContext *mpctx = &(struct MPContext){
3888 .osd_function = OSD_PLAY,
3889 .begin_skip = MP_NOPTS_VALUE,
3890 .play_tree_step = 1,
3891 .global_sub_pos = -1,
3892 .set_of_sub_pos = -1,
3893 .file_format = DEMUXER_TYPE_UNKNOWN,
3894 .last_dvb_step = 1,
3897 InitTimer();
3898 srand(GetTimerMS());
3900 mp_msg_init();
3901 set_av_log_callback();
3903 #ifdef CONFIG_X11
3904 mpctx->x11_state = vo_x11_init_state();
3905 #endif
3906 struct MPOpts *opts = &mpctx->opts;
3907 set_default_mplayer_options(opts);
3908 // Create the config context and register the options
3909 mpctx->mconfig = m_config_new(opts, cfg_include);
3910 m_config_register_options(mpctx->mconfig,mplayer_opts);
3911 m_config_register_options(mpctx->mconfig, common_opts);
3912 mp_input_register_options(mpctx->mconfig);
3914 // Preparse the command line
3915 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3917 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3918 set_path_env();
3919 #endif
3921 #ifdef CONFIG_TV
3922 stream_tv_defaults.immediate = 1;
3923 #endif
3925 parse_cfgfiles(mpctx, mpctx->mconfig);
3927 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3928 if(mpctx->playtree == NULL)
3929 opt_exit = 1;
3930 else {
3931 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3932 if(mpctx->playtree) {
3933 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3934 if(mpctx->playtree_iter) {
3935 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3936 play_tree_iter_free(mpctx->playtree_iter);
3937 mpctx->playtree_iter = NULL;
3939 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3943 mpctx->key_fifo = mp_fifo_create(opts);
3945 print_version("MPlayer");
3947 #if defined(__MINGW32__) || defined(__CYGWIN__)
3949 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3950 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3951 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3952 if (kernel32) {
3953 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3954 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3956 if (setDEP) setDEP(3);
3957 if (setDllDir) setDllDir("");
3959 // stop Windows from showing all kinds of annoying error dialogs
3960 SetErrorMode(0x8003);
3961 // request 1ms timer resolution
3962 timeBeginPeriod(1);
3963 #endif
3965 #ifdef CONFIG_PRIORITY
3966 set_priority();
3967 #endif
3969 if (codec_path)
3970 set_codec_path(codec_path);
3972 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3973 list_video_out();
3974 opt_exit = 1;
3977 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3978 list_audio_out();
3979 opt_exit = 1;
3982 /* Check codecs.conf. */
3983 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3984 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3985 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3986 if(!parse_codec_cfg(NULL)){
3987 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3989 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3992 free( mem_ptr ); // release the buffer created by get_path()
3995 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3996 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3997 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3998 list_codecs(1);
3999 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4000 opt_exit = 1;
4002 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
4003 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4004 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4005 list_codecs(0);
4006 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4007 opt_exit = 1;
4009 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
4010 vfm_help();
4011 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4012 opt_exit = 1;
4014 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
4015 afm_help();
4016 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4017 opt_exit = 1;
4019 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
4020 af_help();
4021 printf("\n");
4022 opt_exit = 1;
4024 #ifdef CONFIG_X11
4025 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
4026 fstype_help();
4027 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4028 opt_exit = 1;
4030 #endif
4031 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
4032 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
4033 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
4034 demuxer_help();
4035 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4036 opt_exit = 1;
4038 if (opts->list_properties) {
4039 property_print_help();
4040 opt_exit = 1;
4043 if(opt_exit)
4044 exit_player(mpctx, EXIT_NONE);
4046 if (!mpctx->filename && !opts->player_idle_mode) {
4047 // no file/vcd/dvd -> show HELP:
4048 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4049 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4052 /* Display what configure line was used */
4053 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4055 // Many users forget to include command line in bugreports...
4056 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
4057 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4058 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
4059 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4062 //------ load global data first ------
4064 mpctx->osd = osd_create();
4066 // check font
4067 #ifdef CONFIG_FREETYPE
4068 init_freetype();
4069 #endif
4070 #ifdef CONFIG_FONTCONFIG
4071 if(font_fontconfig <= 0)
4073 #endif
4074 #ifdef CONFIG_BITMAP_FONT
4075 if(font_name){
4076 vo_font=read_font_desc(font_name,font_factor,verbose>1);
4077 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
4078 filename_recode(font_name));
4079 } else {
4080 // try default:
4081 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
4082 free(mem_ptr); // release the buffer created by get_path()
4083 if(!vo_font)
4084 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
4086 if (sub_font_name)
4087 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
4088 else
4089 mpctx->osd->sub_font = vo_font;
4090 #endif
4091 #ifdef CONFIG_FONTCONFIG
4093 #endif
4095 #ifdef CONFIG_ASS
4096 ass_library = ass_init();
4097 #endif
4099 #ifdef HAVE_RTC
4100 if(opts->rtc)
4102 char *rtc_device = opts->rtc_device;
4103 // seteuid(0); /* Can't hurt to try to get root here */
4104 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4105 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4106 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4107 else {
4108 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4110 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4111 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4112 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4113 close (rtc_fd);
4114 rtc_fd = -1;
4115 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4116 /* variable only by the root */
4117 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4118 close (rtc_fd);
4119 rtc_fd = -1;
4120 } else
4121 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4124 if(rtc_fd<0)
4125 #endif /* HAVE_RTC */
4126 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4127 opts->softsleep ? "software" : timer_name);
4129 #ifdef HAVE_TERMCAP
4130 load_termcap(NULL); // load key-codes
4131 #endif
4133 // ========== Init keyboard FIFO (connection to libvo) ============
4135 // Init input system
4136 current_module = "init_input";
4137 mpctx->input = mp_input_init(&opts->input);
4138 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4139 if(slave_mode)
4140 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4141 else if (opts->consolecontrols)
4142 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4143 // Set the libstream interrupt callback
4144 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4146 #ifdef CONFIG_MENU
4147 if(use_menu) {
4148 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4149 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4150 else {
4151 menu_cfg = get_path("menu.conf");
4152 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4153 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4154 else {
4155 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4156 MPLAYER_CONFDIR "/menu.conf"))
4157 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4158 else {
4159 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4160 use_menu = 0;
4165 #endif
4167 current_module = NULL;
4169 /// Catch signals
4170 #ifndef __MINGW32__
4171 signal(SIGCHLD,child_sighandler);
4172 #endif
4174 #ifdef CONFIG_CRASH_DEBUG
4175 prog_path = argv[0];
4176 #endif
4177 //========= Catch terminate signals: ================
4178 // terminate requests:
4179 signal(SIGTERM,exit_sighandler); // kill
4180 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4182 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4184 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4185 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4186 #ifdef CONFIG_SIGHANDLER
4187 // fatal errors:
4188 signal(SIGBUS,exit_sighandler); // bus error
4189 signal(SIGSEGV,exit_sighandler); // segfault
4190 signal(SIGILL,exit_sighandler); // illegal instruction
4191 signal(SIGFPE,exit_sighandler); // floating point exc.
4192 signal(SIGABRT,exit_sighandler); // abort()
4193 #ifdef CONFIG_CRASH_DEBUG
4194 if (crash_debug)
4195 signal(SIGTRAP,exit_sighandler);
4196 #endif
4197 #endif
4199 // ******************* Now, let's see the per-file stuff ********************
4201 play_next_file:
4203 // init global sub numbers
4204 mpctx->global_sub_size = 0;
4205 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4207 if (mpctx->filename) {
4208 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4209 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4210 load_per_file_config (mpctx->mconfig, mpctx->filename);
4213 if (opts->video_driver_list)
4214 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4215 if (opts->audio_driver_list)
4216 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4218 // We must enable getch2 here to be able to interrupt network connection
4219 // or cache filling
4220 if (opts->consolecontrols && !slave_mode) {
4221 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4222 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4223 else
4224 getch2_enable(); // prepare stdin for hotkeys...
4225 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4226 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4229 // =================== GUI idle loop (STOP state) ===========================
4230 while (opts->player_idle_mode && !mpctx->filename) {
4231 play_tree_t * entry = NULL;
4232 mp_cmd_t * cmd;
4233 if (mpctx->video_out && mpctx->video_out->config_ok)
4234 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4235 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4236 if (mpctx->video_out)
4237 vo_check_events(mpctx->video_out);
4238 usec_sleep(20000);
4240 switch (cmd->id) {
4241 case MP_CMD_LOADFILE:
4242 // prepare a tree entry with the new filename
4243 entry = play_tree_new();
4244 play_tree_add_file(entry, cmd->args[0].v.s);
4245 // The entry is added to the main playtree after the switch().
4246 break;
4247 case MP_CMD_LOADLIST:
4248 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4249 break;
4250 case MP_CMD_QUIT:
4251 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4252 break;
4253 case MP_CMD_VO_FULLSCREEN:
4254 case MP_CMD_GET_PROPERTY:
4255 case MP_CMD_SET_PROPERTY:
4256 case MP_CMD_STEP_PROPERTY:
4257 run_command(mpctx, cmd);
4258 break;
4261 mp_cmd_free(cmd);
4263 if (entry) { // user entered a command that gave a valid entry
4264 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4265 play_tree_free_list(mpctx->playtree->child, 1);
4266 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4268 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4270 play_tree_set_child(mpctx->playtree, entry);
4272 /* Make iterator start at the top the of tree. */
4273 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4274 if (!mpctx->playtree_iter) continue;
4276 // find the first real item in the tree
4277 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4278 // no items!
4279 play_tree_iter_free(mpctx->playtree_iter);
4280 mpctx->playtree_iter = NULL;
4281 continue; // wait for next command
4283 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4286 //---------------------------------------------------------------------------
4288 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4289 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4291 if (mpctx->filename) {
4292 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4293 filename_recode(mpctx->filename));
4294 if(use_filename_title && opts->vo_wintitle == NULL)
4295 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4298 if (edl_filename) {
4299 if (edl_records) free_edl(edl_records);
4300 next_edl_record = edl_records = edl_parse_file();
4302 if (edl_output_filename) {
4303 if (edl_fd) fclose(edl_fd);
4304 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4306 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4307 filename_recode(edl_output_filename));
4311 //==================== Open VOB-Sub ============================
4313 current_module="vobsub";
4314 if (vobsub_name){
4315 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
4316 if(vo_vobsub==NULL)
4317 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4318 filename_recode(vobsub_name));
4319 } else if (sub_auto && mpctx->filename){
4320 /* try to autodetect vobsub from movie filename ::atmos */
4321 char *buf = strdup(mpctx->filename), *psub;
4322 char *pdot = strrchr(buf, '.');
4323 char *pslash = strrchr(buf, '/');
4324 #if defined(__MINGW32__) || defined(__CYGWIN__)
4325 if (!pslash) pslash = strrchr(buf, '\\');
4326 #endif
4327 if (pdot && (!pslash || pdot > pslash))
4328 *pdot = '\0';
4329 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4330 /* try from ~/.mplayer/sub */
4331 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4332 const char *bname = mp_basename(buf);
4333 int l;
4334 l = strlen(psub) + strlen(bname) + 1;
4335 psub = realloc(psub,l);
4336 strcat(psub,bname);
4337 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4338 free(psub);
4340 free(buf);
4342 if(vo_vobsub){
4343 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4344 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4345 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4347 // setup global sub numbering
4348 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4351 //============ Open & Sync STREAM --- fork cache2 ====================
4353 mpctx->stream=NULL;
4354 mpctx->demuxer=NULL;
4355 if (mpctx->d_audio) {
4356 //free_demuxer_stream(mpctx->d_audio);
4357 mpctx->d_audio=NULL;
4359 if (mpctx->d_video) {
4360 //free_demuxer_stream(d_video);
4361 mpctx->d_video=NULL;
4363 mpctx->sh_audio=NULL;
4364 mpctx->sh_video=NULL;
4366 current_module="open_stream";
4367 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4368 if(!mpctx->stream) { // error...
4369 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4370 goto goto_next_file;
4372 mpctx->initialized_flags|=INITIALIZED_STREAM;
4374 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4375 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4376 "playlist support will not be used automatically.\n"
4377 "MPlayer's playlist code is unsafe and should only be used with "
4378 "trusted sources.\nPlayback will probably fail.\n\n");
4379 #if 0
4380 play_tree_t* entry;
4381 // Handle playlist
4382 current_module="handle_playlist";
4383 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4384 filename_recode(mpctx->filename));
4385 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4386 mpctx->eof=playtree_add_playlist(mpctx, entry);
4387 goto goto_next_file;
4388 #endif
4390 mpctx->stream->start_pos+=seek_to_byte;
4392 if(stream_dump_type==5){
4393 unsigned char buf[4096];
4394 int len;
4395 FILE *f;
4396 current_module="dumpstream";
4397 stream_reset(mpctx->stream);
4398 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4399 f=fopen(opts->stream_dump_name,"wb");
4400 if(!f){
4401 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4402 exit_player(mpctx, EXIT_ERROR);
4404 if (opts->chapterrange[0] > 1) {
4405 int chapter = opts->chapterrange[0] - 1;
4406 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4408 while(!mpctx->stream->eof && !async_quit_request){
4409 len=stream_read(mpctx->stream,buf,4096);
4410 if(len>0) {
4411 if(fwrite(buf,len,1,f) != 1) {
4412 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4413 exit_player(mpctx, EXIT_ERROR);
4416 if (opts->chapterrange[1] > 0) {
4417 int chapter = -1;
4418 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4419 &chapter) == STREAM_OK
4420 && chapter + 1 > opts->chapterrange[1])
4421 break;
4424 if(fclose(f)) {
4425 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4426 exit_player(mpctx, EXIT_ERROR);
4428 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4429 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4432 #ifdef CONFIG_DVDREAD
4433 if(mpctx->stream->type==STREAMTYPE_DVD){
4434 current_module="dvd lang->id";
4435 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4436 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4437 // setup global sub numbering
4438 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4439 current_module=NULL;
4441 #endif
4443 #ifdef CONFIG_DVDNAV
4444 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4445 current_module="dvdnav lang->id";
4446 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4447 dvdsub_lang_id = -3;
4448 if(opts->sub_lang && opts->sub_id==-1)
4449 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4450 // setup global sub numbering
4451 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4452 current_module=NULL;
4454 #endif
4456 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4457 goto_enable_cache:
4458 if(stream_cache_size>0){
4459 int res;
4460 float stream_cache_min_percent = opts->stream_cache_min_percent;
4461 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4462 current_module="enable_cache";
4463 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4464 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4465 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4466 if(res == 0)
4467 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4470 //============ Open DEMUXERS --- DETECT file type =======================
4471 current_module="demux_open";
4473 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4475 // HACK to get MOV Reference Files working
4477 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4479 unsigned char* playlist_entry;
4480 play_tree_t *list = NULL, *entry = NULL;
4482 current_module="handle_demux_playlist";
4483 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4485 char *temp;
4486 const char *bname;
4488 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4489 filename_recode(playlist_entry));
4491 bname=mp_basename(playlist_entry);
4492 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4493 continue;
4495 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4496 continue;
4498 entry = play_tree_new();
4500 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4502 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4503 if (temp)
4505 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4506 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4507 strcat(temp, playlist_entry);
4508 if (!strcmp(temp, mpctx->filename)) {
4509 free(temp);
4510 continue;
4512 play_tree_add_file(entry,temp);
4513 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4514 free(temp);
4517 else
4518 play_tree_add_file(entry,playlist_entry);
4520 if(!list)
4521 list = entry;
4522 else
4523 play_tree_append_entry(list,entry);
4525 free_demuxer(mpctx->demuxer);
4526 mpctx->demuxer = NULL;
4528 if (list)
4530 entry = play_tree_new();
4531 play_tree_set_child(entry,list);
4532 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4533 goto goto_next_file;
4537 if(!mpctx->demuxer) {
4538 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4539 goto goto_next_file;
4542 if (mpctx->demuxer->matroska_data.ordered_chapters)
4543 build_ordered_chapter_timeline(mpctx);
4545 if (!mpctx->sources) {
4546 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4547 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4548 .demuxer = mpctx->demuxer};
4549 mpctx->num_sources = 1;
4552 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4554 #ifdef CONFIG_ASS
4555 if (opts->ass_enabled && ass_library) {
4556 for (int j = 0; j < mpctx->num_sources; j++) {
4557 struct demuxer *d = mpctx->sources[j].demuxer;
4558 for (int i = 0; i < d->num_attachments; i++) {
4559 struct demux_attachment *att = d->attachments + i;
4560 if (use_embedded_fonts && attachment_is_font(att))
4561 ass_add_font(ass_library, att->name, att->data, att->data_size);
4565 #endif
4567 current_module="demux_open2";
4569 mpctx->d_audio=mpctx->demuxer->audio;
4570 mpctx->d_video=mpctx->demuxer->video;
4571 mpctx->d_sub=mpctx->demuxer->sub;
4573 if (ts_prog) {
4574 int tmp = ts_prog;
4575 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4577 // select audio stream
4578 if (mpctx->num_sources)
4579 for (int i = 0; i < mpctx->num_sources; i++)
4580 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
4581 opts->audio_lang);
4582 else
4583 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
4585 // DUMP STREAMS:
4586 if((stream_dump_type)&&(stream_dump_type<4)){
4587 FILE *f;
4588 demux_stream_t *ds=NULL;
4589 current_module="dump";
4590 // select stream to dump
4591 switch(stream_dump_type){
4592 case 1: ds=mpctx->d_audio;break;
4593 case 2: ds=mpctx->d_video;break;
4594 case 3: ds=mpctx->d_sub;break;
4596 if(!ds){
4597 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4598 exit_player(mpctx, EXIT_ERROR);
4600 // disable other streams:
4601 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4602 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4603 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4604 // let's dump it!
4605 f=fopen(opts->stream_dump_name,"wb");
4606 if(!f){
4607 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4608 exit_player(mpctx, EXIT_ERROR);
4610 while(!ds->eof){
4611 unsigned char* start;
4612 int in_size=ds_get_packet(ds,&start);
4613 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4614 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4615 if(in_size>0) fwrite(start,in_size,1,f);
4616 if (opts->chapterrange[1] > 0) {
4617 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4618 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4619 break;
4622 fclose(f);
4623 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4624 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4627 mpctx->sh_audio=mpctx->d_audio->sh;
4628 mpctx->sh_video=mpctx->d_video->sh;
4630 if(mpctx->sh_video){
4632 current_module="video_read_properties";
4633 if(!video_read_properties(mpctx->sh_video)) {
4634 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4635 mpctx->sh_video=mpctx->d_video->sh=NULL;
4636 } else {
4637 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4638 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4639 mpctx->sh_video->fps,mpctx->sh_video->frametime
4642 /* need to set fps here for output encoders to pick it up in their init */
4643 if(force_fps){
4644 mpctx->sh_video->fps=force_fps;
4645 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4647 vo_fps = mpctx->sh_video->fps;
4649 if(!mpctx->sh_video->fps && !force_fps){
4650 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4651 mpctx->opts.correct_pts = 1;
4657 if(!mpctx->sh_video && !mpctx->sh_audio){
4658 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4659 #ifdef CONFIG_DVBIN
4660 if(mpctx->stream->type == STREAMTYPE_DVB)
4662 int dir;
4663 int v = mpctx->last_dvb_step;
4664 if(v > 0)
4665 dir = DVB_CHANNEL_HIGHER;
4666 else
4667 dir = DVB_CHANNEL_LOWER;
4669 if(dvb_step_channel(mpctx->stream, dir)) {
4670 mpctx->stop_play = PT_NEXT_ENTRY;
4671 mpctx->dvbin_reopen = 1;
4674 #endif
4675 goto goto_next_file; // exit_player(_("Fatal error"));
4678 /* display clip info */
4679 demux_info_print(mpctx->demuxer);
4681 //================== Read SUBTITLES (DVD & TEXT) ==========================
4682 if(vo_spudec==NULL &&
4683 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4684 init_vo_spudec(mpctx);
4687 // after reading video params we should load subtitles because
4688 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4689 // check .sub
4690 current_module="read_subtitles_file";
4691 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4692 if(sub_name){
4693 for (i = 0; sub_name[i] != NULL; ++i)
4694 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4696 if(sub_auto) { // auto load sub file ...
4697 char *psub = get_path( "sub/" );
4698 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4699 int i = 0;
4700 free(psub); // release the buffer created by get_path() above
4701 while (tmp[i]) {
4702 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4703 free(tmp[i++]);
4705 free(tmp);
4707 if (mpctx->set_of_sub_size > 0)
4708 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4710 if (select_subtitle(mpctx)) {
4711 if(mpctx->subdata)
4712 switch (stream_dump_type) {
4713 case 3: list_sub_file(mpctx->subdata); break;
4714 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4715 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4716 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4717 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4718 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4722 print_file_properties(mpctx, mpctx->filename);
4724 if(!mpctx->sh_video) goto main; // audio-only
4726 if(!reinit_video_chain(mpctx)) {
4727 if(!mpctx->sh_video){
4728 if(!mpctx->sh_audio) goto goto_next_file;
4729 goto main; // exit_player(_("Fatal error"));
4733 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4734 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4736 #ifdef CONFIG_FREETYPE
4737 force_load_font = 1;
4738 #endif
4740 //================== MAIN: ==========================
4741 main:
4742 current_module="main";
4744 if (opts->playing_msg) {
4745 char* msg = property_expand_string(mpctx, opts->playing_msg);
4746 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4747 free(msg);
4751 // Disable the term OSD in verbose mode
4752 if (verbose)
4753 opts->term_osd = 0;
4757 // Make sure old OSD does not stay around,
4758 // e.g. with -fixed-vo and same-resolution files
4759 clear_osd_msgs();
4760 update_osd_msg(mpctx);
4762 //================ SETUP AUDIO ==========================
4764 if(mpctx->sh_audio){
4765 reinit_audio_chain(mpctx);
4766 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4767 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4770 current_module="av_init";
4772 if(mpctx->sh_video){
4773 mpctx->sh_video->timer=0;
4774 if (! ignore_start)
4775 audio_delay += mpctx->sh_video->stream_delay;
4777 if(mpctx->sh_audio){
4778 if (start_volume >= 0)
4779 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4780 if (! ignore_start)
4781 audio_delay -= mpctx->sh_audio->stream_delay;
4782 mpctx->delay=-audio_delay;
4785 if(!mpctx->sh_audio){
4786 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4787 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4788 ds_free_packs(mpctx->d_audio); // free buffered chunks
4789 //mpctx->d_audio->id=-2; // do not read audio chunks
4790 //uninit_player(mpctx, INITIALIZED_AO); // close device
4792 if(!mpctx->sh_video){
4793 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4794 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4795 ds_free_packs(mpctx->d_video);
4796 mpctx->d_video->id=-2;
4797 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4800 if (!mpctx->sh_video && !mpctx->sh_audio)
4801 goto goto_next_file;
4803 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4804 if(force_fps && mpctx->sh_video){
4805 vo_fps = mpctx->sh_video->fps=force_fps;
4806 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4807 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4810 mp_input_set_section(mpctx->input, NULL);
4811 //TODO: add desired (stream-based) sections here
4812 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4813 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4815 //==================== START PLAYING =======================
4817 if(opts->loop_times>1) opts->loop_times--; else
4818 if(opts->loop_times==1) opts->loop_times = -1;
4820 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4822 total_time_usage_start=GetTimer();
4823 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4824 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4825 play_n_frames=play_n_frames_mf;
4827 if(play_n_frames==0){
4828 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4831 mpctx->time_frame = 0;
4832 mpctx->drop_message_shown = 0;
4833 mpctx->restart_playback = true;
4834 mpctx->video_pts = 0;
4835 mpctx->hrseek_active = false;
4836 mpctx->hrseek_framedrop = false;
4837 mpctx->step_frames = 0;
4838 mpctx->total_avsync_change = 0;
4839 mpctx->last_chapter_seek = -1;
4841 // If there's a timeline force an absolute seek to initialize state
4842 if (seek_to_sec || mpctx->timeline) {
4843 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4844 seek(mpctx, mpctx->seek);
4845 end_at.pos += seek_to_sec;
4847 if (opts->chapterrange[0] > 0) {
4848 double pts;
4849 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4850 && pts > -1.0) {
4851 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4852 seek(mpctx, mpctx->seek);
4856 if (end_at.type == END_AT_SIZE) {
4857 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4858 end_at.type = END_AT_NONE;
4861 #ifdef CONFIG_DVDNAV
4862 mp_dvdnav_context_free(mpctx);
4863 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4864 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4865 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4867 #endif
4869 mpctx->seek = (struct seek_params){0};
4870 get_relative_time(mpctx); // reset current delta
4871 // Make sure VO knows current pause state
4872 if (mpctx->sh_video)
4873 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4874 NULL);
4876 while (!mpctx->stop_play)
4877 run_playloop(mpctx);
4879 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4881 #ifdef CONFIG_DVBIN
4882 if(mpctx->dvbin_reopen)
4884 mpctx->stop_play = 0;
4885 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4886 cache_uninit(mpctx->stream);
4887 mpctx->dvbin_reopen = 0;
4888 goto goto_enable_cache;
4890 #endif
4893 goto_next_file: // don't jump here after ao/vo/getch initialization!
4895 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4897 if (opts->benchmark) {
4898 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4899 double total_time_usage;
4900 total_time_usage_start=GetTimer()-total_time_usage_start;
4901 total_time_usage = (float)total_time_usage_start*0.000001;
4902 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4903 video_time_usage,vout_time_usage,audio_time_usage,
4904 total_time_usage-tot,total_time_usage);
4905 if(total_time_usage>0.0)
4906 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4907 100.0*video_time_usage/total_time_usage,
4908 100.0*vout_time_usage/total_time_usage,
4909 100.0*audio_time_usage/total_time_usage,
4910 100.0*(total_time_usage-tot)/total_time_usage,
4911 100.0);
4912 if(total_frame_cnt && frame_dropping)
4913 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4914 total_frame_cnt-drop_frame_cnt,
4915 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4916 drop_frame_cnt,
4917 100*drop_frame_cnt/total_frame_cnt,
4918 total_frame_cnt,
4919 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4922 // time to uninit all, except global stuff:
4923 int uninitialize_parts = INITIALIZED_ALL;
4924 if (opts->fixed_vo)
4925 uninitialize_parts -= INITIALIZED_VO;
4926 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4927 uninitialize_parts -= INITIALIZED_AO;
4928 uninit_player(mpctx, uninitialize_parts);
4930 if(mpctx->set_of_sub_size > 0) {
4931 current_module="sub_free";
4932 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4933 sub_free(mpctx->set_of_subtitles[i]);
4934 #ifdef CONFIG_ASS
4935 if(mpctx->set_of_ass_tracks[i])
4936 ass_free_track( mpctx->set_of_ass_tracks[i] );
4937 #endif
4939 mpctx->set_of_sub_size = 0;
4941 mpctx->vo_sub_last = vo_sub=NULL;
4942 mpctx->subdata=NULL;
4943 #ifdef CONFIG_ASS
4944 mpctx->osd->ass_track = NULL;
4945 if(ass_library)
4946 ass_clear_fonts(ass_library);
4947 #endif
4949 if (!mpctx->stop_play) // In case some goto jumped here...
4950 mpctx->stop_play = PT_NEXT_ENTRY;
4952 int playtree_direction = 1;
4954 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4955 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4956 play_tree_iter_free(mpctx->playtree_iter);
4957 mpctx->playtree_iter = NULL;
4959 mpctx->play_tree_step = 1;
4960 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4961 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4962 if(mpctx->playtree_iter) {
4963 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4964 play_tree_iter_free(mpctx->playtree_iter);
4965 mpctx->playtree_iter = NULL;
4968 } else if (mpctx->stop_play == PT_STOP) {
4969 play_tree_iter_free(mpctx->playtree_iter);
4970 mpctx->playtree_iter = NULL;
4971 } else { // NEXT PREV SRC
4972 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4975 while(mpctx->playtree_iter != NULL) {
4976 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4977 if(mpctx->filename == NULL) {
4978 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4979 play_tree_iter_free(mpctx->playtree_iter);
4980 mpctx->playtree_iter = NULL;
4982 } else
4983 break;
4986 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4987 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4988 mpctx->stop_play = 0;
4989 goto play_next_file;
4993 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4995 return 1;
4997 #endif /* DISABLE_MAIN */