core: fix audio-only + framestep weird behavior
[mplayer/glamo.git] / mplayer.c
blobe2b8a372d173580f5d33b97eacef0f5d68b47d65
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 char *conffile;
873 int conffile_fd;
874 if (!disable_system_conf &&
875 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
876 exit_player(mpctx, EXIT_NONE);
877 if ((conffile = get_path("")) == NULL) {
878 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
879 } else {
880 #ifdef __MINGW32__
881 mkdir(conffile);
882 #else
883 mkdir(conffile, 0777);
884 #endif
885 free(conffile);
886 if ((conffile = get_path("config")) == NULL) {
887 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
888 } else {
889 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
890 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
891 write(conffile_fd, default_config, strlen(default_config));
892 close(conffile_fd);
894 if (!disable_user_conf &&
895 m_config_parse_config_file(conf, conffile) < 0)
896 exit_player(mpctx, EXIT_NONE);
897 free(conffile);
902 #define PROFILE_CFG_PROTOCOL "protocol."
904 static void load_per_protocol_config (m_config_t* conf, const char *const file)
906 char *str;
907 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
908 m_profile_t *p;
910 /* does filename actually uses a protocol ? */
911 str = strstr (file, "://");
912 if (!str)
913 return;
915 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
916 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
917 p = m_config_get_profile (conf, protocol);
918 if (p)
920 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
921 m_config_set_profile(conf,p);
925 #define PROFILE_CFG_EXTENSION "extension."
927 static void load_per_extension_config (m_config_t* conf, const char *const file)
929 char *str;
930 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
931 m_profile_t *p;
933 /* does filename actually have an extension ? */
934 str = strrchr (file, '.');
935 if (!str)
936 return;
938 sprintf (extension, PROFILE_CFG_EXTENSION);
939 strncat (extension, ++str, 7);
940 p = m_config_get_profile (conf, extension);
941 if (p)
943 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
944 m_config_set_profile(conf,p);
948 #define PROFILE_CFG_VO "vo."
949 #define PROFILE_CFG_AO "ao."
951 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
953 char profile[strlen (cfg) + strlen (out) + 1];
954 m_profile_t *p;
956 sprintf (profile, "%s%s", cfg, out);
957 p = m_config_get_profile (conf, profile);
958 if (p)
960 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
961 m_config_set_profile(conf,p);
966 * Tries to load a config file
967 * @return 0 if file was not found, 1 otherwise
969 static int try_load_config(m_config_t *conf, const char *file)
971 struct stat st;
972 if (stat(file, &st))
973 return 0;
974 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
975 m_config_parse_config_file (conf, file);
976 return 1;
979 static void load_per_file_config (m_config_t* conf, const char *const file)
981 char *confpath;
982 char cfg[PATH_MAX];
983 const char *name;
985 if (strlen(file) > PATH_MAX - 14) {
986 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
987 return;
989 sprintf (cfg, "%s.conf", file);
991 name = mp_basename(cfg);
992 if (use_filedir_conf) {
993 char dircfg[PATH_MAX];
994 strcpy(dircfg, cfg);
995 strcpy(dircfg + (name - cfg), "mplayer.conf");
996 try_load_config(conf, dircfg);
998 if (try_load_config(conf, cfg))
999 return;
1002 if ((confpath = get_path (name)) != NULL)
1004 try_load_config(conf, confpath);
1006 free (confpath);
1010 /* When libmpdemux performs a blocking operation (network connection or
1011 * cache filling) if the operation fails we use this function to check
1012 * if it was interrupted by the user.
1013 * The function returns a new value for eof. */
1014 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1016 mp_cmd_t* cmd;
1017 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1018 switch(cmd->id) {
1019 case MP_CMD_QUIT:
1020 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1021 case MP_CMD_PLAY_TREE_STEP: {
1022 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1023 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1024 } break;
1025 case MP_CMD_PLAY_TREE_UP_STEP: {
1026 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1027 } break;
1028 case MP_CMD_PLAY_ALT_SRC_STEP: {
1029 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1030 } break;
1032 mp_cmd_free(cmd);
1034 return stop_play;
1037 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1039 play_tree_add_bpf(entry,mpctx->filename);
1042 if(!entry) {
1043 entry = mpctx->playtree_iter->tree;
1044 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1045 return PT_NEXT_ENTRY;
1047 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1048 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1049 return PT_NEXT_ENTRY;
1052 play_tree_remove(entry,1,1);
1053 return PT_NEXT_SRC;
1055 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1056 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1057 entry = mpctx->playtree_iter->tree;
1058 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1059 return PT_NEXT_ENTRY;
1061 play_tree_remove(entry,1,1);
1063 return PT_NEXT_SRC;
1066 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1068 struct MPOpts *opts = &mpctx->opts;
1069 sub_data *subd = NULL;
1070 struct ass_track *asst = NULL;
1072 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1073 return;
1076 #ifdef CONFIG_ASS
1077 if (opts->ass_enabled) {
1078 #ifdef CONFIG_ICONV
1079 asst = ass_read_stream(ass_library, filename, sub_cp);
1080 #else
1081 asst = ass_read_stream(ass_library, filename, 0);
1082 #endif
1083 if (!asst) {
1084 subd = sub_read_file(filename, fps);
1085 if (subd) {
1086 asst = ass_read_subdata(ass_library, subd, fps);
1087 if (asst) {
1088 sub_free(subd);
1089 subd = NULL;
1093 } else
1094 #endif
1095 subd = sub_read_file(filename, fps);
1098 if (!asst && !subd) {
1099 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1100 "Cannot load subtitles: %s\n", filename_recode(filename));
1101 return;
1104 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1105 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1106 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1107 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1108 filename_recode(filename));
1109 ++mpctx->set_of_sub_size;
1110 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1111 filename_recode(filename));
1114 void init_vo_spudec(struct MPContext *mpctx)
1116 spudec_free(vo_spudec);
1117 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1118 vo_spudec = NULL;
1120 // we currently can't work without video stream
1121 if (!mpctx->sh_video)
1122 return;
1124 if (spudec_ifo) {
1125 unsigned int palette[16], width, height;
1126 current_module="spudec_init_vobsub";
1127 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1128 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1131 #ifdef CONFIG_DVDREAD
1132 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1133 current_module="spudec_init_dvdread";
1134 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1135 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1136 NULL, 0);
1138 #endif
1140 #ifdef CONFIG_DVDNAV
1141 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1142 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1143 current_module="spudec_init_dvdnav";
1144 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1146 #endif
1148 if (vo_spudec==NULL) {
1149 sh_sub_t *sh = mpctx->d_sub->sh;
1150 current_module="spudec_init_normal";
1151 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1152 spudec_set_font_factor(vo_spudec,font_factor);
1155 if (vo_spudec!=NULL) {
1156 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1157 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1162 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1163 * make it all work is to use the builtin SDL-bootstrap code, which
1164 * will be done automatically by replacing our main() if we include SDL.h.
1166 #if defined(__APPLE__) && defined(CONFIG_SDL)
1167 #ifdef CONFIG_SDL_SDL_H
1168 #include <SDL/SDL.h>
1169 #else
1170 #include <SDL.h>
1171 #endif
1172 #endif
1175 * \brief append a formatted string
1176 * \param buf buffer to print into
1177 * \param pos position of terminating 0 in buf
1178 * \param len maximum number of characters in buf, not including terminating 0
1179 * \param format printf format string
1181 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1183 va_list va;
1184 va_start(va, format);
1185 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1186 va_end(va);
1187 if (*pos >= len ) {
1188 buf[len] = 0;
1189 *pos = len;
1194 * \brief append time in the hh:mm:ss.f format
1195 * \param buf buffer to print into
1196 * \param pos position of terminating 0 in buf
1197 * \param len maximum number of characters in buf, not including terminating 0
1198 * \param time time value to convert/append
1200 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1201 int64_t tenths = 10 * time;
1202 int f1 = tenths % 10;
1203 int ss = (tenths / 10) % 60;
1204 int mm = (tenths / 600) % 60;
1205 int hh = tenths / 36000;
1206 if (time <= 0) {
1207 saddf(buf, pos, len, "unknown");
1208 return;
1210 if (hh > 0)
1211 saddf(buf, pos, len, "%2d:", hh);
1212 if (hh > 0 || mm > 0)
1213 saddf(buf, pos, len, "%02d:", mm);
1214 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1217 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1219 struct MPOpts *opts = &mpctx->opts;
1220 sh_video_t * const sh_video = mpctx->sh_video;
1222 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1223 a_pos = playing_audio_pts(mpctx);
1224 if (mpctx->sh_audio && sh_video && at_frame) {
1225 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1226 if (mpctx->time_frame > 0)
1227 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1228 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1229 && !mpctx->drop_message_shown) {
1230 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1231 mpctx->drop_message_shown = true;
1234 if (opts->quiet)
1235 return;
1238 int width;
1239 char *line;
1240 unsigned pos = 0;
1241 get_screen_size();
1242 if (screen_width > 0)
1243 width = screen_width;
1244 else
1245 width = 80;
1246 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1247 /* Windows command line is broken (MinGW's rxvt works, but we
1248 * should not depend on that). */
1249 width--;
1250 #endif
1251 line = malloc(width + 1); // one additional char for the terminating null
1253 // Audio time
1254 if (mpctx->sh_audio) {
1255 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1256 if (!sh_video) {
1257 float len = get_time_length(mpctx);
1258 saddf(line, &pos, width, "(");
1259 sadd_hhmmssf(line, &pos, width, a_pos);
1260 saddf(line, &pos, width, ") of %.1f (", len);
1261 sadd_hhmmssf(line, &pos, width, len);
1262 saddf(line, &pos, width, ") ");
1266 // Video time
1267 if (sh_video)
1268 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1270 // A-V sync
1271 if (mpctx->sh_audio && sh_video)
1272 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1273 mpctx->last_av_difference, mpctx->total_avsync_change);
1275 // Video stats
1276 if (sh_video)
1277 saddf(line, &pos, width, "%3d/%3d ",
1278 (int)sh_video->num_frames,
1279 (int)sh_video->num_frames_decoded);
1281 // CPU usage
1282 if (sh_video) {
1283 if (sh_video->timer > 0.5)
1284 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1285 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1286 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1287 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1288 else
1289 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1290 } else if (mpctx->sh_audio) {
1291 if (mpctx->delay > 0.5)
1292 saddf(line, &pos, width, "%4.1f%% ",
1293 100.0*audio_time_usage/(double)mpctx->delay);
1294 else
1295 saddf(line, &pos, width, "??,?%% ");
1298 // VO stats
1299 if (sh_video)
1300 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1302 #ifdef CONFIG_STREAM_CACHE
1303 // cache stats
1304 if (stream_cache_size > 0)
1305 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1306 #endif
1308 // other
1309 if (opts->playback_speed != 1)
1310 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1312 // end
1313 if (erase_to_end_of_line) {
1314 line[pos] = 0;
1315 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1316 } else {
1317 memset(&line[pos], ' ', width - pos);
1318 line[width] = 0;
1319 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1321 free(line);
1325 * \brief build a chain of audio filters that converts the input format
1326 * to the ao's format, taking into account the current playback_speed.
1327 * \param sh_audio describes the requested input format of the chain.
1328 * \param ao_data describes the requested output format of the chain.
1330 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1331 ao_data_t *ao_data)
1333 struct MPOpts *opts = &mpctx->opts;
1334 int new_srate;
1335 int result;
1336 if (!sh_audio)
1338 mpctx->mixer.afilter = NULL;
1339 return 0;
1341 if(af_control_any_rev(sh_audio->afilter,
1342 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1343 &opts->playback_speed)) {
1344 new_srate = sh_audio->samplerate;
1345 } else {
1346 new_srate = sh_audio->samplerate * opts->playback_speed;
1347 if (new_srate != ao_data->samplerate) {
1348 // limits are taken from libaf/af_resample.c
1349 if (new_srate < 8000)
1350 new_srate = 8000;
1351 if (new_srate > 192000)
1352 new_srate = 192000;
1353 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1356 result = init_audio_filters(sh_audio, new_srate,
1357 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1358 mpctx->mixer.afilter = sh_audio->afilter;
1359 return result;
1363 typedef struct mp_osd_msg mp_osd_msg_t;
1364 struct mp_osd_msg {
1365 /// Previous message on the stack.
1366 mp_osd_msg_t* prev;
1367 /// Message text.
1368 char msg[128];
1369 int id,level,started;
1370 /// Display duration in ms.
1371 unsigned time;
1374 /// OSD message stack.
1375 static mp_osd_msg_t* osd_msg_stack = NULL;
1378 * \brief Add a message on the OSD message stack
1380 * If a message with the same id is already present in the stack
1381 * it is pulled on top of the stack, otherwise a new message is created.
1384 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1385 va_list ap)
1387 mp_osd_msg_t *msg,*last=NULL;
1388 int r;
1390 // look if the id is already in the stack
1391 for(msg = osd_msg_stack ; msg && msg->id != id ;
1392 last = msg, msg = msg->prev);
1393 // not found: alloc it
1394 if(!msg) {
1395 msg = calloc(1,sizeof(mp_osd_msg_t));
1396 msg->prev = osd_msg_stack;
1397 osd_msg_stack = msg;
1398 } else if(last) { // found, but it's not on top of the stack
1399 last->prev = msg->prev;
1400 msg->prev = osd_msg_stack;
1401 osd_msg_stack = msg;
1403 // write the msg
1404 r = vsnprintf(msg->msg, 128, fmt, ap);
1405 if(r >= 128) msg->msg[127] = 0;
1406 // set id and time
1407 msg->id = id;
1408 msg->level = level;
1409 msg->time = time;
1413 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1415 va_list ap;
1416 va_start(ap, fmt);
1417 set_osd_msg_va(id, level, time, fmt, ap);
1418 va_end(ap);
1421 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1423 va_list ap;
1424 va_start(ap, fmt);
1425 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1426 va_end(ap);
1431 * \brief Remove a message from the OSD stack
1433 * This function can be used to get rid of a message right away.
1437 void rm_osd_msg(int id) {
1438 mp_osd_msg_t *msg,*last=NULL;
1440 // Search for the msg
1441 for(msg = osd_msg_stack ; msg && msg->id != id ;
1442 last = msg, msg = msg->prev);
1443 if(!msg) return;
1445 // Detach it from the stack and free it
1446 if(last)
1447 last->prev = msg->prev;
1448 else
1449 osd_msg_stack = msg->prev;
1450 free(msg);
1454 * \brief Remove all messages from the OSD stack
1458 static void clear_osd_msgs(void) {
1459 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1460 while(msg) {
1461 prev = msg->prev;
1462 free(msg);
1463 msg = prev;
1465 osd_msg_stack = NULL;
1469 * \brief Get the current message from the OSD stack.
1471 * This function decrements the message timer and destroys the old ones.
1472 * The message that should be displayed is returned (if any).
1476 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1478 struct MPOpts *opts = &mpctx->opts;
1479 mp_osd_msg_t *msg,*prev,*last = NULL;
1480 static unsigned last_update = 0;
1481 unsigned now = GetTimerMS();
1482 unsigned diff;
1483 char hidden_dec_done = 0;
1485 if (mpctx->osd_visible) {
1486 // 36000000 means max timed visibility is 1 hour into the future, if
1487 // the difference is greater assume it's wrapped around from below 0
1488 if (mpctx->osd_visible - now > 36000000) {
1489 mpctx->osd_visible = 0;
1490 vo_osd_progbar_type = -1; // disable
1491 vo_osd_changed(OSDTYPE_PROGBAR);
1492 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1495 if (mpctx->osd_show_percentage_until - now > 36000000)
1496 mpctx->osd_show_percentage_until = 0;
1498 if(!last_update) last_update = now;
1499 diff = now >= last_update ? now - last_update : 0;
1501 last_update = now;
1503 // Look for the first message in the stack with high enough level.
1504 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1505 prev = msg->prev;
1506 if (msg->level > opts->osd_level && hidden_dec_done)
1507 continue;
1508 // The message has a high enough level or it is the first hidden one
1509 // in both cases we decrement the timer or kill it.
1510 if(!msg->started || msg->time > diff) {
1511 if(msg->started) msg->time -= diff;
1512 else msg->started = 1;
1513 // display it
1514 if (msg->level <= opts->osd_level)
1515 return msg;
1516 hidden_dec_done = 1;
1517 continue;
1519 // kill the message
1520 free(msg);
1521 if(last) {
1522 last->prev = prev;
1523 msg = last;
1524 } else {
1525 osd_msg_stack = prev;
1526 msg = NULL;
1529 // Nothing found
1530 return NULL;
1534 * \brief Display the OSD bar.
1536 * Display the OSD bar or fall back on a simple message.
1540 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1541 struct MPOpts *opts = &mpctx->opts;
1542 if (opts->osd_level < 1)
1543 return;
1545 if(mpctx->sh_video) {
1546 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1547 vo_osd_progbar_type = type;
1548 vo_osd_progbar_value = 256*(val-min)/(max-min);
1549 vo_osd_changed(OSDTYPE_PROGBAR);
1550 return;
1553 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1554 name, ROUND(100*(val-min)/(max-min)));
1558 * \brief Display text subtitles on the OSD
1560 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1562 int i;
1563 vo_sub = subs;
1564 vo_osd_changed(OSDTYPE_SUBTITLE);
1565 if (!mpctx->sh_video) {
1566 // reverse order, since newest set_osd_msg is displayed first
1567 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1568 if (!subs || i >= subs->lines || !subs->text[i])
1569 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1570 else {
1571 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1572 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1573 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1580 * \brief Update the OSD message line.
1582 * This function displays the current message on the vo OSD or on the term.
1583 * If the stack is empty and the OSD level is high enough the timer
1584 * is displayed (only on the vo OSD).
1588 static void update_osd_msg(struct MPContext *mpctx)
1590 struct MPOpts *opts = &mpctx->opts;
1591 mp_osd_msg_t *msg;
1592 struct osd_state *osd = mpctx->osd;
1593 char osd_text_timer[128];
1595 if (mpctx->add_osd_seek_info) {
1596 double percentage = get_percent_pos(mpctx);
1597 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1598 if (mpctx->sh_video)
1599 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1600 mpctx->add_osd_seek_info = false;
1603 // Look if we have a msg
1604 if((msg = get_osd_msg(mpctx))) {
1605 if (strcmp(osd->osd_text, msg->msg)) {
1606 strncpy(osd->osd_text, msg->msg, 127);
1607 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1608 if(opts->term_osd)
1609 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1610 msg->msg);
1612 return;
1615 if(mpctx->sh_video) {
1616 // fallback on the timer
1617 if (opts->osd_level >= 2) {
1618 int len = get_time_length(mpctx);
1619 int percentage = -1;
1620 char percentage_text[10];
1621 int pts = get_current_time(mpctx);
1623 if (mpctx->osd_show_percentage_until)
1624 percentage = get_percent_pos(mpctx);
1626 if (percentage >= 0)
1627 snprintf(percentage_text, 9, " (%d%%)", percentage);
1628 else
1629 percentage_text[0] = 0;
1631 if (opts->osd_level == 3)
1632 snprintf(osd_text_timer, 63,
1633 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1634 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1635 len/3600,(len/60)%60,len%60,percentage_text);
1636 else
1637 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1638 mpctx->osd_function,pts/3600,(pts/60)%60,
1639 pts%60,percentage_text);
1640 } else
1641 osd_text_timer[0]=0;
1643 if (strcmp(osd->osd_text, osd_text_timer)) {
1644 strncpy(osd->osd_text, osd_text_timer, 63);
1645 vo_osd_changed(OSDTYPE_OSD);
1647 return;
1650 // Clear the term osd line
1651 if (opts->term_osd && osd->osd_text[0]) {
1652 osd->osd_text[0] = 0;
1653 printf("%s\n", opts->term_osd_esc);
1657 ///@}
1658 // OSDMsgStack
1661 void reinit_audio_chain(struct MPContext *mpctx)
1663 struct MPOpts *opts = &mpctx->opts;
1664 if (!mpctx->sh_audio)
1665 return;
1666 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1667 current_module="init_audio_codec";
1668 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1669 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1670 goto init_error;
1672 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1673 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1677 current_module="af_preinit";
1678 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1679 ao_data.samplerate=force_srate;
1680 ao_data.channels=0;
1681 ao_data.format = opts->audio_output_format;
1683 // first init to detect best values
1684 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1685 // input:
1686 mpctx->sh_audio->samplerate,
1687 // output:
1688 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1689 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1690 "pre-init!\n");
1691 exit_player(mpctx, EXIT_ERROR);
1693 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1694 current_module="ao2_init";
1695 ao_data.buffersize = opts->ao_buffersize;
1696 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1697 0, // plugin flag
1698 ao_data.samplerate,
1699 ao_data.channels,
1700 ao_data.format, 0);
1701 if(!mpctx->audio_out){
1702 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1703 goto init_error;
1705 mpctx->initialized_flags|=INITIALIZED_AO;
1706 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1707 mpctx->audio_out->info->short_name,
1708 ao_data.samplerate, ao_data.channels,
1709 af_fmt2str_short(ao_data.format),
1710 af_fmt2bits(ao_data.format)/8 );
1711 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1712 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1713 if(strlen(mpctx->audio_out->info->comment) > 0)
1714 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1717 // init audio filters:
1718 current_module="af_init";
1719 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1720 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1721 goto init_error;
1723 mpctx->mixer.audio_out = mpctx->audio_out;
1724 mpctx->mixer.volstep = volstep;
1725 mpctx->syncing_audio = true;
1726 return;
1728 init_error:
1729 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1730 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1731 mpctx->d_audio->id = -2;
1735 ///@}
1736 // Command2Property
1739 // Return pts value corresponding to the end point of audio written to the
1740 // ao so far.
1741 static double written_audio_pts(struct MPContext *mpctx)
1743 sh_audio_t *sh_audio = mpctx->sh_audio;
1744 demux_stream_t *d_audio = mpctx->d_audio;
1745 double buffered_output;
1746 // first calculate the end pts of audio that has been output by decoder
1747 double a_pts = sh_audio->pts;
1748 if (a_pts != MP_NOPTS_VALUE)
1749 // Good, decoder supports new way of calculating audio pts.
1750 // sh_audio->pts is the timestamp of the latest input packet with
1751 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1752 // the amount of bytes the decoder has written after that timestamp.
1753 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1754 else {
1755 // Decoder doesn't support new way of calculating pts (or we're
1756 // being called before it has decoded anything with known timestamp).
1757 // Use the old method of audio pts calculation: take the timestamp
1758 // of last packet with known pts the decoder has read data from,
1759 // and add amount of bytes read after the beginning of that packet
1760 // divided by input bps. This will be inaccurate if the input/output
1761 // ratio is not constant for every audio packet or if it is constant
1762 // but not accurately known in sh_audio->i_bps.
1764 a_pts = d_audio->pts;
1765 // ds_tell_pts returns bytes read after last timestamp from
1766 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1767 // it has read but not decoded
1768 if (sh_audio->i_bps)
1769 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1770 (double)sh_audio->i_bps;
1772 // Now a_pts hopefully holds the pts for end of audio from decoder.
1773 // Substract data in buffers between decoder and audio out.
1775 // Decoded but not filtered
1776 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1778 // Data buffered in audio filters, measured in bytes of "missing" output
1779 buffered_output = af_calc_delay(sh_audio->afilter);
1781 // Data that was ready for ao but was buffered because ao didn't fully
1782 // accept everything to internal buffers yet
1783 buffered_output += sh_audio->a_out_buffer_len;
1785 // Filters divide audio length by playback_speed, so multiply by it
1786 // to get the length in original units without speedup or slowdown
1787 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1789 return a_pts + mpctx->video_offset;
1792 // Return pts value corresponding to currently playing audio.
1793 double playing_audio_pts(struct MPContext *mpctx)
1795 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1796 mpctx->audio_out->get_delay();
1799 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1800 struct MPOpts *opts = &mpctx->opts;
1801 // check for frame-drop:
1802 current_module = "check_framedrop";
1803 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1804 static int dropped_frames;
1805 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1806 float d = delay-mpctx->delay;
1807 ++total_frame_cnt;
1808 // we should avoid dropping too many frames in sequence unless we
1809 // are too late. and we allow 100ms A-V delay here:
1810 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1811 && !mpctx->restart_playback) {
1812 ++drop_frame_cnt;
1813 ++dropped_frames;
1814 return frame_dropping;
1815 } else
1816 dropped_frames = 0;
1818 return 0;
1822 #ifdef HAVE_RTC
1823 int rtc_fd = -1;
1824 #endif
1826 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1828 #ifdef HAVE_RTC
1829 if (rtc_fd >= 0){
1830 // -------- RTC -----------
1831 current_module="sleep_rtc";
1832 while (time_frame > 0.000) {
1833 unsigned long rtc_ts;
1834 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1835 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1836 time_frame -= get_relative_time(mpctx);
1838 } else
1839 #endif
1841 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1842 // unnecessarily high CPU usage
1843 struct MPOpts *opts = &mpctx->opts;
1844 float margin = opts->softsleep ? 0.011 : 0;
1845 current_module = "sleep_timer";
1846 while (time_frame > margin) {
1847 usec_sleep(1000000 * (time_frame - margin));
1848 time_frame -= get_relative_time(mpctx);
1850 if (opts->softsleep){
1851 current_module = "sleep_soft";
1852 if (time_frame < 0)
1853 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1854 while (time_frame > 0)
1855 time_frame -= get_relative_time(mpctx); // burn the CPU
1858 return time_frame;
1861 static int select_subtitle(MPContext *mpctx)
1863 struct MPOpts *opts = &mpctx->opts;
1864 // find the best sub to use
1865 int id;
1866 int found = 0;
1867 mpctx->global_sub_pos = -1; // no subs by default
1868 if (vobsub_id >= 0) {
1869 // if user asks for a vobsub id, use that first.
1870 id = vobsub_id;
1871 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1874 if (!found && opts->sub_id >= 0) {
1875 // if user asks for a dvd sub id, use that next.
1876 id = opts->sub_id;
1877 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1880 if (!found) {
1881 // if there are text subs to use, use those. (autosubs come last here)
1882 id = 0;
1883 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1886 if (!found && opts->sub_id == -1) {
1887 // finally select subs by language and container hints
1888 if (opts->sub_id == -1)
1889 opts->sub_id =
1890 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
1891 opts->sub_lang);
1892 if (opts->sub_id >= 0) {
1893 id = opts->sub_id;
1894 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1897 return found;
1900 #ifdef CONFIG_DVDNAV
1901 #ifndef FF_B_TYPE
1902 #define FF_B_TYPE 3
1903 #endif
1904 /// store decoded video image
1905 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1906 mp_image_t *from_mpi) {
1907 mp_image_t *mpi;
1909 /// Do not store B-frames
1910 if (from_mpi->pict_type == FF_B_TYPE)
1911 return to_mpi;
1913 if (to_mpi &&
1914 to_mpi->w == from_mpi->w &&
1915 to_mpi->h == from_mpi->h &&
1916 to_mpi->imgfmt == from_mpi->imgfmt)
1917 mpi = to_mpi;
1918 else {
1919 if (to_mpi)
1920 free_mp_image(to_mpi);
1921 if (from_mpi->w == 0 || from_mpi->h == 0)
1922 return NULL;
1923 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1926 copy_mpi(mpi,from_mpi);
1927 return mpi;
1930 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1931 struct MPOpts *opts = &ctx->opts;
1932 if (ctx->sh_video) {
1933 /// clear video pts
1934 ctx->d_video->pts = 0.0f;
1935 ctx->sh_video->pts = 0.0f;
1936 ctx->sh_video->i_pts = 0.0f;
1937 ctx->sh_video->last_pts = 0.0f;
1938 ctx->sh_video->num_buffered_pts = 0;
1939 ctx->sh_video->num_frames = 0;
1940 ctx->sh_video->num_frames_decoded = 0;
1941 ctx->sh_video->timer = 0.0f;
1942 ctx->sh_video->stream_delay = 0.0f;
1943 ctx->sh_video->timer = 0;
1944 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1947 if (ctx->sh_audio) {
1948 /// free audio packets and reset
1949 ds_free_packs(ctx->d_audio);
1950 audio_delay -= ctx->sh_audio->stream_delay;
1951 ctx->delay =- audio_delay;
1952 ctx->audio_out->reset();
1953 resync_audio_stream(ctx->sh_audio);
1956 audio_delay = 0.0f;
1957 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
1958 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
1959 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
1960 if (dvdsub_lang_id != opts->sub_id) {
1961 opts->sub_id = dvdsub_lang_id;
1962 select_subtitle(ctx);
1966 /// clear all EOF related flags
1967 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1970 /// Restore last decoded DVDNAV (still frame)
1971 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
1972 int *in_size,
1973 unsigned char **start,
1974 mp_image_t *decoded_frame)
1976 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1977 return decoded_frame;
1979 /// a change occured in dvdnav stream
1980 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
1981 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
1982 mp_dvdnav_context_free(mpctx);
1983 mp_dvdnav_reset_stream(mpctx);
1984 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
1985 mp_dvdnav_cell_has_changed(mpctx->stream,1);
1988 if (*in_size < 0) {
1989 float len;
1991 /// Display still frame, if any
1992 if (mpctx->nav_smpi && !mpctx->nav_buffer)
1993 decoded_frame = mpctx->nav_smpi;
1995 /// increment video frame : continue playing after still frame
1996 len = get_time_length(mpctx);
1997 if (mpctx->sh_video->pts >= len &&
1998 mpctx->sh_video->pts > 0.0 && len > 0.0) {
1999 mp_dvdnav_skip_still(mpctx->stream);
2000 mp_dvdnav_skip_wait(mpctx->stream);
2002 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2004 if (mpctx->nav_buffer) {
2005 *start = mpctx->nav_start;
2006 *in_size = mpctx->nav_in_size;
2007 if (mpctx->nav_start)
2008 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2012 return decoded_frame;
2015 /// Save last decoded DVDNAV (still frame)
2016 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2017 unsigned char *start,
2018 mp_image_t *decoded_frame)
2020 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2021 return;
2023 free(mpctx->nav_buffer);
2025 mpctx->nav_buffer = malloc(in_size);
2026 mpctx->nav_start = start;
2027 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2028 if (mpctx->nav_buffer)
2029 memcpy(mpctx->nav_buffer,start,in_size);
2031 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2032 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2034 #endif /* CONFIG_DVDNAV */
2036 /* Modify video timing to match the audio timeline. There are two main
2037 * reasons this is needed. First, video and audio can start from different
2038 * positions at beginning of file or after a seek (MPlayer starts both
2039 * immediately even if they have different pts). Second, the file can have
2040 * audio timestamps that are inconsistent with the duration of the audio
2041 * packets, for example two consecutive timestamp values differing by
2042 * one second but only a packet with enough samples for half a second
2043 * of playback between them.
2045 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2047 current_module = "av_sync";
2049 if (!mpctx->sh_audio || mpctx->syncing_audio)
2050 return;
2052 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2053 double v_pts = mpctx->sh_video->pts;
2054 double av_delay = a_pts - v_pts;
2055 // Try to sync vo_flip() so it will *finish* at given time
2056 av_delay += mpctx->last_vo_flip_duration;
2057 av_delay -= audio_delay; // This much pts difference is desired
2059 double change = av_delay * 0.1;
2060 double max_change = default_max_pts_correction >= 0 ?
2061 default_max_pts_correction : frame_time * 0.1;
2062 if (change < -max_change)
2063 change = -max_change;
2064 else if (change > max_change)
2065 change = max_change;
2066 mpctx->delay += change;
2067 mpctx->total_avsync_change += change;
2070 #define ASYNC_PLAY_DONE -3
2071 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2073 struct MPOpts *opts = &mpctx->opts;
2074 sh_audio_t * const sh_audio = mpctx->sh_audio;
2075 int res;
2077 // Timing info may not be set without
2078 res = decode_audio(sh_audio, 1);
2079 if (res < 0)
2080 return res;
2082 int bytes;
2083 bool did_retry = false;
2084 while (1) {
2085 double written_pts = written_audio_pts(mpctx);
2086 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2087 - audio_delay;
2088 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2089 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2091 // ogg demuxers give packets without timing
2092 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2093 if (!did_retry) {
2094 // Try to read more data to see packets that have pts
2095 int res = decode_audio(sh_audio, ao_data.bps);
2096 if (res < 0)
2097 return res;
2098 did_retry = true;
2099 continue;
2101 bytes = 0;
2104 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2105 bytes = 0;
2107 if (bytes > 0)
2108 break;
2110 mpctx->syncing_audio = false;
2111 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2112 int res = decode_audio(sh_audio, a);
2113 bytes += sh_audio->a_out_buffer_len;
2114 if (bytes >= 0) {
2115 memmove(sh_audio->a_out_buffer,
2116 sh_audio->a_out_buffer +
2117 sh_audio->a_out_buffer_len - bytes,
2118 bytes);
2119 sh_audio->a_out_buffer_len = bytes;
2120 if (res < 0)
2121 return res;
2122 return decode_audio(sh_audio, playsize);
2124 sh_audio->a_out_buffer_len = 0;
2125 if (res < 0)
2126 return res;
2128 int fillbyte = 0;
2129 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2130 fillbyte = 0x80;
2131 if (bytes >= playsize) {
2132 /* This case could fall back to the one below with
2133 * bytes = playsize, but then silence would keep accumulating
2134 * in a_out_buffer if the AO accepts less data than it asks for
2135 * in playsize. */
2136 char *p = malloc(playsize);
2137 memset(p, fillbyte, playsize);
2138 playsize = mpctx->audio_out->play(p, playsize, 0);
2139 free(p);
2140 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2141 return ASYNC_PLAY_DONE;
2143 mpctx->syncing_audio = false;
2144 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2145 return decode_audio(sh_audio, playsize);
2148 static int fill_audio_out_buffers(struct MPContext *mpctx)
2150 struct MPOpts *opts = &mpctx->opts;
2151 unsigned int t;
2152 double tt;
2153 int playsize;
2154 int playflags=0;
2155 int audio_eof=0;
2156 bool format_change = false;
2157 sh_audio_t * const sh_audio = mpctx->sh_audio;
2159 current_module="play_audio";
2161 while (1) {
2162 int sleep_time;
2163 // all the current uses of ao_data.pts seem to be in aos that handle
2164 // sync completely wrong; there should be no need to use ao_data.pts
2165 // in get_space()
2166 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2167 playsize = mpctx->audio_out->get_space();
2168 if (mpctx->sh_video || playsize >= ao_data.outburst)
2169 break;
2171 // handle audio-only case:
2172 // this is where mplayer sleeps during audio-only playback
2173 // to avoid 100% CPU use
2174 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2175 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2176 usec_sleep(sleep_time * 1000);
2179 // Fill buffer if needed:
2180 current_module="decode_audio";
2181 t = GetTimer();
2183 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2184 mpctx->syncing_audio = false;
2186 int res;
2187 if (mpctx->syncing_audio && mpctx->sh_video)
2188 res = audio_start_sync(mpctx, playsize);
2189 else
2190 res = decode_audio(sh_audio, playsize);
2191 if (res < 0) { // EOF, error or format change
2192 if (res == -2)
2193 format_change = true;
2194 else if (res == ASYNC_PLAY_DONE)
2195 return 1;
2196 else if (mpctx->d_audio->eof) {
2197 audio_eof = 1;
2198 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2199 if (sh_audio->a_out_buffer_len < unitsize)
2200 return 0;
2203 t = GetTimer() - t;
2204 tt = t*0.000001f; audio_time_usage+=tt;
2205 if (playsize > sh_audio->a_out_buffer_len) {
2206 playsize = sh_audio->a_out_buffer_len;
2207 if (audio_eof)
2208 playflags |= AOPLAY_FINAL_CHUNK;
2210 if (!playsize)
2211 return 1;
2213 // play audio:
2214 current_module="play_audio";
2216 // Is this pts value actually useful for the aos that access it?
2217 // They're obviously badly broken in the way they handle av sync;
2218 // would not having access to this make them more broken?
2219 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2220 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2222 if (playsize > 0) {
2223 sh_audio->a_out_buffer_len -= playsize;
2224 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2225 sh_audio->a_out_buffer_len);
2226 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2227 } else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2228 // Sanity check to avoid hanging in case current ao doesn't output
2229 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2230 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2231 sh_audio->a_out_buffer_len = 0;
2234 /* The format change isn't handled too gracefully. A more precise
2235 * implementation would require draining buffered old-format audio
2236 * while displaying video, then doing the output format switch.
2238 if (format_change) {
2239 uninit_player(mpctx, INITIALIZED_AO);
2240 reinit_audio_chain(mpctx);
2243 return 1;
2246 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2247 float *aq_sleep_time)
2249 struct MPOpts *opts = &mpctx->opts;
2250 double audio_limit = 2;
2251 current_module="calc_sleep_time";
2253 *time_frame -= get_relative_time(mpctx); // reset timer
2255 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2256 float delay = mpctx->audio_out->get_delay();
2257 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2259 if (opts->autosync) {
2261 * Adjust this raw delay value by calculating the expected
2262 * delay for this frame and generating a new value which is
2263 * weighted between the two. The higher autosync is, the
2264 * closer to the delay value gets to that which "-nosound"
2265 * would have used, and the longer it will take for A/V
2266 * sync to settle at the right value (but it eventually will.)
2267 * This settling time is very short for values below 100.
2269 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2270 float difference = delay - predicted;
2271 delay = predicted + difference / (float)opts->autosync;
2274 *time_frame = delay - mpctx->delay / opts->playback_speed;
2276 // delay = amount of audio buffered in soundcard/driver
2277 delay = FFMIN(delay, 0.5);
2278 delay = FFMAX(delay, 0.1);
2279 audio_limit = delay;
2280 } else {
2281 // If we're lagging more than 200 ms behind the right playback rate,
2282 // don't try to "catch up".
2283 // If benchmark is set always output frames as fast as possible
2284 // without sleeping.
2285 if (*time_frame < -0.2 || opts->benchmark)
2286 *time_frame = 0;
2289 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2291 if (t <= 0.05)
2292 return 0;
2294 t -= 0.05;
2295 if (t > audio_limit * 0.6)
2296 t = audio_limit * 0.5;
2297 *aq_sleep_time += t;
2298 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2299 return 1;
2302 int reinit_video_chain(struct MPContext *mpctx)
2304 struct MPOpts *opts = &mpctx->opts;
2305 sh_video_t * const sh_video = mpctx->sh_video;
2306 double ar=-1.0;
2307 //================== Init VIDEO (codec & libvo) ==========================
2308 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2309 current_module="preinit_libvo";
2311 //shouldn't we set dvideo->id=-2 when we fail?
2312 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2313 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2314 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2315 goto err_out;
2317 mpctx->initialized_flags|=INITIALIZED_VO;
2320 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2321 mpctx->sh_video->stream_aspect = ar;
2322 current_module="init_video_filters";
2324 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2325 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2327 #ifdef CONFIG_MENU
2328 if(use_menu) {
2329 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2330 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2331 if(!vf_menu) {
2332 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2333 use_menu = 0;
2336 if(vf_menu)
2337 sh_video->vfilter = vf_menu;
2338 #endif
2340 #ifdef CONFIG_ASS
2341 if(opts->ass_enabled) {
2342 int i;
2343 int insert = 1;
2344 if (opts->vf_settings)
2345 for (i = 0; opts->vf_settings[i].name; ++i)
2346 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2347 insert = 0;
2348 break;
2350 if (insert) {
2351 extern vf_info_t vf_info_ass;
2352 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2353 char* vf_arg[] = {"auto", "1", NULL};
2354 int retcode = 0;
2355 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2356 sh_video->vfilter,
2357 "ass", vf_arg,
2358 &retcode);
2359 if (vf_ass)
2360 sh_video->vfilter = vf_ass;
2361 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2362 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2363 else
2364 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2367 #endif
2369 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2371 #ifdef CONFIG_ASS
2372 if (opts->ass_enabled)
2373 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2374 #endif
2376 current_module="init_video_codec";
2378 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2379 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2380 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2382 if(!sh_video->initialized){
2383 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2384 goto err_out;
2387 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2389 if (sh_video->codec)
2390 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2392 sh_video->last_pts = MP_NOPTS_VALUE;
2393 sh_video->num_buffered_pts = 0;
2394 sh_video->next_frame_time = 0;
2396 if (opts->auto_quality > 0) {
2397 // Auto quality option enabled
2398 output_quality=get_video_quality_max(sh_video);
2399 if (opts->auto_quality > output_quality)
2400 opts->auto_quality = output_quality;
2401 else
2402 output_quality = opts->auto_quality;
2403 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2404 set_video_quality(sh_video,output_quality);
2407 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2409 current_module="init_vo";
2411 return 1;
2413 err_out:
2414 mpctx->sh_video = mpctx->d_video->sh = NULL;
2415 return 0;
2418 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2420 struct sh_video *sh_video = mpctx->sh_video;
2421 double frame_time = 0;
2422 struct vo *video_out = mpctx->video_out;
2423 while (1) {
2424 current_module = "filter_video";
2425 // In nocorrect-pts mode there is no way to properly time these frames
2426 if (vo_get_buffered_frame(video_out, 0) >= 0)
2427 break;
2428 if (vf_output_queued_frame(sh_video->vfilter))
2429 break;
2430 unsigned char *packet = NULL;
2431 frame_time = sh_video->next_frame_time;
2432 if (mpctx->restart_playback)
2433 frame_time = 0;
2434 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2435 &packet, force_fps);
2436 if (in_size < 0) {
2437 #ifdef CONFIG_DVDNAV
2438 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2439 if (mp_dvdnav_is_eof(mpctx->stream))
2440 return -1;
2441 if (mpctx->d_video)
2442 mpctx->d_video->eof = 0;
2443 if (mpctx->d_audio)
2444 mpctx->d_audio->eof = 0;
2445 mpctx->stream->eof = 0;
2446 } else
2447 #endif
2448 return -1;
2450 if (in_size > max_framesize)
2451 max_framesize = in_size;
2452 sh_video->timer += frame_time;
2453 if (mpctx->sh_audio)
2454 mpctx->delay -= frame_time;
2455 // video_read_frame can change fps (e.g. for ASF video)
2456 vo_fps = sh_video->fps;
2457 int framedrop_type = check_framedrop(mpctx, frame_time);
2458 current_module = "decode video";
2460 void *decoded_frame;
2461 #ifdef CONFIG_DVDNAV
2462 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2463 if (in_size >= 0 && !decoded_frame)
2464 #endif
2465 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2466 sh_video->pts);
2467 #ifdef CONFIG_DVDNAV
2468 // Save last still frame for future display
2469 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2470 #endif
2471 if (decoded_frame) {
2472 current_module = "filter video";
2473 filter_video(sh_video, decoded_frame, sh_video->pts);
2475 break;
2477 return frame_time;
2480 static void determine_frame_pts(struct MPContext *mpctx)
2482 struct sh_video *sh_video = mpctx->sh_video;
2483 struct MPOpts *opts = &mpctx->opts;
2485 if (opts->user_pts_assoc_mode) {
2486 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2487 } else if (sh_video->pts_assoc_mode == 0) {
2488 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2489 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2490 sh_video->pts_assoc_mode = 1;
2491 else
2492 sh_video->pts_assoc_mode = 2;
2493 } else {
2494 int probcount1 = sh_video->num_reordered_pts_problems;
2495 int probcount2 = sh_video->num_sorted_pts_problems;
2496 if (sh_video->pts_assoc_mode == 2) {
2497 int tmp = probcount1;
2498 probcount1 = probcount2;
2499 probcount2 = tmp;
2501 if (probcount1 >= probcount2 * 1.5 + 2) {
2502 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2503 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2504 "%d.\n", sh_video->pts_assoc_mode);
2507 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2508 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2511 static double update_video(struct MPContext *mpctx)
2513 struct sh_video *sh_video = mpctx->sh_video;
2514 struct vo *video_out = mpctx->video_out;
2515 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2516 mpctx->osd); // hack for vf_expand
2517 if (!mpctx->opts.correct_pts)
2518 return update_video_nocorrect_pts(mpctx);
2520 double pts;
2522 while (1) {
2523 current_module = "filter_video";
2524 if (!mpctx->hrseek_active
2525 && vo_get_buffered_frame(video_out, false) >= 0)
2526 break;
2527 // XXX Time used in this call is not counted in any performance
2528 // timer now
2529 if (vf_output_queued_frame(sh_video->vfilter))
2530 break;
2531 unsigned char *packet = NULL;
2532 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2533 if (pts != MP_NOPTS_VALUE)
2534 pts += mpctx->video_offset;
2535 bool hit_eof = false;
2536 if (in_size < 0) {
2537 // try to extract last frames in case of decoder lag
2538 in_size = 0;
2539 pts = MP_NOPTS_VALUE;
2540 hit_eof = true;
2542 if (in_size > max_framesize)
2543 max_framesize = in_size;
2544 current_module = "decode video";
2545 if (pts >= mpctx->hrseek_pts - .005)
2546 mpctx->hrseek_framedrop = false;
2547 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2548 check_framedrop(mpctx, sh_video->frametime);
2549 void *decoded_frame = decode_video(sh_video, packet, in_size,
2550 framedrop_type, pts);
2551 if (decoded_frame) {
2552 determine_frame_pts(mpctx);
2553 current_module = "filter video";
2554 filter_video(sh_video, decoded_frame, sh_video->pts);
2555 } else if (hit_eof) {
2556 if (vo_get_buffered_frame(video_out, true) < 0)
2557 return -1;
2559 break;
2562 if (!video_out->frame_loaded)
2563 return 0;
2565 pts = video_out->next_pts;
2566 if (pts == MP_NOPTS_VALUE) {
2567 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2568 // Try to use decoder pts from before filters
2569 pts = sh_video->pts;
2570 if (pts == MP_NOPTS_VALUE)
2571 pts = sh_video->last_pts;
2573 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005)
2574 return 0;
2575 mpctx->hrseek_active = false;
2576 sh_video->pts = pts;
2577 if (sh_video->last_pts == MP_NOPTS_VALUE)
2578 sh_video->last_pts = sh_video->pts;
2579 else if (sh_video->last_pts > sh_video->pts) {
2580 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2581 sh_video->pts, sh_video->last_pts);
2582 /* If the difference in pts is small treat it as jitter around the
2583 * right value (possibly caused by incorrect timestamp ordering) and
2584 * just show this frame immediately after the last one.
2585 * Treat bigger differences as timestamp resets and start counting
2586 * timing of later frames from the position of this one. */
2587 if (sh_video->last_pts - sh_video->pts > 0.5)
2588 sh_video->last_pts = sh_video->pts;
2589 else
2590 sh_video->pts = sh_video->last_pts;
2592 double frame_time = sh_video->pts - sh_video->last_pts;
2593 sh_video->last_pts = sh_video->pts;
2594 sh_video->timer += frame_time;
2595 if (mpctx->sh_audio)
2596 mpctx->delay -= frame_time;
2597 return frame_time;
2600 void pause_player(struct MPContext *mpctx)
2602 if (mpctx->paused)
2603 return;
2604 mpctx->paused = 1;
2605 mpctx->step_frames = 0;
2606 mpctx->time_frame -= get_relative_time(mpctx);
2608 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2609 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2611 if (mpctx->audio_out && mpctx->sh_audio)
2612 mpctx->audio_out->pause(); // pause audio, keep data if possible
2615 void unpause_player(struct MPContext *mpctx)
2617 if (!mpctx->paused)
2618 return;
2619 mpctx->paused = 0;
2621 if (mpctx->audio_out && mpctx->sh_audio)
2622 mpctx->audio_out->resume(); // resume audio
2623 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2624 && !mpctx->step_frames)
2625 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2626 (void)get_relative_time(mpctx); // ignore time that passed during pause
2629 void add_step_frame(struct MPContext *mpctx)
2631 mpctx->step_frames++;
2632 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2633 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2634 unpause_player(mpctx);
2637 static void pause_loop(struct MPContext *mpctx)
2639 struct MPOpts *opts = &mpctx->opts;
2640 mp_cmd_t* cmd;
2641 if (!opts->quiet) {
2642 // Small hack to display the pause message on the OSD line.
2643 // The pause string is: "\n == PAUSE == \r" so we need to
2644 // take the first and the last char out
2645 if (opts->term_osd && !mpctx->sh_video) {
2646 char msg[128] = _("\n ===== PAUSE =====\r");
2647 int mlen = strlen(msg);
2648 msg[mlen-1] = '\0';
2649 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2650 update_osd_msg(mpctx);
2651 } else
2652 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2653 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2656 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2657 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2658 if (cmd) {
2659 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2660 run_command(mpctx, cmd);
2661 mp_cmd_free(cmd);
2662 continue;
2664 if (mpctx->sh_video && mpctx->video_out)
2665 vo_check_events(mpctx->video_out);
2666 #ifdef CONFIG_MENU
2667 if (vf_menu)
2668 vf_menu_pause_update(vf_menu);
2669 #endif
2670 usec_sleep(20000);
2671 update_osd_msg(mpctx);
2672 int hack = vo_osd_changed(0);
2673 vo_osd_changed(hack);
2674 if (hack)
2675 break;
2680 // Find the right mute status and record position for new file position
2681 static void edl_seek_reset(MPContext *mpctx)
2683 mpctx->edl_muted = 0;
2684 next_edl_record = edl_records;
2686 while (next_edl_record) {
2687 if (next_edl_record->start_sec >= get_current_time(mpctx))
2688 break;
2690 if (next_edl_record->action == EDL_MUTE)
2691 mpctx->edl_muted = !mpctx->edl_muted;
2692 next_edl_record = next_edl_record->next;
2694 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2695 mixer_mute(&mpctx->mixer);
2699 // Execute EDL command for the current position if one exists
2700 static void edl_update(MPContext *mpctx)
2702 if (!next_edl_record)
2703 return;
2705 if (!mpctx->sh_video) {
2706 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2707 free_edl(edl_records);
2708 next_edl_record = NULL;
2709 edl_records = NULL;
2710 return;
2713 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2714 if (next_edl_record->action == EDL_SKIP) {
2715 mpctx->osd_function = OSD_FFW;
2716 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2717 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2718 "[%f], length [%f]\n", next_edl_record->start_sec,
2719 next_edl_record->stop_sec, next_edl_record->length_sec);
2721 else if (next_edl_record->action == EDL_MUTE) {
2722 mpctx->edl_muted = !mpctx->edl_muted;
2723 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2724 mixer_mute(&mpctx->mixer);
2725 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2726 next_edl_record->start_sec );
2728 next_edl_record = next_edl_record->next;
2732 static void reinit_decoders(struct MPContext *mpctx)
2734 reinit_video_chain(mpctx);
2735 reinit_audio_chain(mpctx);
2736 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2739 static void seek_reset(struct MPContext *mpctx)
2741 if (mpctx->sh_video) {
2742 current_module = "seek_video_reset";
2743 resync_video_stream(mpctx->sh_video);
2744 mpctx->sh_video->timer = 0;
2745 vo_seek_reset(mpctx->video_out);
2746 mpctx->sh_video->timer = 0;
2747 mpctx->sh_video->num_buffered_pts = 0;
2748 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2749 mpctx->delay = 0;
2750 mpctx->time_frame = 0;
2751 mpctx->restart_playback = true;
2752 // Not all demuxers set d_video->pts during seek, so this value
2753 // (which is used by at least vobsub and edl code below) may
2754 // be completely wrong (probably 0).
2755 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2756 mpctx->video_pts = mpctx->sh_video->pts;
2757 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2758 mpctx->sh_video->pts, mpctx->video_offset,
2759 mpctx->d_sub, 1);
2760 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2763 if (mpctx->sh_audio) {
2764 current_module = "seek_audio_reset";
2765 resync_audio_stream(mpctx->sh_audio);
2766 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2767 mpctx->sh_audio->a_buffer_len = 0;
2768 mpctx->sh_audio->a_out_buffer_len = 0;
2769 if (!mpctx->sh_video)
2770 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2771 mpctx->video_offset, mpctx->d_sub, 1);
2774 if (vo_vobsub && mpctx->sh_video) {
2775 current_module = "seek_vobsub_reset";
2776 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2779 edl_seek_reset(mpctx);
2781 mpctx->hrseek_active = false;
2782 mpctx->hrseek_framedrop = false;
2783 mpctx->total_avsync_change = 0;
2784 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2785 drop_frame_cnt = 0;
2787 current_module = NULL;
2790 static bool timeline_set_part(struct MPContext *mpctx, int i)
2792 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2793 struct timeline_part *n = mpctx->timeline + i;
2794 mpctx->timeline_part = i;
2795 mpctx->video_offset = n->start - n->source_start;
2796 if (n->source == p->source)
2797 return false;
2798 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2799 mpctx->demuxer = n->source->demuxer;
2800 mpctx->d_video = mpctx->demuxer->video;
2801 mpctx->d_audio = mpctx->demuxer->audio;
2802 mpctx->d_sub = mpctx->demuxer->sub;
2803 mpctx->sh_video = mpctx->d_video->sh;
2804 mpctx->sh_audio = mpctx->d_audio->sh;
2805 return true;
2808 // Given pts, switch playback to the corresponding part.
2809 // Return offset within that part.
2810 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2811 bool *need_reset)
2813 if (pts < 0)
2814 pts = 0;
2815 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2816 struct timeline_part *p = mpctx->timeline + i;
2817 if (pts < (p+1)->start) {
2818 *need_reset = timeline_set_part(mpctx, i);
2819 return pts - p->start + p->source_start;
2822 return -1;
2826 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2827 static int seek(MPContext *mpctx, struct seek_params seek)
2829 struct MPOpts *opts = &mpctx->opts;
2831 current_module = "seek";
2832 if (mpctx->stop_play == AT_END_OF_FILE)
2833 mpctx->stop_play = KEEP_PLAYING;
2834 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
2835 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
2836 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
2837 || opts->hr_seek > 0 || seek.exact > 0;
2838 if (seek.type == MPSEEK_FACTOR
2839 || seek.type == MPSEEK_ABSOLUTE
2840 && seek.amount < mpctx->last_chapter_pts
2841 || seek.amount < 0)
2842 mpctx->last_chapter_seek = -1;
2843 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
2844 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2845 seek.type = MPSEEK_ABSOLUTE;
2847 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
2848 && seek.type == MPSEEK_RELATIVE) {
2849 seek.type = MPSEEK_ABSOLUTE;
2850 seek.direction = seek.amount > 0 ? 1 : -1;
2851 seek.amount += get_current_time(mpctx);
2854 /* At least the liba52 decoder wants to read from the input stream
2855 * during initialization, so reinit must be done after the demux_seek()
2856 * call that clears possible stream EOF. */
2857 bool need_reset = false;
2858 double demuxer_amount = seek.amount;
2859 if (mpctx->timeline) {
2860 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
2861 &need_reset);
2862 if (demuxer_amount == -1) {
2863 mpctx->stop_play = AT_END_OF_FILE;
2864 // Clear audio from current position
2865 if (mpctx->sh_audio) {
2866 mpctx->audio_out->reset();
2867 mpctx->sh_audio->a_buffer_len = 0;
2868 mpctx->sh_audio->a_out_buffer_len = 0;
2870 return -1;
2873 int demuxer_style = 0;
2874 switch (seek.type) {
2875 case MPSEEK_FACTOR:
2876 demuxer_style |= SEEK_FACTOR; // fallthrough
2877 case MPSEEK_ABSOLUTE:
2878 demuxer_style |= SEEK_ABSOLUTE;
2880 if (hr_seek || seek.direction < 0)
2881 demuxer_style |= SEEK_BACKWARD;
2882 else if (seek.direction > 0)
2883 demuxer_style |= SEEK_FORWARD;
2885 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
2886 demuxer_style);
2887 if (need_reset)
2888 reinit_decoders(mpctx);
2889 if (seekresult == 0)
2890 return -1;
2892 seek_reset(mpctx);
2894 /* Use the target time as "current position" for further relative
2895 * seeks etc until a new video frame has been decoded */
2896 if (seek.type == MPSEEK_ABSOLUTE)
2897 mpctx->video_pts = seek.amount;
2899 if (hr_seek) {
2900 mpctx->hrseek_active = true;
2901 mpctx->hrseek_framedrop = true;
2902 mpctx->hrseek_pts = seek.amount;
2905 mpctx->start_timestamp = GetTimerMS();
2907 return 0;
2910 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
2911 int exact)
2913 struct seek_params *seek = &mpctx->seek;
2914 switch (type) {
2915 case MPSEEK_RELATIVE:
2916 if (seek->type == MPSEEK_FACTOR)
2917 return; // Well... not common enough to bother doing better
2918 seek->amount += amount;
2919 seek->exact = FFMAX(seek->exact, exact);
2920 if (seek->type == MPSEEK_NONE)
2921 seek->exact = exact;
2922 if (seek->type == MPSEEK_ABSOLUTE)
2923 return;
2924 if (seek->amount == 0) {
2925 *seek = (struct seek_params){0};
2926 return;
2928 seek->type = MPSEEK_RELATIVE;
2929 return;
2930 case MPSEEK_ABSOLUTE:
2931 case MPSEEK_FACTOR:
2932 *seek = (struct seek_params) {
2933 .type = type,
2934 .amount = amount,
2935 .exact = exact,
2937 return;
2938 case MPSEEK_NONE:
2939 *seek = (struct seek_params){0};
2940 return;
2942 abort();
2946 double get_time_length(struct MPContext *mpctx)
2948 if (mpctx->timeline)
2949 return mpctx->timeline[mpctx->num_timeline_parts].start;
2951 struct demuxer *demuxer = mpctx->demuxer;
2952 double get_time_ans;
2953 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
2954 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
2955 (void *) &get_time_ans) > 0)
2956 return get_time_ans;
2958 struct sh_video *sh_video = mpctx->d_video->sh;
2959 struct sh_audio *sh_audio = mpctx->d_audio->sh;
2960 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
2961 return (double) (demuxer->movi_end - demuxer->movi_start) /
2962 (sh_video->i_bps + sh_audio->i_bps);
2963 if (sh_video && sh_video->i_bps)
2964 return (double) (demuxer->movi_end - demuxer->movi_start) /
2965 sh_video->i_bps;
2966 if (sh_audio && sh_audio->i_bps)
2967 return (double) (demuxer->movi_end - demuxer->movi_start) /
2968 sh_audio->i_bps;
2969 return 0;
2972 /* If there are timestamps from stream level then use those (for example
2973 * DVDs can have consistent times there while the MPEG-level timestamps
2974 * reset). */
2975 double get_current_time(struct MPContext *mpctx)
2977 struct demuxer *demuxer = mpctx->demuxer;
2978 if (demuxer->stream_pts != MP_NOPTS_VALUE)
2979 return demuxer->stream_pts;
2980 struct sh_video *sh_video = demuxer->video->sh;
2981 if (sh_video)
2982 return mpctx->video_pts;
2983 return playing_audio_pts(mpctx);
2986 int get_percent_pos(struct MPContext *mpctx)
2988 struct demuxer *demuxer = mpctx->demuxer;
2989 int ans = 0;
2990 if (mpctx->timeline)
2991 ans = get_current_time(mpctx) * 100 /
2992 mpctx->timeline[mpctx->num_timeline_parts].start;
2993 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
2995 else {
2996 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
2997 off_t pos = demuxer->filepos > 0 ?
2998 demuxer->filepos : stream_tell(demuxer->stream);
2999 if (len > 0)
3000 ans = (pos - demuxer->movi_start) / len;
3001 else
3002 ans = 0;
3004 if (ans < 0)
3005 ans = 0;
3006 if (ans > 100)
3007 ans = 100;
3008 return ans;
3011 // -2 is no chapters, -1 is before first chapter
3012 int get_current_chapter(struct MPContext *mpctx)
3014 double current_pts = get_current_time(mpctx);
3015 if (!mpctx->chapters)
3016 return FFMAX(mpctx->last_chapter_seek,
3017 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3019 int i;
3020 for (i = 1; i < mpctx->num_chapters; i++)
3021 if (current_pts < mpctx->chapters[i].start)
3022 break;
3023 return FFMAX(mpctx->last_chapter_seek, i - 1);
3026 // currently returns a string allocated with malloc, not talloc
3027 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3029 if (!mpctx->chapters || !mpctx->sh_video)
3030 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3031 return strdup(mpctx->chapters[chapter].name);
3034 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3035 char **chapter_name)
3037 mpctx->last_chapter_seek = -1;
3038 if (!mpctx->chapters || !mpctx->sh_video) {
3039 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3040 chapter_name);
3041 if (res >= 0) {
3042 if (*seek_pts == -1)
3043 seek_reset(mpctx);
3044 else {
3045 mpctx->last_chapter_seek = res;
3046 mpctx->last_chapter_pts = *seek_pts;
3049 return res;
3052 if (chapter >= mpctx->num_chapters)
3053 return -1;
3054 if (chapter < 0)
3055 chapter = 0;
3056 *seek_pts = mpctx->chapters[chapter].start;
3057 mpctx->last_chapter_seek = chapter;
3058 mpctx->last_chapter_pts = *seek_pts;
3059 if (chapter_name)
3060 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3061 return chapter;
3065 static void run_playloop(struct MPContext *mpctx)
3067 struct MPOpts *opts = &mpctx->opts;
3068 float aq_sleep_time = 0;
3070 if (opts->chapterrange[1] > 0) {
3071 int cur_chapter = get_current_chapter(mpctx);
3072 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3073 mpctx->stop_play = PT_NEXT_ENTRY;
3076 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3077 mpctx->sh_audio = mpctx->d_audio->sh;
3078 mpctx->sh_audio->ds = mpctx->d_audio;
3079 reinit_audio_chain(mpctx);
3082 /*========================== PLAY AUDIO ============================*/
3084 if (mpctx->sh_audio && !mpctx->paused
3085 && (!mpctx->restart_playback || !mpctx->sh_video))
3086 if (!fill_audio_out_buffers(mpctx))
3087 // at eof, all audio at least written to ao
3088 if (!mpctx->sh_video)
3089 mpctx->stop_play = AT_END_OF_FILE;
3092 if (!mpctx->sh_video) {
3093 mpctx->restart_playback = false;
3094 if (mpctx->step_frames) {
3095 mpctx->step_frames = 0;
3096 pause_player(mpctx);
3098 // handle audio-only case:
3099 double a_pos = 0;
3100 // sh_audio can be NULL due to video stream switching
3101 // TODO: handle this better
3102 if (mpctx->sh_audio)
3103 a_pos = playing_audio_pts(mpctx);
3105 print_status(mpctx, a_pos, false);
3107 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3108 mpctx->stop_play = PT_NEXT_ENTRY;
3109 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
3110 mpctx->d_sub, 0);
3111 update_osd_msg(mpctx);
3112 } else {
3114 /*========================== PLAY VIDEO ============================*/
3116 vo_pts = mpctx->sh_video->timer * 90000.0;
3117 vo_fps = mpctx->sh_video->fps;
3119 bool blit_frame = mpctx->video_out->frame_loaded;
3120 if (!blit_frame || mpctx->hrseek_active) {
3121 double frame_time = update_video(mpctx);
3122 blit_frame = mpctx->video_out->frame_loaded;
3123 blit_frame &= !mpctx->hrseek_active;
3124 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3125 if (mpctx->sh_video->vf_initialized < 0) {
3126 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3127 "\nFATAL: Could not initialize video filters (-vf) "
3128 "or video output (-vo).\n");
3129 mpctx->stop_play = PT_NEXT_ENTRY;
3130 return;
3132 if (frame_time < 0)
3133 mpctx->stop_play = AT_END_OF_FILE;
3134 else if (!mpctx->restart_playback) {
3135 mpctx->time_frame += frame_time / opts->playback_speed;
3136 adjust_sync(mpctx, frame_time);
3139 if (mpctx->timeline) {
3140 struct timeline_part *next =
3141 mpctx->timeline + mpctx->timeline_part + 1;
3142 if (mpctx->sh_video->pts >= next->start
3143 || mpctx->stop_play == AT_END_OF_FILE
3144 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3145 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3146 .amount = next->start });
3147 return;
3151 // ==========================================================================
3153 current_module = "vo_check_events";
3154 vo_check_events(mpctx->video_out);
3156 #ifdef CONFIG_X11
3157 if (stop_xscreensaver) {
3158 current_module = "stop_xscreensaver";
3159 xscreensaver_heartbeat(mpctx->x11_state);
3161 #endif
3162 if (heartbeat_cmd) {
3163 static unsigned last_heartbeat;
3164 unsigned now = GetTimerMS();
3165 if (now - last_heartbeat > 30000) {
3166 last_heartbeat = now;
3167 system(heartbeat_cmd);
3171 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3172 &mpctx->time_frame,
3173 &aq_sleep_time);
3175 //====================== FLIP PAGE (VIDEO BLT): =========================
3177 current_module = "flip_page";
3178 if (!frame_time_remaining && blit_frame) {
3179 struct sh_video *sh_video = mpctx->sh_video;
3180 mpctx->video_pts = sh_video->pts;
3181 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
3182 mpctx->video_offset, mpctx->d_sub, 0);
3183 update_teletext(sh_video, mpctx->demuxer, 0);
3184 update_osd_msg(mpctx);
3185 struct vf_instance *vf = sh_video->vfilter;
3186 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3187 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3188 vo_osd_changed(0);
3190 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3191 aq_sleep_time += mpctx->time_frame;
3192 // flag 256 means: libvo driver does its timing (dvb card)
3193 if (mpctx->time_frame > 0.001
3194 && !(mpctx->sh_video->output_flags&256))
3195 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3196 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3198 unsigned int t2 = GetTimer();
3199 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
3200 int duration = -1;
3201 double pts2 = mpctx->video_out->next_pts2;
3202 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3203 && !mpctx->restart_playback) {
3204 // expected A/V sync correction is ignored
3205 double diff = (pts2 - mpctx->video_pts);
3206 diff /= opts->playback_speed;
3207 if (mpctx->time_frame < 0)
3208 diff += mpctx->time_frame;
3209 if (diff < 0)
3210 diff = 0;
3211 if (diff > 10)
3212 diff = 10;
3213 duration = diff * 1e6;
3215 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3217 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3218 vout_time_usage += mpctx->last_vo_flip_duration;
3219 if (mpctx->video_out->driver->flip_page_timed) {
3220 // No need to adjust sync based on flip speed
3221 mpctx->last_vo_flip_duration = 0;
3222 // For print_status - VO call finishing early is OK for sync
3223 mpctx->time_frame -= get_relative_time(mpctx);
3225 if (mpctx->restart_playback) {
3226 mpctx->syncing_audio = true;
3227 if (mpctx->sh_audio && !mpctx->paused)
3228 fill_audio_out_buffers(mpctx);
3229 mpctx->restart_playback = false;
3230 mpctx->time_frame = 0;
3231 get_relative_time(mpctx);
3233 print_status(mpctx, MP_NOPTS_VALUE, true);
3234 } else
3235 print_status(mpctx, MP_NOPTS_VALUE, false);
3237 //============================ Auto QUALITY ============================
3239 /*Output quality adjustments:*/
3240 if (opts->auto_quality > 0) {
3241 current_module = "autoq";
3242 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3243 ++output_quality;
3244 else
3245 if (output_quality>1 && aq_sleep_time<0)
3246 --output_quality;
3247 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3248 output_quality = 0;
3249 set_video_quality(mpctx->sh_video, output_quality);
3252 if (!frame_time_remaining && blit_frame) {
3253 if (play_n_frames >= 0) {
3254 --play_n_frames;
3255 if (play_n_frames <= 0)
3256 mpctx->stop_play = PT_NEXT_ENTRY;
3258 if (mpctx->step_frames > 0) {
3259 mpctx->step_frames--;
3260 if (mpctx->step_frames == 0)
3261 pause_player(mpctx);
3265 // FIXME: add size based support for -endpos
3266 if (end_at.type == END_AT_TIME &&
3267 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3268 mpctx->stop_play = PT_NEXT_ENTRY;
3270 } // end if(mpctx->sh_video)
3272 #ifdef CONFIG_DVDNAV
3273 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3274 nav_highlight_t hl;
3275 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3276 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3277 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3278 vo_osd_changed(OSDTYPE_DVDNAV);
3279 } else {
3280 osd_set_nav_box(0, 0, 0, 0);
3281 vo_osd_changed(OSDTYPE_DVDNAV);
3282 vo_osd_changed(OSDTYPE_SPU);
3285 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3286 double ar = -1.0;
3287 if (mpctx->sh_video &&
3288 stream_control(mpctx->demuxer->stream,
3289 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3290 != STREAM_UNSUPPORTED)
3291 mpctx->sh_video->stream_aspect = ar;
3294 #endif
3296 //================= Keyboard events, SEEKing ====================
3298 current_module = "key_events";
3300 while (1) {
3301 mp_cmd_t *cmd;
3302 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3303 /* Allow running consecutive seek commands to combine them,
3304 * but execute the seek before running other commands.
3305 * If the user seeks continuously (keeps arrow key down)
3306 * try to finish showing a frame from one location before doing
3307 * another seek (which could lead to unchanging display). */
3308 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3309 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3310 && GetTimerMS() - mpctx->start_timestamp < 300)
3311 break;
3312 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3313 run_command(mpctx, cmd);
3314 mp_cmd_free(cmd);
3315 if (mpctx->stop_play)
3316 break;
3318 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3319 || mpctx->restart_playback)
3320 break;
3321 if (mpctx->sh_video) {
3322 update_osd_msg(mpctx);
3323 int hack = vo_osd_changed(0);
3324 vo_osd_changed(hack);
3325 if (hack) {
3326 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3327 add_step_frame(mpctx);
3328 break;
3329 } else
3330 vo_osd_changed(0);
3333 pause_loop(mpctx);
3336 // handle -sstep
3337 if (step_sec > 0 && !mpctx->paused) {
3338 mpctx->osd_function = OSD_FFW;
3339 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3342 edl_update(mpctx);
3344 /* Looping. */
3345 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3346 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3348 if (opts->loop_times>1)
3349 opts->loop_times--;
3350 else if (opts->loop_times==1)
3351 opts->loop_times = -1;
3352 play_n_frames = play_n_frames_mf;
3353 mpctx->stop_play = 0;
3354 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3357 if (mpctx->seek.type) {
3358 seek(mpctx, mpctx->seek);
3359 mpctx->seek = (struct seek_params){0};
3364 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3365 struct content_source *sources,
3366 int num_sources,
3367 unsigned char uid_map[][16])
3369 int num_filenames = 0;
3370 char **filenames = NULL;
3371 if (num_sources > 1) {
3372 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3373 "other sources.\n");
3374 if (mpctx->stream->type != STREAMTYPE_FILE) {
3375 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3376 "normal disk file. Will not search for related files.\n");
3377 } else {
3378 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3379 "same directory to find referenced sources.\n");
3380 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3381 &num_filenames);
3385 int num_left = num_sources - 1;
3386 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3387 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3388 filename_recode(filenames[i]));
3389 int format;
3390 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3391 if (!s)
3392 continue;
3393 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3394 mpctx->opts.audio_id,
3395 mpctx->opts.video_id,
3396 mpctx->opts.sub_id, filenames[i]);
3397 if (!d) {
3398 free_stream(s);
3399 continue;
3401 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3402 for (int i = 1; i < num_sources; i++) {
3403 if (sources[i].demuxer)
3404 continue;
3405 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3406 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3407 i, filename_recode(d->filename));
3408 sources[i].stream = s;
3409 sources[i].demuxer = d;
3410 num_left--;
3411 goto match;
3415 free_demuxer(d);
3416 free_stream(s);
3417 continue;
3418 match:
3421 talloc_free(filenames);
3422 if (num_left) {
3423 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3424 "There will be parts MISSING from the video!\n");
3425 for (int i = 1, j = 1; i < num_sources; i++)
3426 if (sources[i].demuxer) {
3427 sources[j] = sources[i];
3428 memcpy(uid_map[j], uid_map[i], 16);
3429 j++;
3432 return num_sources - num_left;
3435 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3437 struct MPOpts *opts = &mpctx->opts;
3439 if (!opts->ordered_chapters) {
3440 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3441 "you have disabled support for them. Ignoring.\n");
3442 return;
3445 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3446 "edit timeline.\n");
3448 struct demuxer *demuxer = mpctx->demuxer;
3449 struct matroska_data *m = &demuxer->matroska_data;
3451 // +1 because sources/uid_map[0] is original file even if all chapters
3452 // actually use other sources and need separate entries
3453 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3454 m->num_ordered_chapters+1);
3455 sources[0].stream = mpctx->stream;
3456 sources[0].demuxer = mpctx->demuxer;
3457 unsigned char uid_map[m->num_ordered_chapters+1][16];
3458 int num_sources = 1;
3459 memcpy(uid_map[0], m->segment_uid, 16);
3461 for (int i = 0; i < m->num_ordered_chapters; i++) {
3462 struct matroska_chapter *c = m->ordered_chapters + i;
3463 if (!c->has_segment_uid)
3464 memcpy(c->segment_uid, m->segment_uid, 16);
3466 for (int j = 0; j < num_sources; j++)
3467 if (!memcmp(c->segment_uid, uid_map[j], 16))
3468 goto found1;
3469 memcpy(uid_map[num_sources], c->segment_uid, 16);
3470 sources[num_sources] = (struct content_source){};
3471 num_sources++;
3472 found1:
3476 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3477 uid_map);
3480 // +1 for terminating chapter with start time marking end of last real one
3481 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3482 m->num_ordered_chapters + 1);
3483 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3484 m->num_ordered_chapters);
3485 uint64_t starttime = 0;
3486 uint64_t missing_time = 0;
3487 int part_count = 0;
3488 int num_chapters = 0;
3489 uint64_t prev_part_offset = 0;
3490 for (int i = 0; i < m->num_ordered_chapters; i++) {
3491 struct matroska_chapter *c = m->ordered_chapters + i;
3493 int j;
3494 for (j = 0; j < num_sources; j++) {
3495 if (!memcmp(c->segment_uid, uid_map[j], 16))
3496 goto found2;
3498 missing_time += c->end - c->start;
3499 continue;
3500 found2:;
3501 /* Only add a separate part if the time or file actually changes.
3502 * Matroska files have chapter divisions that are redundant from
3503 * timeline point of view because the same chapter structure is used
3504 * both to specify the timeline and for normal chapter information.
3505 * Removing a missing inserted external chapter can also cause this.
3506 * We allow for a configurable fudge factor because of files which
3507 * specify chapter end times that are one frame too early;
3508 * we don't want to try seeking over a one frame gap. */
3509 int64_t join_diff = c->start - starttime - prev_part_offset;
3510 if (part_count == 0 || FFABS(join_diff) > opts->chapter_merge_threshold
3511 || sources + j != timeline[part_count - 1].source) {
3512 timeline[part_count].source = sources + j;
3513 timeline[part_count].start = starttime / 1000.;
3514 timeline[part_count].source_start = c->start / 1000.;
3515 prev_part_offset = c->start - starttime;
3516 part_count++;
3517 } else if (part_count > 0 && join_diff) {
3518 /* Chapter was merged at an inexact boundary;
3519 * adjust timestamps to match. */
3520 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3521 "offset %d ms.\n", i, (int) join_diff);
3522 starttime += join_diff;
3524 chapters[num_chapters].start = starttime / 1000.;
3525 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3526 starttime += c->end - c->start;
3527 num_chapters++;
3529 timeline[part_count].start = starttime / 1000.;
3531 if (!part_count) {
3532 // None of the parts come from the file itself???
3533 talloc_free(sources);
3534 talloc_free(timeline);
3535 talloc_free(chapters);
3536 return;
3539 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3540 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3541 timeline[part_count].start);
3542 if (missing_time)
3543 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3544 "from the timeline!\n", missing_time / 1000.);
3545 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3546 for (int i = 0; i < num_sources; i++)
3547 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3548 filename_recode(sources[i].demuxer->filename));
3549 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3550 "source_start, source):\n");
3551 for (int i = 0; i < part_count; i++) {
3552 struct timeline_part *p = timeline + i;
3553 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3554 p->source_start, p->source - sources);
3556 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3557 mpctx->sources = sources;
3558 mpctx->num_sources = num_sources;
3559 mpctx->timeline = timeline;
3560 mpctx->num_timeline_parts = part_count;
3561 mpctx->num_chapters = num_chapters;
3562 mpctx->chapters = chapters;
3564 mpctx->timeline_part = 0;
3565 mpctx->demuxer = timeline[0].source->demuxer;
3569 static int read_keys(void *ctx, int fd)
3571 getch2(ctx);
3572 return mplayer_get_key(ctx, 0);
3576 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3577 * file for some tools to link against. */
3578 #ifndef DISABLE_MAIN
3579 int main(int argc,char* argv[]){
3582 char * mem_ptr;
3584 // movie info:
3586 /* Flag indicating whether MPlayer should exit without playing anything. */
3587 int opt_exit = 0;
3588 int i;
3590 struct MPContext *mpctx = &(struct MPContext){
3591 .osd_function = OSD_PLAY,
3592 .begin_skip = MP_NOPTS_VALUE,
3593 .play_tree_step = 1,
3594 .global_sub_pos = -1,
3595 .set_of_sub_pos = -1,
3596 .file_format = DEMUXER_TYPE_UNKNOWN,
3597 .last_dvb_step = 1,
3600 InitTimer();
3601 srand(GetTimerMS());
3603 mp_msg_init();
3604 set_av_log_callback();
3606 #ifdef CONFIG_X11
3607 mpctx->x11_state = vo_x11_init_state();
3608 #endif
3609 struct MPOpts *opts = &mpctx->opts;
3610 set_default_mplayer_options(opts);
3611 // Create the config context and register the options
3612 mpctx->mconfig = m_config_new(opts, cfg_include);
3613 m_config_register_options(mpctx->mconfig,mplayer_opts);
3614 m_config_register_options(mpctx->mconfig, common_opts);
3615 mp_input_register_options(mpctx->mconfig);
3617 // Preparse the command line
3618 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3620 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3621 set_path_env();
3622 #endif
3624 #ifdef CONFIG_TV
3625 stream_tv_defaults.immediate = 1;
3626 #endif
3628 parse_cfgfiles(mpctx, mpctx->mconfig);
3630 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3631 if(mpctx->playtree == NULL)
3632 opt_exit = 1;
3633 else {
3634 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3635 if(mpctx->playtree) {
3636 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3637 if(mpctx->playtree_iter) {
3638 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3639 play_tree_iter_free(mpctx->playtree_iter);
3640 mpctx->playtree_iter = NULL;
3642 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3646 mpctx->key_fifo = mp_fifo_create(opts);
3648 print_version("MPlayer");
3650 #if defined(__MINGW32__) || defined(__CYGWIN__)
3652 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3653 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3654 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3655 if (kernel32) {
3656 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3657 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3659 if (setDEP) setDEP(3);
3660 if (setDllDir) setDllDir("");
3662 // stop Windows from showing all kinds of annoying error dialogs
3663 SetErrorMode(0x8003);
3664 // request 1ms timer resolution
3665 timeBeginPeriod(1);
3666 #endif
3668 #ifdef CONFIG_PRIORITY
3669 set_priority();
3670 #endif
3672 if (codec_path)
3673 set_codec_path(codec_path);
3675 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3676 list_video_out();
3677 opt_exit = 1;
3680 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3681 list_audio_out();
3682 opt_exit = 1;
3685 /* Check codecs.conf. */
3686 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3687 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3688 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3689 if(!parse_codec_cfg(NULL)){
3690 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3692 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3695 free( mem_ptr ); // release the buffer created by get_path()
3698 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3699 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3700 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3701 list_codecs(1);
3702 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3703 opt_exit = 1;
3705 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3706 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3707 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3708 list_codecs(0);
3709 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3710 opt_exit = 1;
3712 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3713 vfm_help();
3714 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3715 opt_exit = 1;
3717 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3718 afm_help();
3719 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3720 opt_exit = 1;
3722 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3723 af_help();
3724 printf("\n");
3725 opt_exit = 1;
3727 #ifdef CONFIG_X11
3728 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3729 fstype_help();
3730 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3731 opt_exit = 1;
3733 #endif
3734 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3735 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3736 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3737 demuxer_help();
3738 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3739 opt_exit = 1;
3741 if (opts->list_properties) {
3742 property_print_help();
3743 opt_exit = 1;
3746 if(opt_exit)
3747 exit_player(mpctx, EXIT_NONE);
3749 if (!mpctx->filename && !opts->player_idle_mode) {
3750 // no file/vcd/dvd -> show HELP:
3751 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3752 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3755 /* Display what configure line was used */
3756 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3758 // Many users forget to include command line in bugreports...
3759 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3760 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3761 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3762 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3765 //------ load global data first ------
3767 mpctx->osd = osd_create();
3769 // check font
3770 #ifdef CONFIG_FREETYPE
3771 init_freetype();
3772 #endif
3773 #ifdef CONFIG_FONTCONFIG
3774 if(font_fontconfig <= 0)
3776 #endif
3777 #ifdef CONFIG_BITMAP_FONT
3778 if(font_name){
3779 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3780 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3781 filename_recode(font_name));
3782 } else {
3783 // try default:
3784 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3785 free(mem_ptr); // release the buffer created by get_path()
3786 if(!vo_font)
3787 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3789 if (sub_font_name)
3790 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3791 else
3792 mpctx->osd->sub_font = vo_font;
3793 #endif
3794 #ifdef CONFIG_FONTCONFIG
3796 #endif
3798 #ifdef CONFIG_ASS
3799 ass_library = ass_init();
3800 #endif
3802 #ifdef HAVE_RTC
3803 if(opts->rtc)
3805 char *rtc_device = opts->rtc_device;
3806 // seteuid(0); /* Can't hurt to try to get root here */
3807 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3808 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3809 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3810 else {
3811 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3813 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3814 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3815 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3816 close (rtc_fd);
3817 rtc_fd = -1;
3818 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3819 /* variable only by the root */
3820 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3821 close (rtc_fd);
3822 rtc_fd = -1;
3823 } else
3824 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3827 if(rtc_fd<0)
3828 #endif /* HAVE_RTC */
3829 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3830 opts->softsleep ? "software" : timer_name);
3832 #ifdef HAVE_TERMCAP
3833 load_termcap(NULL); // load key-codes
3834 #endif
3836 // ========== Init keyboard FIFO (connection to libvo) ============
3838 // Init input system
3839 current_module = "init_input";
3840 mpctx->input = mp_input_init(&opts->input);
3841 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3842 if(slave_mode)
3843 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3844 else if (opts->consolecontrols)
3845 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3846 // Set the libstream interrupt callback
3847 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3849 #ifdef CONFIG_MENU
3850 if(use_menu) {
3851 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3852 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3853 else {
3854 menu_cfg = get_path("menu.conf");
3855 if(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 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3859 MPLAYER_CONFDIR "/menu.conf"))
3860 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3861 else {
3862 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3863 use_menu = 0;
3868 #endif
3870 current_module = NULL;
3872 /// Catch signals
3873 #ifndef __MINGW32__
3874 signal(SIGCHLD,child_sighandler);
3875 #endif
3877 #ifdef CONFIG_CRASH_DEBUG
3878 prog_path = argv[0];
3879 #endif
3880 //========= Catch terminate signals: ================
3881 // terminate requests:
3882 signal(SIGTERM,exit_sighandler); // kill
3883 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3885 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3887 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3888 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3889 #ifdef CONFIG_SIGHANDLER
3890 // fatal errors:
3891 signal(SIGBUS,exit_sighandler); // bus error
3892 signal(SIGSEGV,exit_sighandler); // segfault
3893 signal(SIGILL,exit_sighandler); // illegal instruction
3894 signal(SIGFPE,exit_sighandler); // floating point exc.
3895 signal(SIGABRT,exit_sighandler); // abort()
3896 #ifdef CONFIG_CRASH_DEBUG
3897 if (crash_debug)
3898 signal(SIGTRAP,exit_sighandler);
3899 #endif
3900 #endif
3902 // ******************* Now, let's see the per-file stuff ********************
3904 play_next_file:
3906 // init global sub numbers
3907 mpctx->global_sub_size = 0;
3908 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3910 if (mpctx->filename) {
3911 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3912 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3913 load_per_file_config (mpctx->mconfig, mpctx->filename);
3916 if (opts->video_driver_list)
3917 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3918 if (opts->audio_driver_list)
3919 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3921 // We must enable getch2 here to be able to interrupt network connection
3922 // or cache filling
3923 if (opts->consolecontrols && !slave_mode) {
3924 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3925 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3926 else
3927 getch2_enable(); // prepare stdin for hotkeys...
3928 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3929 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3932 // =================== GUI idle loop (STOP state) ===========================
3933 while (opts->player_idle_mode && !mpctx->filename) {
3934 play_tree_t * entry = NULL;
3935 mp_cmd_t * cmd;
3936 if (mpctx->video_out && mpctx->video_out->config_ok)
3937 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3938 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3939 if (mpctx->video_out)
3940 vo_check_events(mpctx->video_out);
3941 usec_sleep(20000);
3943 switch (cmd->id) {
3944 case MP_CMD_LOADFILE:
3945 // prepare a tree entry with the new filename
3946 entry = play_tree_new();
3947 play_tree_add_file(entry, cmd->args[0].v.s);
3948 // The entry is added to the main playtree after the switch().
3949 break;
3950 case MP_CMD_LOADLIST:
3951 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3952 break;
3953 case MP_CMD_QUIT:
3954 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3955 break;
3956 case MP_CMD_VO_FULLSCREEN:
3957 case MP_CMD_GET_PROPERTY:
3958 case MP_CMD_SET_PROPERTY:
3959 case MP_CMD_STEP_PROPERTY:
3960 run_command(mpctx, cmd);
3961 break;
3964 mp_cmd_free(cmd);
3966 if (entry) { // user entered a command that gave a valid entry
3967 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3968 play_tree_free_list(mpctx->playtree->child, 1);
3969 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3971 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3973 play_tree_set_child(mpctx->playtree, entry);
3975 /* Make iterator start at the top the of tree. */
3976 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3977 if (!mpctx->playtree_iter) continue;
3979 // find the first real item in the tree
3980 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3981 // no items!
3982 play_tree_iter_free(mpctx->playtree_iter);
3983 mpctx->playtree_iter = NULL;
3984 continue; // wait for next command
3986 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3989 //---------------------------------------------------------------------------
3991 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3992 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3994 if (mpctx->filename) {
3995 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3996 filename_recode(mpctx->filename));
3997 if(use_filename_title && opts->vo_wintitle == NULL)
3998 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4001 if (edl_filename) {
4002 if (edl_records) free_edl(edl_records);
4003 next_edl_record = edl_records = edl_parse_file();
4005 if (edl_output_filename) {
4006 if (edl_fd) fclose(edl_fd);
4007 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4009 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4010 filename_recode(edl_output_filename));
4014 //==================== Open VOB-Sub ============================
4016 current_module="vobsub";
4017 if (vobsub_name){
4018 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
4019 if(vo_vobsub==NULL)
4020 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4021 filename_recode(vobsub_name));
4022 } else if (sub_auto && mpctx->filename){
4023 /* try to autodetect vobsub from movie filename ::atmos */
4024 char *buf = strdup(mpctx->filename), *psub;
4025 char *pdot = strrchr(buf, '.');
4026 char *pslash = strrchr(buf, '/');
4027 #if defined(__MINGW32__) || defined(__CYGWIN__)
4028 if (!pslash) pslash = strrchr(buf, '\\');
4029 #endif
4030 if (pdot && (!pslash || pdot > pslash))
4031 *pdot = '\0';
4032 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4033 /* try from ~/.mplayer/sub */
4034 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4035 const char *bname = mp_basename(buf);
4036 int l;
4037 l = strlen(psub) + strlen(bname) + 1;
4038 psub = realloc(psub,l);
4039 strcat(psub,bname);
4040 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4041 free(psub);
4043 free(buf);
4045 if(vo_vobsub){
4046 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4047 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4048 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4050 // setup global sub numbering
4051 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4054 //============ Open & Sync STREAM --- fork cache2 ====================
4056 mpctx->stream=NULL;
4057 mpctx->demuxer=NULL;
4058 if (mpctx->d_audio) {
4059 //free_demuxer_stream(mpctx->d_audio);
4060 mpctx->d_audio=NULL;
4062 if (mpctx->d_video) {
4063 //free_demuxer_stream(d_video);
4064 mpctx->d_video=NULL;
4066 mpctx->sh_audio=NULL;
4067 mpctx->sh_video=NULL;
4069 current_module="open_stream";
4070 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4071 if(!mpctx->stream) { // error...
4072 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4073 goto goto_next_file;
4075 mpctx->initialized_flags|=INITIALIZED_STREAM;
4077 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4078 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4079 "playlist support will not be used automatically.\n"
4080 "MPlayer's playlist code is unsafe and should only be used with "
4081 "trusted sources.\nPlayback will probably fail.\n\n");
4082 #if 0
4083 play_tree_t* entry;
4084 // Handle playlist
4085 current_module="handle_playlist";
4086 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4087 filename_recode(mpctx->filename));
4088 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4089 mpctx->eof=playtree_add_playlist(mpctx, entry);
4090 goto goto_next_file;
4091 #endif
4093 mpctx->stream->start_pos+=seek_to_byte;
4095 if(stream_dump_type==5){
4096 unsigned char buf[4096];
4097 int len;
4098 FILE *f;
4099 current_module="dumpstream";
4100 stream_reset(mpctx->stream);
4101 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4102 f=fopen(opts->stream_dump_name,"wb");
4103 if(!f){
4104 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4105 exit_player(mpctx, EXIT_ERROR);
4107 if (opts->chapterrange[0] > 1) {
4108 int chapter = opts->chapterrange[0] - 1;
4109 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4111 while(!mpctx->stream->eof && !async_quit_request){
4112 len=stream_read(mpctx->stream,buf,4096);
4113 if(len>0) {
4114 if(fwrite(buf,len,1,f) != 1) {
4115 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4116 exit_player(mpctx, EXIT_ERROR);
4119 if (opts->chapterrange[1] > 0) {
4120 int chapter = -1;
4121 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4122 &chapter) == STREAM_OK
4123 && chapter + 1 > opts->chapterrange[1])
4124 break;
4127 if(fclose(f)) {
4128 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4129 exit_player(mpctx, EXIT_ERROR);
4131 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4132 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4135 #ifdef CONFIG_DVDREAD
4136 if(mpctx->stream->type==STREAMTYPE_DVD){
4137 current_module="dvd lang->id";
4138 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4139 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4140 // setup global sub numbering
4141 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4142 current_module=NULL;
4144 #endif
4146 #ifdef CONFIG_DVDNAV
4147 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4148 current_module="dvdnav lang->id";
4149 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4150 dvdsub_lang_id = -3;
4151 if(opts->sub_lang && opts->sub_id==-1)
4152 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4153 // setup global sub numbering
4154 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4155 current_module=NULL;
4157 #endif
4159 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4160 goto_enable_cache:
4161 if(stream_cache_size>0){
4162 int res;
4163 float stream_cache_min_percent = opts->stream_cache_min_percent;
4164 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4165 current_module="enable_cache";
4166 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4167 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4168 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4169 if(res == 0)
4170 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4173 //============ Open DEMUXERS --- DETECT file type =======================
4174 current_module="demux_open";
4176 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4178 // HACK to get MOV Reference Files working
4180 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4182 unsigned char* playlist_entry;
4183 play_tree_t *list = NULL, *entry = NULL;
4185 current_module="handle_demux_playlist";
4186 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4188 char *temp;
4189 const char *bname;
4191 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4192 filename_recode(playlist_entry));
4194 bname=mp_basename(playlist_entry);
4195 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4196 continue;
4198 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4199 continue;
4201 entry = play_tree_new();
4203 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4205 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4206 if (temp)
4208 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4209 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4210 strcat(temp, playlist_entry);
4211 if (!strcmp(temp, mpctx->filename)) {
4212 free(temp);
4213 continue;
4215 play_tree_add_file(entry,temp);
4216 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4217 free(temp);
4220 else
4221 play_tree_add_file(entry,playlist_entry);
4223 if(!list)
4224 list = entry;
4225 else
4226 play_tree_append_entry(list,entry);
4228 free_demuxer(mpctx->demuxer);
4229 mpctx->demuxer = NULL;
4231 if (list)
4233 entry = play_tree_new();
4234 play_tree_set_child(entry,list);
4235 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4236 goto goto_next_file;
4240 if(!mpctx->demuxer) {
4241 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4242 goto goto_next_file;
4245 if (mpctx->demuxer->matroska_data.ordered_chapters)
4246 build_ordered_chapter_timeline(mpctx);
4248 if (!mpctx->sources) {
4249 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4250 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4251 .demuxer = mpctx->demuxer};
4252 mpctx->num_sources = 1;
4255 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4257 #ifdef CONFIG_ASS
4258 if (opts->ass_enabled && ass_library) {
4259 for (int j = 0; j < mpctx->num_sources; j++) {
4260 struct demuxer *d = mpctx->sources[j].demuxer;
4261 for (int i = 0; i < d->num_attachments; i++) {
4262 struct demux_attachment *att = d->attachments + i;
4263 if (use_embedded_fonts && attachment_is_font(att))
4264 ass_add_font(ass_library, att->name, att->data, att->data_size);
4268 #endif
4270 current_module="demux_open2";
4272 mpctx->d_audio=mpctx->demuxer->audio;
4273 mpctx->d_video=mpctx->demuxer->video;
4274 mpctx->d_sub=mpctx->demuxer->sub;
4276 if (ts_prog) {
4277 int tmp = ts_prog;
4278 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4280 // select audio stream
4281 if (mpctx->num_sources)
4282 for (int i = 0; i < mpctx->num_sources; i++)
4283 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
4284 opts->audio_lang);
4285 else
4286 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
4288 // DUMP STREAMS:
4289 if((stream_dump_type)&&(stream_dump_type<4)){
4290 FILE *f;
4291 demux_stream_t *ds=NULL;
4292 current_module="dump";
4293 // select stream to dump
4294 switch(stream_dump_type){
4295 case 1: ds=mpctx->d_audio;break;
4296 case 2: ds=mpctx->d_video;break;
4297 case 3: ds=mpctx->d_sub;break;
4299 if(!ds){
4300 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4301 exit_player(mpctx, EXIT_ERROR);
4303 // disable other streams:
4304 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4305 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4306 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4307 // let's dump it!
4308 f=fopen(opts->stream_dump_name,"wb");
4309 if(!f){
4310 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4311 exit_player(mpctx, EXIT_ERROR);
4313 while(!ds->eof){
4314 unsigned char* start;
4315 int in_size=ds_get_packet(ds,&start);
4316 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4317 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4318 if(in_size>0) fwrite(start,in_size,1,f);
4319 if (opts->chapterrange[1] > 0) {
4320 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4321 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4322 break;
4325 fclose(f);
4326 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4327 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4330 mpctx->sh_audio=mpctx->d_audio->sh;
4331 mpctx->sh_video=mpctx->d_video->sh;
4333 if(mpctx->sh_video){
4335 current_module="video_read_properties";
4336 if(!video_read_properties(mpctx->sh_video)) {
4337 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4338 mpctx->sh_video=mpctx->d_video->sh=NULL;
4339 } else {
4340 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4341 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4342 mpctx->sh_video->fps,mpctx->sh_video->frametime
4345 /* need to set fps here for output encoders to pick it up in their init */
4346 if(force_fps){
4347 mpctx->sh_video->fps=force_fps;
4348 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4350 vo_fps = mpctx->sh_video->fps;
4352 if(!mpctx->sh_video->fps && !force_fps){
4353 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4354 mpctx->opts.correct_pts = 1;
4360 if(!mpctx->sh_video && !mpctx->sh_audio){
4361 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4362 #ifdef CONFIG_DVBIN
4363 if(mpctx->stream->type == STREAMTYPE_DVB)
4365 int dir;
4366 int v = mpctx->last_dvb_step;
4367 if(v > 0)
4368 dir = DVB_CHANNEL_HIGHER;
4369 else
4370 dir = DVB_CHANNEL_LOWER;
4372 if(dvb_step_channel(mpctx->stream, dir)) {
4373 mpctx->stop_play = PT_NEXT_ENTRY;
4374 mpctx->dvbin_reopen = 1;
4377 #endif
4378 goto goto_next_file; // exit_player(_("Fatal error"));
4381 /* display clip info */
4382 demux_info_print(mpctx->demuxer);
4384 //================== Read SUBTITLES (DVD & TEXT) ==========================
4385 if(vo_spudec==NULL &&
4386 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4387 init_vo_spudec(mpctx);
4390 // after reading video params we should load subtitles because
4391 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4392 // check .sub
4393 current_module="read_subtitles_file";
4394 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4395 if(sub_name){
4396 for (i = 0; sub_name[i] != NULL; ++i)
4397 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4399 if(sub_auto) { // auto load sub file ...
4400 char *psub = get_path( "sub/" );
4401 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4402 int i = 0;
4403 free(psub); // release the buffer created by get_path() above
4404 while (tmp[i]) {
4405 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4406 free(tmp[i++]);
4408 free(tmp);
4410 if (mpctx->set_of_sub_size > 0)
4411 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4413 if (select_subtitle(mpctx)) {
4414 if(subdata)
4415 switch (stream_dump_type) {
4416 case 3: list_sub_file(subdata); break;
4417 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
4418 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
4419 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
4420 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
4421 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
4425 print_file_properties(mpctx, mpctx->filename);
4427 if(!mpctx->sh_video) goto main; // audio-only
4429 if(!reinit_video_chain(mpctx)) {
4430 if(!mpctx->sh_video){
4431 if(!mpctx->sh_audio) goto goto_next_file;
4432 goto main; // exit_player(_("Fatal error"));
4436 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4437 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4439 #ifdef CONFIG_FREETYPE
4440 force_load_font = 1;
4441 #endif
4443 //================== MAIN: ==========================
4444 main:
4445 current_module="main";
4447 if (opts->playing_msg) {
4448 char* msg = property_expand_string(mpctx, opts->playing_msg);
4449 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4450 free(msg);
4454 // Disable the term OSD in verbose mode
4455 if (verbose)
4456 opts->term_osd = 0;
4460 // Make sure old OSD does not stay around,
4461 // e.g. with -fixed-vo and same-resolution files
4462 clear_osd_msgs();
4463 update_osd_msg(mpctx);
4465 //================ SETUP AUDIO ==========================
4467 if(mpctx->sh_audio){
4468 reinit_audio_chain(mpctx);
4469 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4470 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4473 current_module="av_init";
4475 if(mpctx->sh_video){
4476 mpctx->sh_video->timer=0;
4477 if (! ignore_start)
4478 audio_delay += mpctx->sh_video->stream_delay;
4480 if(mpctx->sh_audio){
4481 if (start_volume >= 0)
4482 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4483 if (! ignore_start)
4484 audio_delay -= mpctx->sh_audio->stream_delay;
4485 mpctx->delay=-audio_delay;
4488 if(!mpctx->sh_audio){
4489 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4490 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4491 ds_free_packs(mpctx->d_audio); // free buffered chunks
4492 //mpctx->d_audio->id=-2; // do not read audio chunks
4493 //uninit_player(mpctx, INITIALIZED_AO); // close device
4495 if(!mpctx->sh_video){
4496 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4497 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4498 ds_free_packs(mpctx->d_video);
4499 mpctx->d_video->id=-2;
4500 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4503 if (!mpctx->sh_video && !mpctx->sh_audio)
4504 goto goto_next_file;
4506 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4507 if(force_fps && mpctx->sh_video){
4508 vo_fps = mpctx->sh_video->fps=force_fps;
4509 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4510 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4513 mp_input_set_section(mpctx->input, NULL);
4514 //TODO: add desired (stream-based) sections here
4515 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4516 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4518 //==================== START PLAYING =======================
4520 if(opts->loop_times>1) opts->loop_times--; else
4521 if(opts->loop_times==1) opts->loop_times = -1;
4523 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4525 total_time_usage_start=GetTimer();
4526 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4527 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4528 play_n_frames=play_n_frames_mf;
4530 if(play_n_frames==0){
4531 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4534 mpctx->time_frame = 0;
4535 mpctx->drop_message_shown = 0;
4536 mpctx->restart_playback = true;
4537 mpctx->video_pts = 0;
4538 mpctx->hrseek_active = false;
4539 mpctx->hrseek_framedrop = false;
4540 mpctx->step_frames = 0;
4541 mpctx->total_avsync_change = 0;
4542 mpctx->last_chapter_seek = -1;
4544 // If there's a timeline force an absolute seek to initialize state
4545 if (seek_to_sec || mpctx->timeline) {
4546 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4547 seek(mpctx, mpctx->seek);
4548 end_at.pos += seek_to_sec;
4550 if (opts->chapterrange[0] > 0) {
4551 double pts;
4552 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4553 && pts > -1.0) {
4554 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4555 seek(mpctx, mpctx->seek);
4559 if (end_at.type == END_AT_SIZE) {
4560 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4561 end_at.type = END_AT_NONE;
4564 #ifdef CONFIG_DVDNAV
4565 mp_dvdnav_context_free(mpctx);
4566 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4567 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4568 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4570 #endif
4572 mpctx->seek = (struct seek_params){0};
4573 get_relative_time(mpctx); // reset current delta
4574 // Make sure VO knows current pause state
4575 if (mpctx->sh_video)
4576 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4577 NULL);
4579 while (!mpctx->stop_play)
4580 run_playloop(mpctx);
4582 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4584 #ifdef CONFIG_DVBIN
4585 if(mpctx->dvbin_reopen)
4587 mpctx->stop_play = 0;
4588 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4589 cache_uninit(mpctx->stream);
4590 mpctx->dvbin_reopen = 0;
4591 goto goto_enable_cache;
4593 #endif
4596 goto_next_file: // don't jump here after ao/vo/getch initialization!
4598 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4600 if (opts->benchmark) {
4601 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4602 double total_time_usage;
4603 total_time_usage_start=GetTimer()-total_time_usage_start;
4604 total_time_usage = (float)total_time_usage_start*0.000001;
4605 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4606 video_time_usage,vout_time_usage,audio_time_usage,
4607 total_time_usage-tot,total_time_usage);
4608 if(total_time_usage>0.0)
4609 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4610 100.0*video_time_usage/total_time_usage,
4611 100.0*vout_time_usage/total_time_usage,
4612 100.0*audio_time_usage/total_time_usage,
4613 100.0*(total_time_usage-tot)/total_time_usage,
4614 100.0);
4615 if(total_frame_cnt && frame_dropping)
4616 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4617 total_frame_cnt-drop_frame_cnt,
4618 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4619 drop_frame_cnt,
4620 100*drop_frame_cnt/total_frame_cnt,
4621 total_frame_cnt,
4622 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4625 // time to uninit all, except global stuff:
4626 int uninitialize_parts = INITIALIZED_ALL;
4627 if (opts->fixed_vo)
4628 uninitialize_parts -= INITIALIZED_VO;
4629 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4630 uninitialize_parts -= INITIALIZED_AO;
4631 uninit_player(mpctx, uninitialize_parts);
4633 if(mpctx->set_of_sub_size > 0) {
4634 current_module="sub_free";
4635 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4636 sub_free(mpctx->set_of_subtitles[i]);
4637 #ifdef CONFIG_ASS
4638 if(mpctx->set_of_ass_tracks[i])
4639 ass_free_track( mpctx->set_of_ass_tracks[i] );
4640 #endif
4642 mpctx->set_of_sub_size = 0;
4644 vo_sub_last = vo_sub=NULL;
4645 subdata=NULL;
4646 #ifdef CONFIG_ASS
4647 ass_track = NULL;
4648 if(ass_library)
4649 ass_clear_fonts(ass_library);
4650 #endif
4652 if (!mpctx->stop_play) // In case some goto jumped here...
4653 mpctx->stop_play = PT_NEXT_ENTRY;
4655 int playtree_direction = 1;
4657 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4658 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4659 play_tree_iter_free(mpctx->playtree_iter);
4660 mpctx->playtree_iter = NULL;
4662 mpctx->play_tree_step = 1;
4663 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4664 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4665 if(mpctx->playtree_iter) {
4666 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4667 play_tree_iter_free(mpctx->playtree_iter);
4668 mpctx->playtree_iter = NULL;
4671 } else if (mpctx->stop_play == PT_STOP) {
4672 play_tree_iter_free(mpctx->playtree_iter);
4673 mpctx->playtree_iter = NULL;
4674 } else { // NEXT PREV SRC
4675 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4678 while(mpctx->playtree_iter != NULL) {
4679 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4680 if(mpctx->filename == NULL) {
4681 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4682 play_tree_iter_free(mpctx->playtree_iter);
4683 mpctx->playtree_iter = NULL;
4685 } else
4686 break;
4689 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4690 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4691 mpctx->stop_play = 0;
4692 goto play_next_file;
4696 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4698 return 1;
4700 #endif /* DISABLE_MAIN */