cleanup: rename ass_* functions to mp_ass_*
[mplayer/glamo.git] / mplayer.c
bloba72b0143498297c6c5969c5e1dc5352d5476d4d9
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"
75 #include "sub/dec_sub.h"
77 #include "mp_osd.h"
78 #include "libvo/video_out.h"
80 #include "libvo/font_load.h"
81 #include "libvo/sub.h"
82 #include "ffmpeg_files/intreadwrite.h"
83 #include "av_sub.h"
84 #include "libmpcodecs/dec_teletext.h"
85 #include "cpudetect.h"
86 #include "version.h"
88 #ifdef CONFIG_X11
89 #include "libvo/x11_common.h"
90 #endif
92 #include "libao2/audio_out.h"
94 #include "codec-cfg.h"
96 #include "edl.h"
98 #include "spudec.h"
99 #include "vobsub.h"
101 #include "osdep/getch2.h"
102 #include "osdep/timer.h"
103 #include "osdep/findfiles.h"
105 #include "input/input.h"
107 const int under_mencoder = 0;
108 int slave_mode=0;
109 int enable_mouse_movements=0;
110 float start_volume = -1;
112 #include "osdep/priority.h"
114 char *heartbeat_cmd;
116 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
118 #ifdef HAVE_RTC
119 #ifdef __linux__
120 #include <linux/rtc.h>
121 #else
122 #include <rtc.h>
123 #define RTC_IRQP_SET RTCIO_IRQP_SET
124 #define RTC_PIE_ON RTCIO_PIE_ON
125 #endif /* __linux__ */
126 #endif /* HAVE_RTC */
128 #include "stream/tv.h"
129 #include "stream/stream_radio.h"
130 #ifdef CONFIG_DVBIN
131 #include "stream/dvbin.h"
132 #endif
133 #include "stream/cache2.h"
135 //**************************************************************************//
136 // Playtree
137 //**************************************************************************//
138 #include "playtree.h"
139 #include "playtreeparser.h"
141 //**************************************************************************//
142 // Config
143 //**************************************************************************//
144 #include "parser-cfg.h"
145 #include "parser-mpcmd.h"
147 //**************************************************************************//
148 // Config file
149 //**************************************************************************//
151 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
153 #include "path.h"
155 //**************************************************************************//
156 //**************************************************************************//
157 // Input media streaming & demultiplexer:
158 //**************************************************************************//
160 static int max_framesize=0;
162 #include "stream/stream.h"
163 #include "libmpdemux/demuxer.h"
164 #include "libmpdemux/stheader.h"
166 #ifdef CONFIG_DVDREAD
167 #include "stream/stream_dvd.h"
168 #endif
169 #include "stream/stream_dvdnav.h"
171 #include "libmpcodecs/dec_audio.h"
172 #include "libmpcodecs/dec_video.h"
173 #include "libmpcodecs/mp_image.h"
174 #include "libmpcodecs/vf.h"
175 #include "libmpcodecs/vd.h"
177 #include "mixer.h"
179 #include "mp_core.h"
180 #include "options.h"
181 #include "defaultopts.h"
183 static const char help_text[]=_(
184 "Usage: mplayer [options] [url|path/]filename\n"
185 "\n"
186 "Basic options: (complete list in the man page)\n"
187 " -vo <drv> select video output driver ('-vo help' for a list)\n"
188 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
189 #ifdef CONFIG_VCD
190 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
191 #endif
192 #ifdef CONFIG_DVDREAD
193 " dvd://<titleno> play DVD title from device instead of plain file\n"
194 #endif
195 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
196 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
197 " -nosound do not play sound\n"
198 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
199 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
200 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
201 " -playlist <file> specify playlist file\n"
202 " -vid x -aid y select video (x) and audio (y) stream to play\n"
203 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
204 " -pp <quality> enable postprocessing filter (details in the man page)\n"
205 " -framedrop enable frame dropping (for slow machines)\n"
206 "\n"
207 "Basic keys: (complete list in the man page, also check input.conf)\n"
208 " <- or -> seek backward/forward 10 seconds\n"
209 " down or up seek backward/forward 1 minute\n"
210 " pgdown or pgup seek backward/forward 10 minutes\n"
211 " < or > step backward/forward in playlist\n"
212 " p or SPACE pause movie (press any key to continue)\n"
213 " q or ESC stop playing and quit program\n"
214 " + or - adjust audio delay by +/- 0.1 second\n"
215 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
216 " * or / increase or decrease PCM volume\n"
217 " x or z adjust subtitle delay by +/- 0.1 second\n"
218 " r or t adjust subtitle position up/down, also see -vf expand\n"
219 "\n"
220 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
221 "\n");
224 #define Exit_SIGILL_RTCpuSel _(\
225 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
226 " It may be a bug in our new runtime CPU-detection code...\n"\
227 " Please read DOCS/HTML/en/bugreports.html.\n")
229 #define Exit_SIGILL _(\
230 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
231 " It usually happens when you run it on a CPU different than the one it was\n"\
232 " compiled/optimized for.\n"\
233 " Verify this!\n")
235 #define Exit_SIGSEGV_SIGFPE _(\
236 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
237 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
238 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
240 #define Exit_SIGCRASH _(\
241 "- MPlayer crashed. This shouldn't happen.\n"\
242 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
243 " gcc version. If you think it's MPlayer's fault, please read\n"\
244 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
245 " won't help unless you provide this information when reporting a possible bug.\n")
247 #define SystemTooSlow _("\n\n"\
248 " ************************************************\n"\
249 " **** Your system is too SLOW to play this! ****\n"\
250 " ************************************************\n\n"\
251 "Possible reasons, problems, workarounds:\n"\
252 "- Most common: broken/buggy _audio_ driver\n"\
253 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
254 " - Experiment with different values for -autosync, 30 is a good start.\n"\
255 "- Slow video output\n"\
256 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
257 "- Slow CPU\n"\
258 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
259 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
260 "- Broken file\n"\
261 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
262 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
263 " - Try -cache 8192.\n"\
264 "- Are you using -cache to play a non-interleaved AVI file?\n"\
265 " - Try -nocache.\n"\
266 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
267 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
270 //**************************************************************************//
271 //**************************************************************************//
273 #include "mp_fifo.h"
275 // benchmark:
276 double video_time_usage=0;
277 double vout_time_usage=0;
278 static double audio_time_usage=0;
279 static int total_time_usage_start=0;
280 static int total_frame_cnt=0;
281 static int drop_frame_cnt=0; // total number of dropped frames
283 // options:
284 static int output_quality=0;
286 // seek:
287 static double seek_to_sec;
288 static off_t seek_to_byte=0;
289 static off_t step_sec=0;
291 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
293 // codecs:
294 char **audio_codec_list=NULL; // override audio codec
295 char **video_codec_list=NULL; // override video codec
296 char **audio_fm_list=NULL; // override audio codec family
297 char **video_fm_list=NULL; // override video codec family
299 // this dvdsub_id was selected via slang
300 // use this to allow dvdnav to follow -slang across stream resets,
301 // in particular the subtitle ID for a language changes
302 int dvdsub_lang_id;
303 int vobsub_id=-1;
304 static char* spudec_ifo=NULL;
305 int forced_subs_only=0;
306 int file_filter=1;
308 // cache2:
309 int stream_cache_size=-1;
311 // dump:
312 int stream_dump_type=0;
314 // A-V sync:
315 static float default_max_pts_correction=-1;//0.01f;
316 float audio_delay=0;
317 static int ignore_start=0;
319 double force_fps=0;
320 static int force_srate=0;
321 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
322 static int play_n_frames=-1;
323 static int play_n_frames_mf=-1;
325 // sub:
326 char *font_name=NULL;
327 char *sub_font_name=NULL;
328 extern int font_fontconfig;
329 float font_factor=0.75;
330 char **sub_name=NULL;
331 float sub_delay=0;
332 float sub_fps=0;
333 int sub_auto = 1;
334 char *vobsub_name=NULL;
335 int subcc_enabled=0;
336 int suboverlap_enabled = 1;
338 #include "ass_mp.h"
340 char* current_module=NULL; // for debugging
343 // ---
345 #ifdef CONFIG_MENU
346 #include "m_struct.h"
347 #include "libmenu/menu.h"
348 static const vf_info_t* const libmenu_vfs[] = {
349 &vf_info_menu,
350 NULL
352 static vf_instance_t* vf_menu = NULL;
353 int use_menu = 0;
354 static char* menu_cfg = NULL;
355 static char* menu_root = "main";
356 #endif
359 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
360 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
361 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
362 int use_filedir_conf;
363 int use_filename_title;
365 #include "mpcommon.h"
366 #include "command.h"
368 #include "metadata.h"
370 const void *mpctx_get_video_out(MPContext *mpctx)
372 return mpctx->video_out;
375 const void *mpctx_get_audio_out(MPContext *mpctx)
377 return mpctx->audio_out;
380 void *mpctx_get_demuxer(MPContext *mpctx)
382 return mpctx->demuxer;
385 void *mpctx_get_playtree_iter(MPContext *mpctx)
387 return mpctx->playtree_iter;
390 void *mpctx_get_mixer(MPContext *mpctx)
392 return &mpctx->mixer;
395 int mpctx_get_global_sub_size(MPContext *mpctx)
397 return mpctx->global_sub_size;
400 int mpctx_get_osd_function(MPContext *mpctx)
402 return mpctx->osd_function;
405 static float get_relative_time(struct MPContext *mpctx)
407 unsigned int new_time = GetTimer();
408 unsigned int delta = new_time - mpctx->last_time;
409 mpctx->last_time = new_time;
410 return delta * 0.000001;
413 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
414 switch (type)
416 /* check for valid video stream */
417 case META_VIDEO_CODEC:
418 case META_VIDEO_BITRATE:
419 case META_VIDEO_RESOLUTION:
421 if (!mpctx->sh_video)
422 return 0;
423 break;
426 /* check for valid audio stream */
427 case META_AUDIO_CODEC:
428 case META_AUDIO_BITRATE:
429 case META_AUDIO_SAMPLES:
431 if (!mpctx->sh_audio)
432 return 0;
433 break;
436 /* check for valid demuxer */
437 case META_INFO_TITLE:
438 case META_INFO_ARTIST:
439 case META_INFO_ALBUM:
440 case META_INFO_YEAR:
441 case META_INFO_COMMENT:
442 case META_INFO_TRACK:
443 case META_INFO_GENRE:
445 if (!mpctx->demuxer)
446 return 0;
447 break;
450 default:
451 break;
454 return 1;
457 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
458 char **info = mpctx->demuxer->info;
459 int n;
461 if (!info || !tag)
462 return talloc_strdup(NULL, "");
464 for (n = 0; info[2*n] != NULL ; n++)
465 if (!strcasecmp (info[2*n], tag))
466 break;
468 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
471 char *get_metadata(struct MPContext *mpctx, metadata_t type)
473 sh_audio_t * const sh_audio = mpctx->sh_audio;
474 sh_video_t * const sh_video = mpctx->sh_video;
476 if (!is_valid_metadata_type(mpctx, type))
477 return NULL;
479 switch (type) {
480 case META_NAME:
481 return talloc_strdup(NULL, mp_basename(mpctx->filename));
482 case META_VIDEO_CODEC:
483 if (sh_video->format == 0x10000001)
484 return talloc_strdup(NULL, "mpeg1");
485 else if (sh_video->format == 0x10000002)
486 return talloc_strdup(NULL, "mpeg2");
487 else if (sh_video->format == 0x10000004)
488 return talloc_strdup(NULL, "mpeg4");
489 else if (sh_video->format == 0x10000005)
490 return talloc_strdup(NULL, "h264");
491 else if (sh_video->format >= 0x20202020)
492 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
493 else
494 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
495 case META_VIDEO_BITRATE:
496 return talloc_asprintf(NULL, "%d kbps",
497 (int) (sh_video->i_bps * 8 / 1024));
498 case META_VIDEO_RESOLUTION:
499 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
500 sh_video->disp_h);
501 case META_AUDIO_CODEC:
502 if (sh_audio->codec && sh_audio->codec->name)
503 return talloc_strdup(NULL, sh_audio->codec->name);
504 return talloc_strdup(NULL, "");
505 case META_AUDIO_BITRATE:
506 return talloc_asprintf(NULL, "%d kbps",
507 (int) (sh_audio->i_bps * 8/1000));
508 case META_AUDIO_SAMPLES:
509 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
510 sh_audio->channels);
512 /* check for valid demuxer */
513 case META_INFO_TITLE:
514 return get_demuxer_info(mpctx, "Title");
516 case META_INFO_ARTIST:
517 return get_demuxer_info(mpctx, "Artist");
519 case META_INFO_ALBUM:
520 return get_demuxer_info(mpctx, "Album");
522 case META_INFO_YEAR:
523 return get_demuxer_info(mpctx, "Year");
525 case META_INFO_COMMENT:
526 return get_demuxer_info(mpctx, "Comment");
528 case META_INFO_TRACK:
529 return get_demuxer_info(mpctx, "Track");
531 case META_INFO_GENRE:
532 return get_demuxer_info(mpctx, "Genre");
534 default:
535 break;
538 return talloc_strdup(NULL, "");
541 static void print_file_properties(struct MPContext *mpctx, const char *filename)
543 double start_pts = MP_NOPTS_VALUE;
544 double video_start_pts = MP_NOPTS_VALUE;
545 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
546 filename_recode(filename));
547 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
548 if (mpctx->sh_video) {
549 /* Assume FOURCC if all bytes >= 0x20 (' ') */
550 if (mpctx->sh_video->format >= 0x20202020)
551 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
552 else
553 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
554 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
555 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
556 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
557 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
558 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
559 video_start_pts = ds_get_next_pts(mpctx->d_video);
561 if (mpctx->sh_audio) {
562 /* Assume FOURCC if all bytes >= 0x20 (' ') */
563 if (mpctx->sh_audio->format >= 0x20202020)
564 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
565 else
566 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
567 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
568 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
569 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
570 start_pts = ds_get_next_pts(mpctx->d_audio);
572 if (video_start_pts != MP_NOPTS_VALUE) {
573 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
574 (mpctx->sh_video && video_start_pts < start_pts))
575 start_pts = video_start_pts;
577 if (start_pts != MP_NOPTS_VALUE)
578 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
579 else
580 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
581 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
582 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
583 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
584 if (mpctx->demuxer) {
585 if (mpctx->demuxer->num_chapters == 0)
586 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
587 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
591 /// step size of mixer changes
592 int volstep = 3;
594 #ifdef CONFIG_DVDNAV
595 static void mp_dvdnav_context_free(MPContext *ctx){
596 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
597 ctx->nav_smpi = NULL;
598 free(ctx->nav_buffer);
599 ctx->nav_buffer = NULL;
600 ctx->nav_start = NULL;
601 ctx->nav_in_size = 0;
603 #endif
605 static void uninit_subs(struct demuxer *demuxer)
607 for (int i = 0; i < MAX_S_STREAMS; i++) {
608 struct sh_sub *sh = demuxer->s_streams[i];
609 if (sh && sh->initialized)
610 sub_uninit(sh);
614 void uninit_player(struct MPContext *mpctx, unsigned int mask){
615 mask &= mpctx->initialized_flags;
617 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
619 if(mask&INITIALIZED_ACODEC){
620 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
621 current_module="uninit_acodec";
622 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
623 mpctx->sh_audio=NULL;
624 mpctx->mixer.afilter = NULL;
627 if (mask & INITIALIZED_SUB) {
628 mpctx->initialized_flags &= ~INITIALIZED_SUB;
629 if (mpctx->d_sub->sh)
630 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
633 if(mask&INITIALIZED_VCODEC){
634 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
635 current_module="uninit_vcodec";
636 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
637 mpctx->sh_video=NULL;
638 #ifdef CONFIG_MENU
639 vf_menu=NULL;
640 #endif
643 if(mask&INITIALIZED_DEMUXER){
644 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
645 current_module="free_demuxer";
646 if (mpctx->num_sources) {
647 mpctx->demuxer = mpctx->sources[0].demuxer;
648 for (int i = 1; i < mpctx->num_sources; i++) {
649 uninit_subs(mpctx->sources[i].demuxer);
650 free_stream(mpctx->sources[i].stream);
651 free_demuxer(mpctx->sources[i].demuxer);
654 talloc_free(mpctx->sources);
655 mpctx->sources = NULL;
656 mpctx->num_sources = 0;
657 talloc_free(mpctx->timeline);
658 mpctx->timeline = NULL;
659 mpctx->num_timeline_parts = 0;
660 talloc_free(mpctx->chapters);
661 mpctx->chapters = NULL;
662 mpctx->num_chapters = 0;
663 mpctx->video_offset = 0;
664 if(mpctx->demuxer){
665 mpctx->stream=mpctx->demuxer->stream;
666 uninit_subs(mpctx->demuxer);
667 free_demuxer(mpctx->demuxer);
669 mpctx->demuxer=NULL;
672 // kill the cache process:
673 if(mask&INITIALIZED_STREAM){
674 mpctx->initialized_flags&=~INITIALIZED_STREAM;
675 current_module="uninit_stream";
676 if(mpctx->stream) free_stream(mpctx->stream);
677 mpctx->stream=NULL;
680 if(mask&INITIALIZED_VO){
681 mpctx->initialized_flags&=~INITIALIZED_VO;
682 current_module="uninit_vo";
683 vo_destroy(mpctx->video_out);
684 mpctx->video_out=NULL;
685 #ifdef CONFIG_DVDNAV
686 mp_dvdnav_context_free(mpctx);
687 #endif
690 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
691 if(mask&INITIALIZED_GETCH2){
692 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
693 current_module="uninit_getch2";
694 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
695 // restore terminal:
696 getch2_disable();
699 if(mask&INITIALIZED_VOBSUB){
700 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
701 current_module="uninit_vobsub";
702 if(vo_vobsub) vobsub_close(vo_vobsub);
703 vo_vobsub=NULL;
706 if (mask&INITIALIZED_SPUDEC){
707 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
708 current_module="uninit_spudec";
709 spudec_free(vo_spudec);
710 vo_spudec=NULL;
713 if(mask&INITIALIZED_AO){
714 mpctx->initialized_flags&=~INITIALIZED_AO;
715 current_module="uninit_ao";
716 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
717 if (mpctx->audio_out)
718 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
719 mpctx->audio_out=NULL;
722 current_module=NULL;
725 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
727 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
728 uninit_player(mpctx, INITIALIZED_ALL);
729 #if defined(__MINGW32__) || defined(__CYGWIN__)
730 timeEndPeriod(1);
731 #endif
732 #ifdef CONFIG_X11
733 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
734 #endif
736 current_module="uninit_input";
737 mp_input_uninit(mpctx->input);
738 #ifdef CONFIG_MENU
739 if (use_menu)
740 menu_uninit();
741 #endif
743 #ifdef CONFIG_FREETYPE
744 current_module="uninit_font";
745 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
746 free_font_desc(mpctx->osd->sub_font);
747 free_font_desc(vo_font);
748 vo_font = NULL;
749 done_freetype();
750 #endif
751 osd_free(mpctx->osd);
753 #ifdef CONFIG_ASS
754 ass_library_done(ass_library);
755 ass_library = NULL;
756 #endif
758 current_module="exit_player";
760 // free mplayer config
761 if(mpctx->mconfig)
762 m_config_free(mpctx->mconfig);
763 mpctx->mconfig = NULL;
765 if(mpctx->playtree_iter)
766 play_tree_iter_free(mpctx->playtree_iter);
767 mpctx->playtree_iter = NULL;
768 if(mpctx->playtree)
769 play_tree_free(mpctx->playtree, 1);
770 mpctx->playtree = NULL;
772 talloc_free(mpctx->key_fifo);
774 free(edl_records); // free mem allocated for EDL
775 edl_records = NULL;
776 switch(how) {
777 case EXIT_QUIT:
778 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
779 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
780 break;
781 case EXIT_EOF:
782 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
783 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
784 break;
785 case EXIT_ERROR:
786 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
787 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
788 break;
789 default:
790 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
792 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
794 exit(rc);
797 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
799 exit_player_with_rc(mpctx, how, 1);
802 #ifndef __MINGW32__
803 static void child_sighandler(int x){
804 pid_t pid;
805 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
807 #endif
809 #ifdef CONFIG_CRASH_DEBUG
810 static char *prog_path;
811 static int crash_debug = 0;
812 #endif
814 static void exit_sighandler(int x){
815 static int sig_count=0;
816 #ifdef CONFIG_CRASH_DEBUG
817 if (!crash_debug || x != SIGTRAP)
818 #endif
819 ++sig_count;
820 if(sig_count==5)
822 /* We're crashing bad and can't uninit cleanly :(
823 * by popular request, we make one last (dirty)
824 * effort to restore the user's
825 * terminal. */
826 getch2_disable();
827 exit(1);
829 if(sig_count==6) exit(1);
830 if(sig_count>6){
831 // can't stop :(
832 #ifndef __MINGW32__
833 kill(getpid(),SIGKILL);
834 #endif
836 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
837 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
838 "\nMPlayer interrupted by signal %d in module: %s\n", x,
839 current_module ? current_module : "unknown");
840 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
841 if(sig_count<=1)
842 switch(x){
843 case SIGINT:
844 case SIGPIPE:
845 case SIGQUIT:
846 case SIGTERM:
847 case SIGKILL:
848 async_quit_request = 1;
849 return; // killed from keyboard (^C) or killed [-9]
850 case SIGILL:
851 #if CONFIG_RUNTIME_CPUDETECT
852 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
853 #else
854 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
855 #endif
856 case SIGFPE:
857 case SIGSEGV:
858 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
859 default:
860 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
861 #ifdef CONFIG_CRASH_DEBUG
862 if (crash_debug) {
863 int gdb_pid;
864 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
865 gdb_pid = fork();
866 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
867 if (gdb_pid == 0) { // We are the child
868 char spid[20];
869 snprintf(spid, sizeof(spid), "%i", getppid());
870 getch2_disable(); // allow terminal to work properly with gdb
871 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
872 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
873 } else if (gdb_pid < 0)
874 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
875 else {
876 waitpid(gdb_pid, NULL, 0);
878 if (x == SIGTRAP) return;
880 #endif
882 getch2_disable();
883 exit(1);
886 #include "cfg-mplayer.h"
888 static int cfg_include(m_option_t *conf, char *filename)
890 return m_config_parse_config_file(conf->priv, filename);
893 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
895 struct MPOpts *opts = &mpctx->opts;
896 char *conffile;
897 int conffile_fd;
898 if (!(opts->noconfig & 2) &&
899 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
900 exit_player(mpctx, EXIT_NONE);
901 if ((conffile = get_path("")) == NULL) {
902 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
903 } else {
904 #ifdef __MINGW32__
905 mkdir(conffile);
906 #else
907 mkdir(conffile, 0777);
908 #endif
909 free(conffile);
910 if ((conffile = get_path("config")) == NULL) {
911 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
912 } else {
913 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
914 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
915 write(conffile_fd, default_config, strlen(default_config));
916 close(conffile_fd);
918 if (!(opts->noconfig & 1) &&
919 m_config_parse_config_file(conf, conffile) < 0)
920 exit_player(mpctx, EXIT_NONE);
921 free(conffile);
926 #define PROFILE_CFG_PROTOCOL "protocol."
928 static void load_per_protocol_config (m_config_t* conf, const char *const file)
930 char *str;
931 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
932 m_profile_t *p;
934 /* does filename actually uses a protocol ? */
935 str = strstr (file, "://");
936 if (!str)
937 return;
939 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
940 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
941 p = m_config_get_profile (conf, protocol);
942 if (p)
944 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
945 m_config_set_profile(conf,p);
949 #define PROFILE_CFG_EXTENSION "extension."
951 static void load_per_extension_config (m_config_t* conf, const char *const file)
953 char *str;
954 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
955 m_profile_t *p;
957 /* does filename actually have an extension ? */
958 str = strrchr (file, '.');
959 if (!str)
960 return;
962 sprintf (extension, PROFILE_CFG_EXTENSION);
963 strncat (extension, ++str, 7);
964 p = m_config_get_profile (conf, extension);
965 if (p)
967 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
968 m_config_set_profile(conf,p);
972 #define PROFILE_CFG_VO "vo."
973 #define PROFILE_CFG_AO "ao."
975 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
977 char profile[strlen (cfg) + strlen (out) + 1];
978 m_profile_t *p;
980 sprintf (profile, "%s%s", cfg, out);
981 p = m_config_get_profile (conf, profile);
982 if (p)
984 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
985 m_config_set_profile(conf,p);
990 * Tries to load a config file
991 * @return 0 if file was not found, 1 otherwise
993 static int try_load_config(m_config_t *conf, const char *file)
995 struct stat st;
996 if (stat(file, &st))
997 return 0;
998 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
999 m_config_parse_config_file (conf, file);
1000 return 1;
1003 static void load_per_file_config (m_config_t* conf, const char *const file)
1005 char *confpath;
1006 char cfg[PATH_MAX];
1007 const char *name;
1009 if (strlen(file) > PATH_MAX - 14) {
1010 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1011 return;
1013 sprintf (cfg, "%s.conf", file);
1015 name = mp_basename(cfg);
1016 if (use_filedir_conf) {
1017 char dircfg[PATH_MAX];
1018 strcpy(dircfg, cfg);
1019 strcpy(dircfg + (name - cfg), "mplayer.conf");
1020 try_load_config(conf, dircfg);
1022 if (try_load_config(conf, cfg))
1023 return;
1026 if ((confpath = get_path (name)) != NULL)
1028 try_load_config(conf, confpath);
1030 free (confpath);
1034 /* When libmpdemux performs a blocking operation (network connection or
1035 * cache filling) if the operation fails we use this function to check
1036 * if it was interrupted by the user.
1037 * The function returns a new value for eof. */
1038 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1040 mp_cmd_t* cmd;
1041 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1042 switch(cmd->id) {
1043 case MP_CMD_QUIT:
1044 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1045 case MP_CMD_PLAY_TREE_STEP: {
1046 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1047 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1048 } break;
1049 case MP_CMD_PLAY_TREE_UP_STEP: {
1050 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1051 } break;
1052 case MP_CMD_PLAY_ALT_SRC_STEP: {
1053 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1054 } break;
1056 mp_cmd_free(cmd);
1058 return stop_play;
1061 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1063 play_tree_add_bpf(entry,mpctx->filename);
1066 if(!entry) {
1067 entry = mpctx->playtree_iter->tree;
1068 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1069 return PT_NEXT_ENTRY;
1071 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1072 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1073 return PT_NEXT_ENTRY;
1076 play_tree_remove(entry,1,1);
1077 return PT_NEXT_SRC;
1079 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1080 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1081 entry = mpctx->playtree_iter->tree;
1082 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1083 return PT_NEXT_ENTRY;
1085 play_tree_remove(entry,1,1);
1087 return PT_NEXT_SRC;
1090 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1092 struct MPOpts *opts = &mpctx->opts;
1093 sub_data *subd = NULL;
1094 struct ass_track *asst = NULL;
1095 bool is_native_ass = false;
1097 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1098 return;
1100 #ifdef CONFIG_ASS
1101 if (opts->ass_enabled) {
1102 #ifdef CONFIG_ICONV
1103 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1104 #else
1105 asst = mp_ass_read_stream(ass_library, filename, 0);
1106 #endif
1107 is_native_ass = asst;
1108 if (!asst) {
1109 subd = sub_read_file(filename, fps, &mpctx->opts);
1110 if (subd) {
1111 asst = mp_ass_read_subdata(ass_library, subd, fps);
1112 sub_free(subd);
1113 subd = NULL;
1116 } else
1117 #endif
1118 subd = sub_read_file(filename, fps, &mpctx->opts);
1121 if (!asst && !subd) {
1122 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1123 "Cannot load subtitles: %s\n", filename_recode(filename));
1124 return;
1127 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1128 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1129 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1130 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1131 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1132 filename_recode(filename));
1133 ++mpctx->set_of_sub_size;
1134 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1135 filename_recode(filename));
1138 void init_vo_spudec(struct MPContext *mpctx)
1140 spudec_free(vo_spudec);
1141 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1142 vo_spudec = NULL;
1144 // we currently can't work without video stream
1145 if (!mpctx->sh_video)
1146 return;
1148 if (spudec_ifo) {
1149 unsigned int palette[16], width, height;
1150 current_module="spudec_init_vobsub";
1151 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1152 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1155 #ifdef CONFIG_DVDREAD
1156 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1157 current_module="spudec_init_dvdread";
1158 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1159 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1160 NULL, 0);
1162 #endif
1164 #ifdef CONFIG_DVDNAV
1165 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1166 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1167 current_module="spudec_init_dvdnav";
1168 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1170 #endif
1172 if (vo_spudec==NULL) {
1173 sh_sub_t *sh = mpctx->d_sub->sh;
1174 current_module="spudec_init_normal";
1175 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1176 spudec_set_font_factor(vo_spudec,font_factor);
1179 if (vo_spudec!=NULL) {
1180 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1181 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1186 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1187 * make it all work is to use the builtin SDL-bootstrap code, which
1188 * will be done automatically by replacing our main() if we include SDL.h.
1190 #if defined(__APPLE__) && defined(CONFIG_SDL)
1191 #ifdef CONFIG_SDL_SDL_H
1192 #include <SDL/SDL.h>
1193 #else
1194 #include <SDL.h>
1195 #endif
1196 #endif
1199 * \brief append a formatted string
1200 * \param buf buffer to print into
1201 * \param pos position of terminating 0 in buf
1202 * \param len maximum number of characters in buf, not including terminating 0
1203 * \param format printf format string
1205 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1207 va_list va;
1208 va_start(va, format);
1209 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1210 va_end(va);
1211 if (*pos >= len ) {
1212 buf[len] = 0;
1213 *pos = len;
1218 * \brief append time in the hh:mm:ss.f format
1219 * \param buf buffer to print into
1220 * \param pos position of terminating 0 in buf
1221 * \param len maximum number of characters in buf, not including terminating 0
1222 * \param time time value to convert/append
1224 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1225 int64_t tenths = 10 * time;
1226 int f1 = tenths % 10;
1227 int ss = (tenths / 10) % 60;
1228 int mm = (tenths / 600) % 60;
1229 int hh = tenths / 36000;
1230 if (time <= 0) {
1231 saddf(buf, pos, len, "unknown");
1232 return;
1234 if (hh > 0)
1235 saddf(buf, pos, len, "%2d:", hh);
1236 if (hh > 0 || mm > 0)
1237 saddf(buf, pos, len, "%02d:", mm);
1238 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1241 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1243 struct MPOpts *opts = &mpctx->opts;
1244 sh_video_t * const sh_video = mpctx->sh_video;
1246 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1247 a_pos = playing_audio_pts(mpctx);
1248 if (mpctx->sh_audio && sh_video && at_frame) {
1249 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1250 if (mpctx->time_frame > 0)
1251 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1252 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1253 && !mpctx->drop_message_shown) {
1254 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1255 mpctx->drop_message_shown = true;
1258 if (opts->quiet)
1259 return;
1262 int width;
1263 char *line;
1264 unsigned pos = 0;
1265 get_screen_size();
1266 if (screen_width > 0)
1267 width = screen_width;
1268 else
1269 width = 80;
1270 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1271 /* Windows command line is broken (MinGW's rxvt works, but we
1272 * should not depend on that). */
1273 width--;
1274 #endif
1275 line = malloc(width + 1); // one additional char for the terminating null
1277 // Audio time
1278 if (mpctx->sh_audio) {
1279 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1280 if (!sh_video) {
1281 float len = get_time_length(mpctx);
1282 saddf(line, &pos, width, "(");
1283 sadd_hhmmssf(line, &pos, width, a_pos);
1284 saddf(line, &pos, width, ") of %.1f (", len);
1285 sadd_hhmmssf(line, &pos, width, len);
1286 saddf(line, &pos, width, ") ");
1290 // Video time
1291 if (sh_video)
1292 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1294 // A-V sync
1295 if (mpctx->sh_audio && sh_video)
1296 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1297 mpctx->last_av_difference, mpctx->total_avsync_change);
1299 // Video stats
1300 if (sh_video)
1301 saddf(line, &pos, width, "%3d/%3d ",
1302 (int)sh_video->num_frames,
1303 (int)sh_video->num_frames_decoded);
1305 // CPU usage
1306 if (sh_video) {
1307 if (sh_video->timer > 0.5)
1308 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1309 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1310 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1311 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1312 else
1313 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1314 } else if (mpctx->sh_audio) {
1315 if (mpctx->delay > 0.5)
1316 saddf(line, &pos, width, "%4.1f%% ",
1317 100.0*audio_time_usage/(double)mpctx->delay);
1318 else
1319 saddf(line, &pos, width, "??,?%% ");
1322 // VO stats
1323 if (sh_video)
1324 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1326 #ifdef CONFIG_STREAM_CACHE
1327 // cache stats
1328 if (stream_cache_size > 0)
1329 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1330 #endif
1332 // other
1333 if (opts->playback_speed != 1)
1334 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1336 // end
1337 if (erase_to_end_of_line) {
1338 line[pos] = 0;
1339 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1340 } else {
1341 memset(&line[pos], ' ', width - pos);
1342 line[width] = 0;
1343 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1345 free(line);
1349 * \brief build a chain of audio filters that converts the input format
1350 * to the ao's format, taking into account the current playback_speed.
1351 * \param sh_audio describes the requested input format of the chain.
1352 * \param ao_data describes the requested output format of the chain.
1354 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1355 ao_data_t *ao_data)
1357 struct MPOpts *opts = &mpctx->opts;
1358 int new_srate;
1359 int result;
1360 if (!sh_audio)
1362 mpctx->mixer.afilter = NULL;
1363 return 0;
1365 if(af_control_any_rev(sh_audio->afilter,
1366 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1367 &opts->playback_speed)) {
1368 new_srate = sh_audio->samplerate;
1369 } else {
1370 new_srate = sh_audio->samplerate * opts->playback_speed;
1371 if (new_srate != ao_data->samplerate) {
1372 // limits are taken from libaf/af_resample.c
1373 if (new_srate < 8000)
1374 new_srate = 8000;
1375 if (new_srate > 192000)
1376 new_srate = 192000;
1377 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1380 result = init_audio_filters(sh_audio, new_srate,
1381 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1382 mpctx->mixer.afilter = sh_audio->afilter;
1383 return result;
1387 typedef struct mp_osd_msg mp_osd_msg_t;
1388 struct mp_osd_msg {
1389 /// Previous message on the stack.
1390 mp_osd_msg_t* prev;
1391 /// Message text.
1392 char msg[128];
1393 int id,level,started;
1394 /// Display duration in ms.
1395 unsigned time;
1398 /// OSD message stack.
1399 static mp_osd_msg_t* osd_msg_stack = NULL;
1402 * \brief Add a message on the OSD message stack
1404 * If a message with the same id is already present in the stack
1405 * it is pulled on top of the stack, otherwise a new message is created.
1408 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1409 va_list ap)
1411 mp_osd_msg_t *msg,*last=NULL;
1412 int r;
1414 // look if the id is already in the stack
1415 for(msg = osd_msg_stack ; msg && msg->id != id ;
1416 last = msg, msg = msg->prev);
1417 // not found: alloc it
1418 if(!msg) {
1419 msg = calloc(1,sizeof(mp_osd_msg_t));
1420 msg->prev = osd_msg_stack;
1421 osd_msg_stack = msg;
1422 } else if(last) { // found, but it's not on top of the stack
1423 last->prev = msg->prev;
1424 msg->prev = osd_msg_stack;
1425 osd_msg_stack = msg;
1427 // write the msg
1428 r = vsnprintf(msg->msg, 128, fmt, ap);
1429 if(r >= 128) msg->msg[127] = 0;
1430 // set id and time
1431 msg->id = id;
1432 msg->level = level;
1433 msg->time = time;
1437 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1439 va_list ap;
1440 va_start(ap, fmt);
1441 set_osd_msg_va(id, level, time, fmt, ap);
1442 va_end(ap);
1445 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1447 va_list ap;
1448 va_start(ap, fmt);
1449 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1450 va_end(ap);
1455 * \brief Remove a message from the OSD stack
1457 * This function can be used to get rid of a message right away.
1461 void rm_osd_msg(int id) {
1462 mp_osd_msg_t *msg,*last=NULL;
1464 // Search for the msg
1465 for(msg = osd_msg_stack ; msg && msg->id != id ;
1466 last = msg, msg = msg->prev);
1467 if(!msg) return;
1469 // Detach it from the stack and free it
1470 if(last)
1471 last->prev = msg->prev;
1472 else
1473 osd_msg_stack = msg->prev;
1474 free(msg);
1478 * \brief Remove all messages from the OSD stack
1482 static void clear_osd_msgs(void) {
1483 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1484 while(msg) {
1485 prev = msg->prev;
1486 free(msg);
1487 msg = prev;
1489 osd_msg_stack = NULL;
1493 * \brief Get the current message from the OSD stack.
1495 * This function decrements the message timer and destroys the old ones.
1496 * The message that should be displayed is returned (if any).
1500 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1502 struct MPOpts *opts = &mpctx->opts;
1503 mp_osd_msg_t *msg,*prev,*last = NULL;
1504 static unsigned last_update = 0;
1505 unsigned now = GetTimerMS();
1506 unsigned diff;
1507 char hidden_dec_done = 0;
1509 if (mpctx->osd_visible) {
1510 // 36000000 means max timed visibility is 1 hour into the future, if
1511 // the difference is greater assume it's wrapped around from below 0
1512 if (mpctx->osd_visible - now > 36000000) {
1513 mpctx->osd_visible = 0;
1514 vo_osd_progbar_type = -1; // disable
1515 vo_osd_changed(OSDTYPE_PROGBAR);
1516 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1519 if (mpctx->osd_show_percentage_until - now > 36000000)
1520 mpctx->osd_show_percentage_until = 0;
1522 if(!last_update) last_update = now;
1523 diff = now >= last_update ? now - last_update : 0;
1525 last_update = now;
1527 // Look for the first message in the stack with high enough level.
1528 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1529 prev = msg->prev;
1530 if (msg->level > opts->osd_level && hidden_dec_done)
1531 continue;
1532 // The message has a high enough level or it is the first hidden one
1533 // in both cases we decrement the timer or kill it.
1534 if(!msg->started || msg->time > diff) {
1535 if(msg->started) msg->time -= diff;
1536 else msg->started = 1;
1537 // display it
1538 if (msg->level <= opts->osd_level)
1539 return msg;
1540 hidden_dec_done = 1;
1541 continue;
1543 // kill the message
1544 free(msg);
1545 if(last) {
1546 last->prev = prev;
1547 msg = last;
1548 } else {
1549 osd_msg_stack = prev;
1550 msg = NULL;
1553 // Nothing found
1554 return NULL;
1558 * \brief Display the OSD bar.
1560 * Display the OSD bar or fall back on a simple message.
1564 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1565 struct MPOpts *opts = &mpctx->opts;
1566 if (opts->osd_level < 1)
1567 return;
1569 if(mpctx->sh_video) {
1570 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1571 vo_osd_progbar_type = type;
1572 vo_osd_progbar_value = 256*(val-min)/(max-min);
1573 vo_osd_changed(OSDTYPE_PROGBAR);
1574 return;
1577 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1578 name, ROUND(100*(val-min)/(max-min)));
1582 * \brief Display text subtitles on the OSD
1584 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1586 int i;
1587 vo_sub = subs;
1588 vo_osd_changed(OSDTYPE_SUBTITLE);
1589 if (!mpctx->sh_video) {
1590 // reverse order, since newest set_osd_msg is displayed first
1591 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1592 if (!subs || i >= subs->lines || !subs->text[i])
1593 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1594 else {
1595 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1596 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1597 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1604 * \brief Update the OSD message line.
1606 * This function displays the current message on the vo OSD or on the term.
1607 * If the stack is empty and the OSD level is high enough the timer
1608 * is displayed (only on the vo OSD).
1612 static void update_osd_msg(struct MPContext *mpctx)
1614 struct MPOpts *opts = &mpctx->opts;
1615 mp_osd_msg_t *msg;
1616 struct osd_state *osd = mpctx->osd;
1617 char osd_text_timer[128];
1619 if (mpctx->add_osd_seek_info) {
1620 double percentage = get_percent_pos(mpctx);
1621 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1622 if (mpctx->sh_video)
1623 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1624 mpctx->add_osd_seek_info = false;
1627 // Look if we have a msg
1628 if((msg = get_osd_msg(mpctx))) {
1629 if (strcmp(osd->osd_text, msg->msg)) {
1630 strncpy(osd->osd_text, msg->msg, 127);
1631 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1632 if(opts->term_osd)
1633 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1634 msg->msg);
1636 return;
1639 if(mpctx->sh_video) {
1640 // fallback on the timer
1641 if (opts->osd_level >= 2) {
1642 int len = get_time_length(mpctx);
1643 int percentage = -1;
1644 char percentage_text[10];
1645 int pts = get_current_time(mpctx);
1647 if (mpctx->osd_show_percentage_until)
1648 percentage = get_percent_pos(mpctx);
1650 if (percentage >= 0)
1651 snprintf(percentage_text, 9, " (%d%%)", percentage);
1652 else
1653 percentage_text[0] = 0;
1655 if (opts->osd_level == 3)
1656 snprintf(osd_text_timer, 63,
1657 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1658 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1659 len/3600,(len/60)%60,len%60,percentage_text);
1660 else
1661 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1662 mpctx->osd_function,pts/3600,(pts/60)%60,
1663 pts%60,percentage_text);
1664 } else
1665 osd_text_timer[0]=0;
1667 if (strcmp(osd->osd_text, osd_text_timer)) {
1668 strncpy(osd->osd_text, osd_text_timer, 63);
1669 vo_osd_changed(OSDTYPE_OSD);
1671 return;
1674 // Clear the term osd line
1675 if (opts->term_osd && osd->osd_text[0]) {
1676 osd->osd_text[0] = 0;
1677 printf("%s\n", opts->term_osd_esc);
1681 ///@}
1682 // OSDMsgStack
1685 void reinit_audio_chain(struct MPContext *mpctx)
1687 struct MPOpts *opts = &mpctx->opts;
1688 if (!mpctx->sh_audio)
1689 return;
1690 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1691 current_module="init_audio_codec";
1692 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1693 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1694 goto init_error;
1696 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1697 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1701 current_module="af_preinit";
1702 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1703 ao_data.samplerate=force_srate;
1704 ao_data.channels=0;
1705 ao_data.format = opts->audio_output_format;
1707 // first init to detect best values
1708 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1709 // input:
1710 mpctx->sh_audio->samplerate,
1711 // output:
1712 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1713 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1714 "pre-init!\n");
1715 exit_player(mpctx, EXIT_ERROR);
1717 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1718 current_module="ao2_init";
1719 ao_data.buffersize = opts->ao_buffersize;
1720 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1721 0, // plugin flag
1722 ao_data.samplerate,
1723 ao_data.channels,
1724 ao_data.format, 0);
1725 if(!mpctx->audio_out){
1726 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1727 goto init_error;
1729 mpctx->initialized_flags|=INITIALIZED_AO;
1730 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1731 mpctx->audio_out->info->short_name,
1732 ao_data.samplerate, ao_data.channels,
1733 af_fmt2str_short(ao_data.format),
1734 af_fmt2bits(ao_data.format)/8 );
1735 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1736 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1737 if(strlen(mpctx->audio_out->info->comment) > 0)
1738 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1741 // init audio filters:
1742 current_module="af_init";
1743 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1744 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1745 goto init_error;
1747 mpctx->mixer.audio_out = mpctx->audio_out;
1748 mpctx->mixer.volstep = volstep;
1749 mpctx->syncing_audio = true;
1750 return;
1752 init_error:
1753 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1754 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1755 mpctx->d_audio->id = -2;
1759 ///@}
1760 // Command2Property
1763 // Return pts value corresponding to the end point of audio written to the
1764 // ao so far.
1765 static double written_audio_pts(struct MPContext *mpctx)
1767 sh_audio_t *sh_audio = mpctx->sh_audio;
1768 demux_stream_t *d_audio = mpctx->d_audio;
1769 double buffered_output;
1770 // first calculate the end pts of audio that has been output by decoder
1771 double a_pts = sh_audio->pts;
1772 if (a_pts != MP_NOPTS_VALUE)
1773 // Good, decoder supports new way of calculating audio pts.
1774 // sh_audio->pts is the timestamp of the latest input packet with
1775 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1776 // the amount of bytes the decoder has written after that timestamp.
1777 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1778 else {
1779 // Decoder doesn't support new way of calculating pts (or we're
1780 // being called before it has decoded anything with known timestamp).
1781 // Use the old method of audio pts calculation: take the timestamp
1782 // of last packet with known pts the decoder has read data from,
1783 // and add amount of bytes read after the beginning of that packet
1784 // divided by input bps. This will be inaccurate if the input/output
1785 // ratio is not constant for every audio packet or if it is constant
1786 // but not accurately known in sh_audio->i_bps.
1788 a_pts = d_audio->pts;
1789 // ds_tell_pts returns bytes read after last timestamp from
1790 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1791 // it has read but not decoded
1792 if (sh_audio->i_bps)
1793 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1794 (double)sh_audio->i_bps;
1796 // Now a_pts hopefully holds the pts for end of audio from decoder.
1797 // Substract data in buffers between decoder and audio out.
1799 // Decoded but not filtered
1800 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1802 // Data buffered in audio filters, measured in bytes of "missing" output
1803 buffered_output = af_calc_delay(sh_audio->afilter);
1805 // Data that was ready for ao but was buffered because ao didn't fully
1806 // accept everything to internal buffers yet
1807 buffered_output += sh_audio->a_out_buffer_len;
1809 // Filters divide audio length by playback_speed, so multiply by it
1810 // to get the length in original units without speedup or slowdown
1811 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1813 return a_pts + mpctx->video_offset;
1816 // Return pts value corresponding to currently playing audio.
1817 double playing_audio_pts(struct MPContext *mpctx)
1819 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1820 mpctx->audio_out->get_delay();
1823 static bool is_av_sub(int type)
1825 return type == 'b' || type == 'p' || type == 'x';
1828 void update_subtitles(struct MPContext *mpctx, double refpts,
1829 double sub_offset, bool reset)
1831 struct MPOpts *opts = &mpctx->opts;
1832 struct sh_video *sh_video = mpctx->sh_video;
1833 struct demux_stream *d_sub = mpctx->d_sub;
1834 double curpts = refpts + sub_delay;
1835 unsigned char *packet=NULL;
1836 int len;
1837 struct sh_sub *sh_sub = d_sub->sh;
1838 int type = sh_sub ? sh_sub->type : 'v';
1839 static subtitle subs;
1840 if (reset) {
1841 if (sh_sub)
1842 sub_reset(sh_sub, mpctx->osd);
1843 sub_clear_text(&subs, MP_NOPTS_VALUE);
1844 if (vo_sub)
1845 set_osd_subtitle(mpctx, NULL);
1846 if (vo_spudec) {
1847 spudec_reset(vo_spudec);
1848 vo_osd_changed(OSDTYPE_SPU);
1850 #ifdef CONFIG_FFMPEG
1851 if (is_av_sub(type))
1852 reset_avsub(sh_sub);
1853 #endif
1854 return;
1856 // find sub
1857 if (mpctx->subdata) {
1858 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1859 current_module = "find_sub";
1860 find_sub(mpctx, mpctx->subdata, curpts *
1861 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1862 if (vo_sub)
1863 mpctx->vo_sub_last = vo_sub;
1866 // DVD sub:
1867 if (vobsub_id >= 0 || type == 'v') {
1868 int timestamp;
1869 current_module = "spudec";
1870 /* Get a sub packet from the DVD or a vobsub */
1871 while(1) {
1872 // Vobsub
1873 len = 0;
1874 if (vo_vobsub) {
1875 if (curpts >= 0) {
1876 len = vobsub_get_packet(vo_vobsub, curpts,
1877 (void**)&packet, &timestamp);
1878 if (len > 0) {
1879 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);
1882 } else {
1883 // DVD sub
1884 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1885 if (len > 0) {
1886 // XXX This is wrong, sh_video->pts can be arbitrarily
1887 // much behind demuxing position. Unfortunately using
1888 // d_video->pts which would have been the simplest
1889 // improvement doesn't work because mpeg specific hacks
1890 // in video.c set d_video->pts to 0.
1891 float x = d_sub->pts - refpts;
1892 if (x > -20 && x < 20) // prevent missing subs on pts reset
1893 timestamp = 90000*d_sub->pts;
1894 else timestamp = 90000*curpts;
1895 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1896 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1897 refpts, d_sub->pts, timestamp);
1900 if (len<=0 || !packet) break;
1901 // create it only here, since with some broken demuxers we might
1902 // type = v but no DVD sub and we currently do not change the
1903 // "original frame size" ever after init, leading to wrong-sized
1904 // PGS subtitles.
1905 if (!vo_spudec)
1906 vo_spudec = spudec_new(NULL);
1907 if (vo_vobsub || timestamp >= 0)
1908 spudec_assemble(vo_spudec, packet, len, timestamp);
1910 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1911 if (type == 'd' && !d_sub->demuxer->teletext) {
1912 tt_stream_props tsp = {0};
1913 void *ptr = &tsp;
1914 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1915 d_sub->demuxer->teletext = ptr;
1917 if (d_sub->non_interleaved)
1918 ds_get_next_pts(d_sub);
1920 while (d_sub->first) {
1921 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1922 if (subpts > curpts) {
1923 // Libass handled subs can be fed to it in advance
1924 if (!opts->ass_enabled || !is_text_sub(type))
1925 break;
1926 // Try to avoid demuxing whole file at once
1927 if (d_sub->non_interleaved && subpts > curpts + 1)
1928 break;
1930 double duration = d_sub->first->duration;
1931 len = ds_get_packet_sub(d_sub, &packet);
1932 if (is_av_sub(type)) {
1933 #ifdef CONFIG_FFMPEG
1934 decode_avsub(sh_sub, packet, len, subpts, duration);
1935 #endif
1936 continue;
1938 if (type == 'm') {
1939 if (len < 2) continue;
1940 len = FFMIN(len - 2, AV_RB16(packet));
1941 packet += 2;
1943 if (type == 'd') {
1944 if (d_sub->demuxer->teletext) {
1945 uint8_t *p = packet;
1946 p++;
1947 len--;
1948 while (len >= 46) {
1949 int sublen = p[1];
1950 if (p[0] == 2 || p[0] == 3)
1951 teletext_control(d_sub->demuxer->teletext,
1952 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1953 p += sublen + 2;
1954 len -= sublen + 2;
1957 continue;
1959 if (sh_sub && sh_sub->active) {
1960 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
1961 continue;
1963 if (subpts != MP_NOPTS_VALUE) {
1964 if (duration < 0)
1965 sub_clear_text(&subs, MP_NOPTS_VALUE);
1966 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1967 int i;
1968 unsigned char* p = packet;
1969 for (i=0; i < 8 && *p != '\0'; p++)
1970 if (*p == ',')
1971 i++;
1972 if (*p == '\0') /* Broken line? */
1973 continue;
1974 len -= p - packet;
1975 packet = p;
1977 double endpts = MP_NOPTS_VALUE;
1978 if (subpts != MP_NOPTS_VALUE && duration >= 0)
1979 endpts = subpts + duration;
1980 sub_add_text(&subs, packet, len, endpts);
1981 set_osd_subtitle(mpctx, &subs);
1983 if (d_sub->non_interleaved)
1984 ds_get_next_pts(d_sub);
1986 if (!opts->ass_enabled)
1987 if (sub_clear_text(&subs, curpts))
1988 set_osd_subtitle(mpctx, &subs);
1990 if (vo_spudec) {
1991 spudec_heartbeat(vo_spudec, 90000*curpts);
1992 if (spudec_changed(vo_spudec))
1993 vo_osd_changed(OSDTYPE_SPU);
1996 current_module=NULL;
1999 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2001 int page_changed;
2003 if (!demuxer->teletext)
2004 return;
2006 //Also forcing page update when such ioctl is not supported or call error occured
2007 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2008 page_changed=1;
2010 if(!page_changed)
2011 return;
2013 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2014 vo_osd_teletext_page=NULL;
2015 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2016 vo_osd_teletext_half=0;
2017 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2018 vo_osd_teletext_mode=0;
2019 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2020 vo_osd_teletext_format=0;
2021 vo_osd_changed(OSDTYPE_TELETEXT);
2023 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2026 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2027 struct MPOpts *opts = &mpctx->opts;
2028 // check for frame-drop:
2029 current_module = "check_framedrop";
2030 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2031 static int dropped_frames;
2032 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
2033 float d = delay-mpctx->delay;
2034 ++total_frame_cnt;
2035 // we should avoid dropping too many frames in sequence unless we
2036 // are too late. and we allow 100ms A-V delay here:
2037 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2038 && !mpctx->restart_playback) {
2039 ++drop_frame_cnt;
2040 ++dropped_frames;
2041 return frame_dropping;
2042 } else
2043 dropped_frames = 0;
2045 return 0;
2049 #ifdef HAVE_RTC
2050 int rtc_fd = -1;
2051 #endif
2053 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2055 #ifdef HAVE_RTC
2056 if (rtc_fd >= 0){
2057 // -------- RTC -----------
2058 current_module="sleep_rtc";
2059 while (time_frame > 0.000) {
2060 unsigned long rtc_ts;
2061 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2062 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2063 time_frame -= get_relative_time(mpctx);
2065 } else
2066 #endif
2068 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2069 // unnecessarily high CPU usage
2070 struct MPOpts *opts = &mpctx->opts;
2071 float margin = opts->softsleep ? 0.011 : 0;
2072 current_module = "sleep_timer";
2073 while (time_frame > margin) {
2074 usec_sleep(1000000 * (time_frame - margin));
2075 time_frame -= get_relative_time(mpctx);
2077 if (opts->softsleep){
2078 current_module = "sleep_soft";
2079 if (time_frame < 0)
2080 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2081 while (time_frame > 0)
2082 time_frame -= get_relative_time(mpctx); // burn the CPU
2085 return time_frame;
2088 static int select_subtitle(MPContext *mpctx)
2090 struct MPOpts *opts = &mpctx->opts;
2091 // find the best sub to use
2092 int id;
2093 int found = 0;
2094 mpctx->global_sub_pos = -1; // no subs by default
2095 if (vobsub_id >= 0) {
2096 // if user asks for a vobsub id, use that first.
2097 id = vobsub_id;
2098 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2101 if (!found && opts->sub_id >= 0) {
2102 // if user asks for a dvd sub id, use that next.
2103 id = opts->sub_id;
2104 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2107 if (!found) {
2108 // if there are text subs to use, use those. (autosubs come last here)
2109 id = 0;
2110 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2113 if (!found && opts->sub_id == -1) {
2114 // finally select subs by language and container hints
2115 if (opts->sub_id == -1)
2116 opts->sub_id =
2117 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2118 opts->sub_lang);
2119 if (opts->sub_id >= 0) {
2120 id = opts->sub_id;
2121 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2124 return found;
2127 #ifdef CONFIG_DVDNAV
2128 #ifndef FF_B_TYPE
2129 #define FF_B_TYPE 3
2130 #endif
2131 /// store decoded video image
2132 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2133 mp_image_t *from_mpi) {
2134 mp_image_t *mpi;
2136 /// Do not store B-frames
2137 if (from_mpi->pict_type == FF_B_TYPE)
2138 return to_mpi;
2140 if (to_mpi &&
2141 to_mpi->w == from_mpi->w &&
2142 to_mpi->h == from_mpi->h &&
2143 to_mpi->imgfmt == from_mpi->imgfmt)
2144 mpi = to_mpi;
2145 else {
2146 if (to_mpi)
2147 free_mp_image(to_mpi);
2148 if (from_mpi->w == 0 || from_mpi->h == 0)
2149 return NULL;
2150 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2153 copy_mpi(mpi,from_mpi);
2154 return mpi;
2157 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2158 struct MPOpts *opts = &ctx->opts;
2159 if (ctx->sh_video) {
2160 /// clear video pts
2161 ctx->d_video->pts = 0.0f;
2162 ctx->sh_video->pts = 0.0f;
2163 ctx->sh_video->i_pts = 0.0f;
2164 ctx->sh_video->last_pts = 0.0f;
2165 ctx->sh_video->num_buffered_pts = 0;
2166 ctx->sh_video->num_frames = 0;
2167 ctx->sh_video->num_frames_decoded = 0;
2168 ctx->sh_video->timer = 0.0f;
2169 ctx->sh_video->stream_delay = 0.0f;
2170 ctx->sh_video->timer = 0;
2171 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2174 if (ctx->sh_audio) {
2175 /// free audio packets and reset
2176 ds_free_packs(ctx->d_audio);
2177 audio_delay -= ctx->sh_audio->stream_delay;
2178 ctx->delay =- audio_delay;
2179 ctx->audio_out->reset();
2180 resync_audio_stream(ctx->sh_audio);
2183 audio_delay = 0.0f;
2184 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2185 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2186 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2187 if (dvdsub_lang_id != opts->sub_id) {
2188 opts->sub_id = dvdsub_lang_id;
2189 select_subtitle(ctx);
2193 /// clear all EOF related flags
2194 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2197 /// Restore last decoded DVDNAV (still frame)
2198 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2199 int *in_size,
2200 unsigned char **start,
2201 mp_image_t *decoded_frame)
2203 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2204 return decoded_frame;
2206 /// a change occured in dvdnav stream
2207 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2208 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2209 mp_dvdnav_context_free(mpctx);
2210 mp_dvdnav_reset_stream(mpctx);
2211 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2212 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2215 if (*in_size < 0) {
2216 float len;
2218 /// Display still frame, if any
2219 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2220 decoded_frame = mpctx->nav_smpi;
2222 /// increment video frame : continue playing after still frame
2223 len = get_time_length(mpctx);
2224 if (mpctx->sh_video->pts >= len &&
2225 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2226 mp_dvdnav_skip_still(mpctx->stream);
2227 mp_dvdnav_skip_wait(mpctx->stream);
2229 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2231 if (mpctx->nav_buffer) {
2232 *start = mpctx->nav_start;
2233 *in_size = mpctx->nav_in_size;
2234 if (mpctx->nav_start)
2235 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2239 return decoded_frame;
2242 /// Save last decoded DVDNAV (still frame)
2243 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2244 unsigned char *start,
2245 mp_image_t *decoded_frame)
2247 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2248 return;
2250 free(mpctx->nav_buffer);
2252 mpctx->nav_buffer = malloc(in_size);
2253 mpctx->nav_start = start;
2254 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2255 if (mpctx->nav_buffer)
2256 memcpy(mpctx->nav_buffer,start,in_size);
2258 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2259 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2261 #endif /* CONFIG_DVDNAV */
2263 /* Modify video timing to match the audio timeline. There are two main
2264 * reasons this is needed. First, video and audio can start from different
2265 * positions at beginning of file or after a seek (MPlayer starts both
2266 * immediately even if they have different pts). Second, the file can have
2267 * audio timestamps that are inconsistent with the duration of the audio
2268 * packets, for example two consecutive timestamp values differing by
2269 * one second but only a packet with enough samples for half a second
2270 * of playback between them.
2272 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2274 current_module = "av_sync";
2276 if (!mpctx->sh_audio || mpctx->syncing_audio)
2277 return;
2279 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2280 double v_pts = mpctx->sh_video->pts;
2281 double av_delay = a_pts - v_pts;
2282 // Try to sync vo_flip() so it will *finish* at given time
2283 av_delay += mpctx->last_vo_flip_duration;
2284 av_delay -= audio_delay; // This much pts difference is desired
2286 double change = av_delay * 0.1;
2287 double max_change = default_max_pts_correction >= 0 ?
2288 default_max_pts_correction : frame_time * 0.1;
2289 if (change < -max_change)
2290 change = -max_change;
2291 else if (change > max_change)
2292 change = max_change;
2293 mpctx->delay += change;
2294 mpctx->total_avsync_change += change;
2297 #define ASYNC_PLAY_DONE -3
2298 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2300 struct MPOpts *opts = &mpctx->opts;
2301 sh_audio_t * const sh_audio = mpctx->sh_audio;
2302 int res;
2304 // Timing info may not be set without
2305 res = decode_audio(sh_audio, 1);
2306 if (res < 0)
2307 return res;
2309 int bytes;
2310 bool did_retry = false;
2311 while (1) {
2312 double written_pts = written_audio_pts(mpctx);
2313 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2314 - audio_delay;
2315 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2316 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2318 // ogg demuxers give packets without timing
2319 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2320 if (!did_retry) {
2321 // Try to read more data to see packets that have pts
2322 int res = decode_audio(sh_audio, ao_data.bps);
2323 if (res < 0)
2324 return res;
2325 did_retry = true;
2326 continue;
2328 bytes = 0;
2331 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2332 bytes = 0;
2334 if (bytes > 0)
2335 break;
2337 mpctx->syncing_audio = false;
2338 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2339 int res = decode_audio(sh_audio, a);
2340 bytes += sh_audio->a_out_buffer_len;
2341 if (bytes >= 0) {
2342 memmove(sh_audio->a_out_buffer,
2343 sh_audio->a_out_buffer +
2344 sh_audio->a_out_buffer_len - bytes,
2345 bytes);
2346 sh_audio->a_out_buffer_len = bytes;
2347 if (res < 0)
2348 return res;
2349 return decode_audio(sh_audio, playsize);
2351 sh_audio->a_out_buffer_len = 0;
2352 if (res < 0)
2353 return res;
2355 int fillbyte = 0;
2356 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2357 fillbyte = 0x80;
2358 if (bytes >= playsize) {
2359 /* This case could fall back to the one below with
2360 * bytes = playsize, but then silence would keep accumulating
2361 * in a_out_buffer if the AO accepts less data than it asks for
2362 * in playsize. */
2363 char *p = malloc(playsize);
2364 memset(p, fillbyte, playsize);
2365 playsize = mpctx->audio_out->play(p, playsize, 0);
2366 free(p);
2367 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2368 return ASYNC_PLAY_DONE;
2370 mpctx->syncing_audio = false;
2371 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2372 return decode_audio(sh_audio, playsize);
2375 static int fill_audio_out_buffers(struct MPContext *mpctx)
2377 struct MPOpts *opts = &mpctx->opts;
2378 unsigned int t;
2379 double tt;
2380 int playsize;
2381 int playflags=0;
2382 int audio_eof=0;
2383 bool format_change = false;
2384 sh_audio_t * const sh_audio = mpctx->sh_audio;
2386 current_module="play_audio";
2388 while (1) {
2389 int sleep_time;
2390 // all the current uses of ao_data.pts seem to be in aos that handle
2391 // sync completely wrong; there should be no need to use ao_data.pts
2392 // in get_space()
2393 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2394 playsize = mpctx->audio_out->get_space();
2395 if (mpctx->sh_video || playsize >= ao_data.outburst)
2396 break;
2398 // handle audio-only case:
2399 // this is where mplayer sleeps during audio-only playback
2400 // to avoid 100% CPU use
2401 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2402 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2403 usec_sleep(sleep_time * 1000);
2406 // Fill buffer if needed:
2407 current_module="decode_audio";
2408 t = GetTimer();
2410 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2411 mpctx->syncing_audio = false;
2413 int res;
2414 if (mpctx->syncing_audio && mpctx->sh_video)
2415 res = audio_start_sync(mpctx, playsize);
2416 else
2417 res = decode_audio(sh_audio, playsize);
2418 if (res < 0) { // EOF, error or format change
2419 if (res == -2)
2420 format_change = true;
2421 else if (res == ASYNC_PLAY_DONE)
2422 return 1;
2423 else if (mpctx->d_audio->eof) {
2424 audio_eof = 1;
2425 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2426 if (sh_audio->a_out_buffer_len < unitsize)
2427 return 0;
2430 t = GetTimer() - t;
2431 tt = t*0.000001f; audio_time_usage+=tt;
2432 if (playsize > sh_audio->a_out_buffer_len) {
2433 playsize = sh_audio->a_out_buffer_len;
2434 if (audio_eof)
2435 playflags |= AOPLAY_FINAL_CHUNK;
2437 if (!playsize)
2438 return 1;
2440 // play audio:
2441 current_module="play_audio";
2443 // Is this pts value actually useful for the aos that access it?
2444 // They're obviously badly broken in the way they handle av sync;
2445 // would not having access to this make them more broken?
2446 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2447 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2449 if (playsize > 0) {
2450 sh_audio->a_out_buffer_len -= playsize;
2451 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2452 sh_audio->a_out_buffer_len);
2453 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2454 } else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2455 // Sanity check to avoid hanging in case current ao doesn't output
2456 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2457 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2458 sh_audio->a_out_buffer_len = 0;
2461 /* The format change isn't handled too gracefully. A more precise
2462 * implementation would require draining buffered old-format audio
2463 * while displaying video, then doing the output format switch.
2465 if (format_change) {
2466 uninit_player(mpctx, INITIALIZED_AO);
2467 reinit_audio_chain(mpctx);
2470 return 1;
2473 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2474 float *aq_sleep_time)
2476 struct MPOpts *opts = &mpctx->opts;
2477 double audio_limit = 2;
2478 current_module="calc_sleep_time";
2480 if (mpctx->restart_playback)
2481 return 0;
2483 *time_frame -= get_relative_time(mpctx); // reset timer
2485 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2486 float delay = mpctx->audio_out->get_delay();
2487 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2489 if (opts->autosync) {
2491 * Adjust this raw delay value by calculating the expected
2492 * delay for this frame and generating a new value which is
2493 * weighted between the two. The higher autosync is, the
2494 * closer to the delay value gets to that which "-nosound"
2495 * would have used, and the longer it will take for A/V
2496 * sync to settle at the right value (but it eventually will.)
2497 * This settling time is very short for values below 100.
2499 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2500 float difference = delay - predicted;
2501 delay = predicted + difference / (float)opts->autosync;
2504 *time_frame = delay - mpctx->delay / opts->playback_speed;
2506 // delay = amount of audio buffered in soundcard/driver
2507 delay = FFMIN(delay, 0.5);
2508 delay = FFMAX(delay, 0.1);
2509 audio_limit = delay;
2510 } else {
2511 // If we're lagging more than 200 ms behind the right playback rate,
2512 // don't try to "catch up".
2513 // If benchmark is set always output frames as fast as possible
2514 // without sleeping.
2515 if (*time_frame < -0.2 || opts->benchmark)
2516 *time_frame = 0;
2519 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2521 if (t <= 0.05)
2522 return 0;
2524 t -= 0.05;
2525 if (t > audio_limit * 0.6)
2526 t = audio_limit * 0.5;
2527 *aq_sleep_time += t;
2528 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2529 return 1;
2532 int reinit_video_chain(struct MPContext *mpctx)
2534 struct MPOpts *opts = &mpctx->opts;
2535 sh_video_t * const sh_video = mpctx->sh_video;
2536 double ar=-1.0;
2537 //================== Init VIDEO (codec & libvo) ==========================
2538 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2539 current_module="preinit_libvo";
2541 //shouldn't we set dvideo->id=-2 when we fail?
2542 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2543 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2544 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2545 goto err_out;
2547 mpctx->initialized_flags|=INITIALIZED_VO;
2550 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2551 mpctx->sh_video->stream_aspect = ar;
2552 current_module="init_video_filters";
2554 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2555 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2557 #ifdef CONFIG_MENU
2558 if(use_menu) {
2559 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2560 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2561 if(!vf_menu) {
2562 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2563 use_menu = 0;
2566 if(vf_menu)
2567 sh_video->vfilter = vf_menu;
2568 #endif
2570 #ifdef CONFIG_ASS
2571 if(opts->ass_enabled) {
2572 int i;
2573 int insert = 1;
2574 if (opts->vf_settings)
2575 for (i = 0; opts->vf_settings[i].name; ++i)
2576 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2577 insert = 0;
2578 break;
2580 if (insert) {
2581 extern vf_info_t vf_info_ass;
2582 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2583 char* vf_arg[] = {"auto", "1", NULL};
2584 int retcode = 0;
2585 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2586 sh_video->vfilter,
2587 "ass", vf_arg,
2588 &retcode);
2589 if (vf_ass)
2590 sh_video->vfilter = vf_ass;
2591 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2592 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2593 else
2594 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2597 #endif
2599 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2601 #ifdef CONFIG_ASS
2602 if (opts->ass_enabled)
2603 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2604 #endif
2606 current_module="init_video_codec";
2608 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2609 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2610 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2612 if(!sh_video->initialized){
2613 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2614 goto err_out;
2617 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2619 if (sh_video->codec)
2620 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2622 sh_video->last_pts = MP_NOPTS_VALUE;
2623 sh_video->num_buffered_pts = 0;
2624 sh_video->next_frame_time = 0;
2626 if (opts->auto_quality > 0) {
2627 // Auto quality option enabled
2628 output_quality=get_video_quality_max(sh_video);
2629 if (opts->auto_quality > output_quality)
2630 opts->auto_quality = output_quality;
2631 else
2632 output_quality = opts->auto_quality;
2633 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2634 set_video_quality(sh_video,output_quality);
2637 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2639 current_module="init_vo";
2641 return 1;
2643 err_out:
2644 mpctx->sh_video = mpctx->d_video->sh = NULL;
2645 return 0;
2648 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2650 struct sh_video *sh_video = mpctx->sh_video;
2651 double frame_time = 0;
2652 struct vo *video_out = mpctx->video_out;
2653 while (1) {
2654 current_module = "filter_video";
2655 // In nocorrect-pts mode there is no way to properly time these frames
2656 if (vo_get_buffered_frame(video_out, 0) >= 0)
2657 break;
2658 if (vf_output_queued_frame(sh_video->vfilter))
2659 break;
2660 unsigned char *packet = NULL;
2661 frame_time = sh_video->next_frame_time;
2662 if (mpctx->restart_playback)
2663 frame_time = 0;
2664 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2665 &packet, force_fps);
2666 if (in_size < 0) {
2667 #ifdef CONFIG_DVDNAV
2668 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2669 if (mp_dvdnav_is_eof(mpctx->stream))
2670 return -1;
2671 if (mpctx->d_video)
2672 mpctx->d_video->eof = 0;
2673 if (mpctx->d_audio)
2674 mpctx->d_audio->eof = 0;
2675 mpctx->stream->eof = 0;
2676 } else
2677 #endif
2678 return -1;
2680 if (in_size > max_framesize)
2681 max_framesize = in_size;
2682 sh_video->timer += frame_time;
2683 if (mpctx->sh_audio)
2684 mpctx->delay -= frame_time;
2685 // video_read_frame can change fps (e.g. for ASF video)
2686 vo_fps = sh_video->fps;
2687 int framedrop_type = check_framedrop(mpctx, frame_time);
2688 current_module = "decode video";
2690 void *decoded_frame;
2691 #ifdef CONFIG_DVDNAV
2692 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2693 if (in_size >= 0 && !decoded_frame)
2694 #endif
2695 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2696 sh_video->pts);
2697 #ifdef CONFIG_DVDNAV
2698 // Save last still frame for future display
2699 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2700 #endif
2701 if (decoded_frame) {
2702 current_module = "filter video";
2703 filter_video(sh_video, decoded_frame, sh_video->pts);
2705 break;
2707 return frame_time;
2710 static void determine_frame_pts(struct MPContext *mpctx)
2712 struct sh_video *sh_video = mpctx->sh_video;
2713 struct MPOpts *opts = &mpctx->opts;
2715 if (opts->user_pts_assoc_mode) {
2716 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2717 } else if (sh_video->pts_assoc_mode == 0) {
2718 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2719 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2720 sh_video->pts_assoc_mode = 1;
2721 else
2722 sh_video->pts_assoc_mode = 2;
2723 } else {
2724 int probcount1 = sh_video->num_reordered_pts_problems;
2725 int probcount2 = sh_video->num_sorted_pts_problems;
2726 if (sh_video->pts_assoc_mode == 2) {
2727 int tmp = probcount1;
2728 probcount1 = probcount2;
2729 probcount2 = tmp;
2731 if (probcount1 >= probcount2 * 1.5 + 2) {
2732 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2733 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2734 "%d.\n", sh_video->pts_assoc_mode);
2737 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2738 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2741 static double update_video(struct MPContext *mpctx)
2743 struct sh_video *sh_video = mpctx->sh_video;
2744 struct vo *video_out = mpctx->video_out;
2745 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2746 mpctx->osd); // hack for vf_expand
2747 if (!mpctx->opts.correct_pts)
2748 return update_video_nocorrect_pts(mpctx);
2750 double pts;
2752 while (1) {
2753 current_module = "filter_video";
2754 if (!mpctx->hrseek_active
2755 && vo_get_buffered_frame(video_out, false) >= 0)
2756 break;
2757 // XXX Time used in this call is not counted in any performance
2758 // timer now
2759 if (vf_output_queued_frame(sh_video->vfilter))
2760 break;
2761 unsigned char *packet = NULL;
2762 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2763 if (pts != MP_NOPTS_VALUE)
2764 pts += mpctx->video_offset;
2765 bool hit_eof = false;
2766 if (in_size < 0) {
2767 // try to extract last frames in case of decoder lag
2768 in_size = 0;
2769 pts = MP_NOPTS_VALUE;
2770 hit_eof = true;
2772 if (in_size > max_framesize)
2773 max_framesize = in_size;
2774 current_module = "decode video";
2775 if (pts >= mpctx->hrseek_pts - .005)
2776 mpctx->hrseek_framedrop = false;
2777 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2778 check_framedrop(mpctx, sh_video->frametime);
2779 void *decoded_frame = decode_video(sh_video, packet, in_size,
2780 framedrop_type, pts);
2781 if (decoded_frame) {
2782 determine_frame_pts(mpctx);
2783 current_module = "filter video";
2784 filter_video(sh_video, decoded_frame, sh_video->pts);
2785 } else if (hit_eof) {
2786 if (vo_get_buffered_frame(video_out, true) < 0)
2787 return -1;
2789 break;
2792 if (!video_out->frame_loaded)
2793 return 0;
2795 pts = video_out->next_pts;
2796 if (pts == MP_NOPTS_VALUE) {
2797 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2798 // Try to use decoder pts from before filters
2799 pts = sh_video->pts;
2800 if (pts == MP_NOPTS_VALUE)
2801 pts = sh_video->last_pts;
2803 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005)
2804 return 0;
2805 mpctx->hrseek_active = false;
2806 sh_video->pts = pts;
2807 if (sh_video->last_pts == MP_NOPTS_VALUE)
2808 sh_video->last_pts = sh_video->pts;
2809 else if (sh_video->last_pts > sh_video->pts) {
2810 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2811 sh_video->pts, sh_video->last_pts);
2812 /* If the difference in pts is small treat it as jitter around the
2813 * right value (possibly caused by incorrect timestamp ordering) and
2814 * just show this frame immediately after the last one.
2815 * Treat bigger differences as timestamp resets and start counting
2816 * timing of later frames from the position of this one. */
2817 if (sh_video->last_pts - sh_video->pts > 0.5)
2818 sh_video->last_pts = sh_video->pts;
2819 else
2820 sh_video->pts = sh_video->last_pts;
2822 double frame_time = sh_video->pts - sh_video->last_pts;
2823 sh_video->last_pts = sh_video->pts;
2824 sh_video->timer += frame_time;
2825 if (mpctx->sh_audio)
2826 mpctx->delay -= frame_time;
2827 return frame_time;
2830 void pause_player(struct MPContext *mpctx)
2832 if (mpctx->paused)
2833 return;
2834 mpctx->paused = 1;
2835 mpctx->step_frames = 0;
2836 mpctx->time_frame -= get_relative_time(mpctx);
2838 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2839 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2841 if (mpctx->audio_out && mpctx->sh_audio)
2842 mpctx->audio_out->pause(); // pause audio, keep data if possible
2845 void unpause_player(struct MPContext *mpctx)
2847 if (!mpctx->paused)
2848 return;
2849 mpctx->paused = 0;
2851 if (mpctx->audio_out && mpctx->sh_audio)
2852 mpctx->audio_out->resume(); // resume audio
2853 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2854 && !mpctx->step_frames)
2855 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2856 (void)get_relative_time(mpctx); // ignore time that passed during pause
2859 void add_step_frame(struct MPContext *mpctx)
2861 mpctx->step_frames++;
2862 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2863 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2864 unpause_player(mpctx);
2867 static void pause_loop(struct MPContext *mpctx)
2869 struct MPOpts *opts = &mpctx->opts;
2870 mp_cmd_t* cmd;
2871 if (!opts->quiet) {
2872 // Small hack to display the pause message on the OSD line.
2873 // The pause string is: "\n == PAUSE == \r" so we need to
2874 // take the first and the last char out
2875 if (opts->term_osd && !mpctx->sh_video) {
2876 char msg[128] = _("\n ===== PAUSE =====\r");
2877 int mlen = strlen(msg);
2878 msg[mlen-1] = '\0';
2879 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2880 update_osd_msg(mpctx);
2881 } else
2882 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2883 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2886 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2887 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2888 if (cmd) {
2889 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2890 run_command(mpctx, cmd);
2891 mp_cmd_free(cmd);
2892 continue;
2894 if (mpctx->sh_video && mpctx->video_out)
2895 vo_check_events(mpctx->video_out);
2896 #ifdef CONFIG_MENU
2897 if (vf_menu)
2898 vf_menu_pause_update(vf_menu);
2899 #endif
2900 usec_sleep(20000);
2901 update_osd_msg(mpctx);
2902 int hack = vo_osd_changed(0);
2903 vo_osd_changed(hack);
2904 if (hack)
2905 break;
2910 // Find the right mute status and record position for new file position
2911 static void edl_seek_reset(MPContext *mpctx)
2913 mpctx->edl_muted = 0;
2914 next_edl_record = edl_records;
2916 while (next_edl_record) {
2917 if (next_edl_record->start_sec >= get_current_time(mpctx))
2918 break;
2920 if (next_edl_record->action == EDL_MUTE)
2921 mpctx->edl_muted = !mpctx->edl_muted;
2922 next_edl_record = next_edl_record->next;
2924 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2925 mixer_mute(&mpctx->mixer);
2929 // Execute EDL command for the current position if one exists
2930 static void edl_update(MPContext *mpctx)
2932 if (!next_edl_record)
2933 return;
2935 if (!mpctx->sh_video) {
2936 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2937 free_edl(edl_records);
2938 next_edl_record = NULL;
2939 edl_records = NULL;
2940 return;
2943 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2944 if (next_edl_record->action == EDL_SKIP) {
2945 mpctx->osd_function = OSD_FFW;
2946 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2947 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2948 "[%f], length [%f]\n", next_edl_record->start_sec,
2949 next_edl_record->stop_sec, next_edl_record->length_sec);
2951 else if (next_edl_record->action == EDL_MUTE) {
2952 mpctx->edl_muted = !mpctx->edl_muted;
2953 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2954 mixer_mute(&mpctx->mixer);
2955 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2956 next_edl_record->start_sec );
2958 next_edl_record = next_edl_record->next;
2962 static void reinit_decoders(struct MPContext *mpctx)
2964 reinit_video_chain(mpctx);
2965 reinit_audio_chain(mpctx);
2966 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
2969 static void seek_reset(struct MPContext *mpctx)
2971 if (mpctx->sh_video) {
2972 current_module = "seek_video_reset";
2973 resync_video_stream(mpctx->sh_video);
2974 mpctx->sh_video->timer = 0;
2975 vo_seek_reset(mpctx->video_out);
2976 mpctx->sh_video->timer = 0;
2977 mpctx->sh_video->num_buffered_pts = 0;
2978 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2979 mpctx->delay = 0;
2980 mpctx->time_frame = 0;
2981 mpctx->restart_playback = true;
2982 // Not all demuxers set d_video->pts during seek, so this value
2983 // (which is used by at least vobsub and edl code below) may
2984 // be completely wrong (probably 0).
2985 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2986 mpctx->video_pts = mpctx->sh_video->pts;
2987 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
2988 true);
2989 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2992 if (mpctx->sh_audio) {
2993 current_module = "seek_audio_reset";
2994 resync_audio_stream(mpctx->sh_audio);
2995 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2996 mpctx->sh_audio->a_buffer_len = 0;
2997 mpctx->sh_audio->a_out_buffer_len = 0;
2998 if (!mpctx->sh_video)
2999 update_subtitles(mpctx, mpctx->sh_audio->pts,
3000 mpctx->video_offset, true);
3003 if (vo_vobsub && mpctx->sh_video) {
3004 current_module = "seek_vobsub_reset";
3005 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3008 edl_seek_reset(mpctx);
3010 mpctx->hrseek_active = false;
3011 mpctx->hrseek_framedrop = false;
3012 mpctx->total_avsync_change = 0;
3013 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3014 drop_frame_cnt = 0;
3016 current_module = NULL;
3019 static bool timeline_set_part(struct MPContext *mpctx, int i)
3021 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3022 struct timeline_part *n = mpctx->timeline + i;
3023 mpctx->timeline_part = i;
3024 mpctx->video_offset = n->start - n->source_start;
3025 if (n->source == p->source)
3026 return false;
3027 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC | INITIALIZED_SUB);
3028 mpctx->demuxer = n->source->demuxer;
3029 mpctx->d_video = mpctx->demuxer->video;
3030 mpctx->d_audio = mpctx->demuxer->audio;
3031 mpctx->d_sub = mpctx->demuxer->sub;
3032 mpctx->sh_video = mpctx->d_video->sh;
3033 mpctx->sh_audio = mpctx->d_audio->sh;
3034 return true;
3037 // Given pts, switch playback to the corresponding part.
3038 // Return offset within that part.
3039 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3040 bool *need_reset)
3042 if (pts < 0)
3043 pts = 0;
3044 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3045 struct timeline_part *p = mpctx->timeline + i;
3046 if (pts < (p+1)->start) {
3047 *need_reset = timeline_set_part(mpctx, i);
3048 return pts - p->start + p->source_start;
3051 return -1;
3055 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3056 static int seek(MPContext *mpctx, struct seek_params seek)
3058 struct MPOpts *opts = &mpctx->opts;
3060 current_module = "seek";
3061 if (mpctx->stop_play == AT_END_OF_FILE)
3062 mpctx->stop_play = KEEP_PLAYING;
3063 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3064 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3065 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3066 || opts->hr_seek > 0 || seek.exact > 0;
3067 if (seek.type == MPSEEK_FACTOR
3068 || seek.type == MPSEEK_ABSOLUTE
3069 && seek.amount < mpctx->last_chapter_pts
3070 || seek.amount < 0)
3071 mpctx->last_chapter_seek = -1;
3072 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3073 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3074 seek.type = MPSEEK_ABSOLUTE;
3076 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3077 && seek.type == MPSEEK_RELATIVE) {
3078 seek.type = MPSEEK_ABSOLUTE;
3079 seek.direction = seek.amount > 0 ? 1 : -1;
3080 seek.amount += get_current_time(mpctx);
3083 /* At least the liba52 decoder wants to read from the input stream
3084 * during initialization, so reinit must be done after the demux_seek()
3085 * call that clears possible stream EOF. */
3086 bool need_reset = false;
3087 double demuxer_amount = seek.amount;
3088 if (mpctx->timeline) {
3089 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3090 &need_reset);
3091 if (demuxer_amount == -1) {
3092 mpctx->stop_play = AT_END_OF_FILE;
3093 // Clear audio from current position
3094 if (mpctx->sh_audio) {
3095 mpctx->audio_out->reset();
3096 mpctx->sh_audio->a_buffer_len = 0;
3097 mpctx->sh_audio->a_out_buffer_len = 0;
3099 return -1;
3102 int demuxer_style = 0;
3103 switch (seek.type) {
3104 case MPSEEK_FACTOR:
3105 demuxer_style |= SEEK_FACTOR; // fallthrough
3106 case MPSEEK_ABSOLUTE:
3107 demuxer_style |= SEEK_ABSOLUTE;
3109 if (hr_seek || seek.direction < 0)
3110 demuxer_style |= SEEK_BACKWARD;
3111 else if (seek.direction > 0)
3112 demuxer_style |= SEEK_FORWARD;
3114 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3115 demuxer_style);
3116 if (need_reset)
3117 reinit_decoders(mpctx);
3118 if (seekresult == 0)
3119 return -1;
3121 seek_reset(mpctx);
3123 /* Use the target time as "current position" for further relative
3124 * seeks etc until a new video frame has been decoded */
3125 if (seek.type == MPSEEK_ABSOLUTE)
3126 mpctx->video_pts = seek.amount;
3128 if (hr_seek) {
3129 mpctx->hrseek_active = true;
3130 mpctx->hrseek_framedrop = true;
3131 mpctx->hrseek_pts = seek.amount;
3134 mpctx->start_timestamp = GetTimerMS();
3136 return 0;
3139 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3140 int exact)
3142 struct seek_params *seek = &mpctx->seek;
3143 switch (type) {
3144 case MPSEEK_RELATIVE:
3145 if (seek->type == MPSEEK_FACTOR)
3146 return; // Well... not common enough to bother doing better
3147 seek->amount += amount;
3148 seek->exact = FFMAX(seek->exact, exact);
3149 if (seek->type == MPSEEK_NONE)
3150 seek->exact = exact;
3151 if (seek->type == MPSEEK_ABSOLUTE)
3152 return;
3153 if (seek->amount == 0) {
3154 *seek = (struct seek_params){0};
3155 return;
3157 seek->type = MPSEEK_RELATIVE;
3158 return;
3159 case MPSEEK_ABSOLUTE:
3160 case MPSEEK_FACTOR:
3161 *seek = (struct seek_params) {
3162 .type = type,
3163 .amount = amount,
3164 .exact = exact,
3166 return;
3167 case MPSEEK_NONE:
3168 *seek = (struct seek_params){0};
3169 return;
3171 abort();
3175 double get_time_length(struct MPContext *mpctx)
3177 if (mpctx->timeline)
3178 return mpctx->timeline[mpctx->num_timeline_parts].start;
3180 struct demuxer *demuxer = mpctx->demuxer;
3181 double get_time_ans;
3182 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3183 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3184 (void *) &get_time_ans) > 0)
3185 return get_time_ans;
3187 struct sh_video *sh_video = mpctx->d_video->sh;
3188 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3189 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3190 return (double) (demuxer->movi_end - demuxer->movi_start) /
3191 (sh_video->i_bps + sh_audio->i_bps);
3192 if (sh_video && sh_video->i_bps)
3193 return (double) (demuxer->movi_end - demuxer->movi_start) /
3194 sh_video->i_bps;
3195 if (sh_audio && sh_audio->i_bps)
3196 return (double) (demuxer->movi_end - demuxer->movi_start) /
3197 sh_audio->i_bps;
3198 return 0;
3201 /* If there are timestamps from stream level then use those (for example
3202 * DVDs can have consistent times there while the MPEG-level timestamps
3203 * reset). */
3204 double get_current_time(struct MPContext *mpctx)
3206 struct demuxer *demuxer = mpctx->demuxer;
3207 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3208 return demuxer->stream_pts;
3209 struct sh_video *sh_video = demuxer->video->sh;
3210 if (sh_video)
3211 return mpctx->video_pts;
3212 return playing_audio_pts(mpctx);
3215 int get_percent_pos(struct MPContext *mpctx)
3217 struct demuxer *demuxer = mpctx->demuxer;
3218 int ans = 0;
3219 if (mpctx->timeline)
3220 ans = get_current_time(mpctx) * 100 /
3221 mpctx->timeline[mpctx->num_timeline_parts].start;
3222 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3224 else {
3225 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3226 off_t pos = demuxer->filepos > 0 ?
3227 demuxer->filepos : stream_tell(demuxer->stream);
3228 if (len > 0)
3229 ans = (pos - demuxer->movi_start) / len;
3230 else
3231 ans = 0;
3233 if (ans < 0)
3234 ans = 0;
3235 if (ans > 100)
3236 ans = 100;
3237 return ans;
3240 // -2 is no chapters, -1 is before first chapter
3241 int get_current_chapter(struct MPContext *mpctx)
3243 double current_pts = get_current_time(mpctx);
3244 if (!mpctx->chapters)
3245 return FFMAX(mpctx->last_chapter_seek,
3246 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3248 int i;
3249 for (i = 1; i < mpctx->num_chapters; i++)
3250 if (current_pts < mpctx->chapters[i].start)
3251 break;
3252 return FFMAX(mpctx->last_chapter_seek, i - 1);
3255 // currently returns a string allocated with malloc, not talloc
3256 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3258 if (!mpctx->chapters || !mpctx->sh_video)
3259 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3260 return strdup(mpctx->chapters[chapter].name);
3263 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3264 char **chapter_name)
3266 mpctx->last_chapter_seek = -1;
3267 if (!mpctx->chapters || !mpctx->sh_video) {
3268 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3269 chapter_name);
3270 if (res >= 0) {
3271 if (*seek_pts == -1)
3272 seek_reset(mpctx);
3273 else {
3274 mpctx->last_chapter_seek = res;
3275 mpctx->last_chapter_pts = *seek_pts;
3278 return res;
3281 if (chapter >= mpctx->num_chapters)
3282 return -1;
3283 if (chapter < 0)
3284 chapter = 0;
3285 *seek_pts = mpctx->chapters[chapter].start;
3286 mpctx->last_chapter_seek = chapter;
3287 mpctx->last_chapter_pts = *seek_pts;
3288 if (chapter_name)
3289 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3290 return chapter;
3294 static void run_playloop(struct MPContext *mpctx)
3296 struct MPOpts *opts = &mpctx->opts;
3297 float aq_sleep_time = 0;
3299 if (opts->chapterrange[1] > 0) {
3300 int cur_chapter = get_current_chapter(mpctx);
3301 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3302 mpctx->stop_play = PT_NEXT_ENTRY;
3305 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3306 mpctx->sh_audio = mpctx->d_audio->sh;
3307 mpctx->sh_audio->ds = mpctx->d_audio;
3308 reinit_audio_chain(mpctx);
3311 /*========================== PLAY AUDIO ============================*/
3313 if (mpctx->sh_audio && !mpctx->paused
3314 && (!mpctx->restart_playback || !mpctx->sh_video))
3315 if (!fill_audio_out_buffers(mpctx))
3316 // at eof, all audio at least written to ao
3317 if (!mpctx->sh_video)
3318 mpctx->stop_play = AT_END_OF_FILE;
3321 if (!mpctx->sh_video) {
3322 mpctx->restart_playback = false;
3323 if (mpctx->step_frames) {
3324 mpctx->step_frames = 0;
3325 pause_player(mpctx);
3327 // handle audio-only case:
3328 double a_pos = 0;
3329 // sh_audio can be NULL due to video stream switching
3330 // TODO: handle this better
3331 if (mpctx->sh_audio)
3332 a_pos = playing_audio_pts(mpctx);
3334 print_status(mpctx, a_pos, false);
3336 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3337 mpctx->stop_play = PT_NEXT_ENTRY;
3338 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3339 update_osd_msg(mpctx);
3340 } else {
3342 /*========================== PLAY VIDEO ============================*/
3344 vo_pts = mpctx->sh_video->timer * 90000.0;
3345 vo_fps = mpctx->sh_video->fps;
3347 bool blit_frame = mpctx->video_out->frame_loaded;
3348 if (!blit_frame || mpctx->hrseek_active) {
3349 double frame_time = update_video(mpctx);
3350 blit_frame = mpctx->video_out->frame_loaded;
3351 blit_frame &= !mpctx->hrseek_active;
3352 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3353 if (mpctx->sh_video->vf_initialized < 0) {
3354 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3355 "\nFATAL: Could not initialize video filters (-vf) "
3356 "or video output (-vo).\n");
3357 mpctx->stop_play = PT_NEXT_ENTRY;
3358 return;
3360 if (frame_time < 0)
3361 mpctx->stop_play = AT_END_OF_FILE;
3362 else if (!mpctx->restart_playback) {
3363 mpctx->time_frame += frame_time / opts->playback_speed;
3364 adjust_sync(mpctx, frame_time);
3367 if (mpctx->timeline) {
3368 struct timeline_part *next =
3369 mpctx->timeline + mpctx->timeline_part + 1;
3370 if (mpctx->sh_video->pts >= next->start
3371 || mpctx->stop_play == AT_END_OF_FILE
3372 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3373 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3374 .amount = next->start });
3375 return;
3379 // ==========================================================================
3381 current_module = "vo_check_events";
3382 vo_check_events(mpctx->video_out);
3384 #ifdef CONFIG_X11
3385 if (stop_xscreensaver) {
3386 current_module = "stop_xscreensaver";
3387 xscreensaver_heartbeat(mpctx->x11_state);
3389 #endif
3390 if (heartbeat_cmd) {
3391 static unsigned last_heartbeat;
3392 unsigned now = GetTimerMS();
3393 if (now - last_heartbeat > 30000) {
3394 last_heartbeat = now;
3395 system(heartbeat_cmd);
3399 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3400 &mpctx->time_frame,
3401 &aq_sleep_time);
3403 //====================== FLIP PAGE (VIDEO BLT): =========================
3405 current_module = "flip_page";
3406 if (!frame_time_remaining && blit_frame) {
3407 struct sh_video *sh_video = mpctx->sh_video;
3408 mpctx->video_pts = sh_video->pts;
3409 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3410 update_teletext(sh_video, mpctx->demuxer, 0);
3411 update_osd_msg(mpctx);
3412 struct vf_instance *vf = sh_video->vfilter;
3413 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3414 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3415 vo_osd_changed(0);
3417 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3418 aq_sleep_time += mpctx->time_frame;
3419 // flag 256 means: libvo driver does its timing (dvb card)
3420 if (mpctx->time_frame > 0.001
3421 && !(mpctx->sh_video->output_flags&256))
3422 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3423 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3425 unsigned int t2 = GetTimer();
3426 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
3427 int duration = -1;
3428 double pts2 = mpctx->video_out->next_pts2;
3429 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3430 && !mpctx->restart_playback) {
3431 // expected A/V sync correction is ignored
3432 double diff = (pts2 - mpctx->video_pts);
3433 diff /= opts->playback_speed;
3434 if (mpctx->time_frame < 0)
3435 diff += mpctx->time_frame;
3436 if (diff < 0)
3437 diff = 0;
3438 if (diff > 10)
3439 diff = 10;
3440 duration = diff * 1e6;
3442 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3444 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3445 vout_time_usage += mpctx->last_vo_flip_duration;
3446 if (mpctx->video_out->driver->flip_page_timed) {
3447 // No need to adjust sync based on flip speed
3448 mpctx->last_vo_flip_duration = 0;
3449 // For print_status - VO call finishing early is OK for sync
3450 mpctx->time_frame -= get_relative_time(mpctx);
3452 if (mpctx->restart_playback) {
3453 mpctx->syncing_audio = true;
3454 if (mpctx->sh_audio && !mpctx->paused)
3455 fill_audio_out_buffers(mpctx);
3456 mpctx->restart_playback = false;
3457 mpctx->time_frame = 0;
3458 get_relative_time(mpctx);
3460 print_status(mpctx, MP_NOPTS_VALUE, true);
3461 } else
3462 print_status(mpctx, MP_NOPTS_VALUE, false);
3464 //============================ Auto QUALITY ============================
3466 /*Output quality adjustments:*/
3467 if (opts->auto_quality > 0) {
3468 current_module = "autoq";
3469 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3470 ++output_quality;
3471 else
3472 if (output_quality>1 && aq_sleep_time<0)
3473 --output_quality;
3474 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3475 output_quality = 0;
3476 set_video_quality(mpctx->sh_video, output_quality);
3479 if (!frame_time_remaining && blit_frame) {
3480 if (play_n_frames >= 0) {
3481 --play_n_frames;
3482 if (play_n_frames <= 0)
3483 mpctx->stop_play = PT_NEXT_ENTRY;
3485 if (mpctx->step_frames > 0) {
3486 mpctx->step_frames--;
3487 if (mpctx->step_frames == 0)
3488 pause_player(mpctx);
3492 // FIXME: add size based support for -endpos
3493 if (end_at.type == END_AT_TIME &&
3494 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3495 mpctx->stop_play = PT_NEXT_ENTRY;
3497 } // end if(mpctx->sh_video)
3499 #ifdef CONFIG_DVDNAV
3500 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3501 nav_highlight_t hl;
3502 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3503 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3504 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3505 vo_osd_changed(OSDTYPE_DVDNAV);
3506 } else {
3507 osd_set_nav_box(0, 0, 0, 0);
3508 vo_osd_changed(OSDTYPE_DVDNAV);
3509 vo_osd_changed(OSDTYPE_SPU);
3512 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3513 double ar = -1.0;
3514 if (mpctx->sh_video &&
3515 stream_control(mpctx->demuxer->stream,
3516 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3517 != STREAM_UNSUPPORTED)
3518 mpctx->sh_video->stream_aspect = ar;
3521 #endif
3523 //================= Keyboard events, SEEKing ====================
3525 current_module = "key_events";
3527 while (1) {
3528 mp_cmd_t *cmd;
3529 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3530 /* Allow running consecutive seek commands to combine them,
3531 * but execute the seek before running other commands.
3532 * If the user seeks continuously (keeps arrow key down)
3533 * try to finish showing a frame from one location before doing
3534 * another seek (which could lead to unchanging display). */
3535 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3536 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3537 && GetTimerMS() - mpctx->start_timestamp < 300)
3538 break;
3539 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3540 run_command(mpctx, cmd);
3541 mp_cmd_free(cmd);
3542 if (mpctx->stop_play)
3543 break;
3545 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3546 || mpctx->restart_playback)
3547 break;
3548 if (mpctx->sh_video) {
3549 update_osd_msg(mpctx);
3550 int hack = vo_osd_changed(0);
3551 vo_osd_changed(hack);
3552 if (hack) {
3553 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3554 add_step_frame(mpctx);
3555 break;
3556 } else
3557 vo_osd_changed(0);
3560 pause_loop(mpctx);
3563 // handle -sstep
3564 if (step_sec > 0 && !mpctx->paused) {
3565 mpctx->osd_function = OSD_FFW;
3566 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3569 edl_update(mpctx);
3571 /* Looping. */
3572 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3573 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3575 if (opts->loop_times>1)
3576 opts->loop_times--;
3577 else if (opts->loop_times==1)
3578 opts->loop_times = -1;
3579 play_n_frames = play_n_frames_mf;
3580 mpctx->stop_play = 0;
3581 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3584 if (mpctx->seek.type) {
3585 seek(mpctx, mpctx->seek);
3586 mpctx->seek = (struct seek_params){0};
3591 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3592 struct content_source *sources,
3593 int num_sources,
3594 unsigned char uid_map[][16])
3596 int num_filenames = 0;
3597 char **filenames = NULL;
3598 if (num_sources > 1) {
3599 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3600 "other sources.\n");
3601 if (mpctx->stream->type != STREAMTYPE_FILE) {
3602 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3603 "normal disk file. Will not search for related files.\n");
3604 } else {
3605 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3606 "same directory to find referenced sources.\n");
3607 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3608 &num_filenames);
3612 int num_left = num_sources - 1;
3613 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3614 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3615 filename_recode(filenames[i]));
3616 int format;
3617 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3618 if (!s)
3619 continue;
3620 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3621 mpctx->opts.audio_id,
3622 mpctx->opts.video_id,
3623 mpctx->opts.sub_id, filenames[i]);
3624 if (!d) {
3625 free_stream(s);
3626 continue;
3628 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3629 for (int i = 1; i < num_sources; i++) {
3630 if (sources[i].demuxer)
3631 continue;
3632 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3633 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3634 i, filename_recode(d->filename));
3635 sources[i].stream = s;
3636 sources[i].demuxer = d;
3637 num_left--;
3638 goto match;
3642 free_demuxer(d);
3643 free_stream(s);
3644 continue;
3645 match:
3648 talloc_free(filenames);
3649 if (num_left) {
3650 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3651 "There will be parts MISSING from the video!\n");
3652 for (int i = 1, j = 1; i < num_sources; i++)
3653 if (sources[i].demuxer) {
3654 sources[j] = sources[i];
3655 memcpy(uid_map[j], uid_map[i], 16);
3656 j++;
3659 return num_sources - num_left;
3662 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3664 struct MPOpts *opts = &mpctx->opts;
3666 if (!opts->ordered_chapters) {
3667 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3668 "you have disabled support for them. Ignoring.\n");
3669 return;
3672 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3673 "edit timeline.\n");
3675 struct demuxer *demuxer = mpctx->demuxer;
3676 struct matroska_data *m = &demuxer->matroska_data;
3678 // +1 because sources/uid_map[0] is original file even if all chapters
3679 // actually use other sources and need separate entries
3680 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3681 m->num_ordered_chapters+1);
3682 sources[0].stream = mpctx->stream;
3683 sources[0].demuxer = mpctx->demuxer;
3684 unsigned char uid_map[m->num_ordered_chapters+1][16];
3685 int num_sources = 1;
3686 memcpy(uid_map[0], m->segment_uid, 16);
3688 for (int i = 0; i < m->num_ordered_chapters; i++) {
3689 struct matroska_chapter *c = m->ordered_chapters + i;
3690 if (!c->has_segment_uid)
3691 memcpy(c->segment_uid, m->segment_uid, 16);
3693 for (int j = 0; j < num_sources; j++)
3694 if (!memcmp(c->segment_uid, uid_map[j], 16))
3695 goto found1;
3696 memcpy(uid_map[num_sources], c->segment_uid, 16);
3697 sources[num_sources] = (struct content_source){};
3698 num_sources++;
3699 found1:
3703 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3704 uid_map);
3707 // +1 for terminating chapter with start time marking end of last real one
3708 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3709 m->num_ordered_chapters + 1);
3710 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3711 m->num_ordered_chapters);
3712 uint64_t starttime = 0;
3713 uint64_t missing_time = 0;
3714 int part_count = 0;
3715 int num_chapters = 0;
3716 uint64_t prev_part_offset = 0;
3717 for (int i = 0; i < m->num_ordered_chapters; i++) {
3718 struct matroska_chapter *c = m->ordered_chapters + i;
3720 int j;
3721 for (j = 0; j < num_sources; j++) {
3722 if (!memcmp(c->segment_uid, uid_map[j], 16))
3723 goto found2;
3725 missing_time += c->end - c->start;
3726 continue;
3727 found2:;
3728 /* Only add a separate part if the time or file actually changes.
3729 * Matroska files have chapter divisions that are redundant from
3730 * timeline point of view because the same chapter structure is used
3731 * both to specify the timeline and for normal chapter information.
3732 * Removing a missing inserted external chapter can also cause this.
3733 * We allow for a configurable fudge factor because of files which
3734 * specify chapter end times that are one frame too early;
3735 * we don't want to try seeking over a one frame gap. */
3736 int64_t join_diff = c->start - starttime - prev_part_offset;
3737 if (part_count == 0 || FFABS(join_diff) > opts->chapter_merge_threshold
3738 || sources + j != timeline[part_count - 1].source) {
3739 timeline[part_count].source = sources + j;
3740 timeline[part_count].start = starttime / 1000.;
3741 timeline[part_count].source_start = c->start / 1000.;
3742 prev_part_offset = c->start - starttime;
3743 part_count++;
3744 } else if (part_count > 0 && join_diff) {
3745 /* Chapter was merged at an inexact boundary;
3746 * adjust timestamps to match. */
3747 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3748 "offset %d ms.\n", i, (int) join_diff);
3749 starttime += join_diff;
3751 chapters[num_chapters].start = starttime / 1000.;
3752 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3753 starttime += c->end - c->start;
3754 num_chapters++;
3756 timeline[part_count].start = starttime / 1000.;
3758 if (!part_count) {
3759 // None of the parts come from the file itself???
3760 talloc_free(sources);
3761 talloc_free(timeline);
3762 talloc_free(chapters);
3763 return;
3766 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3767 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3768 timeline[part_count].start);
3769 if (missing_time)
3770 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3771 "from the timeline!\n", missing_time / 1000.);
3772 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3773 for (int i = 0; i < num_sources; i++)
3774 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3775 filename_recode(sources[i].demuxer->filename));
3776 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3777 "source_start, source):\n");
3778 for (int i = 0; i < part_count; i++) {
3779 struct timeline_part *p = timeline + i;
3780 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3781 p->source_start, p->source - sources);
3783 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3784 mpctx->sources = sources;
3785 mpctx->num_sources = num_sources;
3786 mpctx->timeline = timeline;
3787 mpctx->num_timeline_parts = part_count;
3788 mpctx->num_chapters = num_chapters;
3789 mpctx->chapters = chapters;
3791 mpctx->timeline_part = 0;
3792 mpctx->demuxer = timeline[0].source->demuxer;
3796 static int read_keys(void *ctx, int fd)
3798 getch2(ctx);
3799 return mplayer_get_key(ctx, 0);
3802 static bool attachment_is_font(struct demux_attachment *att)
3804 if (!att->name || !att->type || !att->data || !att->data_size)
3805 return false;
3806 // match against MIME types
3807 if (strcmp(att->type, "application/x-truetype-font") == 0
3808 || strcmp(att->type, "application/x-font") == 0)
3809 return true;
3810 // fallback: match against file extension
3811 if (strlen(att->name) > 4) {
3812 char *ext = att->name + strlen(att->name) - 4;
3813 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3814 || strcasecmp(ext, ".otf") == 0)
3815 return true;
3817 return false;
3820 static int select_audio(demuxer_t *demuxer, int audio_id, char *audio_lang)
3822 if (audio_id == -1)
3823 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3824 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3825 demuxer_switch_audio(demuxer, audio_id);
3826 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3827 demuxer->audio->id = -2;
3828 demuxer->audio->sh = NULL;
3830 return demuxer->audio->id;
3833 static void print_version(const char* name)
3835 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3837 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3838 GetCpuCaps(&gCpuCaps);
3839 #if ARCH_X86
3840 mp_msg(MSGT_CPLAYER, MSGL_V,
3841 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3842 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3843 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3844 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3845 #if CONFIG_RUNTIME_CPUDETECT
3846 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3847 #else
3848 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3849 if (HAVE_MMX)
3850 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3851 if (HAVE_MMX2)
3852 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3853 if (HAVE_AMD3DNOW)
3854 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3855 if (HAVE_AMD3DNOWEXT)
3856 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3857 if (HAVE_SSE)
3858 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3859 if (HAVE_SSE2)
3860 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3861 if (HAVE_SSSE3)
3862 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3863 if (HAVE_CMOV)
3864 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3865 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3866 #endif /* CONFIG_RUNTIME_CPUDETECT */
3867 #endif /* ARCH_X86 */
3870 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3871 * file for some tools to link against. */
3872 #ifndef DISABLE_MAIN
3873 int main(int argc,char* argv[]){
3874 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3875 talloc_enable_leak_report();
3877 char * mem_ptr;
3879 // movie info:
3881 /* Flag indicating whether MPlayer should exit without playing anything. */
3882 int opt_exit = 0;
3883 int i;
3885 struct MPContext *mpctx = &(struct MPContext){
3886 .osd_function = OSD_PLAY,
3887 .begin_skip = MP_NOPTS_VALUE,
3888 .play_tree_step = 1,
3889 .global_sub_pos = -1,
3890 .set_of_sub_pos = -1,
3891 .file_format = DEMUXER_TYPE_UNKNOWN,
3892 .last_dvb_step = 1,
3895 InitTimer();
3896 srand(GetTimerMS());
3898 mp_msg_init();
3899 set_av_log_callback();
3901 #ifdef CONFIG_X11
3902 mpctx->x11_state = vo_x11_init_state();
3903 #endif
3904 struct MPOpts *opts = &mpctx->opts;
3905 set_default_mplayer_options(opts);
3906 // Create the config context and register the options
3907 mpctx->mconfig = m_config_new(opts, cfg_include);
3908 m_config_register_options(mpctx->mconfig,mplayer_opts);
3909 m_config_register_options(mpctx->mconfig, common_opts);
3910 mp_input_register_options(mpctx->mconfig);
3912 // Preparse the command line
3913 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3915 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3916 set_path_env();
3917 #endif
3919 #ifdef CONFIG_TV
3920 stream_tv_defaults.immediate = 1;
3921 #endif
3923 parse_cfgfiles(mpctx, mpctx->mconfig);
3925 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3926 if(mpctx->playtree == NULL)
3927 opt_exit = 1;
3928 else {
3929 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3930 if(mpctx->playtree) {
3931 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3932 if(mpctx->playtree_iter) {
3933 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3934 play_tree_iter_free(mpctx->playtree_iter);
3935 mpctx->playtree_iter = NULL;
3937 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3941 mpctx->key_fifo = mp_fifo_create(opts);
3943 print_version("MPlayer");
3945 #if defined(__MINGW32__) || defined(__CYGWIN__)
3947 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3948 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3949 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3950 if (kernel32) {
3951 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3952 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3954 if (setDEP) setDEP(3);
3955 if (setDllDir) setDllDir("");
3957 // stop Windows from showing all kinds of annoying error dialogs
3958 SetErrorMode(0x8003);
3959 // request 1ms timer resolution
3960 timeBeginPeriod(1);
3961 #endif
3963 #ifdef CONFIG_PRIORITY
3964 set_priority();
3965 #endif
3967 if (codec_path)
3968 set_codec_path(codec_path);
3970 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3971 list_video_out();
3972 opt_exit = 1;
3975 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3976 list_audio_out();
3977 opt_exit = 1;
3980 /* Check codecs.conf. */
3981 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3982 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3983 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3984 if(!parse_codec_cfg(NULL)){
3985 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3987 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3990 free( mem_ptr ); // release the buffer created by get_path()
3993 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3994 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3995 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3996 list_codecs(1);
3997 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3998 opt_exit = 1;
4000 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
4001 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4002 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4003 list_codecs(0);
4004 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4005 opt_exit = 1;
4007 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
4008 vfm_help();
4009 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4010 opt_exit = 1;
4012 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
4013 afm_help();
4014 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4015 opt_exit = 1;
4017 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
4018 af_help();
4019 printf("\n");
4020 opt_exit = 1;
4022 #ifdef CONFIG_X11
4023 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
4024 fstype_help();
4025 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4026 opt_exit = 1;
4028 #endif
4029 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
4030 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
4031 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
4032 demuxer_help();
4033 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4034 opt_exit = 1;
4036 if (opts->list_properties) {
4037 property_print_help();
4038 opt_exit = 1;
4041 if(opt_exit)
4042 exit_player(mpctx, EXIT_NONE);
4044 if (!mpctx->filename && !opts->player_idle_mode) {
4045 // no file/vcd/dvd -> show HELP:
4046 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4047 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4050 /* Display what configure line was used */
4051 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4053 // Many users forget to include command line in bugreports...
4054 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
4055 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4056 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
4057 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4060 //------ load global data first ------
4062 mpctx->osd = osd_create();
4064 // check font
4065 #ifdef CONFIG_FREETYPE
4066 init_freetype();
4067 #endif
4068 #ifdef CONFIG_FONTCONFIG
4069 if(font_fontconfig <= 0)
4071 #endif
4072 #ifdef CONFIG_BITMAP_FONT
4073 if(font_name){
4074 vo_font=read_font_desc(font_name,font_factor,verbose>1);
4075 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
4076 filename_recode(font_name));
4077 } else {
4078 // try default:
4079 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
4080 free(mem_ptr); // release the buffer created by get_path()
4081 if(!vo_font)
4082 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
4084 if (sub_font_name)
4085 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
4086 else
4087 mpctx->osd->sub_font = vo_font;
4088 #endif
4089 #ifdef CONFIG_FONTCONFIG
4091 #endif
4093 #ifdef CONFIG_ASS
4094 ass_library = mp_ass_init();
4095 #endif
4097 #ifdef HAVE_RTC
4098 if(opts->rtc)
4100 char *rtc_device = opts->rtc_device;
4101 // seteuid(0); /* Can't hurt to try to get root here */
4102 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4103 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4104 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4105 else {
4106 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4108 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4109 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4110 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4111 close (rtc_fd);
4112 rtc_fd = -1;
4113 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4114 /* variable only by the root */
4115 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4116 close (rtc_fd);
4117 rtc_fd = -1;
4118 } else
4119 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4122 if(rtc_fd<0)
4123 #endif /* HAVE_RTC */
4124 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4125 opts->softsleep ? "software" : timer_name);
4127 #ifdef HAVE_TERMCAP
4128 load_termcap(NULL); // load key-codes
4129 #endif
4131 // ========== Init keyboard FIFO (connection to libvo) ============
4133 // Init input system
4134 current_module = "init_input";
4135 mpctx->input = mp_input_init(&opts->input);
4136 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4137 if(slave_mode)
4138 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4139 else if (opts->consolecontrols)
4140 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4141 // Set the libstream interrupt callback
4142 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4144 #ifdef CONFIG_MENU
4145 if(use_menu) {
4146 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4147 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4148 else {
4149 menu_cfg = get_path("menu.conf");
4150 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4151 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4152 else {
4153 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4154 MPLAYER_CONFDIR "/menu.conf"))
4155 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4156 else {
4157 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4158 use_menu = 0;
4163 #endif
4165 current_module = NULL;
4167 /// Catch signals
4168 #ifndef __MINGW32__
4169 signal(SIGCHLD,child_sighandler);
4170 #endif
4172 #ifdef CONFIG_CRASH_DEBUG
4173 prog_path = argv[0];
4174 #endif
4175 //========= Catch terminate signals: ================
4176 // terminate requests:
4177 signal(SIGTERM,exit_sighandler); // kill
4178 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4180 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4182 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4183 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4184 #ifdef CONFIG_SIGHANDLER
4185 // fatal errors:
4186 signal(SIGBUS,exit_sighandler); // bus error
4187 signal(SIGSEGV,exit_sighandler); // segfault
4188 signal(SIGILL,exit_sighandler); // illegal instruction
4189 signal(SIGFPE,exit_sighandler); // floating point exc.
4190 signal(SIGABRT,exit_sighandler); // abort()
4191 #ifdef CONFIG_CRASH_DEBUG
4192 if (crash_debug)
4193 signal(SIGTRAP,exit_sighandler);
4194 #endif
4195 #endif
4197 // ******************* Now, let's see the per-file stuff ********************
4199 play_next_file:
4201 // init global sub numbers
4202 mpctx->global_sub_size = 0;
4203 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4205 if (mpctx->filename) {
4206 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4207 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4208 load_per_file_config (mpctx->mconfig, mpctx->filename);
4211 if (opts->video_driver_list)
4212 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4213 if (opts->audio_driver_list)
4214 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4216 // We must enable getch2 here to be able to interrupt network connection
4217 // or cache filling
4218 if (opts->consolecontrols && !slave_mode) {
4219 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4220 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4221 else
4222 getch2_enable(); // prepare stdin for hotkeys...
4223 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4224 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4227 // =================== GUI idle loop (STOP state) ===========================
4228 while (opts->player_idle_mode && !mpctx->filename) {
4229 play_tree_t * entry = NULL;
4230 mp_cmd_t * cmd;
4231 if (mpctx->video_out && mpctx->video_out->config_ok)
4232 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4233 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4234 if (mpctx->video_out)
4235 vo_check_events(mpctx->video_out);
4236 usec_sleep(20000);
4238 switch (cmd->id) {
4239 case MP_CMD_LOADFILE:
4240 // prepare a tree entry with the new filename
4241 entry = play_tree_new();
4242 play_tree_add_file(entry, cmd->args[0].v.s);
4243 // The entry is added to the main playtree after the switch().
4244 break;
4245 case MP_CMD_LOADLIST:
4246 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4247 break;
4248 case MP_CMD_QUIT:
4249 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4250 break;
4251 case MP_CMD_VO_FULLSCREEN:
4252 case MP_CMD_GET_PROPERTY:
4253 case MP_CMD_SET_PROPERTY:
4254 case MP_CMD_STEP_PROPERTY:
4255 run_command(mpctx, cmd);
4256 break;
4259 mp_cmd_free(cmd);
4261 if (entry) { // user entered a command that gave a valid entry
4262 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4263 play_tree_free_list(mpctx->playtree->child, 1);
4264 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4266 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4268 play_tree_set_child(mpctx->playtree, entry);
4270 /* Make iterator start at the top the of tree. */
4271 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4272 if (!mpctx->playtree_iter) continue;
4274 // find the first real item in the tree
4275 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4276 // no items!
4277 play_tree_iter_free(mpctx->playtree_iter);
4278 mpctx->playtree_iter = NULL;
4279 continue; // wait for next command
4281 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4284 //---------------------------------------------------------------------------
4286 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4287 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4289 if (mpctx->filename) {
4290 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4291 filename_recode(mpctx->filename));
4292 if(use_filename_title && opts->vo_wintitle == NULL)
4293 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4296 if (edl_filename) {
4297 if (edl_records) free_edl(edl_records);
4298 next_edl_record = edl_records = edl_parse_file();
4300 if (edl_output_filename) {
4301 if (edl_fd) fclose(edl_fd);
4302 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4304 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4305 filename_recode(edl_output_filename));
4309 //==================== Open VOB-Sub ============================
4311 current_module="vobsub";
4312 if (vobsub_name){
4313 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
4314 if(vo_vobsub==NULL)
4315 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4316 filename_recode(vobsub_name));
4317 } else if (sub_auto && mpctx->filename){
4318 /* try to autodetect vobsub from movie filename ::atmos */
4319 char *buf = strdup(mpctx->filename), *psub;
4320 char *pdot = strrchr(buf, '.');
4321 char *pslash = strrchr(buf, '/');
4322 #if defined(__MINGW32__) || defined(__CYGWIN__)
4323 if (!pslash) pslash = strrchr(buf, '\\');
4324 #endif
4325 if (pdot && (!pslash || pdot > pslash))
4326 *pdot = '\0';
4327 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4328 /* try from ~/.mplayer/sub */
4329 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4330 const char *bname = mp_basename(buf);
4331 int l;
4332 l = strlen(psub) + strlen(bname) + 1;
4333 psub = realloc(psub,l);
4334 strcat(psub,bname);
4335 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4336 free(psub);
4338 free(buf);
4340 if(vo_vobsub){
4341 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4342 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4343 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4345 // setup global sub numbering
4346 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4349 //============ Open & Sync STREAM --- fork cache2 ====================
4351 mpctx->stream=NULL;
4352 mpctx->demuxer=NULL;
4353 if (mpctx->d_audio) {
4354 //free_demuxer_stream(mpctx->d_audio);
4355 mpctx->d_audio=NULL;
4357 if (mpctx->d_video) {
4358 //free_demuxer_stream(d_video);
4359 mpctx->d_video=NULL;
4361 mpctx->sh_audio=NULL;
4362 mpctx->sh_video=NULL;
4364 current_module="open_stream";
4365 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4366 if(!mpctx->stream) { // error...
4367 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4368 goto goto_next_file;
4370 mpctx->initialized_flags|=INITIALIZED_STREAM;
4372 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4373 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4374 "playlist support will not be used automatically.\n"
4375 "MPlayer's playlist code is unsafe and should only be used with "
4376 "trusted sources.\nPlayback will probably fail.\n\n");
4377 #if 0
4378 play_tree_t* entry;
4379 // Handle playlist
4380 current_module="handle_playlist";
4381 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4382 filename_recode(mpctx->filename));
4383 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4384 mpctx->eof=playtree_add_playlist(mpctx, entry);
4385 goto goto_next_file;
4386 #endif
4388 mpctx->stream->start_pos+=seek_to_byte;
4390 if(stream_dump_type==5){
4391 unsigned char buf[4096];
4392 int len;
4393 FILE *f;
4394 current_module="dumpstream";
4395 stream_reset(mpctx->stream);
4396 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4397 f=fopen(opts->stream_dump_name,"wb");
4398 if(!f){
4399 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4400 exit_player(mpctx, EXIT_ERROR);
4402 if (opts->chapterrange[0] > 1) {
4403 int chapter = opts->chapterrange[0] - 1;
4404 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4406 while(!mpctx->stream->eof && !async_quit_request){
4407 len=stream_read(mpctx->stream,buf,4096);
4408 if(len>0) {
4409 if(fwrite(buf,len,1,f) != 1) {
4410 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4411 exit_player(mpctx, EXIT_ERROR);
4414 if (opts->chapterrange[1] > 0) {
4415 int chapter = -1;
4416 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4417 &chapter) == STREAM_OK
4418 && chapter + 1 > opts->chapterrange[1])
4419 break;
4422 if(fclose(f)) {
4423 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4424 exit_player(mpctx, EXIT_ERROR);
4426 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4427 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4430 #ifdef CONFIG_DVDREAD
4431 if(mpctx->stream->type==STREAMTYPE_DVD){
4432 current_module="dvd lang->id";
4433 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4434 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4435 // setup global sub numbering
4436 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4437 current_module=NULL;
4439 #endif
4441 #ifdef CONFIG_DVDNAV
4442 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4443 current_module="dvdnav lang->id";
4444 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4445 dvdsub_lang_id = -3;
4446 if(opts->sub_lang && opts->sub_id==-1)
4447 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4448 // setup global sub numbering
4449 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4450 current_module=NULL;
4452 #endif
4454 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4455 goto_enable_cache:
4456 if(stream_cache_size>0){
4457 int res;
4458 float stream_cache_min_percent = opts->stream_cache_min_percent;
4459 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4460 current_module="enable_cache";
4461 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4462 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4463 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4464 if(res == 0)
4465 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4468 //============ Open DEMUXERS --- DETECT file type =======================
4469 current_module="demux_open";
4471 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4473 // HACK to get MOV Reference Files working
4475 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4477 unsigned char* playlist_entry;
4478 play_tree_t *list = NULL, *entry = NULL;
4480 current_module="handle_demux_playlist";
4481 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4483 char *temp;
4484 const char *bname;
4486 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4487 filename_recode(playlist_entry));
4489 bname=mp_basename(playlist_entry);
4490 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4491 continue;
4493 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4494 continue;
4496 entry = play_tree_new();
4498 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4500 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4501 if (temp)
4503 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4504 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4505 strcat(temp, playlist_entry);
4506 if (!strcmp(temp, mpctx->filename)) {
4507 free(temp);
4508 continue;
4510 play_tree_add_file(entry,temp);
4511 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4512 free(temp);
4515 else
4516 play_tree_add_file(entry,playlist_entry);
4518 if(!list)
4519 list = entry;
4520 else
4521 play_tree_append_entry(list,entry);
4523 free_demuxer(mpctx->demuxer);
4524 mpctx->demuxer = NULL;
4526 if (list)
4528 entry = play_tree_new();
4529 play_tree_set_child(entry,list);
4530 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4531 goto goto_next_file;
4535 if(!mpctx->demuxer) {
4536 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4537 goto goto_next_file;
4540 if (mpctx->demuxer->matroska_data.ordered_chapters)
4541 build_ordered_chapter_timeline(mpctx);
4543 if (!mpctx->sources) {
4544 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4545 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4546 .demuxer = mpctx->demuxer};
4547 mpctx->num_sources = 1;
4550 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4552 #ifdef CONFIG_ASS
4553 if (opts->ass_enabled && ass_library) {
4554 for (int j = 0; j < mpctx->num_sources; j++) {
4555 struct demuxer *d = mpctx->sources[j].demuxer;
4556 for (int i = 0; i < d->num_attachments; i++) {
4557 struct demux_attachment *att = d->attachments + i;
4558 if (use_embedded_fonts && attachment_is_font(att))
4559 ass_add_font(ass_library, att->name, att->data, att->data_size);
4563 #endif
4565 current_module="demux_open2";
4567 mpctx->d_audio=mpctx->demuxer->audio;
4568 mpctx->d_video=mpctx->demuxer->video;
4569 mpctx->d_sub=mpctx->demuxer->sub;
4571 if (ts_prog) {
4572 int tmp = ts_prog;
4573 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4575 // select audio stream
4576 if (mpctx->num_sources)
4577 for (int i = 0; i < mpctx->num_sources; i++)
4578 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
4579 opts->audio_lang);
4580 else
4581 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
4583 // DUMP STREAMS:
4584 if((stream_dump_type)&&(stream_dump_type<4)){
4585 FILE *f;
4586 demux_stream_t *ds=NULL;
4587 current_module="dump";
4588 // select stream to dump
4589 switch(stream_dump_type){
4590 case 1: ds=mpctx->d_audio;break;
4591 case 2: ds=mpctx->d_video;break;
4592 case 3: ds=mpctx->d_sub;break;
4594 if(!ds){
4595 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4596 exit_player(mpctx, EXIT_ERROR);
4598 // disable other streams:
4599 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4600 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4601 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4602 // let's dump it!
4603 f=fopen(opts->stream_dump_name,"wb");
4604 if(!f){
4605 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4606 exit_player(mpctx, EXIT_ERROR);
4608 while(!ds->eof){
4609 unsigned char* start;
4610 int in_size=ds_get_packet(ds,&start);
4611 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4612 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4613 if(in_size>0) fwrite(start,in_size,1,f);
4614 if (opts->chapterrange[1] > 0) {
4615 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4616 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4617 break;
4620 fclose(f);
4621 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4622 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4625 mpctx->sh_audio=mpctx->d_audio->sh;
4626 mpctx->sh_video=mpctx->d_video->sh;
4628 if(mpctx->sh_video){
4630 current_module="video_read_properties";
4631 if(!video_read_properties(mpctx->sh_video)) {
4632 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4633 mpctx->sh_video=mpctx->d_video->sh=NULL;
4634 } else {
4635 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4636 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4637 mpctx->sh_video->fps,mpctx->sh_video->frametime
4640 /* need to set fps here for output encoders to pick it up in their init */
4641 if(force_fps){
4642 mpctx->sh_video->fps=force_fps;
4643 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4645 vo_fps = mpctx->sh_video->fps;
4647 if(!mpctx->sh_video->fps && !force_fps){
4648 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4649 mpctx->opts.correct_pts = 1;
4655 if(!mpctx->sh_video && !mpctx->sh_audio){
4656 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4657 #ifdef CONFIG_DVBIN
4658 if(mpctx->stream->type == STREAMTYPE_DVB)
4660 int dir;
4661 int v = mpctx->last_dvb_step;
4662 if(v > 0)
4663 dir = DVB_CHANNEL_HIGHER;
4664 else
4665 dir = DVB_CHANNEL_LOWER;
4667 if(dvb_step_channel(mpctx->stream, dir)) {
4668 mpctx->stop_play = PT_NEXT_ENTRY;
4669 mpctx->dvbin_reopen = 1;
4672 #endif
4673 goto goto_next_file; // exit_player(_("Fatal error"));
4676 /* display clip info */
4677 demux_info_print(mpctx->demuxer);
4679 //================== Read SUBTITLES (DVD & TEXT) ==========================
4680 if(vo_spudec==NULL &&
4681 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4682 init_vo_spudec(mpctx);
4685 // after reading video params we should load subtitles because
4686 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4687 // check .sub
4688 current_module="read_subtitles_file";
4689 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4690 if(sub_name){
4691 for (i = 0; sub_name[i] != NULL; ++i)
4692 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4694 if(sub_auto) { // auto load sub file ...
4695 char *psub = get_path( "sub/" );
4696 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4697 int i = 0;
4698 free(psub); // release the buffer created by get_path() above
4699 while (tmp[i]) {
4700 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4701 free(tmp[i++]);
4703 free(tmp);
4705 if (mpctx->set_of_sub_size > 0)
4706 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4708 if (select_subtitle(mpctx)) {
4709 if(mpctx->subdata)
4710 switch (stream_dump_type) {
4711 case 3: list_sub_file(mpctx->subdata); break;
4712 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4713 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4714 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4715 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4716 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4720 print_file_properties(mpctx, mpctx->filename);
4722 if(!mpctx->sh_video) goto main; // audio-only
4724 if(!reinit_video_chain(mpctx)) {
4725 if(!mpctx->sh_video){
4726 if(!mpctx->sh_audio) goto goto_next_file;
4727 goto main; // exit_player(_("Fatal error"));
4731 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4732 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4734 #ifdef CONFIG_FREETYPE
4735 force_load_font = 1;
4736 #endif
4738 //================== MAIN: ==========================
4739 main:
4740 current_module="main";
4742 if (opts->playing_msg) {
4743 char* msg = property_expand_string(mpctx, opts->playing_msg);
4744 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4745 free(msg);
4749 // Disable the term OSD in verbose mode
4750 if (verbose)
4751 opts->term_osd = 0;
4755 // Make sure old OSD does not stay around,
4756 // e.g. with -fixed-vo and same-resolution files
4757 clear_osd_msgs();
4758 update_osd_msg(mpctx);
4760 //================ SETUP AUDIO ==========================
4762 if(mpctx->sh_audio){
4763 reinit_audio_chain(mpctx);
4764 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4765 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4768 current_module="av_init";
4770 if(mpctx->sh_video){
4771 mpctx->sh_video->timer=0;
4772 if (! ignore_start)
4773 audio_delay += mpctx->sh_video->stream_delay;
4775 if(mpctx->sh_audio){
4776 if (start_volume >= 0)
4777 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4778 if (! ignore_start)
4779 audio_delay -= mpctx->sh_audio->stream_delay;
4780 mpctx->delay=-audio_delay;
4783 if(!mpctx->sh_audio){
4784 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4785 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4786 ds_free_packs(mpctx->d_audio); // free buffered chunks
4787 //mpctx->d_audio->id=-2; // do not read audio chunks
4788 //uninit_player(mpctx, INITIALIZED_AO); // close device
4790 if(!mpctx->sh_video){
4791 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4792 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4793 ds_free_packs(mpctx->d_video);
4794 mpctx->d_video->id=-2;
4795 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4798 if (!mpctx->sh_video && !mpctx->sh_audio)
4799 goto goto_next_file;
4801 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4802 if(force_fps && mpctx->sh_video){
4803 vo_fps = mpctx->sh_video->fps=force_fps;
4804 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4805 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4808 mp_input_set_section(mpctx->input, NULL);
4809 //TODO: add desired (stream-based) sections here
4810 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4811 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4813 //==================== START PLAYING =======================
4815 if(opts->loop_times>1) opts->loop_times--; else
4816 if(opts->loop_times==1) opts->loop_times = -1;
4818 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4820 total_time_usage_start=GetTimer();
4821 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4822 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4823 play_n_frames=play_n_frames_mf;
4825 if(play_n_frames==0){
4826 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4829 mpctx->time_frame = 0;
4830 mpctx->drop_message_shown = 0;
4831 mpctx->restart_playback = true;
4832 mpctx->video_pts = 0;
4833 mpctx->hrseek_active = false;
4834 mpctx->hrseek_framedrop = false;
4835 mpctx->step_frames = 0;
4836 mpctx->total_avsync_change = 0;
4837 mpctx->last_chapter_seek = -1;
4839 // If there's a timeline force an absolute seek to initialize state
4840 if (seek_to_sec || mpctx->timeline) {
4841 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4842 seek(mpctx, mpctx->seek);
4843 end_at.pos += seek_to_sec;
4845 if (opts->chapterrange[0] > 0) {
4846 double pts;
4847 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4848 && pts > -1.0) {
4849 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4850 seek(mpctx, mpctx->seek);
4854 if (end_at.type == END_AT_SIZE) {
4855 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4856 end_at.type = END_AT_NONE;
4859 #ifdef CONFIG_DVDNAV
4860 mp_dvdnav_context_free(mpctx);
4861 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4862 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4863 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4865 #endif
4867 mpctx->seek = (struct seek_params){0};
4868 get_relative_time(mpctx); // reset current delta
4869 // Make sure VO knows current pause state
4870 if (mpctx->sh_video)
4871 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4872 NULL);
4874 while (!mpctx->stop_play)
4875 run_playloop(mpctx);
4877 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4879 #ifdef CONFIG_DVBIN
4880 if(mpctx->dvbin_reopen)
4882 mpctx->stop_play = 0;
4883 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4884 cache_uninit(mpctx->stream);
4885 mpctx->dvbin_reopen = 0;
4886 goto goto_enable_cache;
4888 #endif
4891 goto_next_file: // don't jump here after ao/vo/getch initialization!
4893 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4895 if (opts->benchmark) {
4896 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4897 double total_time_usage;
4898 total_time_usage_start=GetTimer()-total_time_usage_start;
4899 total_time_usage = (float)total_time_usage_start*0.000001;
4900 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4901 video_time_usage,vout_time_usage,audio_time_usage,
4902 total_time_usage-tot,total_time_usage);
4903 if(total_time_usage>0.0)
4904 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4905 100.0*video_time_usage/total_time_usage,
4906 100.0*vout_time_usage/total_time_usage,
4907 100.0*audio_time_usage/total_time_usage,
4908 100.0*(total_time_usage-tot)/total_time_usage,
4909 100.0);
4910 if(total_frame_cnt && frame_dropping)
4911 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4912 total_frame_cnt-drop_frame_cnt,
4913 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4914 drop_frame_cnt,
4915 100*drop_frame_cnt/total_frame_cnt,
4916 total_frame_cnt,
4917 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4920 // time to uninit all, except global stuff:
4921 int uninitialize_parts = INITIALIZED_ALL;
4922 if (opts->fixed_vo)
4923 uninitialize_parts -= INITIALIZED_VO;
4924 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4925 uninitialize_parts -= INITIALIZED_AO;
4926 uninit_player(mpctx, uninitialize_parts);
4928 if(mpctx->set_of_sub_size > 0) {
4929 current_module="sub_free";
4930 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4931 sub_free(mpctx->set_of_subtitles[i]);
4932 #ifdef CONFIG_ASS
4933 if(mpctx->set_of_ass_tracks[i])
4934 ass_free_track( mpctx->set_of_ass_tracks[i] );
4935 #endif
4937 mpctx->set_of_sub_size = 0;
4939 mpctx->vo_sub_last = vo_sub=NULL;
4940 mpctx->subdata=NULL;
4941 #ifdef CONFIG_ASS
4942 mpctx->osd->ass_track = NULL;
4943 if(ass_library)
4944 ass_clear_fonts(ass_library);
4945 #endif
4947 if (!mpctx->stop_play) // In case some goto jumped here...
4948 mpctx->stop_play = PT_NEXT_ENTRY;
4950 int playtree_direction = 1;
4952 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4953 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4954 play_tree_iter_free(mpctx->playtree_iter);
4955 mpctx->playtree_iter = NULL;
4957 mpctx->play_tree_step = 1;
4958 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4959 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4960 if(mpctx->playtree_iter) {
4961 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4962 play_tree_iter_free(mpctx->playtree_iter);
4963 mpctx->playtree_iter = NULL;
4966 } else if (mpctx->stop_play == PT_STOP) {
4967 play_tree_iter_free(mpctx->playtree_iter);
4968 mpctx->playtree_iter = NULL;
4969 } else { // NEXT PREV SRC
4970 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4973 while(mpctx->playtree_iter != NULL) {
4974 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4975 if(mpctx->filename == NULL) {
4976 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4977 play_tree_iter_free(mpctx->playtree_iter);
4978 mpctx->playtree_iter = NULL;
4980 } else
4981 break;
4984 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4985 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4986 mpctx->stop_play = 0;
4987 goto play_next_file;
4991 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4993 return 1;
4995 #endif /* DISABLE_MAIN */