core: move global "subdata" and "vo_sub_last" to mpctx
[mplayer/glamo.git] / mplayer.c
blob567114cfd3c1a08af006200731199d196c8a2c91
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 /// \file
20 /// \ingroup Properties Command2Property OSDMsgStack
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdbool.h>
25 #include <math.h>
27 #include "config.h"
28 #include "talloc.h"
30 #if defined(__MINGW32__) || defined(__CYGWIN__)
31 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
32 #include <windows.h>
33 #endif
34 #include <string.h>
35 #include <unistd.h>
37 // #include <sys/mman.h>
38 #include <sys/types.h>
39 #ifndef __MINGW32__
40 #include <sys/ioctl.h>
41 #include <sys/wait.h>
42 #else
43 #define SIGHUP 1 /* hangup */
44 #define SIGQUIT 3 /* quit */
45 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
46 #define SIGBUS 10 /* bus error */
47 #define SIGPIPE 13 /* broken pipe */
48 #endif
50 #include <sys/time.h>
51 #include <sys/stat.h>
53 #include <signal.h>
54 #include <time.h>
55 #include <fcntl.h>
56 #include <limits.h>
58 #include <errno.h>
60 #include "mp_msg.h"
61 #include "av_log.h"
64 #include "m_option.h"
65 #include "m_config.h"
66 #include "mplayer.h"
67 #include "access_mpcontext.h"
68 #include "m_property.h"
70 #include "cfg-mplayer-def.h"
72 #include "libavutil/avstring.h"
74 #include "subreader.h"
76 #include "mp_osd.h"
77 #include "libvo/video_out.h"
79 #include "libvo/font_load.h"
80 #include "libvo/sub.h"
82 #ifdef CONFIG_X11
83 #include "libvo/x11_common.h"
84 #endif
86 #include "libao2/audio_out.h"
88 #include "codec-cfg.h"
90 #include "edl.h"
92 #include "spudec.h"
93 #include "vobsub.h"
95 #include "osdep/getch2.h"
96 #include "osdep/timer.h"
97 #include "osdep/findfiles.h"
99 #include "input/input.h"
101 const int under_mencoder = 0;
102 int slave_mode=0;
103 int enable_mouse_movements=0;
104 float start_volume = -1;
106 #include "osdep/priority.h"
108 char *heartbeat_cmd;
110 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
112 #ifdef HAVE_RTC
113 #ifdef __linux__
114 #include <linux/rtc.h>
115 #else
116 #include <rtc.h>
117 #define RTC_IRQP_SET RTCIO_IRQP_SET
118 #define RTC_PIE_ON RTCIO_PIE_ON
119 #endif /* __linux__ */
120 #endif /* HAVE_RTC */
122 #include "stream/tv.h"
123 #include "stream/stream_radio.h"
124 #ifdef CONFIG_DVBIN
125 #include "stream/dvbin.h"
126 #endif
127 #include "stream/cache2.h"
129 //**************************************************************************//
130 // Playtree
131 //**************************************************************************//
132 #include "playtree.h"
133 #include "playtreeparser.h"
135 //**************************************************************************//
136 // Config
137 //**************************************************************************//
138 #include "parser-cfg.h"
139 #include "parser-mpcmd.h"
141 //**************************************************************************//
142 // Config file
143 //**************************************************************************//
145 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
147 #include "path.h"
149 //**************************************************************************//
150 //**************************************************************************//
151 // Input media streaming & demultiplexer:
152 //**************************************************************************//
154 static int max_framesize=0;
156 #include "stream/stream.h"
157 #include "libmpdemux/demuxer.h"
158 #include "libmpdemux/stheader.h"
160 #ifdef CONFIG_DVDREAD
161 #include "stream/stream_dvd.h"
162 #endif
163 #include "stream/stream_dvdnav.h"
165 #include "libmpcodecs/dec_audio.h"
166 #include "libmpcodecs/dec_video.h"
167 #include "libmpcodecs/mp_image.h"
168 #include "libmpcodecs/vf.h"
169 #include "libmpcodecs/vd.h"
171 #include "mixer.h"
173 #include "mp_core.h"
174 #include "options.h"
175 #include "defaultopts.h"
177 static const char help_text[]=_(
178 "Usage: mplayer [options] [url|path/]filename\n"
179 "\n"
180 "Basic options: (complete list in the man page)\n"
181 " -vo <drv> select video output driver ('-vo help' for a list)\n"
182 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
183 #ifdef CONFIG_VCD
184 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
185 #endif
186 #ifdef CONFIG_DVDREAD
187 " dvd://<titleno> play DVD title from device instead of plain file\n"
188 #endif
189 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
190 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
191 " -nosound do not play sound\n"
192 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
193 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
194 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
195 " -playlist <file> specify playlist file\n"
196 " -vid x -aid y select video (x) and audio (y) stream to play\n"
197 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
198 " -pp <quality> enable postprocessing filter (details in the man page)\n"
199 " -framedrop enable frame dropping (for slow machines)\n"
200 "\n"
201 "Basic keys: (complete list in the man page, also check input.conf)\n"
202 " <- or -> seek backward/forward 10 seconds\n"
203 " down or up seek backward/forward 1 minute\n"
204 " pgdown or pgup seek backward/forward 10 minutes\n"
205 " < or > step backward/forward in playlist\n"
206 " p or SPACE pause movie (press any key to continue)\n"
207 " q or ESC stop playing and quit program\n"
208 " + or - adjust audio delay by +/- 0.1 second\n"
209 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
210 " * or / increase or decrease PCM volume\n"
211 " x or z adjust subtitle delay by +/- 0.1 second\n"
212 " r or t adjust subtitle position up/down, also see -vf expand\n"
213 "\n"
214 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
215 "\n");
218 #define Exit_SIGILL_RTCpuSel _(\
219 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
220 " It may be a bug in our new runtime CPU-detection code...\n"\
221 " Please read DOCS/HTML/en/bugreports.html.\n")
223 #define Exit_SIGILL _(\
224 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
225 " It usually happens when you run it on a CPU different than the one it was\n"\
226 " compiled/optimized for.\n"\
227 " Verify this!\n")
229 #define Exit_SIGSEGV_SIGFPE _(\
230 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
231 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
232 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
234 #define Exit_SIGCRASH _(\
235 "- MPlayer crashed. This shouldn't happen.\n"\
236 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
237 " gcc version. If you think it's MPlayer's fault, please read\n"\
238 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
239 " won't help unless you provide this information when reporting a possible bug.\n")
241 #define SystemTooSlow _("\n\n"\
242 " ************************************************\n"\
243 " **** Your system is too SLOW to play this! ****\n"\
244 " ************************************************\n\n"\
245 "Possible reasons, problems, workarounds:\n"\
246 "- Most common: broken/buggy _audio_ driver\n"\
247 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
248 " - Experiment with different values for -autosync, 30 is a good start.\n"\
249 "- Slow video output\n"\
250 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
251 "- Slow CPU\n"\
252 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
253 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
254 "- Broken file\n"\
255 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
256 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
257 " - Try -cache 8192.\n"\
258 "- Are you using -cache to play a non-interleaved AVI file?\n"\
259 " - Try -nocache.\n"\
260 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
261 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
264 //**************************************************************************//
265 //**************************************************************************//
267 #include "mp_fifo.h"
269 // benchmark:
270 double video_time_usage=0;
271 double vout_time_usage=0;
272 static double audio_time_usage=0;
273 static int total_time_usage_start=0;
274 static int total_frame_cnt=0;
275 static int drop_frame_cnt=0; // total number of dropped frames
277 // options:
278 static int output_quality=0;
280 // seek:
281 static double seek_to_sec;
282 static off_t seek_to_byte=0;
283 static off_t step_sec=0;
285 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
287 // codecs:
288 char **audio_codec_list=NULL; // override audio codec
289 char **video_codec_list=NULL; // override video codec
290 char **audio_fm_list=NULL; // override audio codec family
291 char **video_fm_list=NULL; // override video codec family
293 // this dvdsub_id was selected via slang
294 // use this to allow dvdnav to follow -slang across stream resets,
295 // in particular the subtitle ID for a language changes
296 int dvdsub_lang_id;
297 int vobsub_id=-1;
298 static char* spudec_ifo=NULL;
299 int forced_subs_only=0;
300 int file_filter=1;
302 // cache2:
303 int stream_cache_size=-1;
305 // dump:
306 int stream_dump_type=0;
308 // A-V sync:
309 static float default_max_pts_correction=-1;//0.01f;
310 float audio_delay=0;
311 static int ignore_start=0;
313 double force_fps=0;
314 static int force_srate=0;
315 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
316 static int play_n_frames=-1;
317 static int play_n_frames_mf=-1;
319 // sub:
320 char *font_name=NULL;
321 char *sub_font_name=NULL;
322 extern int font_fontconfig;
323 float font_factor=0.75;
324 char **sub_name=NULL;
325 float sub_delay=0;
326 float sub_fps=0;
327 int sub_auto = 1;
328 char *vobsub_name=NULL;
329 int subcc_enabled=0;
330 int suboverlap_enabled = 1;
332 #include "ass_mp.h"
334 char* current_module=NULL; // for debugging
337 // ---
339 #ifdef CONFIG_MENU
340 #include "m_struct.h"
341 #include "libmenu/menu.h"
342 static const vf_info_t* const libmenu_vfs[] = {
343 &vf_info_menu,
344 NULL
346 static vf_instance_t* vf_menu = NULL;
347 int use_menu = 0;
348 static char* menu_cfg = NULL;
349 static char* menu_root = "main";
350 #endif
353 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
354 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
355 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
356 int use_filedir_conf;
357 int use_filename_title;
359 #include "mpcommon.h"
360 #include "command.h"
362 #include "metadata.h"
364 const void *mpctx_get_video_out(MPContext *mpctx)
366 return mpctx->video_out;
369 const void *mpctx_get_audio_out(MPContext *mpctx)
371 return mpctx->audio_out;
374 void *mpctx_get_demuxer(MPContext *mpctx)
376 return mpctx->demuxer;
379 void *mpctx_get_playtree_iter(MPContext *mpctx)
381 return mpctx->playtree_iter;
384 void *mpctx_get_mixer(MPContext *mpctx)
386 return &mpctx->mixer;
389 int mpctx_get_global_sub_size(MPContext *mpctx)
391 return mpctx->global_sub_size;
394 int mpctx_get_osd_function(MPContext *mpctx)
396 return mpctx->osd_function;
399 static float get_relative_time(struct MPContext *mpctx)
401 unsigned int new_time = GetTimer();
402 unsigned int delta = new_time - mpctx->last_time;
403 mpctx->last_time = new_time;
404 return delta * 0.000001;
407 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
408 switch (type)
410 /* check for valid video stream */
411 case META_VIDEO_CODEC:
412 case META_VIDEO_BITRATE:
413 case META_VIDEO_RESOLUTION:
415 if (!mpctx->sh_video)
416 return 0;
417 break;
420 /* check for valid audio stream */
421 case META_AUDIO_CODEC:
422 case META_AUDIO_BITRATE:
423 case META_AUDIO_SAMPLES:
425 if (!mpctx->sh_audio)
426 return 0;
427 break;
430 /* check for valid demuxer */
431 case META_INFO_TITLE:
432 case META_INFO_ARTIST:
433 case META_INFO_ALBUM:
434 case META_INFO_YEAR:
435 case META_INFO_COMMENT:
436 case META_INFO_TRACK:
437 case META_INFO_GENRE:
439 if (!mpctx->demuxer)
440 return 0;
441 break;
444 default:
445 break;
448 return 1;
451 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
452 char **info = mpctx->demuxer->info;
453 int n;
455 if (!info || !tag)
456 return talloc_strdup(NULL, "");
458 for (n = 0; info[2*n] != NULL ; n++)
459 if (!strcasecmp (info[2*n], tag))
460 break;
462 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
465 char *get_metadata(struct MPContext *mpctx, metadata_t type)
467 sh_audio_t * const sh_audio = mpctx->sh_audio;
468 sh_video_t * const sh_video = mpctx->sh_video;
470 if (!is_valid_metadata_type(mpctx, type))
471 return NULL;
473 switch (type) {
474 case META_NAME:
475 return talloc_strdup(NULL, mp_basename(mpctx->filename));
476 case META_VIDEO_CODEC:
477 if (sh_video->format == 0x10000001)
478 return talloc_strdup(NULL, "mpeg1");
479 else if (sh_video->format == 0x10000002)
480 return talloc_strdup(NULL, "mpeg2");
481 else if (sh_video->format == 0x10000004)
482 return talloc_strdup(NULL, "mpeg4");
483 else if (sh_video->format == 0x10000005)
484 return talloc_strdup(NULL, "h264");
485 else if (sh_video->format >= 0x20202020)
486 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
487 else
488 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
489 case META_VIDEO_BITRATE:
490 return talloc_asprintf(NULL, "%d kbps",
491 (int) (sh_video->i_bps * 8 / 1024));
492 case META_VIDEO_RESOLUTION:
493 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
494 sh_video->disp_h);
495 case META_AUDIO_CODEC:
496 if (sh_audio->codec && sh_audio->codec->name)
497 return talloc_strdup(NULL, sh_audio->codec->name);
498 return talloc_strdup(NULL, "");
499 case META_AUDIO_BITRATE:
500 return talloc_asprintf(NULL, "%d kbps",
501 (int) (sh_audio->i_bps * 8/1000));
502 case META_AUDIO_SAMPLES:
503 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
504 sh_audio->channels);
506 /* check for valid demuxer */
507 case META_INFO_TITLE:
508 return get_demuxer_info(mpctx, "Title");
510 case META_INFO_ARTIST:
511 return get_demuxer_info(mpctx, "Artist");
513 case META_INFO_ALBUM:
514 return get_demuxer_info(mpctx, "Album");
516 case META_INFO_YEAR:
517 return get_demuxer_info(mpctx, "Year");
519 case META_INFO_COMMENT:
520 return get_demuxer_info(mpctx, "Comment");
522 case META_INFO_TRACK:
523 return get_demuxer_info(mpctx, "Track");
525 case META_INFO_GENRE:
526 return get_demuxer_info(mpctx, "Genre");
528 default:
529 break;
532 return talloc_strdup(NULL, "");
535 static void print_file_properties(struct MPContext *mpctx, const char *filename)
537 double start_pts = MP_NOPTS_VALUE;
538 double video_start_pts = MP_NOPTS_VALUE;
539 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
540 filename_recode(filename));
541 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
542 if (mpctx->sh_video) {
543 /* Assume FOURCC if all bytes >= 0x20 (' ') */
544 if (mpctx->sh_video->format >= 0x20202020)
545 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
546 else
547 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
548 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
549 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
550 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
551 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
552 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
553 video_start_pts = ds_get_next_pts(mpctx->d_video);
555 if (mpctx->sh_audio) {
556 /* Assume FOURCC if all bytes >= 0x20 (' ') */
557 if (mpctx->sh_audio->format >= 0x20202020)
558 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
559 else
560 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
561 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
562 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
563 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
564 start_pts = ds_get_next_pts(mpctx->d_audio);
566 if (video_start_pts != MP_NOPTS_VALUE) {
567 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
568 (mpctx->sh_video && video_start_pts < start_pts))
569 start_pts = video_start_pts;
571 if (start_pts != MP_NOPTS_VALUE)
572 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
573 else
574 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
575 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
576 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
577 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
578 if (mpctx->demuxer) {
579 if (mpctx->demuxer->num_chapters == 0)
580 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
581 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
585 /// step size of mixer changes
586 int volstep = 3;
588 #ifdef CONFIG_DVDNAV
589 static void mp_dvdnav_context_free(MPContext *ctx){
590 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
591 ctx->nav_smpi = NULL;
592 free(ctx->nav_buffer);
593 ctx->nav_buffer = NULL;
594 ctx->nav_start = NULL;
595 ctx->nav_in_size = 0;
597 #endif
599 void uninit_player(struct MPContext *mpctx, unsigned int mask){
600 mask &= mpctx->initialized_flags;
602 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
604 if(mask&INITIALIZED_ACODEC){
605 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
606 current_module="uninit_acodec";
607 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
608 mpctx->sh_audio=NULL;
609 mpctx->mixer.afilter = NULL;
612 if(mask&INITIALIZED_VCODEC){
613 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
614 current_module="uninit_vcodec";
615 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
616 mpctx->sh_video=NULL;
617 #ifdef CONFIG_MENU
618 vf_menu=NULL;
619 #endif
622 if(mask&INITIALIZED_DEMUXER){
623 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
624 current_module="free_demuxer";
625 if (mpctx->num_sources) {
626 mpctx->demuxer = mpctx->sources[0].demuxer;
627 for (int i = 1; i < mpctx->num_sources; i++) {
628 free_stream(mpctx->sources[i].stream);
629 free_demuxer(mpctx->sources[i].demuxer);
632 talloc_free(mpctx->sources);
633 mpctx->sources = NULL;
634 mpctx->num_sources = 0;
635 talloc_free(mpctx->timeline);
636 mpctx->timeline = NULL;
637 mpctx->num_timeline_parts = 0;
638 talloc_free(mpctx->chapters);
639 mpctx->chapters = NULL;
640 mpctx->num_chapters = 0;
641 mpctx->video_offset = 0;
642 if(mpctx->demuxer){
643 mpctx->stream=mpctx->demuxer->stream;
644 free_demuxer(mpctx->demuxer);
646 mpctx->demuxer=NULL;
649 // kill the cache process:
650 if(mask&INITIALIZED_STREAM){
651 mpctx->initialized_flags&=~INITIALIZED_STREAM;
652 current_module="uninit_stream";
653 if(mpctx->stream) free_stream(mpctx->stream);
654 mpctx->stream=NULL;
657 if(mask&INITIALIZED_VO){
658 mpctx->initialized_flags&=~INITIALIZED_VO;
659 current_module="uninit_vo";
660 vo_destroy(mpctx->video_out);
661 mpctx->video_out=NULL;
662 #ifdef CONFIG_DVDNAV
663 mp_dvdnav_context_free(mpctx);
664 #endif
667 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
668 if(mask&INITIALIZED_GETCH2){
669 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
670 current_module="uninit_getch2";
671 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
672 // restore terminal:
673 getch2_disable();
676 if(mask&INITIALIZED_VOBSUB){
677 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
678 current_module="uninit_vobsub";
679 if(vo_vobsub) vobsub_close(vo_vobsub);
680 vo_vobsub=NULL;
683 if (mask&INITIALIZED_SPUDEC){
684 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
685 current_module="uninit_spudec";
686 spudec_free(vo_spudec);
687 vo_spudec=NULL;
690 if(mask&INITIALIZED_AO){
691 mpctx->initialized_flags&=~INITIALIZED_AO;
692 current_module="uninit_ao";
693 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
694 if (mpctx->audio_out)
695 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
696 mpctx->audio_out=NULL;
699 current_module=NULL;
702 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
704 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
705 uninit_player(mpctx, INITIALIZED_ALL);
706 #if defined(__MINGW32__) || defined(__CYGWIN__)
707 timeEndPeriod(1);
708 #endif
709 #ifdef CONFIG_X11
710 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
711 #endif
713 current_module="uninit_input";
714 mp_input_uninit(mpctx->input);
715 #ifdef CONFIG_MENU
716 if (use_menu)
717 menu_uninit();
718 #endif
720 #ifdef CONFIG_FREETYPE
721 current_module="uninit_font";
722 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
723 free_font_desc(mpctx->osd->sub_font);
724 free_font_desc(vo_font);
725 vo_font = NULL;
726 done_freetype();
727 #endif
728 osd_free(mpctx->osd);
730 #ifdef CONFIG_ASS
731 ass_library_done(ass_library);
732 ass_library = NULL;
733 #endif
735 current_module="exit_player";
737 // free mplayer config
738 if(mpctx->mconfig)
739 m_config_free(mpctx->mconfig);
740 mpctx->mconfig = NULL;
742 if(mpctx->playtree_iter)
743 play_tree_iter_free(mpctx->playtree_iter);
744 mpctx->playtree_iter = NULL;
745 if(mpctx->playtree)
746 play_tree_free(mpctx->playtree, 1);
747 mpctx->playtree = NULL;
749 talloc_free(mpctx->key_fifo);
751 free(edl_records); // free mem allocated for EDL
752 edl_records = NULL;
753 switch(how) {
754 case EXIT_QUIT:
755 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
756 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
757 break;
758 case EXIT_EOF:
759 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
760 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
761 break;
762 case EXIT_ERROR:
763 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
764 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
765 break;
766 default:
767 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
769 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
771 exit(rc);
774 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
776 exit_player_with_rc(mpctx, how, 1);
779 #ifndef __MINGW32__
780 static void child_sighandler(int x){
781 pid_t pid;
782 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
784 #endif
786 #ifdef CONFIG_CRASH_DEBUG
787 static char *prog_path;
788 static int crash_debug = 0;
789 #endif
791 static void exit_sighandler(int x){
792 static int sig_count=0;
793 #ifdef CONFIG_CRASH_DEBUG
794 if (!crash_debug || x != SIGTRAP)
795 #endif
796 ++sig_count;
797 if(sig_count==5)
799 /* We're crashing bad and can't uninit cleanly :(
800 * by popular request, we make one last (dirty)
801 * effort to restore the user's
802 * terminal. */
803 getch2_disable();
804 exit(1);
806 if(sig_count==6) exit(1);
807 if(sig_count>6){
808 // can't stop :(
809 #ifndef __MINGW32__
810 kill(getpid(),SIGKILL);
811 #endif
813 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
814 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
815 "\nMPlayer interrupted by signal %d in module: %s\n", x,
816 current_module ? current_module : "unknown");
817 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
818 if(sig_count<=1)
819 switch(x){
820 case SIGINT:
821 case SIGPIPE:
822 case SIGQUIT:
823 case SIGTERM:
824 case SIGKILL:
825 async_quit_request = 1;
826 return; // killed from keyboard (^C) or killed [-9]
827 case SIGILL:
828 #if CONFIG_RUNTIME_CPUDETECT
829 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
830 #else
831 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
832 #endif
833 case SIGFPE:
834 case SIGSEGV:
835 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
836 default:
837 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
838 #ifdef CONFIG_CRASH_DEBUG
839 if (crash_debug) {
840 int gdb_pid;
841 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
842 gdb_pid = fork();
843 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
844 if (gdb_pid == 0) { // We are the child
845 char spid[20];
846 snprintf(spid, sizeof(spid), "%i", getppid());
847 getch2_disable(); // allow terminal to work properly with gdb
848 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
849 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
850 } else if (gdb_pid < 0)
851 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
852 else {
853 waitpid(gdb_pid, NULL, 0);
855 if (x == SIGTRAP) return;
857 #endif
859 getch2_disable();
860 exit(1);
863 #include "cfg-mplayer.h"
865 static int cfg_include(m_option_t *conf, char *filename)
867 return m_config_parse_config_file(conf->priv, filename);
870 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
872 struct MPOpts *opts = &mpctx->opts;
873 char *conffile;
874 int conffile_fd;
875 if (!(opts->noconfig & 2) &&
876 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
877 exit_player(mpctx, EXIT_NONE);
878 if ((conffile = get_path("")) == NULL) {
879 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
880 } else {
881 #ifdef __MINGW32__
882 mkdir(conffile);
883 #else
884 mkdir(conffile, 0777);
885 #endif
886 free(conffile);
887 if ((conffile = get_path("config")) == NULL) {
888 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
889 } else {
890 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
891 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
892 write(conffile_fd, default_config, strlen(default_config));
893 close(conffile_fd);
895 if (!(opts->noconfig & 1) &&
896 m_config_parse_config_file(conf, conffile) < 0)
897 exit_player(mpctx, EXIT_NONE);
898 free(conffile);
903 #define PROFILE_CFG_PROTOCOL "protocol."
905 static void load_per_protocol_config (m_config_t* conf, const char *const file)
907 char *str;
908 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
909 m_profile_t *p;
911 /* does filename actually uses a protocol ? */
912 str = strstr (file, "://");
913 if (!str)
914 return;
916 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
917 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
918 p = m_config_get_profile (conf, protocol);
919 if (p)
921 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
922 m_config_set_profile(conf,p);
926 #define PROFILE_CFG_EXTENSION "extension."
928 static void load_per_extension_config (m_config_t* conf, const char *const file)
930 char *str;
931 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
932 m_profile_t *p;
934 /* does filename actually have an extension ? */
935 str = strrchr (file, '.');
936 if (!str)
937 return;
939 sprintf (extension, PROFILE_CFG_EXTENSION);
940 strncat (extension, ++str, 7);
941 p = m_config_get_profile (conf, extension);
942 if (p)
944 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
945 m_config_set_profile(conf,p);
949 #define PROFILE_CFG_VO "vo."
950 #define PROFILE_CFG_AO "ao."
952 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
954 char profile[strlen (cfg) + strlen (out) + 1];
955 m_profile_t *p;
957 sprintf (profile, "%s%s", cfg, out);
958 p = m_config_get_profile (conf, profile);
959 if (p)
961 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
962 m_config_set_profile(conf,p);
967 * Tries to load a config file
968 * @return 0 if file was not found, 1 otherwise
970 static int try_load_config(m_config_t *conf, const char *file)
972 struct stat st;
973 if (stat(file, &st))
974 return 0;
975 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
976 m_config_parse_config_file (conf, file);
977 return 1;
980 static void load_per_file_config (m_config_t* conf, const char *const file)
982 char *confpath;
983 char cfg[PATH_MAX];
984 const char *name;
986 if (strlen(file) > PATH_MAX - 14) {
987 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
988 return;
990 sprintf (cfg, "%s.conf", file);
992 name = mp_basename(cfg);
993 if (use_filedir_conf) {
994 char dircfg[PATH_MAX];
995 strcpy(dircfg, cfg);
996 strcpy(dircfg + (name - cfg), "mplayer.conf");
997 try_load_config(conf, dircfg);
999 if (try_load_config(conf, cfg))
1000 return;
1003 if ((confpath = get_path (name)) != NULL)
1005 try_load_config(conf, confpath);
1007 free (confpath);
1011 /* When libmpdemux performs a blocking operation (network connection or
1012 * cache filling) if the operation fails we use this function to check
1013 * if it was interrupted by the user.
1014 * The function returns a new value for eof. */
1015 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1017 mp_cmd_t* cmd;
1018 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1019 switch(cmd->id) {
1020 case MP_CMD_QUIT:
1021 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1022 case MP_CMD_PLAY_TREE_STEP: {
1023 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1024 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1025 } break;
1026 case MP_CMD_PLAY_TREE_UP_STEP: {
1027 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1028 } break;
1029 case MP_CMD_PLAY_ALT_SRC_STEP: {
1030 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1031 } break;
1033 mp_cmd_free(cmd);
1035 return stop_play;
1038 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1040 play_tree_add_bpf(entry,mpctx->filename);
1043 if(!entry) {
1044 entry = mpctx->playtree_iter->tree;
1045 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1046 return PT_NEXT_ENTRY;
1048 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1049 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1050 return PT_NEXT_ENTRY;
1053 play_tree_remove(entry,1,1);
1054 return PT_NEXT_SRC;
1056 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1057 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1058 entry = mpctx->playtree_iter->tree;
1059 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1060 return PT_NEXT_ENTRY;
1062 play_tree_remove(entry,1,1);
1064 return PT_NEXT_SRC;
1067 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1069 struct MPOpts *opts = &mpctx->opts;
1070 sub_data *subd = NULL;
1071 struct ass_track *asst = NULL;
1073 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1074 return;
1077 #ifdef CONFIG_ASS
1078 if (opts->ass_enabled) {
1079 #ifdef CONFIG_ICONV
1080 asst = ass_read_stream(ass_library, filename, sub_cp);
1081 #else
1082 asst = ass_read_stream(ass_library, filename, 0);
1083 #endif
1084 if (!asst) {
1085 subd = sub_read_file(filename, fps);
1086 if (subd) {
1087 asst = ass_read_subdata(ass_library, subd, fps);
1088 if (asst) {
1089 sub_free(subd);
1090 subd = NULL;
1094 } else
1095 #endif
1096 subd = sub_read_file(filename, fps);
1099 if (!asst && !subd) {
1100 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1101 "Cannot load subtitles: %s\n", filename_recode(filename));
1102 return;
1105 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1106 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1107 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1108 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1109 filename_recode(filename));
1110 ++mpctx->set_of_sub_size;
1111 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1112 filename_recode(filename));
1115 void init_vo_spudec(struct MPContext *mpctx)
1117 spudec_free(vo_spudec);
1118 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1119 vo_spudec = NULL;
1121 // we currently can't work without video stream
1122 if (!mpctx->sh_video)
1123 return;
1125 if (spudec_ifo) {
1126 unsigned int palette[16], width, height;
1127 current_module="spudec_init_vobsub";
1128 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1129 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1132 #ifdef CONFIG_DVDREAD
1133 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1134 current_module="spudec_init_dvdread";
1135 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1136 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1137 NULL, 0);
1139 #endif
1141 #ifdef CONFIG_DVDNAV
1142 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1143 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1144 current_module="spudec_init_dvdnav";
1145 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1147 #endif
1149 if (vo_spudec==NULL) {
1150 sh_sub_t *sh = mpctx->d_sub->sh;
1151 current_module="spudec_init_normal";
1152 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1153 spudec_set_font_factor(vo_spudec,font_factor);
1156 if (vo_spudec!=NULL) {
1157 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1158 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1163 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1164 * make it all work is to use the builtin SDL-bootstrap code, which
1165 * will be done automatically by replacing our main() if we include SDL.h.
1167 #if defined(__APPLE__) && defined(CONFIG_SDL)
1168 #ifdef CONFIG_SDL_SDL_H
1169 #include <SDL/SDL.h>
1170 #else
1171 #include <SDL.h>
1172 #endif
1173 #endif
1176 * \brief append a formatted string
1177 * \param buf buffer to print into
1178 * \param pos position of terminating 0 in buf
1179 * \param len maximum number of characters in buf, not including terminating 0
1180 * \param format printf format string
1182 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1184 va_list va;
1185 va_start(va, format);
1186 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1187 va_end(va);
1188 if (*pos >= len ) {
1189 buf[len] = 0;
1190 *pos = len;
1195 * \brief append time in the hh:mm:ss.f format
1196 * \param buf buffer to print into
1197 * \param pos position of terminating 0 in buf
1198 * \param len maximum number of characters in buf, not including terminating 0
1199 * \param time time value to convert/append
1201 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1202 int64_t tenths = 10 * time;
1203 int f1 = tenths % 10;
1204 int ss = (tenths / 10) % 60;
1205 int mm = (tenths / 600) % 60;
1206 int hh = tenths / 36000;
1207 if (time <= 0) {
1208 saddf(buf, pos, len, "unknown");
1209 return;
1211 if (hh > 0)
1212 saddf(buf, pos, len, "%2d:", hh);
1213 if (hh > 0 || mm > 0)
1214 saddf(buf, pos, len, "%02d:", mm);
1215 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1218 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1220 struct MPOpts *opts = &mpctx->opts;
1221 sh_video_t * const sh_video = mpctx->sh_video;
1223 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1224 a_pos = playing_audio_pts(mpctx);
1225 if (mpctx->sh_audio && sh_video && at_frame) {
1226 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1227 if (mpctx->time_frame > 0)
1228 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1229 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1230 && !mpctx->drop_message_shown) {
1231 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1232 mpctx->drop_message_shown = true;
1235 if (opts->quiet)
1236 return;
1239 int width;
1240 char *line;
1241 unsigned pos = 0;
1242 get_screen_size();
1243 if (screen_width > 0)
1244 width = screen_width;
1245 else
1246 width = 80;
1247 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1248 /* Windows command line is broken (MinGW's rxvt works, but we
1249 * should not depend on that). */
1250 width--;
1251 #endif
1252 line = malloc(width + 1); // one additional char for the terminating null
1254 // Audio time
1255 if (mpctx->sh_audio) {
1256 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1257 if (!sh_video) {
1258 float len = get_time_length(mpctx);
1259 saddf(line, &pos, width, "(");
1260 sadd_hhmmssf(line, &pos, width, a_pos);
1261 saddf(line, &pos, width, ") of %.1f (", len);
1262 sadd_hhmmssf(line, &pos, width, len);
1263 saddf(line, &pos, width, ") ");
1267 // Video time
1268 if (sh_video)
1269 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1271 // A-V sync
1272 if (mpctx->sh_audio && sh_video)
1273 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1274 mpctx->last_av_difference, mpctx->total_avsync_change);
1276 // Video stats
1277 if (sh_video)
1278 saddf(line, &pos, width, "%3d/%3d ",
1279 (int)sh_video->num_frames,
1280 (int)sh_video->num_frames_decoded);
1282 // CPU usage
1283 if (sh_video) {
1284 if (sh_video->timer > 0.5)
1285 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1286 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1287 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1288 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1289 else
1290 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1291 } else if (mpctx->sh_audio) {
1292 if (mpctx->delay > 0.5)
1293 saddf(line, &pos, width, "%4.1f%% ",
1294 100.0*audio_time_usage/(double)mpctx->delay);
1295 else
1296 saddf(line, &pos, width, "??,?%% ");
1299 // VO stats
1300 if (sh_video)
1301 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1303 #ifdef CONFIG_STREAM_CACHE
1304 // cache stats
1305 if (stream_cache_size > 0)
1306 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1307 #endif
1309 // other
1310 if (opts->playback_speed != 1)
1311 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1313 // end
1314 if (erase_to_end_of_line) {
1315 line[pos] = 0;
1316 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1317 } else {
1318 memset(&line[pos], ' ', width - pos);
1319 line[width] = 0;
1320 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1322 free(line);
1326 * \brief build a chain of audio filters that converts the input format
1327 * to the ao's format, taking into account the current playback_speed.
1328 * \param sh_audio describes the requested input format of the chain.
1329 * \param ao_data describes the requested output format of the chain.
1331 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1332 ao_data_t *ao_data)
1334 struct MPOpts *opts = &mpctx->opts;
1335 int new_srate;
1336 int result;
1337 if (!sh_audio)
1339 mpctx->mixer.afilter = NULL;
1340 return 0;
1342 if(af_control_any_rev(sh_audio->afilter,
1343 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1344 &opts->playback_speed)) {
1345 new_srate = sh_audio->samplerate;
1346 } else {
1347 new_srate = sh_audio->samplerate * opts->playback_speed;
1348 if (new_srate != ao_data->samplerate) {
1349 // limits are taken from libaf/af_resample.c
1350 if (new_srate < 8000)
1351 new_srate = 8000;
1352 if (new_srate > 192000)
1353 new_srate = 192000;
1354 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1357 result = init_audio_filters(sh_audio, new_srate,
1358 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1359 mpctx->mixer.afilter = sh_audio->afilter;
1360 return result;
1364 typedef struct mp_osd_msg mp_osd_msg_t;
1365 struct mp_osd_msg {
1366 /// Previous message on the stack.
1367 mp_osd_msg_t* prev;
1368 /// Message text.
1369 char msg[128];
1370 int id,level,started;
1371 /// Display duration in ms.
1372 unsigned time;
1375 /// OSD message stack.
1376 static mp_osd_msg_t* osd_msg_stack = NULL;
1379 * \brief Add a message on the OSD message stack
1381 * If a message with the same id is already present in the stack
1382 * it is pulled on top of the stack, otherwise a new message is created.
1385 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1386 va_list ap)
1388 mp_osd_msg_t *msg,*last=NULL;
1389 int r;
1391 // look if the id is already in the stack
1392 for(msg = osd_msg_stack ; msg && msg->id != id ;
1393 last = msg, msg = msg->prev);
1394 // not found: alloc it
1395 if(!msg) {
1396 msg = calloc(1,sizeof(mp_osd_msg_t));
1397 msg->prev = osd_msg_stack;
1398 osd_msg_stack = msg;
1399 } else if(last) { // found, but it's not on top of the stack
1400 last->prev = msg->prev;
1401 msg->prev = osd_msg_stack;
1402 osd_msg_stack = msg;
1404 // write the msg
1405 r = vsnprintf(msg->msg, 128, fmt, ap);
1406 if(r >= 128) msg->msg[127] = 0;
1407 // set id and time
1408 msg->id = id;
1409 msg->level = level;
1410 msg->time = time;
1414 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1416 va_list ap;
1417 va_start(ap, fmt);
1418 set_osd_msg_va(id, level, time, fmt, ap);
1419 va_end(ap);
1422 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1424 va_list ap;
1425 va_start(ap, fmt);
1426 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1427 va_end(ap);
1432 * \brief Remove a message from the OSD stack
1434 * This function can be used to get rid of a message right away.
1438 void rm_osd_msg(int id) {
1439 mp_osd_msg_t *msg,*last=NULL;
1441 // Search for the msg
1442 for(msg = osd_msg_stack ; msg && msg->id != id ;
1443 last = msg, msg = msg->prev);
1444 if(!msg) return;
1446 // Detach it from the stack and free it
1447 if(last)
1448 last->prev = msg->prev;
1449 else
1450 osd_msg_stack = msg->prev;
1451 free(msg);
1455 * \brief Remove all messages from the OSD stack
1459 static void clear_osd_msgs(void) {
1460 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1461 while(msg) {
1462 prev = msg->prev;
1463 free(msg);
1464 msg = prev;
1466 osd_msg_stack = NULL;
1470 * \brief Get the current message from the OSD stack.
1472 * This function decrements the message timer and destroys the old ones.
1473 * The message that should be displayed is returned (if any).
1477 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1479 struct MPOpts *opts = &mpctx->opts;
1480 mp_osd_msg_t *msg,*prev,*last = NULL;
1481 static unsigned last_update = 0;
1482 unsigned now = GetTimerMS();
1483 unsigned diff;
1484 char hidden_dec_done = 0;
1486 if (mpctx->osd_visible) {
1487 // 36000000 means max timed visibility is 1 hour into the future, if
1488 // the difference is greater assume it's wrapped around from below 0
1489 if (mpctx->osd_visible - now > 36000000) {
1490 mpctx->osd_visible = 0;
1491 vo_osd_progbar_type = -1; // disable
1492 vo_osd_changed(OSDTYPE_PROGBAR);
1493 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1496 if (mpctx->osd_show_percentage_until - now > 36000000)
1497 mpctx->osd_show_percentage_until = 0;
1499 if(!last_update) last_update = now;
1500 diff = now >= last_update ? now - last_update : 0;
1502 last_update = now;
1504 // Look for the first message in the stack with high enough level.
1505 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1506 prev = msg->prev;
1507 if (msg->level > opts->osd_level && hidden_dec_done)
1508 continue;
1509 // The message has a high enough level or it is the first hidden one
1510 // in both cases we decrement the timer or kill it.
1511 if(!msg->started || msg->time > diff) {
1512 if(msg->started) msg->time -= diff;
1513 else msg->started = 1;
1514 // display it
1515 if (msg->level <= opts->osd_level)
1516 return msg;
1517 hidden_dec_done = 1;
1518 continue;
1520 // kill the message
1521 free(msg);
1522 if(last) {
1523 last->prev = prev;
1524 msg = last;
1525 } else {
1526 osd_msg_stack = prev;
1527 msg = NULL;
1530 // Nothing found
1531 return NULL;
1535 * \brief Display the OSD bar.
1537 * Display the OSD bar or fall back on a simple message.
1541 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1542 struct MPOpts *opts = &mpctx->opts;
1543 if (opts->osd_level < 1)
1544 return;
1546 if(mpctx->sh_video) {
1547 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1548 vo_osd_progbar_type = type;
1549 vo_osd_progbar_value = 256*(val-min)/(max-min);
1550 vo_osd_changed(OSDTYPE_PROGBAR);
1551 return;
1554 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1555 name, ROUND(100*(val-min)/(max-min)));
1559 * \brief Display text subtitles on the OSD
1561 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1563 int i;
1564 vo_sub = subs;
1565 vo_osd_changed(OSDTYPE_SUBTITLE);
1566 if (!mpctx->sh_video) {
1567 // reverse order, since newest set_osd_msg is displayed first
1568 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1569 if (!subs || i >= subs->lines || !subs->text[i])
1570 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1571 else {
1572 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1573 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1574 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1581 * \brief Update the OSD message line.
1583 * This function displays the current message on the vo OSD or on the term.
1584 * If the stack is empty and the OSD level is high enough the timer
1585 * is displayed (only on the vo OSD).
1589 static void update_osd_msg(struct MPContext *mpctx)
1591 struct MPOpts *opts = &mpctx->opts;
1592 mp_osd_msg_t *msg;
1593 struct osd_state *osd = mpctx->osd;
1594 char osd_text_timer[128];
1596 if (mpctx->add_osd_seek_info) {
1597 double percentage = get_percent_pos(mpctx);
1598 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1599 if (mpctx->sh_video)
1600 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1601 mpctx->add_osd_seek_info = false;
1604 // Look if we have a msg
1605 if((msg = get_osd_msg(mpctx))) {
1606 if (strcmp(osd->osd_text, msg->msg)) {
1607 strncpy(osd->osd_text, msg->msg, 127);
1608 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1609 if(opts->term_osd)
1610 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1611 msg->msg);
1613 return;
1616 if(mpctx->sh_video) {
1617 // fallback on the timer
1618 if (opts->osd_level >= 2) {
1619 int len = get_time_length(mpctx);
1620 int percentage = -1;
1621 char percentage_text[10];
1622 int pts = get_current_time(mpctx);
1624 if (mpctx->osd_show_percentage_until)
1625 percentage = get_percent_pos(mpctx);
1627 if (percentage >= 0)
1628 snprintf(percentage_text, 9, " (%d%%)", percentage);
1629 else
1630 percentage_text[0] = 0;
1632 if (opts->osd_level == 3)
1633 snprintf(osd_text_timer, 63,
1634 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1635 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1636 len/3600,(len/60)%60,len%60,percentage_text);
1637 else
1638 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1639 mpctx->osd_function,pts/3600,(pts/60)%60,
1640 pts%60,percentage_text);
1641 } else
1642 osd_text_timer[0]=0;
1644 if (strcmp(osd->osd_text, osd_text_timer)) {
1645 strncpy(osd->osd_text, osd_text_timer, 63);
1646 vo_osd_changed(OSDTYPE_OSD);
1648 return;
1651 // Clear the term osd line
1652 if (opts->term_osd && osd->osd_text[0]) {
1653 osd->osd_text[0] = 0;
1654 printf("%s\n", opts->term_osd_esc);
1658 ///@}
1659 // OSDMsgStack
1662 void reinit_audio_chain(struct MPContext *mpctx)
1664 struct MPOpts *opts = &mpctx->opts;
1665 if (!mpctx->sh_audio)
1666 return;
1667 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1668 current_module="init_audio_codec";
1669 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1670 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1671 goto init_error;
1673 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1674 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1678 current_module="af_preinit";
1679 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1680 ao_data.samplerate=force_srate;
1681 ao_data.channels=0;
1682 ao_data.format = opts->audio_output_format;
1684 // first init to detect best values
1685 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1686 // input:
1687 mpctx->sh_audio->samplerate,
1688 // output:
1689 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1690 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1691 "pre-init!\n");
1692 exit_player(mpctx, EXIT_ERROR);
1694 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1695 current_module="ao2_init";
1696 ao_data.buffersize = opts->ao_buffersize;
1697 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1698 0, // plugin flag
1699 ao_data.samplerate,
1700 ao_data.channels,
1701 ao_data.format, 0);
1702 if(!mpctx->audio_out){
1703 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1704 goto init_error;
1706 mpctx->initialized_flags|=INITIALIZED_AO;
1707 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1708 mpctx->audio_out->info->short_name,
1709 ao_data.samplerate, ao_data.channels,
1710 af_fmt2str_short(ao_data.format),
1711 af_fmt2bits(ao_data.format)/8 );
1712 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1713 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1714 if(strlen(mpctx->audio_out->info->comment) > 0)
1715 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1718 // init audio filters:
1719 current_module="af_init";
1720 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1721 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1722 goto init_error;
1724 mpctx->mixer.audio_out = mpctx->audio_out;
1725 mpctx->mixer.volstep = volstep;
1726 mpctx->syncing_audio = true;
1727 return;
1729 init_error:
1730 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1731 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1732 mpctx->d_audio->id = -2;
1736 ///@}
1737 // Command2Property
1740 // Return pts value corresponding to the end point of audio written to the
1741 // ao so far.
1742 static double written_audio_pts(struct MPContext *mpctx)
1744 sh_audio_t *sh_audio = mpctx->sh_audio;
1745 demux_stream_t *d_audio = mpctx->d_audio;
1746 double buffered_output;
1747 // first calculate the end pts of audio that has been output by decoder
1748 double a_pts = sh_audio->pts;
1749 if (a_pts != MP_NOPTS_VALUE)
1750 // Good, decoder supports new way of calculating audio pts.
1751 // sh_audio->pts is the timestamp of the latest input packet with
1752 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1753 // the amount of bytes the decoder has written after that timestamp.
1754 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1755 else {
1756 // Decoder doesn't support new way of calculating pts (or we're
1757 // being called before it has decoded anything with known timestamp).
1758 // Use the old method of audio pts calculation: take the timestamp
1759 // of last packet with known pts the decoder has read data from,
1760 // and add amount of bytes read after the beginning of that packet
1761 // divided by input bps. This will be inaccurate if the input/output
1762 // ratio is not constant for every audio packet or if it is constant
1763 // but not accurately known in sh_audio->i_bps.
1765 a_pts = d_audio->pts;
1766 // ds_tell_pts returns bytes read after last timestamp from
1767 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1768 // it has read but not decoded
1769 if (sh_audio->i_bps)
1770 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1771 (double)sh_audio->i_bps;
1773 // Now a_pts hopefully holds the pts for end of audio from decoder.
1774 // Substract data in buffers between decoder and audio out.
1776 // Decoded but not filtered
1777 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1779 // Data buffered in audio filters, measured in bytes of "missing" output
1780 buffered_output = af_calc_delay(sh_audio->afilter);
1782 // Data that was ready for ao but was buffered because ao didn't fully
1783 // accept everything to internal buffers yet
1784 buffered_output += sh_audio->a_out_buffer_len;
1786 // Filters divide audio length by playback_speed, so multiply by it
1787 // to get the length in original units without speedup or slowdown
1788 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1790 return a_pts + mpctx->video_offset;
1793 // Return pts value corresponding to currently playing audio.
1794 double playing_audio_pts(struct MPContext *mpctx)
1796 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1797 mpctx->audio_out->get_delay();
1800 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1801 struct MPOpts *opts = &mpctx->opts;
1802 // check for frame-drop:
1803 current_module = "check_framedrop";
1804 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1805 static int dropped_frames;
1806 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1807 float d = delay-mpctx->delay;
1808 ++total_frame_cnt;
1809 // we should avoid dropping too many frames in sequence unless we
1810 // are too late. and we allow 100ms A-V delay here:
1811 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1812 && !mpctx->restart_playback) {
1813 ++drop_frame_cnt;
1814 ++dropped_frames;
1815 return frame_dropping;
1816 } else
1817 dropped_frames = 0;
1819 return 0;
1823 #ifdef HAVE_RTC
1824 int rtc_fd = -1;
1825 #endif
1827 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1829 #ifdef HAVE_RTC
1830 if (rtc_fd >= 0){
1831 // -------- RTC -----------
1832 current_module="sleep_rtc";
1833 while (time_frame > 0.000) {
1834 unsigned long rtc_ts;
1835 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1836 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1837 time_frame -= get_relative_time(mpctx);
1839 } else
1840 #endif
1842 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1843 // unnecessarily high CPU usage
1844 struct MPOpts *opts = &mpctx->opts;
1845 float margin = opts->softsleep ? 0.011 : 0;
1846 current_module = "sleep_timer";
1847 while (time_frame > margin) {
1848 usec_sleep(1000000 * (time_frame - margin));
1849 time_frame -= get_relative_time(mpctx);
1851 if (opts->softsleep){
1852 current_module = "sleep_soft";
1853 if (time_frame < 0)
1854 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1855 while (time_frame > 0)
1856 time_frame -= get_relative_time(mpctx); // burn the CPU
1859 return time_frame;
1862 static int select_subtitle(MPContext *mpctx)
1864 struct MPOpts *opts = &mpctx->opts;
1865 // find the best sub to use
1866 int id;
1867 int found = 0;
1868 mpctx->global_sub_pos = -1; // no subs by default
1869 if (vobsub_id >= 0) {
1870 // if user asks for a vobsub id, use that first.
1871 id = vobsub_id;
1872 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1875 if (!found && opts->sub_id >= 0) {
1876 // if user asks for a dvd sub id, use that next.
1877 id = opts->sub_id;
1878 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1881 if (!found) {
1882 // if there are text subs to use, use those. (autosubs come last here)
1883 id = 0;
1884 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1887 if (!found && opts->sub_id == -1) {
1888 // finally select subs by language and container hints
1889 if (opts->sub_id == -1)
1890 opts->sub_id =
1891 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
1892 opts->sub_lang);
1893 if (opts->sub_id >= 0) {
1894 id = opts->sub_id;
1895 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1898 return found;
1901 #ifdef CONFIG_DVDNAV
1902 #ifndef FF_B_TYPE
1903 #define FF_B_TYPE 3
1904 #endif
1905 /// store decoded video image
1906 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1907 mp_image_t *from_mpi) {
1908 mp_image_t *mpi;
1910 /// Do not store B-frames
1911 if (from_mpi->pict_type == FF_B_TYPE)
1912 return to_mpi;
1914 if (to_mpi &&
1915 to_mpi->w == from_mpi->w &&
1916 to_mpi->h == from_mpi->h &&
1917 to_mpi->imgfmt == from_mpi->imgfmt)
1918 mpi = to_mpi;
1919 else {
1920 if (to_mpi)
1921 free_mp_image(to_mpi);
1922 if (from_mpi->w == 0 || from_mpi->h == 0)
1923 return NULL;
1924 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1927 copy_mpi(mpi,from_mpi);
1928 return mpi;
1931 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1932 struct MPOpts *opts = &ctx->opts;
1933 if (ctx->sh_video) {
1934 /// clear video pts
1935 ctx->d_video->pts = 0.0f;
1936 ctx->sh_video->pts = 0.0f;
1937 ctx->sh_video->i_pts = 0.0f;
1938 ctx->sh_video->last_pts = 0.0f;
1939 ctx->sh_video->num_buffered_pts = 0;
1940 ctx->sh_video->num_frames = 0;
1941 ctx->sh_video->num_frames_decoded = 0;
1942 ctx->sh_video->timer = 0.0f;
1943 ctx->sh_video->stream_delay = 0.0f;
1944 ctx->sh_video->timer = 0;
1945 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1948 if (ctx->sh_audio) {
1949 /// free audio packets and reset
1950 ds_free_packs(ctx->d_audio);
1951 audio_delay -= ctx->sh_audio->stream_delay;
1952 ctx->delay =- audio_delay;
1953 ctx->audio_out->reset();
1954 resync_audio_stream(ctx->sh_audio);
1957 audio_delay = 0.0f;
1958 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
1959 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
1960 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
1961 if (dvdsub_lang_id != opts->sub_id) {
1962 opts->sub_id = dvdsub_lang_id;
1963 select_subtitle(ctx);
1967 /// clear all EOF related flags
1968 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1971 /// Restore last decoded DVDNAV (still frame)
1972 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
1973 int *in_size,
1974 unsigned char **start,
1975 mp_image_t *decoded_frame)
1977 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1978 return decoded_frame;
1980 /// a change occured in dvdnav stream
1981 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
1982 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
1983 mp_dvdnav_context_free(mpctx);
1984 mp_dvdnav_reset_stream(mpctx);
1985 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
1986 mp_dvdnav_cell_has_changed(mpctx->stream,1);
1989 if (*in_size < 0) {
1990 float len;
1992 /// Display still frame, if any
1993 if (mpctx->nav_smpi && !mpctx->nav_buffer)
1994 decoded_frame = mpctx->nav_smpi;
1996 /// increment video frame : continue playing after still frame
1997 len = get_time_length(mpctx);
1998 if (mpctx->sh_video->pts >= len &&
1999 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2000 mp_dvdnav_skip_still(mpctx->stream);
2001 mp_dvdnav_skip_wait(mpctx->stream);
2003 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2005 if (mpctx->nav_buffer) {
2006 *start = mpctx->nav_start;
2007 *in_size = mpctx->nav_in_size;
2008 if (mpctx->nav_start)
2009 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2013 return decoded_frame;
2016 /// Save last decoded DVDNAV (still frame)
2017 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2018 unsigned char *start,
2019 mp_image_t *decoded_frame)
2021 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2022 return;
2024 free(mpctx->nav_buffer);
2026 mpctx->nav_buffer = malloc(in_size);
2027 mpctx->nav_start = start;
2028 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2029 if (mpctx->nav_buffer)
2030 memcpy(mpctx->nav_buffer,start,in_size);
2032 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2033 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2035 #endif /* CONFIG_DVDNAV */
2037 /* Modify video timing to match the audio timeline. There are two main
2038 * reasons this is needed. First, video and audio can start from different
2039 * positions at beginning of file or after a seek (MPlayer starts both
2040 * immediately even if they have different pts). Second, the file can have
2041 * audio timestamps that are inconsistent with the duration of the audio
2042 * packets, for example two consecutive timestamp values differing by
2043 * one second but only a packet with enough samples for half a second
2044 * of playback between them.
2046 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2048 current_module = "av_sync";
2050 if (!mpctx->sh_audio || mpctx->syncing_audio)
2051 return;
2053 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2054 double v_pts = mpctx->sh_video->pts;
2055 double av_delay = a_pts - v_pts;
2056 // Try to sync vo_flip() so it will *finish* at given time
2057 av_delay += mpctx->last_vo_flip_duration;
2058 av_delay -= audio_delay; // This much pts difference is desired
2060 double change = av_delay * 0.1;
2061 double max_change = default_max_pts_correction >= 0 ?
2062 default_max_pts_correction : frame_time * 0.1;
2063 if (change < -max_change)
2064 change = -max_change;
2065 else if (change > max_change)
2066 change = max_change;
2067 mpctx->delay += change;
2068 mpctx->total_avsync_change += change;
2071 #define ASYNC_PLAY_DONE -3
2072 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2074 struct MPOpts *opts = &mpctx->opts;
2075 sh_audio_t * const sh_audio = mpctx->sh_audio;
2076 int res;
2078 // Timing info may not be set without
2079 res = decode_audio(sh_audio, 1);
2080 if (res < 0)
2081 return res;
2083 int bytes;
2084 bool did_retry = false;
2085 while (1) {
2086 double written_pts = written_audio_pts(mpctx);
2087 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2088 - audio_delay;
2089 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2090 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2092 // ogg demuxers give packets without timing
2093 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2094 if (!did_retry) {
2095 // Try to read more data to see packets that have pts
2096 int res = decode_audio(sh_audio, ao_data.bps);
2097 if (res < 0)
2098 return res;
2099 did_retry = true;
2100 continue;
2102 bytes = 0;
2105 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2106 bytes = 0;
2108 if (bytes > 0)
2109 break;
2111 mpctx->syncing_audio = false;
2112 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2113 int res = decode_audio(sh_audio, a);
2114 bytes += sh_audio->a_out_buffer_len;
2115 if (bytes >= 0) {
2116 memmove(sh_audio->a_out_buffer,
2117 sh_audio->a_out_buffer +
2118 sh_audio->a_out_buffer_len - bytes,
2119 bytes);
2120 sh_audio->a_out_buffer_len = bytes;
2121 if (res < 0)
2122 return res;
2123 return decode_audio(sh_audio, playsize);
2125 sh_audio->a_out_buffer_len = 0;
2126 if (res < 0)
2127 return res;
2129 int fillbyte = 0;
2130 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2131 fillbyte = 0x80;
2132 if (bytes >= playsize) {
2133 /* This case could fall back to the one below with
2134 * bytes = playsize, but then silence would keep accumulating
2135 * in a_out_buffer if the AO accepts less data than it asks for
2136 * in playsize. */
2137 char *p = malloc(playsize);
2138 memset(p, fillbyte, playsize);
2139 playsize = mpctx->audio_out->play(p, playsize, 0);
2140 free(p);
2141 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2142 return ASYNC_PLAY_DONE;
2144 mpctx->syncing_audio = false;
2145 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2146 return decode_audio(sh_audio, playsize);
2149 static int fill_audio_out_buffers(struct MPContext *mpctx)
2151 struct MPOpts *opts = &mpctx->opts;
2152 unsigned int t;
2153 double tt;
2154 int playsize;
2155 int playflags=0;
2156 int audio_eof=0;
2157 bool format_change = false;
2158 sh_audio_t * const sh_audio = mpctx->sh_audio;
2160 current_module="play_audio";
2162 while (1) {
2163 int sleep_time;
2164 // all the current uses of ao_data.pts seem to be in aos that handle
2165 // sync completely wrong; there should be no need to use ao_data.pts
2166 // in get_space()
2167 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2168 playsize = mpctx->audio_out->get_space();
2169 if (mpctx->sh_video || playsize >= ao_data.outburst)
2170 break;
2172 // handle audio-only case:
2173 // this is where mplayer sleeps during audio-only playback
2174 // to avoid 100% CPU use
2175 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2176 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2177 usec_sleep(sleep_time * 1000);
2180 // Fill buffer if needed:
2181 current_module="decode_audio";
2182 t = GetTimer();
2184 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2185 mpctx->syncing_audio = false;
2187 int res;
2188 if (mpctx->syncing_audio && mpctx->sh_video)
2189 res = audio_start_sync(mpctx, playsize);
2190 else
2191 res = decode_audio(sh_audio, playsize);
2192 if (res < 0) { // EOF, error or format change
2193 if (res == -2)
2194 format_change = true;
2195 else if (res == ASYNC_PLAY_DONE)
2196 return 1;
2197 else if (mpctx->d_audio->eof) {
2198 audio_eof = 1;
2199 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2200 if (sh_audio->a_out_buffer_len < unitsize)
2201 return 0;
2204 t = GetTimer() - t;
2205 tt = t*0.000001f; audio_time_usage+=tt;
2206 if (playsize > sh_audio->a_out_buffer_len) {
2207 playsize = sh_audio->a_out_buffer_len;
2208 if (audio_eof)
2209 playflags |= AOPLAY_FINAL_CHUNK;
2211 if (!playsize)
2212 return 1;
2214 // play audio:
2215 current_module="play_audio";
2217 // Is this pts value actually useful for the aos that access it?
2218 // They're obviously badly broken in the way they handle av sync;
2219 // would not having access to this make them more broken?
2220 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2221 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2223 if (playsize > 0) {
2224 sh_audio->a_out_buffer_len -= playsize;
2225 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2226 sh_audio->a_out_buffer_len);
2227 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2228 } else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2229 // Sanity check to avoid hanging in case current ao doesn't output
2230 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2231 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2232 sh_audio->a_out_buffer_len = 0;
2235 /* The format change isn't handled too gracefully. A more precise
2236 * implementation would require draining buffered old-format audio
2237 * while displaying video, then doing the output format switch.
2239 if (format_change) {
2240 uninit_player(mpctx, INITIALIZED_AO);
2241 reinit_audio_chain(mpctx);
2244 return 1;
2247 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2248 float *aq_sleep_time)
2250 struct MPOpts *opts = &mpctx->opts;
2251 double audio_limit = 2;
2252 current_module="calc_sleep_time";
2254 if (mpctx->restart_playback)
2255 return 0;
2257 *time_frame -= get_relative_time(mpctx); // reset timer
2259 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2260 float delay = mpctx->audio_out->get_delay();
2261 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2263 if (opts->autosync) {
2265 * Adjust this raw delay value by calculating the expected
2266 * delay for this frame and generating a new value which is
2267 * weighted between the two. The higher autosync is, the
2268 * closer to the delay value gets to that which "-nosound"
2269 * would have used, and the longer it will take for A/V
2270 * sync to settle at the right value (but it eventually will.)
2271 * This settling time is very short for values below 100.
2273 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2274 float difference = delay - predicted;
2275 delay = predicted + difference / (float)opts->autosync;
2278 *time_frame = delay - mpctx->delay / opts->playback_speed;
2280 // delay = amount of audio buffered in soundcard/driver
2281 delay = FFMIN(delay, 0.5);
2282 delay = FFMAX(delay, 0.1);
2283 audio_limit = delay;
2284 } else {
2285 // If we're lagging more than 200 ms behind the right playback rate,
2286 // don't try to "catch up".
2287 // If benchmark is set always output frames as fast as possible
2288 // without sleeping.
2289 if (*time_frame < -0.2 || opts->benchmark)
2290 *time_frame = 0;
2293 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2295 if (t <= 0.05)
2296 return 0;
2298 t -= 0.05;
2299 if (t > audio_limit * 0.6)
2300 t = audio_limit * 0.5;
2301 *aq_sleep_time += t;
2302 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2303 return 1;
2306 int reinit_video_chain(struct MPContext *mpctx)
2308 struct MPOpts *opts = &mpctx->opts;
2309 sh_video_t * const sh_video = mpctx->sh_video;
2310 double ar=-1.0;
2311 //================== Init VIDEO (codec & libvo) ==========================
2312 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2313 current_module="preinit_libvo";
2315 //shouldn't we set dvideo->id=-2 when we fail?
2316 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2317 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2318 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2319 goto err_out;
2321 mpctx->initialized_flags|=INITIALIZED_VO;
2324 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2325 mpctx->sh_video->stream_aspect = ar;
2326 current_module="init_video_filters";
2328 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2329 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2331 #ifdef CONFIG_MENU
2332 if(use_menu) {
2333 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2334 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2335 if(!vf_menu) {
2336 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2337 use_menu = 0;
2340 if(vf_menu)
2341 sh_video->vfilter = vf_menu;
2342 #endif
2344 #ifdef CONFIG_ASS
2345 if(opts->ass_enabled) {
2346 int i;
2347 int insert = 1;
2348 if (opts->vf_settings)
2349 for (i = 0; opts->vf_settings[i].name; ++i)
2350 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2351 insert = 0;
2352 break;
2354 if (insert) {
2355 extern vf_info_t vf_info_ass;
2356 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2357 char* vf_arg[] = {"auto", "1", NULL};
2358 int retcode = 0;
2359 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2360 sh_video->vfilter,
2361 "ass", vf_arg,
2362 &retcode);
2363 if (vf_ass)
2364 sh_video->vfilter = vf_ass;
2365 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2366 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2367 else
2368 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2371 #endif
2373 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2375 #ifdef CONFIG_ASS
2376 if (opts->ass_enabled)
2377 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2378 #endif
2380 current_module="init_video_codec";
2382 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2383 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2384 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2386 if(!sh_video->initialized){
2387 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2388 goto err_out;
2391 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2393 if (sh_video->codec)
2394 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2396 sh_video->last_pts = MP_NOPTS_VALUE;
2397 sh_video->num_buffered_pts = 0;
2398 sh_video->next_frame_time = 0;
2400 if (opts->auto_quality > 0) {
2401 // Auto quality option enabled
2402 output_quality=get_video_quality_max(sh_video);
2403 if (opts->auto_quality > output_quality)
2404 opts->auto_quality = output_quality;
2405 else
2406 output_quality = opts->auto_quality;
2407 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2408 set_video_quality(sh_video,output_quality);
2411 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2413 current_module="init_vo";
2415 return 1;
2417 err_out:
2418 mpctx->sh_video = mpctx->d_video->sh = NULL;
2419 return 0;
2422 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2424 struct sh_video *sh_video = mpctx->sh_video;
2425 double frame_time = 0;
2426 struct vo *video_out = mpctx->video_out;
2427 while (1) {
2428 current_module = "filter_video";
2429 // In nocorrect-pts mode there is no way to properly time these frames
2430 if (vo_get_buffered_frame(video_out, 0) >= 0)
2431 break;
2432 if (vf_output_queued_frame(sh_video->vfilter))
2433 break;
2434 unsigned char *packet = NULL;
2435 frame_time = sh_video->next_frame_time;
2436 if (mpctx->restart_playback)
2437 frame_time = 0;
2438 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2439 &packet, force_fps);
2440 if (in_size < 0) {
2441 #ifdef CONFIG_DVDNAV
2442 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2443 if (mp_dvdnav_is_eof(mpctx->stream))
2444 return -1;
2445 if (mpctx->d_video)
2446 mpctx->d_video->eof = 0;
2447 if (mpctx->d_audio)
2448 mpctx->d_audio->eof = 0;
2449 mpctx->stream->eof = 0;
2450 } else
2451 #endif
2452 return -1;
2454 if (in_size > max_framesize)
2455 max_framesize = in_size;
2456 sh_video->timer += frame_time;
2457 if (mpctx->sh_audio)
2458 mpctx->delay -= frame_time;
2459 // video_read_frame can change fps (e.g. for ASF video)
2460 vo_fps = sh_video->fps;
2461 int framedrop_type = check_framedrop(mpctx, frame_time);
2462 current_module = "decode video";
2464 void *decoded_frame;
2465 #ifdef CONFIG_DVDNAV
2466 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2467 if (in_size >= 0 && !decoded_frame)
2468 #endif
2469 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2470 sh_video->pts);
2471 #ifdef CONFIG_DVDNAV
2472 // Save last still frame for future display
2473 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2474 #endif
2475 if (decoded_frame) {
2476 current_module = "filter video";
2477 filter_video(sh_video, decoded_frame, sh_video->pts);
2479 break;
2481 return frame_time;
2484 static void determine_frame_pts(struct MPContext *mpctx)
2486 struct sh_video *sh_video = mpctx->sh_video;
2487 struct MPOpts *opts = &mpctx->opts;
2489 if (opts->user_pts_assoc_mode) {
2490 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2491 } else if (sh_video->pts_assoc_mode == 0) {
2492 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2493 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2494 sh_video->pts_assoc_mode = 1;
2495 else
2496 sh_video->pts_assoc_mode = 2;
2497 } else {
2498 int probcount1 = sh_video->num_reordered_pts_problems;
2499 int probcount2 = sh_video->num_sorted_pts_problems;
2500 if (sh_video->pts_assoc_mode == 2) {
2501 int tmp = probcount1;
2502 probcount1 = probcount2;
2503 probcount2 = tmp;
2505 if (probcount1 >= probcount2 * 1.5 + 2) {
2506 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2507 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2508 "%d.\n", sh_video->pts_assoc_mode);
2511 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2512 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2515 static double update_video(struct MPContext *mpctx)
2517 struct sh_video *sh_video = mpctx->sh_video;
2518 struct vo *video_out = mpctx->video_out;
2519 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2520 mpctx->osd); // hack for vf_expand
2521 if (!mpctx->opts.correct_pts)
2522 return update_video_nocorrect_pts(mpctx);
2524 double pts;
2526 while (1) {
2527 current_module = "filter_video";
2528 if (!mpctx->hrseek_active
2529 && vo_get_buffered_frame(video_out, false) >= 0)
2530 break;
2531 // XXX Time used in this call is not counted in any performance
2532 // timer now
2533 if (vf_output_queued_frame(sh_video->vfilter))
2534 break;
2535 unsigned char *packet = NULL;
2536 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2537 if (pts != MP_NOPTS_VALUE)
2538 pts += mpctx->video_offset;
2539 bool hit_eof = false;
2540 if (in_size < 0) {
2541 // try to extract last frames in case of decoder lag
2542 in_size = 0;
2543 pts = MP_NOPTS_VALUE;
2544 hit_eof = true;
2546 if (in_size > max_framesize)
2547 max_framesize = in_size;
2548 current_module = "decode video";
2549 if (pts >= mpctx->hrseek_pts - .005)
2550 mpctx->hrseek_framedrop = false;
2551 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2552 check_framedrop(mpctx, sh_video->frametime);
2553 void *decoded_frame = decode_video(sh_video, packet, in_size,
2554 framedrop_type, pts);
2555 if (decoded_frame) {
2556 determine_frame_pts(mpctx);
2557 current_module = "filter video";
2558 filter_video(sh_video, decoded_frame, sh_video->pts);
2559 } else if (hit_eof) {
2560 if (vo_get_buffered_frame(video_out, true) < 0)
2561 return -1;
2563 break;
2566 if (!video_out->frame_loaded)
2567 return 0;
2569 pts = video_out->next_pts;
2570 if (pts == MP_NOPTS_VALUE) {
2571 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2572 // Try to use decoder pts from before filters
2573 pts = sh_video->pts;
2574 if (pts == MP_NOPTS_VALUE)
2575 pts = sh_video->last_pts;
2577 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005)
2578 return 0;
2579 mpctx->hrseek_active = false;
2580 sh_video->pts = pts;
2581 if (sh_video->last_pts == MP_NOPTS_VALUE)
2582 sh_video->last_pts = sh_video->pts;
2583 else if (sh_video->last_pts > sh_video->pts) {
2584 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2585 sh_video->pts, sh_video->last_pts);
2586 /* If the difference in pts is small treat it as jitter around the
2587 * right value (possibly caused by incorrect timestamp ordering) and
2588 * just show this frame immediately after the last one.
2589 * Treat bigger differences as timestamp resets and start counting
2590 * timing of later frames from the position of this one. */
2591 if (sh_video->last_pts - sh_video->pts > 0.5)
2592 sh_video->last_pts = sh_video->pts;
2593 else
2594 sh_video->pts = sh_video->last_pts;
2596 double frame_time = sh_video->pts - sh_video->last_pts;
2597 sh_video->last_pts = sh_video->pts;
2598 sh_video->timer += frame_time;
2599 if (mpctx->sh_audio)
2600 mpctx->delay -= frame_time;
2601 return frame_time;
2604 void pause_player(struct MPContext *mpctx)
2606 if (mpctx->paused)
2607 return;
2608 mpctx->paused = 1;
2609 mpctx->step_frames = 0;
2610 mpctx->time_frame -= get_relative_time(mpctx);
2612 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2613 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2615 if (mpctx->audio_out && mpctx->sh_audio)
2616 mpctx->audio_out->pause(); // pause audio, keep data if possible
2619 void unpause_player(struct MPContext *mpctx)
2621 if (!mpctx->paused)
2622 return;
2623 mpctx->paused = 0;
2625 if (mpctx->audio_out && mpctx->sh_audio)
2626 mpctx->audio_out->resume(); // resume audio
2627 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2628 && !mpctx->step_frames)
2629 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2630 (void)get_relative_time(mpctx); // ignore time that passed during pause
2633 void add_step_frame(struct MPContext *mpctx)
2635 mpctx->step_frames++;
2636 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2637 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2638 unpause_player(mpctx);
2641 static void pause_loop(struct MPContext *mpctx)
2643 struct MPOpts *opts = &mpctx->opts;
2644 mp_cmd_t* cmd;
2645 if (!opts->quiet) {
2646 // Small hack to display the pause message on the OSD line.
2647 // The pause string is: "\n == PAUSE == \r" so we need to
2648 // take the first and the last char out
2649 if (opts->term_osd && !mpctx->sh_video) {
2650 char msg[128] = _("\n ===== PAUSE =====\r");
2651 int mlen = strlen(msg);
2652 msg[mlen-1] = '\0';
2653 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2654 update_osd_msg(mpctx);
2655 } else
2656 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2657 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2660 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2661 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2662 if (cmd) {
2663 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2664 run_command(mpctx, cmd);
2665 mp_cmd_free(cmd);
2666 continue;
2668 if (mpctx->sh_video && mpctx->video_out)
2669 vo_check_events(mpctx->video_out);
2670 #ifdef CONFIG_MENU
2671 if (vf_menu)
2672 vf_menu_pause_update(vf_menu);
2673 #endif
2674 usec_sleep(20000);
2675 update_osd_msg(mpctx);
2676 int hack = vo_osd_changed(0);
2677 vo_osd_changed(hack);
2678 if (hack)
2679 break;
2684 // Find the right mute status and record position for new file position
2685 static void edl_seek_reset(MPContext *mpctx)
2687 mpctx->edl_muted = 0;
2688 next_edl_record = edl_records;
2690 while (next_edl_record) {
2691 if (next_edl_record->start_sec >= get_current_time(mpctx))
2692 break;
2694 if (next_edl_record->action == EDL_MUTE)
2695 mpctx->edl_muted = !mpctx->edl_muted;
2696 next_edl_record = next_edl_record->next;
2698 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2699 mixer_mute(&mpctx->mixer);
2703 // Execute EDL command for the current position if one exists
2704 static void edl_update(MPContext *mpctx)
2706 if (!next_edl_record)
2707 return;
2709 if (!mpctx->sh_video) {
2710 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2711 free_edl(edl_records);
2712 next_edl_record = NULL;
2713 edl_records = NULL;
2714 return;
2717 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2718 if (next_edl_record->action == EDL_SKIP) {
2719 mpctx->osd_function = OSD_FFW;
2720 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2721 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2722 "[%f], length [%f]\n", next_edl_record->start_sec,
2723 next_edl_record->stop_sec, next_edl_record->length_sec);
2725 else if (next_edl_record->action == EDL_MUTE) {
2726 mpctx->edl_muted = !mpctx->edl_muted;
2727 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2728 mixer_mute(&mpctx->mixer);
2729 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2730 next_edl_record->start_sec );
2732 next_edl_record = next_edl_record->next;
2736 static void reinit_decoders(struct MPContext *mpctx)
2738 reinit_video_chain(mpctx);
2739 reinit_audio_chain(mpctx);
2740 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2743 static void seek_reset(struct MPContext *mpctx)
2745 if (mpctx->sh_video) {
2746 current_module = "seek_video_reset";
2747 resync_video_stream(mpctx->sh_video);
2748 mpctx->sh_video->timer = 0;
2749 vo_seek_reset(mpctx->video_out);
2750 mpctx->sh_video->timer = 0;
2751 mpctx->sh_video->num_buffered_pts = 0;
2752 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2753 mpctx->delay = 0;
2754 mpctx->time_frame = 0;
2755 mpctx->restart_playback = true;
2756 // Not all demuxers set d_video->pts during seek, so this value
2757 // (which is used by at least vobsub and edl code below) may
2758 // be completely wrong (probably 0).
2759 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2760 mpctx->video_pts = mpctx->sh_video->pts;
2761 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2762 mpctx->sh_video->pts, mpctx->video_offset,
2763 mpctx->d_sub, 1);
2764 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2767 if (mpctx->sh_audio) {
2768 current_module = "seek_audio_reset";
2769 resync_audio_stream(mpctx->sh_audio);
2770 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2771 mpctx->sh_audio->a_buffer_len = 0;
2772 mpctx->sh_audio->a_out_buffer_len = 0;
2773 if (!mpctx->sh_video)
2774 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2775 mpctx->video_offset, mpctx->d_sub, 1);
2778 if (vo_vobsub && mpctx->sh_video) {
2779 current_module = "seek_vobsub_reset";
2780 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2783 edl_seek_reset(mpctx);
2785 mpctx->hrseek_active = false;
2786 mpctx->hrseek_framedrop = false;
2787 mpctx->total_avsync_change = 0;
2788 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2789 drop_frame_cnt = 0;
2791 current_module = NULL;
2794 static bool timeline_set_part(struct MPContext *mpctx, int i)
2796 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2797 struct timeline_part *n = mpctx->timeline + i;
2798 mpctx->timeline_part = i;
2799 mpctx->video_offset = n->start - n->source_start;
2800 if (n->source == p->source)
2801 return false;
2802 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2803 mpctx->demuxer = n->source->demuxer;
2804 mpctx->d_video = mpctx->demuxer->video;
2805 mpctx->d_audio = mpctx->demuxer->audio;
2806 mpctx->d_sub = mpctx->demuxer->sub;
2807 mpctx->sh_video = mpctx->d_video->sh;
2808 mpctx->sh_audio = mpctx->d_audio->sh;
2809 return true;
2812 // Given pts, switch playback to the corresponding part.
2813 // Return offset within that part.
2814 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2815 bool *need_reset)
2817 if (pts < 0)
2818 pts = 0;
2819 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2820 struct timeline_part *p = mpctx->timeline + i;
2821 if (pts < (p+1)->start) {
2822 *need_reset = timeline_set_part(mpctx, i);
2823 return pts - p->start + p->source_start;
2826 return -1;
2830 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2831 static int seek(MPContext *mpctx, struct seek_params seek)
2833 struct MPOpts *opts = &mpctx->opts;
2835 current_module = "seek";
2836 if (mpctx->stop_play == AT_END_OF_FILE)
2837 mpctx->stop_play = KEEP_PLAYING;
2838 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
2839 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
2840 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
2841 || opts->hr_seek > 0 || seek.exact > 0;
2842 if (seek.type == MPSEEK_FACTOR
2843 || seek.type == MPSEEK_ABSOLUTE
2844 && seek.amount < mpctx->last_chapter_pts
2845 || seek.amount < 0)
2846 mpctx->last_chapter_seek = -1;
2847 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
2848 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2849 seek.type = MPSEEK_ABSOLUTE;
2851 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
2852 && seek.type == MPSEEK_RELATIVE) {
2853 seek.type = MPSEEK_ABSOLUTE;
2854 seek.direction = seek.amount > 0 ? 1 : -1;
2855 seek.amount += get_current_time(mpctx);
2858 /* At least the liba52 decoder wants to read from the input stream
2859 * during initialization, so reinit must be done after the demux_seek()
2860 * call that clears possible stream EOF. */
2861 bool need_reset = false;
2862 double demuxer_amount = seek.amount;
2863 if (mpctx->timeline) {
2864 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
2865 &need_reset);
2866 if (demuxer_amount == -1) {
2867 mpctx->stop_play = AT_END_OF_FILE;
2868 // Clear audio from current position
2869 if (mpctx->sh_audio) {
2870 mpctx->audio_out->reset();
2871 mpctx->sh_audio->a_buffer_len = 0;
2872 mpctx->sh_audio->a_out_buffer_len = 0;
2874 return -1;
2877 int demuxer_style = 0;
2878 switch (seek.type) {
2879 case MPSEEK_FACTOR:
2880 demuxer_style |= SEEK_FACTOR; // fallthrough
2881 case MPSEEK_ABSOLUTE:
2882 demuxer_style |= SEEK_ABSOLUTE;
2884 if (hr_seek || seek.direction < 0)
2885 demuxer_style |= SEEK_BACKWARD;
2886 else if (seek.direction > 0)
2887 demuxer_style |= SEEK_FORWARD;
2889 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
2890 demuxer_style);
2891 if (need_reset)
2892 reinit_decoders(mpctx);
2893 if (seekresult == 0)
2894 return -1;
2896 seek_reset(mpctx);
2898 /* Use the target time as "current position" for further relative
2899 * seeks etc until a new video frame has been decoded */
2900 if (seek.type == MPSEEK_ABSOLUTE)
2901 mpctx->video_pts = seek.amount;
2903 if (hr_seek) {
2904 mpctx->hrseek_active = true;
2905 mpctx->hrseek_framedrop = true;
2906 mpctx->hrseek_pts = seek.amount;
2909 mpctx->start_timestamp = GetTimerMS();
2911 return 0;
2914 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
2915 int exact)
2917 struct seek_params *seek = &mpctx->seek;
2918 switch (type) {
2919 case MPSEEK_RELATIVE:
2920 if (seek->type == MPSEEK_FACTOR)
2921 return; // Well... not common enough to bother doing better
2922 seek->amount += amount;
2923 seek->exact = FFMAX(seek->exact, exact);
2924 if (seek->type == MPSEEK_NONE)
2925 seek->exact = exact;
2926 if (seek->type == MPSEEK_ABSOLUTE)
2927 return;
2928 if (seek->amount == 0) {
2929 *seek = (struct seek_params){0};
2930 return;
2932 seek->type = MPSEEK_RELATIVE;
2933 return;
2934 case MPSEEK_ABSOLUTE:
2935 case MPSEEK_FACTOR:
2936 *seek = (struct seek_params) {
2937 .type = type,
2938 .amount = amount,
2939 .exact = exact,
2941 return;
2942 case MPSEEK_NONE:
2943 *seek = (struct seek_params){0};
2944 return;
2946 abort();
2950 double get_time_length(struct MPContext *mpctx)
2952 if (mpctx->timeline)
2953 return mpctx->timeline[mpctx->num_timeline_parts].start;
2955 struct demuxer *demuxer = mpctx->demuxer;
2956 double get_time_ans;
2957 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
2958 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
2959 (void *) &get_time_ans) > 0)
2960 return get_time_ans;
2962 struct sh_video *sh_video = mpctx->d_video->sh;
2963 struct sh_audio *sh_audio = mpctx->d_audio->sh;
2964 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
2965 return (double) (demuxer->movi_end - demuxer->movi_start) /
2966 (sh_video->i_bps + sh_audio->i_bps);
2967 if (sh_video && sh_video->i_bps)
2968 return (double) (demuxer->movi_end - demuxer->movi_start) /
2969 sh_video->i_bps;
2970 if (sh_audio && sh_audio->i_bps)
2971 return (double) (demuxer->movi_end - demuxer->movi_start) /
2972 sh_audio->i_bps;
2973 return 0;
2976 /* If there are timestamps from stream level then use those (for example
2977 * DVDs can have consistent times there while the MPEG-level timestamps
2978 * reset). */
2979 double get_current_time(struct MPContext *mpctx)
2981 struct demuxer *demuxer = mpctx->demuxer;
2982 if (demuxer->stream_pts != MP_NOPTS_VALUE)
2983 return demuxer->stream_pts;
2984 struct sh_video *sh_video = demuxer->video->sh;
2985 if (sh_video)
2986 return mpctx->video_pts;
2987 return playing_audio_pts(mpctx);
2990 int get_percent_pos(struct MPContext *mpctx)
2992 struct demuxer *demuxer = mpctx->demuxer;
2993 int ans = 0;
2994 if (mpctx->timeline)
2995 ans = get_current_time(mpctx) * 100 /
2996 mpctx->timeline[mpctx->num_timeline_parts].start;
2997 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
2999 else {
3000 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3001 off_t pos = demuxer->filepos > 0 ?
3002 demuxer->filepos : stream_tell(demuxer->stream);
3003 if (len > 0)
3004 ans = (pos - demuxer->movi_start) / len;
3005 else
3006 ans = 0;
3008 if (ans < 0)
3009 ans = 0;
3010 if (ans > 100)
3011 ans = 100;
3012 return ans;
3015 // -2 is no chapters, -1 is before first chapter
3016 int get_current_chapter(struct MPContext *mpctx)
3018 double current_pts = get_current_time(mpctx);
3019 if (!mpctx->chapters)
3020 return FFMAX(mpctx->last_chapter_seek,
3021 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3023 int i;
3024 for (i = 1; i < mpctx->num_chapters; i++)
3025 if (current_pts < mpctx->chapters[i].start)
3026 break;
3027 return FFMAX(mpctx->last_chapter_seek, i - 1);
3030 // currently returns a string allocated with malloc, not talloc
3031 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3033 if (!mpctx->chapters || !mpctx->sh_video)
3034 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3035 return strdup(mpctx->chapters[chapter].name);
3038 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3039 char **chapter_name)
3041 mpctx->last_chapter_seek = -1;
3042 if (!mpctx->chapters || !mpctx->sh_video) {
3043 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3044 chapter_name);
3045 if (res >= 0) {
3046 if (*seek_pts == -1)
3047 seek_reset(mpctx);
3048 else {
3049 mpctx->last_chapter_seek = res;
3050 mpctx->last_chapter_pts = *seek_pts;
3053 return res;
3056 if (chapter >= mpctx->num_chapters)
3057 return -1;
3058 if (chapter < 0)
3059 chapter = 0;
3060 *seek_pts = mpctx->chapters[chapter].start;
3061 mpctx->last_chapter_seek = chapter;
3062 mpctx->last_chapter_pts = *seek_pts;
3063 if (chapter_name)
3064 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3065 return chapter;
3069 static void run_playloop(struct MPContext *mpctx)
3071 struct MPOpts *opts = &mpctx->opts;
3072 float aq_sleep_time = 0;
3074 if (opts->chapterrange[1] > 0) {
3075 int cur_chapter = get_current_chapter(mpctx);
3076 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3077 mpctx->stop_play = PT_NEXT_ENTRY;
3080 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3081 mpctx->sh_audio = mpctx->d_audio->sh;
3082 mpctx->sh_audio->ds = mpctx->d_audio;
3083 reinit_audio_chain(mpctx);
3086 /*========================== PLAY AUDIO ============================*/
3088 if (mpctx->sh_audio && !mpctx->paused
3089 && (!mpctx->restart_playback || !mpctx->sh_video))
3090 if (!fill_audio_out_buffers(mpctx))
3091 // at eof, all audio at least written to ao
3092 if (!mpctx->sh_video)
3093 mpctx->stop_play = AT_END_OF_FILE;
3096 if (!mpctx->sh_video) {
3097 mpctx->restart_playback = false;
3098 if (mpctx->step_frames) {
3099 mpctx->step_frames = 0;
3100 pause_player(mpctx);
3102 // handle audio-only case:
3103 double a_pos = 0;
3104 // sh_audio can be NULL due to video stream switching
3105 // TODO: handle this better
3106 if (mpctx->sh_audio)
3107 a_pos = playing_audio_pts(mpctx);
3109 print_status(mpctx, a_pos, false);
3111 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3112 mpctx->stop_play = PT_NEXT_ENTRY;
3113 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
3114 mpctx->d_sub, 0);
3115 update_osd_msg(mpctx);
3116 } else {
3118 /*========================== PLAY VIDEO ============================*/
3120 vo_pts = mpctx->sh_video->timer * 90000.0;
3121 vo_fps = mpctx->sh_video->fps;
3123 bool blit_frame = mpctx->video_out->frame_loaded;
3124 if (!blit_frame || mpctx->hrseek_active) {
3125 double frame_time = update_video(mpctx);
3126 blit_frame = mpctx->video_out->frame_loaded;
3127 blit_frame &= !mpctx->hrseek_active;
3128 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3129 if (mpctx->sh_video->vf_initialized < 0) {
3130 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3131 "\nFATAL: Could not initialize video filters (-vf) "
3132 "or video output (-vo).\n");
3133 mpctx->stop_play = PT_NEXT_ENTRY;
3134 return;
3136 if (frame_time < 0)
3137 mpctx->stop_play = AT_END_OF_FILE;
3138 else if (!mpctx->restart_playback) {
3139 mpctx->time_frame += frame_time / opts->playback_speed;
3140 adjust_sync(mpctx, frame_time);
3143 if (mpctx->timeline) {
3144 struct timeline_part *next =
3145 mpctx->timeline + mpctx->timeline_part + 1;
3146 if (mpctx->sh_video->pts >= next->start
3147 || mpctx->stop_play == AT_END_OF_FILE
3148 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3149 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3150 .amount = next->start });
3151 return;
3155 // ==========================================================================
3157 current_module = "vo_check_events";
3158 vo_check_events(mpctx->video_out);
3160 #ifdef CONFIG_X11
3161 if (stop_xscreensaver) {
3162 current_module = "stop_xscreensaver";
3163 xscreensaver_heartbeat(mpctx->x11_state);
3165 #endif
3166 if (heartbeat_cmd) {
3167 static unsigned last_heartbeat;
3168 unsigned now = GetTimerMS();
3169 if (now - last_heartbeat > 30000) {
3170 last_heartbeat = now;
3171 system(heartbeat_cmd);
3175 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3176 &mpctx->time_frame,
3177 &aq_sleep_time);
3179 //====================== FLIP PAGE (VIDEO BLT): =========================
3181 current_module = "flip_page";
3182 if (!frame_time_remaining && blit_frame) {
3183 struct sh_video *sh_video = mpctx->sh_video;
3184 mpctx->video_pts = sh_video->pts;
3185 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
3186 mpctx->video_offset, mpctx->d_sub, 0);
3187 update_teletext(sh_video, mpctx->demuxer, 0);
3188 update_osd_msg(mpctx);
3189 struct vf_instance *vf = sh_video->vfilter;
3190 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3191 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3192 vo_osd_changed(0);
3194 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3195 aq_sleep_time += mpctx->time_frame;
3196 // flag 256 means: libvo driver does its timing (dvb card)
3197 if (mpctx->time_frame > 0.001
3198 && !(mpctx->sh_video->output_flags&256))
3199 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3200 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3202 unsigned int t2 = GetTimer();
3203 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
3204 int duration = -1;
3205 double pts2 = mpctx->video_out->next_pts2;
3206 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3207 && !mpctx->restart_playback) {
3208 // expected A/V sync correction is ignored
3209 double diff = (pts2 - mpctx->video_pts);
3210 diff /= opts->playback_speed;
3211 if (mpctx->time_frame < 0)
3212 diff += mpctx->time_frame;
3213 if (diff < 0)
3214 diff = 0;
3215 if (diff > 10)
3216 diff = 10;
3217 duration = diff * 1e6;
3219 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3221 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3222 vout_time_usage += mpctx->last_vo_flip_duration;
3223 if (mpctx->video_out->driver->flip_page_timed) {
3224 // No need to adjust sync based on flip speed
3225 mpctx->last_vo_flip_duration = 0;
3226 // For print_status - VO call finishing early is OK for sync
3227 mpctx->time_frame -= get_relative_time(mpctx);
3229 if (mpctx->restart_playback) {
3230 mpctx->syncing_audio = true;
3231 if (mpctx->sh_audio && !mpctx->paused)
3232 fill_audio_out_buffers(mpctx);
3233 mpctx->restart_playback = false;
3234 mpctx->time_frame = 0;
3235 get_relative_time(mpctx);
3237 print_status(mpctx, MP_NOPTS_VALUE, true);
3238 } else
3239 print_status(mpctx, MP_NOPTS_VALUE, false);
3241 //============================ Auto QUALITY ============================
3243 /*Output quality adjustments:*/
3244 if (opts->auto_quality > 0) {
3245 current_module = "autoq";
3246 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3247 ++output_quality;
3248 else
3249 if (output_quality>1 && aq_sleep_time<0)
3250 --output_quality;
3251 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3252 output_quality = 0;
3253 set_video_quality(mpctx->sh_video, output_quality);
3256 if (!frame_time_remaining && blit_frame) {
3257 if (play_n_frames >= 0) {
3258 --play_n_frames;
3259 if (play_n_frames <= 0)
3260 mpctx->stop_play = PT_NEXT_ENTRY;
3262 if (mpctx->step_frames > 0) {
3263 mpctx->step_frames--;
3264 if (mpctx->step_frames == 0)
3265 pause_player(mpctx);
3269 // FIXME: add size based support for -endpos
3270 if (end_at.type == END_AT_TIME &&
3271 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3272 mpctx->stop_play = PT_NEXT_ENTRY;
3274 } // end if(mpctx->sh_video)
3276 #ifdef CONFIG_DVDNAV
3277 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3278 nav_highlight_t hl;
3279 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3280 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3281 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3282 vo_osd_changed(OSDTYPE_DVDNAV);
3283 } else {
3284 osd_set_nav_box(0, 0, 0, 0);
3285 vo_osd_changed(OSDTYPE_DVDNAV);
3286 vo_osd_changed(OSDTYPE_SPU);
3289 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3290 double ar = -1.0;
3291 if (mpctx->sh_video &&
3292 stream_control(mpctx->demuxer->stream,
3293 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3294 != STREAM_UNSUPPORTED)
3295 mpctx->sh_video->stream_aspect = ar;
3298 #endif
3300 //================= Keyboard events, SEEKing ====================
3302 current_module = "key_events";
3304 while (1) {
3305 mp_cmd_t *cmd;
3306 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3307 /* Allow running consecutive seek commands to combine them,
3308 * but execute the seek before running other commands.
3309 * If the user seeks continuously (keeps arrow key down)
3310 * try to finish showing a frame from one location before doing
3311 * another seek (which could lead to unchanging display). */
3312 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3313 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3314 && GetTimerMS() - mpctx->start_timestamp < 300)
3315 break;
3316 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3317 run_command(mpctx, cmd);
3318 mp_cmd_free(cmd);
3319 if (mpctx->stop_play)
3320 break;
3322 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3323 || mpctx->restart_playback)
3324 break;
3325 if (mpctx->sh_video) {
3326 update_osd_msg(mpctx);
3327 int hack = vo_osd_changed(0);
3328 vo_osd_changed(hack);
3329 if (hack) {
3330 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3331 add_step_frame(mpctx);
3332 break;
3333 } else
3334 vo_osd_changed(0);
3337 pause_loop(mpctx);
3340 // handle -sstep
3341 if (step_sec > 0 && !mpctx->paused) {
3342 mpctx->osd_function = OSD_FFW;
3343 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3346 edl_update(mpctx);
3348 /* Looping. */
3349 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3350 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3352 if (opts->loop_times>1)
3353 opts->loop_times--;
3354 else if (opts->loop_times==1)
3355 opts->loop_times = -1;
3356 play_n_frames = play_n_frames_mf;
3357 mpctx->stop_play = 0;
3358 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3361 if (mpctx->seek.type) {
3362 seek(mpctx, mpctx->seek);
3363 mpctx->seek = (struct seek_params){0};
3368 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3369 struct content_source *sources,
3370 int num_sources,
3371 unsigned char uid_map[][16])
3373 int num_filenames = 0;
3374 char **filenames = NULL;
3375 if (num_sources > 1) {
3376 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3377 "other sources.\n");
3378 if (mpctx->stream->type != STREAMTYPE_FILE) {
3379 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3380 "normal disk file. Will not search for related files.\n");
3381 } else {
3382 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3383 "same directory to find referenced sources.\n");
3384 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3385 &num_filenames);
3389 int num_left = num_sources - 1;
3390 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3391 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3392 filename_recode(filenames[i]));
3393 int format;
3394 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3395 if (!s)
3396 continue;
3397 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3398 mpctx->opts.audio_id,
3399 mpctx->opts.video_id,
3400 mpctx->opts.sub_id, filenames[i]);
3401 if (!d) {
3402 free_stream(s);
3403 continue;
3405 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3406 for (int i = 1; i < num_sources; i++) {
3407 if (sources[i].demuxer)
3408 continue;
3409 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3410 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3411 i, filename_recode(d->filename));
3412 sources[i].stream = s;
3413 sources[i].demuxer = d;
3414 num_left--;
3415 goto match;
3419 free_demuxer(d);
3420 free_stream(s);
3421 continue;
3422 match:
3425 talloc_free(filenames);
3426 if (num_left) {
3427 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3428 "There will be parts MISSING from the video!\n");
3429 for (int i = 1, j = 1; i < num_sources; i++)
3430 if (sources[i].demuxer) {
3431 sources[j] = sources[i];
3432 memcpy(uid_map[j], uid_map[i], 16);
3433 j++;
3436 return num_sources - num_left;
3439 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3441 struct MPOpts *opts = &mpctx->opts;
3443 if (!opts->ordered_chapters) {
3444 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3445 "you have disabled support for them. Ignoring.\n");
3446 return;
3449 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3450 "edit timeline.\n");
3452 struct demuxer *demuxer = mpctx->demuxer;
3453 struct matroska_data *m = &demuxer->matroska_data;
3455 // +1 because sources/uid_map[0] is original file even if all chapters
3456 // actually use other sources and need separate entries
3457 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3458 m->num_ordered_chapters+1);
3459 sources[0].stream = mpctx->stream;
3460 sources[0].demuxer = mpctx->demuxer;
3461 unsigned char uid_map[m->num_ordered_chapters+1][16];
3462 int num_sources = 1;
3463 memcpy(uid_map[0], m->segment_uid, 16);
3465 for (int i = 0; i < m->num_ordered_chapters; i++) {
3466 struct matroska_chapter *c = m->ordered_chapters + i;
3467 if (!c->has_segment_uid)
3468 memcpy(c->segment_uid, m->segment_uid, 16);
3470 for (int j = 0; j < num_sources; j++)
3471 if (!memcmp(c->segment_uid, uid_map[j], 16))
3472 goto found1;
3473 memcpy(uid_map[num_sources], c->segment_uid, 16);
3474 sources[num_sources] = (struct content_source){};
3475 num_sources++;
3476 found1:
3480 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3481 uid_map);
3484 // +1 for terminating chapter with start time marking end of last real one
3485 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3486 m->num_ordered_chapters + 1);
3487 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3488 m->num_ordered_chapters);
3489 uint64_t starttime = 0;
3490 uint64_t missing_time = 0;
3491 int part_count = 0;
3492 int num_chapters = 0;
3493 uint64_t prev_part_offset = 0;
3494 for (int i = 0; i < m->num_ordered_chapters; i++) {
3495 struct matroska_chapter *c = m->ordered_chapters + i;
3497 int j;
3498 for (j = 0; j < num_sources; j++) {
3499 if (!memcmp(c->segment_uid, uid_map[j], 16))
3500 goto found2;
3502 missing_time += c->end - c->start;
3503 continue;
3504 found2:;
3505 /* Only add a separate part if the time or file actually changes.
3506 * Matroska files have chapter divisions that are redundant from
3507 * timeline point of view because the same chapter structure is used
3508 * both to specify the timeline and for normal chapter information.
3509 * Removing a missing inserted external chapter can also cause this.
3510 * We allow for a configurable fudge factor because of files which
3511 * specify chapter end times that are one frame too early;
3512 * we don't want to try seeking over a one frame gap. */
3513 int64_t join_diff = c->start - starttime - prev_part_offset;
3514 if (part_count == 0 || FFABS(join_diff) > opts->chapter_merge_threshold
3515 || sources + j != timeline[part_count - 1].source) {
3516 timeline[part_count].source = sources + j;
3517 timeline[part_count].start = starttime / 1000.;
3518 timeline[part_count].source_start = c->start / 1000.;
3519 prev_part_offset = c->start - starttime;
3520 part_count++;
3521 } else if (part_count > 0 && join_diff) {
3522 /* Chapter was merged at an inexact boundary;
3523 * adjust timestamps to match. */
3524 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3525 "offset %d ms.\n", i, (int) join_diff);
3526 starttime += join_diff;
3528 chapters[num_chapters].start = starttime / 1000.;
3529 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3530 starttime += c->end - c->start;
3531 num_chapters++;
3533 timeline[part_count].start = starttime / 1000.;
3535 if (!part_count) {
3536 // None of the parts come from the file itself???
3537 talloc_free(sources);
3538 talloc_free(timeline);
3539 talloc_free(chapters);
3540 return;
3543 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3544 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3545 timeline[part_count].start);
3546 if (missing_time)
3547 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3548 "from the timeline!\n", missing_time / 1000.);
3549 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3550 for (int i = 0; i < num_sources; i++)
3551 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3552 filename_recode(sources[i].demuxer->filename));
3553 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3554 "source_start, source):\n");
3555 for (int i = 0; i < part_count; i++) {
3556 struct timeline_part *p = timeline + i;
3557 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3558 p->source_start, p->source - sources);
3560 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3561 mpctx->sources = sources;
3562 mpctx->num_sources = num_sources;
3563 mpctx->timeline = timeline;
3564 mpctx->num_timeline_parts = part_count;
3565 mpctx->num_chapters = num_chapters;
3566 mpctx->chapters = chapters;
3568 mpctx->timeline_part = 0;
3569 mpctx->demuxer = timeline[0].source->demuxer;
3573 static int read_keys(void *ctx, int fd)
3575 getch2(ctx);
3576 return mplayer_get_key(ctx, 0);
3580 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3581 * file for some tools to link against. */
3582 #ifndef DISABLE_MAIN
3583 int main(int argc,char* argv[]){
3586 char * mem_ptr;
3588 // movie info:
3590 /* Flag indicating whether MPlayer should exit without playing anything. */
3591 int opt_exit = 0;
3592 int i;
3594 struct MPContext *mpctx = &(struct MPContext){
3595 .osd_function = OSD_PLAY,
3596 .begin_skip = MP_NOPTS_VALUE,
3597 .play_tree_step = 1,
3598 .global_sub_pos = -1,
3599 .set_of_sub_pos = -1,
3600 .file_format = DEMUXER_TYPE_UNKNOWN,
3601 .last_dvb_step = 1,
3604 InitTimer();
3605 srand(GetTimerMS());
3607 mp_msg_init();
3608 set_av_log_callback();
3610 #ifdef CONFIG_X11
3611 mpctx->x11_state = vo_x11_init_state();
3612 #endif
3613 struct MPOpts *opts = &mpctx->opts;
3614 set_default_mplayer_options(opts);
3615 // Create the config context and register the options
3616 mpctx->mconfig = m_config_new(opts, cfg_include);
3617 m_config_register_options(mpctx->mconfig,mplayer_opts);
3618 m_config_register_options(mpctx->mconfig, common_opts);
3619 mp_input_register_options(mpctx->mconfig);
3621 // Preparse the command line
3622 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3624 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3625 set_path_env();
3626 #endif
3628 #ifdef CONFIG_TV
3629 stream_tv_defaults.immediate = 1;
3630 #endif
3632 parse_cfgfiles(mpctx, mpctx->mconfig);
3634 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3635 if(mpctx->playtree == NULL)
3636 opt_exit = 1;
3637 else {
3638 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3639 if(mpctx->playtree) {
3640 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3641 if(mpctx->playtree_iter) {
3642 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3643 play_tree_iter_free(mpctx->playtree_iter);
3644 mpctx->playtree_iter = NULL;
3646 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3650 mpctx->key_fifo = mp_fifo_create(opts);
3652 print_version("MPlayer");
3654 #if defined(__MINGW32__) || defined(__CYGWIN__)
3656 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3657 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3658 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3659 if (kernel32) {
3660 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3661 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3663 if (setDEP) setDEP(3);
3664 if (setDllDir) setDllDir("");
3666 // stop Windows from showing all kinds of annoying error dialogs
3667 SetErrorMode(0x8003);
3668 // request 1ms timer resolution
3669 timeBeginPeriod(1);
3670 #endif
3672 #ifdef CONFIG_PRIORITY
3673 set_priority();
3674 #endif
3676 if (codec_path)
3677 set_codec_path(codec_path);
3679 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3680 list_video_out();
3681 opt_exit = 1;
3684 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3685 list_audio_out();
3686 opt_exit = 1;
3689 /* Check codecs.conf. */
3690 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3691 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3692 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3693 if(!parse_codec_cfg(NULL)){
3694 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3696 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3699 free( mem_ptr ); // release the buffer created by get_path()
3702 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3703 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3704 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3705 list_codecs(1);
3706 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3707 opt_exit = 1;
3709 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3710 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3711 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3712 list_codecs(0);
3713 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3714 opt_exit = 1;
3716 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3717 vfm_help();
3718 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3719 opt_exit = 1;
3721 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3722 afm_help();
3723 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3724 opt_exit = 1;
3726 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3727 af_help();
3728 printf("\n");
3729 opt_exit = 1;
3731 #ifdef CONFIG_X11
3732 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3733 fstype_help();
3734 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3735 opt_exit = 1;
3737 #endif
3738 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3739 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3740 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3741 demuxer_help();
3742 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3743 opt_exit = 1;
3745 if (opts->list_properties) {
3746 property_print_help();
3747 opt_exit = 1;
3750 if(opt_exit)
3751 exit_player(mpctx, EXIT_NONE);
3753 if (!mpctx->filename && !opts->player_idle_mode) {
3754 // no file/vcd/dvd -> show HELP:
3755 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3756 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3759 /* Display what configure line was used */
3760 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3762 // Many users forget to include command line in bugreports...
3763 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3764 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3765 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3766 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3769 //------ load global data first ------
3771 mpctx->osd = osd_create();
3773 // check font
3774 #ifdef CONFIG_FREETYPE
3775 init_freetype();
3776 #endif
3777 #ifdef CONFIG_FONTCONFIG
3778 if(font_fontconfig <= 0)
3780 #endif
3781 #ifdef CONFIG_BITMAP_FONT
3782 if(font_name){
3783 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3784 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3785 filename_recode(font_name));
3786 } else {
3787 // try default:
3788 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3789 free(mem_ptr); // release the buffer created by get_path()
3790 if(!vo_font)
3791 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3793 if (sub_font_name)
3794 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3795 else
3796 mpctx->osd->sub_font = vo_font;
3797 #endif
3798 #ifdef CONFIG_FONTCONFIG
3800 #endif
3802 #ifdef CONFIG_ASS
3803 ass_library = ass_init();
3804 #endif
3806 #ifdef HAVE_RTC
3807 if(opts->rtc)
3809 char *rtc_device = opts->rtc_device;
3810 // seteuid(0); /* Can't hurt to try to get root here */
3811 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3812 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3813 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3814 else {
3815 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3817 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3818 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3819 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3820 close (rtc_fd);
3821 rtc_fd = -1;
3822 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3823 /* variable only by the root */
3824 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3825 close (rtc_fd);
3826 rtc_fd = -1;
3827 } else
3828 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3831 if(rtc_fd<0)
3832 #endif /* HAVE_RTC */
3833 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3834 opts->softsleep ? "software" : timer_name);
3836 #ifdef HAVE_TERMCAP
3837 load_termcap(NULL); // load key-codes
3838 #endif
3840 // ========== Init keyboard FIFO (connection to libvo) ============
3842 // Init input system
3843 current_module = "init_input";
3844 mpctx->input = mp_input_init(&opts->input);
3845 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3846 if(slave_mode)
3847 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3848 else if (opts->consolecontrols)
3849 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3850 // Set the libstream interrupt callback
3851 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3853 #ifdef CONFIG_MENU
3854 if(use_menu) {
3855 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3856 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3857 else {
3858 menu_cfg = get_path("menu.conf");
3859 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3860 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3861 else {
3862 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3863 MPLAYER_CONFDIR "/menu.conf"))
3864 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3865 else {
3866 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3867 use_menu = 0;
3872 #endif
3874 current_module = NULL;
3876 /// Catch signals
3877 #ifndef __MINGW32__
3878 signal(SIGCHLD,child_sighandler);
3879 #endif
3881 #ifdef CONFIG_CRASH_DEBUG
3882 prog_path = argv[0];
3883 #endif
3884 //========= Catch terminate signals: ================
3885 // terminate requests:
3886 signal(SIGTERM,exit_sighandler); // kill
3887 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3889 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3891 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3892 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3893 #ifdef CONFIG_SIGHANDLER
3894 // fatal errors:
3895 signal(SIGBUS,exit_sighandler); // bus error
3896 signal(SIGSEGV,exit_sighandler); // segfault
3897 signal(SIGILL,exit_sighandler); // illegal instruction
3898 signal(SIGFPE,exit_sighandler); // floating point exc.
3899 signal(SIGABRT,exit_sighandler); // abort()
3900 #ifdef CONFIG_CRASH_DEBUG
3901 if (crash_debug)
3902 signal(SIGTRAP,exit_sighandler);
3903 #endif
3904 #endif
3906 // ******************* Now, let's see the per-file stuff ********************
3908 play_next_file:
3910 // init global sub numbers
3911 mpctx->global_sub_size = 0;
3912 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3914 if (mpctx->filename) {
3915 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3916 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3917 load_per_file_config (mpctx->mconfig, mpctx->filename);
3920 if (opts->video_driver_list)
3921 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3922 if (opts->audio_driver_list)
3923 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3925 // We must enable getch2 here to be able to interrupt network connection
3926 // or cache filling
3927 if (opts->consolecontrols && !slave_mode) {
3928 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3929 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3930 else
3931 getch2_enable(); // prepare stdin for hotkeys...
3932 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3933 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3936 // =================== GUI idle loop (STOP state) ===========================
3937 while (opts->player_idle_mode && !mpctx->filename) {
3938 play_tree_t * entry = NULL;
3939 mp_cmd_t * cmd;
3940 if (mpctx->video_out && mpctx->video_out->config_ok)
3941 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3942 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3943 if (mpctx->video_out)
3944 vo_check_events(mpctx->video_out);
3945 usec_sleep(20000);
3947 switch (cmd->id) {
3948 case MP_CMD_LOADFILE:
3949 // prepare a tree entry with the new filename
3950 entry = play_tree_new();
3951 play_tree_add_file(entry, cmd->args[0].v.s);
3952 // The entry is added to the main playtree after the switch().
3953 break;
3954 case MP_CMD_LOADLIST:
3955 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3956 break;
3957 case MP_CMD_QUIT:
3958 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3959 break;
3960 case MP_CMD_VO_FULLSCREEN:
3961 case MP_CMD_GET_PROPERTY:
3962 case MP_CMD_SET_PROPERTY:
3963 case MP_CMD_STEP_PROPERTY:
3964 run_command(mpctx, cmd);
3965 break;
3968 mp_cmd_free(cmd);
3970 if (entry) { // user entered a command that gave a valid entry
3971 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3972 play_tree_free_list(mpctx->playtree->child, 1);
3973 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3975 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3977 play_tree_set_child(mpctx->playtree, entry);
3979 /* Make iterator start at the top the of tree. */
3980 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3981 if (!mpctx->playtree_iter) continue;
3983 // find the first real item in the tree
3984 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3985 // no items!
3986 play_tree_iter_free(mpctx->playtree_iter);
3987 mpctx->playtree_iter = NULL;
3988 continue; // wait for next command
3990 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3993 //---------------------------------------------------------------------------
3995 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3996 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3998 if (mpctx->filename) {
3999 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4000 filename_recode(mpctx->filename));
4001 if(use_filename_title && opts->vo_wintitle == NULL)
4002 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4005 if (edl_filename) {
4006 if (edl_records) free_edl(edl_records);
4007 next_edl_record = edl_records = edl_parse_file();
4009 if (edl_output_filename) {
4010 if (edl_fd) fclose(edl_fd);
4011 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4013 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4014 filename_recode(edl_output_filename));
4018 //==================== Open VOB-Sub ============================
4020 current_module="vobsub";
4021 if (vobsub_name){
4022 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
4023 if(vo_vobsub==NULL)
4024 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4025 filename_recode(vobsub_name));
4026 } else if (sub_auto && mpctx->filename){
4027 /* try to autodetect vobsub from movie filename ::atmos */
4028 char *buf = strdup(mpctx->filename), *psub;
4029 char *pdot = strrchr(buf, '.');
4030 char *pslash = strrchr(buf, '/');
4031 #if defined(__MINGW32__) || defined(__CYGWIN__)
4032 if (!pslash) pslash = strrchr(buf, '\\');
4033 #endif
4034 if (pdot && (!pslash || pdot > pslash))
4035 *pdot = '\0';
4036 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4037 /* try from ~/.mplayer/sub */
4038 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4039 const char *bname = mp_basename(buf);
4040 int l;
4041 l = strlen(psub) + strlen(bname) + 1;
4042 psub = realloc(psub,l);
4043 strcat(psub,bname);
4044 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4045 free(psub);
4047 free(buf);
4049 if(vo_vobsub){
4050 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4051 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4052 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4054 // setup global sub numbering
4055 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4058 //============ Open & Sync STREAM --- fork cache2 ====================
4060 mpctx->stream=NULL;
4061 mpctx->demuxer=NULL;
4062 if (mpctx->d_audio) {
4063 //free_demuxer_stream(mpctx->d_audio);
4064 mpctx->d_audio=NULL;
4066 if (mpctx->d_video) {
4067 //free_demuxer_stream(d_video);
4068 mpctx->d_video=NULL;
4070 mpctx->sh_audio=NULL;
4071 mpctx->sh_video=NULL;
4073 current_module="open_stream";
4074 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4075 if(!mpctx->stream) { // error...
4076 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4077 goto goto_next_file;
4079 mpctx->initialized_flags|=INITIALIZED_STREAM;
4081 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4082 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4083 "playlist support will not be used automatically.\n"
4084 "MPlayer's playlist code is unsafe and should only be used with "
4085 "trusted sources.\nPlayback will probably fail.\n\n");
4086 #if 0
4087 play_tree_t* entry;
4088 // Handle playlist
4089 current_module="handle_playlist";
4090 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4091 filename_recode(mpctx->filename));
4092 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4093 mpctx->eof=playtree_add_playlist(mpctx, entry);
4094 goto goto_next_file;
4095 #endif
4097 mpctx->stream->start_pos+=seek_to_byte;
4099 if(stream_dump_type==5){
4100 unsigned char buf[4096];
4101 int len;
4102 FILE *f;
4103 current_module="dumpstream";
4104 stream_reset(mpctx->stream);
4105 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4106 f=fopen(opts->stream_dump_name,"wb");
4107 if(!f){
4108 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4109 exit_player(mpctx, EXIT_ERROR);
4111 if (opts->chapterrange[0] > 1) {
4112 int chapter = opts->chapterrange[0] - 1;
4113 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4115 while(!mpctx->stream->eof && !async_quit_request){
4116 len=stream_read(mpctx->stream,buf,4096);
4117 if(len>0) {
4118 if(fwrite(buf,len,1,f) != 1) {
4119 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4120 exit_player(mpctx, EXIT_ERROR);
4123 if (opts->chapterrange[1] > 0) {
4124 int chapter = -1;
4125 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4126 &chapter) == STREAM_OK
4127 && chapter + 1 > opts->chapterrange[1])
4128 break;
4131 if(fclose(f)) {
4132 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4133 exit_player(mpctx, EXIT_ERROR);
4135 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4136 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4139 #ifdef CONFIG_DVDREAD
4140 if(mpctx->stream->type==STREAMTYPE_DVD){
4141 current_module="dvd lang->id";
4142 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4143 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4144 // setup global sub numbering
4145 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4146 current_module=NULL;
4148 #endif
4150 #ifdef CONFIG_DVDNAV
4151 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4152 current_module="dvdnav lang->id";
4153 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4154 dvdsub_lang_id = -3;
4155 if(opts->sub_lang && opts->sub_id==-1)
4156 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4157 // setup global sub numbering
4158 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4159 current_module=NULL;
4161 #endif
4163 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4164 goto_enable_cache:
4165 if(stream_cache_size>0){
4166 int res;
4167 float stream_cache_min_percent = opts->stream_cache_min_percent;
4168 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4169 current_module="enable_cache";
4170 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4171 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4172 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4173 if(res == 0)
4174 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4177 //============ Open DEMUXERS --- DETECT file type =======================
4178 current_module="demux_open";
4180 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4182 // HACK to get MOV Reference Files working
4184 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4186 unsigned char* playlist_entry;
4187 play_tree_t *list = NULL, *entry = NULL;
4189 current_module="handle_demux_playlist";
4190 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4192 char *temp;
4193 const char *bname;
4195 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4196 filename_recode(playlist_entry));
4198 bname=mp_basename(playlist_entry);
4199 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4200 continue;
4202 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4203 continue;
4205 entry = play_tree_new();
4207 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4209 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4210 if (temp)
4212 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4213 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4214 strcat(temp, playlist_entry);
4215 if (!strcmp(temp, mpctx->filename)) {
4216 free(temp);
4217 continue;
4219 play_tree_add_file(entry,temp);
4220 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4221 free(temp);
4224 else
4225 play_tree_add_file(entry,playlist_entry);
4227 if(!list)
4228 list = entry;
4229 else
4230 play_tree_append_entry(list,entry);
4232 free_demuxer(mpctx->demuxer);
4233 mpctx->demuxer = NULL;
4235 if (list)
4237 entry = play_tree_new();
4238 play_tree_set_child(entry,list);
4239 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4240 goto goto_next_file;
4244 if(!mpctx->demuxer) {
4245 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4246 goto goto_next_file;
4249 if (mpctx->demuxer->matroska_data.ordered_chapters)
4250 build_ordered_chapter_timeline(mpctx);
4252 if (!mpctx->sources) {
4253 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4254 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4255 .demuxer = mpctx->demuxer};
4256 mpctx->num_sources = 1;
4259 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4261 #ifdef CONFIG_ASS
4262 if (opts->ass_enabled && ass_library) {
4263 for (int j = 0; j < mpctx->num_sources; j++) {
4264 struct demuxer *d = mpctx->sources[j].demuxer;
4265 for (int i = 0; i < d->num_attachments; i++) {
4266 struct demux_attachment *att = d->attachments + i;
4267 if (use_embedded_fonts && attachment_is_font(att))
4268 ass_add_font(ass_library, att->name, att->data, att->data_size);
4272 #endif
4274 current_module="demux_open2";
4276 mpctx->d_audio=mpctx->demuxer->audio;
4277 mpctx->d_video=mpctx->demuxer->video;
4278 mpctx->d_sub=mpctx->demuxer->sub;
4280 if (ts_prog) {
4281 int tmp = ts_prog;
4282 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4284 // select audio stream
4285 if (mpctx->num_sources)
4286 for (int i = 0; i < mpctx->num_sources; i++)
4287 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
4288 opts->audio_lang);
4289 else
4290 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
4292 // DUMP STREAMS:
4293 if((stream_dump_type)&&(stream_dump_type<4)){
4294 FILE *f;
4295 demux_stream_t *ds=NULL;
4296 current_module="dump";
4297 // select stream to dump
4298 switch(stream_dump_type){
4299 case 1: ds=mpctx->d_audio;break;
4300 case 2: ds=mpctx->d_video;break;
4301 case 3: ds=mpctx->d_sub;break;
4303 if(!ds){
4304 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4305 exit_player(mpctx, EXIT_ERROR);
4307 // disable other streams:
4308 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4309 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4310 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4311 // let's dump it!
4312 f=fopen(opts->stream_dump_name,"wb");
4313 if(!f){
4314 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4315 exit_player(mpctx, EXIT_ERROR);
4317 while(!ds->eof){
4318 unsigned char* start;
4319 int in_size=ds_get_packet(ds,&start);
4320 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4321 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4322 if(in_size>0) fwrite(start,in_size,1,f);
4323 if (opts->chapterrange[1] > 0) {
4324 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4325 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4326 break;
4329 fclose(f);
4330 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4331 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4334 mpctx->sh_audio=mpctx->d_audio->sh;
4335 mpctx->sh_video=mpctx->d_video->sh;
4337 if(mpctx->sh_video){
4339 current_module="video_read_properties";
4340 if(!video_read_properties(mpctx->sh_video)) {
4341 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4342 mpctx->sh_video=mpctx->d_video->sh=NULL;
4343 } else {
4344 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4345 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4346 mpctx->sh_video->fps,mpctx->sh_video->frametime
4349 /* need to set fps here for output encoders to pick it up in their init */
4350 if(force_fps){
4351 mpctx->sh_video->fps=force_fps;
4352 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4354 vo_fps = mpctx->sh_video->fps;
4356 if(!mpctx->sh_video->fps && !force_fps){
4357 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4358 mpctx->opts.correct_pts = 1;
4364 if(!mpctx->sh_video && !mpctx->sh_audio){
4365 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4366 #ifdef CONFIG_DVBIN
4367 if(mpctx->stream->type == STREAMTYPE_DVB)
4369 int dir;
4370 int v = mpctx->last_dvb_step;
4371 if(v > 0)
4372 dir = DVB_CHANNEL_HIGHER;
4373 else
4374 dir = DVB_CHANNEL_LOWER;
4376 if(dvb_step_channel(mpctx->stream, dir)) {
4377 mpctx->stop_play = PT_NEXT_ENTRY;
4378 mpctx->dvbin_reopen = 1;
4381 #endif
4382 goto goto_next_file; // exit_player(_("Fatal error"));
4385 /* display clip info */
4386 demux_info_print(mpctx->demuxer);
4388 //================== Read SUBTITLES (DVD & TEXT) ==========================
4389 if(vo_spudec==NULL &&
4390 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4391 init_vo_spudec(mpctx);
4394 // after reading video params we should load subtitles because
4395 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4396 // check .sub
4397 current_module="read_subtitles_file";
4398 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4399 if(sub_name){
4400 for (i = 0; sub_name[i] != NULL; ++i)
4401 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4403 if(sub_auto) { // auto load sub file ...
4404 char *psub = get_path( "sub/" );
4405 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4406 int i = 0;
4407 free(psub); // release the buffer created by get_path() above
4408 while (tmp[i]) {
4409 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4410 free(tmp[i++]);
4412 free(tmp);
4414 if (mpctx->set_of_sub_size > 0)
4415 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4417 if (select_subtitle(mpctx)) {
4418 if(mpctx->subdata)
4419 switch (stream_dump_type) {
4420 case 3: list_sub_file(mpctx->subdata); break;
4421 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4422 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4423 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4424 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4425 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4429 print_file_properties(mpctx, mpctx->filename);
4431 if(!mpctx->sh_video) goto main; // audio-only
4433 if(!reinit_video_chain(mpctx)) {
4434 if(!mpctx->sh_video){
4435 if(!mpctx->sh_audio) goto goto_next_file;
4436 goto main; // exit_player(_("Fatal error"));
4440 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4441 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4443 #ifdef CONFIG_FREETYPE
4444 force_load_font = 1;
4445 #endif
4447 //================== MAIN: ==========================
4448 main:
4449 current_module="main";
4451 if (opts->playing_msg) {
4452 char* msg = property_expand_string(mpctx, opts->playing_msg);
4453 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4454 free(msg);
4458 // Disable the term OSD in verbose mode
4459 if (verbose)
4460 opts->term_osd = 0;
4464 // Make sure old OSD does not stay around,
4465 // e.g. with -fixed-vo and same-resolution files
4466 clear_osd_msgs();
4467 update_osd_msg(mpctx);
4469 //================ SETUP AUDIO ==========================
4471 if(mpctx->sh_audio){
4472 reinit_audio_chain(mpctx);
4473 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4474 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4477 current_module="av_init";
4479 if(mpctx->sh_video){
4480 mpctx->sh_video->timer=0;
4481 if (! ignore_start)
4482 audio_delay += mpctx->sh_video->stream_delay;
4484 if(mpctx->sh_audio){
4485 if (start_volume >= 0)
4486 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4487 if (! ignore_start)
4488 audio_delay -= mpctx->sh_audio->stream_delay;
4489 mpctx->delay=-audio_delay;
4492 if(!mpctx->sh_audio){
4493 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4494 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4495 ds_free_packs(mpctx->d_audio); // free buffered chunks
4496 //mpctx->d_audio->id=-2; // do not read audio chunks
4497 //uninit_player(mpctx, INITIALIZED_AO); // close device
4499 if(!mpctx->sh_video){
4500 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4501 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4502 ds_free_packs(mpctx->d_video);
4503 mpctx->d_video->id=-2;
4504 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4507 if (!mpctx->sh_video && !mpctx->sh_audio)
4508 goto goto_next_file;
4510 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4511 if(force_fps && mpctx->sh_video){
4512 vo_fps = mpctx->sh_video->fps=force_fps;
4513 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4514 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4517 mp_input_set_section(mpctx->input, NULL);
4518 //TODO: add desired (stream-based) sections here
4519 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4520 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4522 //==================== START PLAYING =======================
4524 if(opts->loop_times>1) opts->loop_times--; else
4525 if(opts->loop_times==1) opts->loop_times = -1;
4527 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4529 total_time_usage_start=GetTimer();
4530 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4531 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4532 play_n_frames=play_n_frames_mf;
4534 if(play_n_frames==0){
4535 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4538 mpctx->time_frame = 0;
4539 mpctx->drop_message_shown = 0;
4540 mpctx->restart_playback = true;
4541 mpctx->video_pts = 0;
4542 mpctx->hrseek_active = false;
4543 mpctx->hrseek_framedrop = false;
4544 mpctx->step_frames = 0;
4545 mpctx->total_avsync_change = 0;
4546 mpctx->last_chapter_seek = -1;
4548 // If there's a timeline force an absolute seek to initialize state
4549 if (seek_to_sec || mpctx->timeline) {
4550 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4551 seek(mpctx, mpctx->seek);
4552 end_at.pos += seek_to_sec;
4554 if (opts->chapterrange[0] > 0) {
4555 double pts;
4556 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4557 && pts > -1.0) {
4558 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4559 seek(mpctx, mpctx->seek);
4563 if (end_at.type == END_AT_SIZE) {
4564 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4565 end_at.type = END_AT_NONE;
4568 #ifdef CONFIG_DVDNAV
4569 mp_dvdnav_context_free(mpctx);
4570 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4571 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4572 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4574 #endif
4576 mpctx->seek = (struct seek_params){0};
4577 get_relative_time(mpctx); // reset current delta
4578 // Make sure VO knows current pause state
4579 if (mpctx->sh_video)
4580 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4581 NULL);
4583 while (!mpctx->stop_play)
4584 run_playloop(mpctx);
4586 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4588 #ifdef CONFIG_DVBIN
4589 if(mpctx->dvbin_reopen)
4591 mpctx->stop_play = 0;
4592 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4593 cache_uninit(mpctx->stream);
4594 mpctx->dvbin_reopen = 0;
4595 goto goto_enable_cache;
4597 #endif
4600 goto_next_file: // don't jump here after ao/vo/getch initialization!
4602 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4604 if (opts->benchmark) {
4605 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4606 double total_time_usage;
4607 total_time_usage_start=GetTimer()-total_time_usage_start;
4608 total_time_usage = (float)total_time_usage_start*0.000001;
4609 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4610 video_time_usage,vout_time_usage,audio_time_usage,
4611 total_time_usage-tot,total_time_usage);
4612 if(total_time_usage>0.0)
4613 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4614 100.0*video_time_usage/total_time_usage,
4615 100.0*vout_time_usage/total_time_usage,
4616 100.0*audio_time_usage/total_time_usage,
4617 100.0*(total_time_usage-tot)/total_time_usage,
4618 100.0);
4619 if(total_frame_cnt && frame_dropping)
4620 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4621 total_frame_cnt-drop_frame_cnt,
4622 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4623 drop_frame_cnt,
4624 100*drop_frame_cnt/total_frame_cnt,
4625 total_frame_cnt,
4626 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4629 // time to uninit all, except global stuff:
4630 int uninitialize_parts = INITIALIZED_ALL;
4631 if (opts->fixed_vo)
4632 uninitialize_parts -= INITIALIZED_VO;
4633 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4634 uninitialize_parts -= INITIALIZED_AO;
4635 uninit_player(mpctx, uninitialize_parts);
4637 if(mpctx->set_of_sub_size > 0) {
4638 current_module="sub_free";
4639 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4640 sub_free(mpctx->set_of_subtitles[i]);
4641 #ifdef CONFIG_ASS
4642 if(mpctx->set_of_ass_tracks[i])
4643 ass_free_track( mpctx->set_of_ass_tracks[i] );
4644 #endif
4646 mpctx->set_of_sub_size = 0;
4648 mpctx->vo_sub_last = vo_sub=NULL;
4649 mpctx->subdata=NULL;
4650 #ifdef CONFIG_ASS
4651 ass_track = NULL;
4652 if(ass_library)
4653 ass_clear_fonts(ass_library);
4654 #endif
4656 if (!mpctx->stop_play) // In case some goto jumped here...
4657 mpctx->stop_play = PT_NEXT_ENTRY;
4659 int playtree_direction = 1;
4661 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4662 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4663 play_tree_iter_free(mpctx->playtree_iter);
4664 mpctx->playtree_iter = NULL;
4666 mpctx->play_tree_step = 1;
4667 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4668 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4669 if(mpctx->playtree_iter) {
4670 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4671 play_tree_iter_free(mpctx->playtree_iter);
4672 mpctx->playtree_iter = NULL;
4675 } else if (mpctx->stop_play == PT_STOP) {
4676 play_tree_iter_free(mpctx->playtree_iter);
4677 mpctx->playtree_iter = NULL;
4678 } else { // NEXT PREV SRC
4679 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4682 while(mpctx->playtree_iter != NULL) {
4683 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4684 if(mpctx->filename == NULL) {
4685 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4686 play_tree_iter_free(mpctx->playtree_iter);
4687 mpctx->playtree_iter = NULL;
4689 } else
4690 break;
4693 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4694 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4695 mpctx->stop_play = 0;
4696 goto play_next_file;
4700 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4702 return 1;
4704 #endif /* DISABLE_MAIN */