mp_msg: Remove uses of MSGT_MENCODER
[mplayer/glamo.git] / mplayer.c
blobe5c9019ccc0f347d0935e79181de91f341052e3b
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 int slave_mode=0;
102 int enable_mouse_movements=0;
103 float start_volume = -1;
105 #include "osdep/priority.h"
107 char *heartbeat_cmd;
109 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
111 #ifdef HAVE_RTC
112 #ifdef __linux__
113 #include <linux/rtc.h>
114 #else
115 #include <rtc.h>
116 #define RTC_IRQP_SET RTCIO_IRQP_SET
117 #define RTC_PIE_ON RTCIO_PIE_ON
118 #endif /* __linux__ */
119 #endif /* HAVE_RTC */
121 #include "stream/tv.h"
122 #include "stream/stream_radio.h"
123 #ifdef CONFIG_DVBIN
124 #include "stream/dvbin.h"
125 #endif
126 #include "stream/cache2.h"
128 //**************************************************************************//
129 // Playtree
130 //**************************************************************************//
131 #include "playtree.h"
132 #include "playtreeparser.h"
134 //**************************************************************************//
135 // Config
136 //**************************************************************************//
137 #include "parser-cfg.h"
138 #include "parser-mpcmd.h"
140 //**************************************************************************//
141 // Config file
142 //**************************************************************************//
144 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
146 #include "path.h"
148 //**************************************************************************//
149 //**************************************************************************//
150 // Input media streaming & demultiplexer:
151 //**************************************************************************//
153 static int max_framesize=0;
155 #include "stream/stream.h"
156 #include "libmpdemux/demuxer.h"
157 #include "libmpdemux/stheader.h"
159 #ifdef CONFIG_DVDREAD
160 #include "stream/stream_dvd.h"
161 #endif
162 #include "stream/stream_dvdnav.h"
164 #include "libmpcodecs/dec_audio.h"
165 #include "libmpcodecs/dec_video.h"
166 #include "libmpcodecs/mp_image.h"
167 #include "libmpcodecs/vf.h"
168 #include "libmpcodecs/vd.h"
170 #include "mixer.h"
172 #include "mp_core.h"
173 #include "options.h"
174 #include "defaultopts.h"
176 static const char help_text[]=_(
177 "Usage: mplayer [options] [url|path/]filename\n"
178 "\n"
179 "Basic options: (complete list in the man page)\n"
180 " -vo <drv> select video output driver ('-vo help' for a list)\n"
181 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
182 #ifdef CONFIG_VCD
183 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
184 #endif
185 #ifdef CONFIG_DVDREAD
186 " dvd://<titleno> play DVD title from device instead of plain file\n"
187 #endif
188 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
189 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
190 " -nosound do not play sound\n"
191 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
192 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
193 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
194 " -playlist <file> specify playlist file\n"
195 " -vid x -aid y select video (x) and audio (y) stream to play\n"
196 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
197 " -pp <quality> enable postprocessing filter (details in the man page)\n"
198 " -framedrop enable frame dropping (for slow machines)\n"
199 "\n"
200 "Basic keys: (complete list in the man page, also check input.conf)\n"
201 " <- or -> seek backward/forward 10 seconds\n"
202 " down or up seek backward/forward 1 minute\n"
203 " pgdown or pgup seek backward/forward 10 minutes\n"
204 " < or > step backward/forward in playlist\n"
205 " p or SPACE pause movie (press any key to continue)\n"
206 " q or ESC stop playing and quit program\n"
207 " + or - adjust audio delay by +/- 0.1 second\n"
208 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
209 " * or / increase or decrease PCM volume\n"
210 " x or z adjust subtitle delay by +/- 0.1 second\n"
211 " r or t adjust subtitle position up/down, also see -vf expand\n"
212 "\n"
213 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
214 "\n");
217 #define Exit_SIGILL_RTCpuSel _(\
218 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
219 " It may be a bug in our new runtime CPU-detection code...\n"\
220 " Please read DOCS/HTML/en/bugreports.html.\n")
222 #define Exit_SIGILL _(\
223 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
224 " It usually happens when you run it on a CPU different than the one it was\n"\
225 " compiled/optimized for.\n"\
226 " Verify this!\n")
228 #define Exit_SIGSEGV_SIGFPE _(\
229 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
230 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
231 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
233 #define Exit_SIGCRASH _(\
234 "- MPlayer crashed. This shouldn't happen.\n"\
235 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
236 " gcc version. If you think it's MPlayer's fault, please read\n"\
237 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
238 " won't help unless you provide this information when reporting a possible bug.\n")
240 #define SystemTooSlow _("\n\n"\
241 " ************************************************\n"\
242 " **** Your system is too SLOW to play this! ****\n"\
243 " ************************************************\n\n"\
244 "Possible reasons, problems, workarounds:\n"\
245 "- Most common: broken/buggy _audio_ driver\n"\
246 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
247 " - Experiment with different values for -autosync, 30 is a good start.\n"\
248 "- Slow video output\n"\
249 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
250 "- Slow CPU\n"\
251 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
252 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
253 "- Broken file\n"\
254 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
255 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
256 " - Try -cache 8192.\n"\
257 "- Are you using -cache to play a non-interleaved AVI file?\n"\
258 " - Try -nocache.\n"\
259 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
260 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
263 //**************************************************************************//
264 //**************************************************************************//
266 #include "mp_fifo.h"
268 // benchmark:
269 double video_time_usage=0;
270 double vout_time_usage=0;
271 static double audio_time_usage=0;
272 static int total_time_usage_start=0;
273 static int total_frame_cnt=0;
274 static int drop_frame_cnt=0; // total number of dropped frames
276 // options:
277 static int output_quality=0;
279 // seek:
280 static double seek_to_sec;
281 static off_t seek_to_byte=0;
282 static off_t step_sec=0;
284 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
286 // codecs:
287 char **audio_codec_list=NULL; // override audio codec
288 char **video_codec_list=NULL; // override video codec
289 char **audio_fm_list=NULL; // override audio codec family
290 char **video_fm_list=NULL; // override video codec family
292 // this dvdsub_id was selected via slang
293 // use this to allow dvdnav to follow -slang across stream resets,
294 // in particular the subtitle ID for a language changes
295 int dvdsub_lang_id;
296 int vobsub_id=-1;
297 static char* spudec_ifo=NULL;
298 int forced_subs_only=0;
299 int file_filter=1;
301 // cache2:
302 int stream_cache_size=-1;
304 // dump:
305 int stream_dump_type=0;
307 // A-V sync:
308 static float default_max_pts_correction=-1;//0.01f;
309 float audio_delay=0;
310 static int ignore_start=0;
312 double force_fps=0;
313 static int force_srate=0;
314 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
315 static int play_n_frames=-1;
316 static int play_n_frames_mf=-1;
318 // sub:
319 char *font_name=NULL;
320 char *sub_font_name=NULL;
321 extern int font_fontconfig;
322 float font_factor=0.75;
323 char **sub_name=NULL;
324 float sub_delay=0;
325 float sub_fps=0;
326 int sub_auto = 1;
327 char *vobsub_name=NULL;
328 int subcc_enabled=0;
329 int suboverlap_enabled = 1;
331 #include "ass_mp.h"
333 char* current_module=NULL; // for debugging
336 // ---
338 #ifdef CONFIG_MENU
339 #include "m_struct.h"
340 #include "libmenu/menu.h"
341 static const vf_info_t* const libmenu_vfs[] = {
342 &vf_info_menu,
343 NULL
345 static vf_instance_t* vf_menu = NULL;
346 int use_menu = 0;
347 static char* menu_cfg = NULL;
348 static char* menu_root = "main";
349 #endif
352 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
353 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
354 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
355 int use_filedir_conf;
356 int use_filename_title;
358 #include "mpcommon.h"
359 #include "command.h"
361 #include "metadata.h"
363 const void *mpctx_get_video_out(MPContext *mpctx)
365 return mpctx->video_out;
368 const void *mpctx_get_audio_out(MPContext *mpctx)
370 return mpctx->audio_out;
373 void *mpctx_get_demuxer(MPContext *mpctx)
375 return mpctx->demuxer;
378 void *mpctx_get_playtree_iter(MPContext *mpctx)
380 return mpctx->playtree_iter;
383 void *mpctx_get_mixer(MPContext *mpctx)
385 return &mpctx->mixer;
388 int mpctx_get_global_sub_size(MPContext *mpctx)
390 return mpctx->global_sub_size;
393 int mpctx_get_osd_function(MPContext *mpctx)
395 return mpctx->osd_function;
398 static float get_relative_time(struct MPContext *mpctx)
400 unsigned int new_time = GetTimer();
401 unsigned int delta = new_time - mpctx->last_time;
402 mpctx->last_time = new_time;
403 return delta * 0.000001;
406 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
407 switch (type)
409 /* check for valid video stream */
410 case META_VIDEO_CODEC:
411 case META_VIDEO_BITRATE:
412 case META_VIDEO_RESOLUTION:
414 if (!mpctx->sh_video)
415 return 0;
416 break;
419 /* check for valid audio stream */
420 case META_AUDIO_CODEC:
421 case META_AUDIO_BITRATE:
422 case META_AUDIO_SAMPLES:
424 if (!mpctx->sh_audio)
425 return 0;
426 break;
429 /* check for valid demuxer */
430 case META_INFO_TITLE:
431 case META_INFO_ARTIST:
432 case META_INFO_ALBUM:
433 case META_INFO_YEAR:
434 case META_INFO_COMMENT:
435 case META_INFO_TRACK:
436 case META_INFO_GENRE:
438 if (!mpctx->demuxer)
439 return 0;
440 break;
443 default:
444 break;
447 return 1;
450 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
451 char **info = mpctx->demuxer->info;
452 int n;
454 if (!info || !tag)
455 return talloc_strdup(NULL, "");
457 for (n = 0; info[2*n] != NULL ; n++)
458 if (!strcasecmp (info[2*n], tag))
459 break;
461 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
464 char *get_metadata(struct MPContext *mpctx, metadata_t type)
466 sh_audio_t * const sh_audio = mpctx->sh_audio;
467 sh_video_t * const sh_video = mpctx->sh_video;
469 if (!is_valid_metadata_type(mpctx, type))
470 return NULL;
472 switch (type) {
473 case META_NAME:
474 return talloc_strdup(NULL, mp_basename(mpctx->filename));
475 case META_VIDEO_CODEC:
476 if (sh_video->format == 0x10000001)
477 return talloc_strdup(NULL, "mpeg1");
478 else if (sh_video->format == 0x10000002)
479 return talloc_strdup(NULL, "mpeg2");
480 else if (sh_video->format == 0x10000004)
481 return talloc_strdup(NULL, "mpeg4");
482 else if (sh_video->format == 0x10000005)
483 return talloc_strdup(NULL, "h264");
484 else if (sh_video->format >= 0x20202020)
485 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
486 else
487 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
488 case META_VIDEO_BITRATE:
489 return talloc_asprintf(NULL, "%d kbps",
490 (int) (sh_video->i_bps * 8 / 1024));
491 case META_VIDEO_RESOLUTION:
492 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
493 sh_video->disp_h);
494 case META_AUDIO_CODEC:
495 if (sh_audio->codec && sh_audio->codec->name)
496 return talloc_strdup(NULL, sh_audio->codec->name);
497 return talloc_strdup(NULL, "");
498 case META_AUDIO_BITRATE:
499 return talloc_asprintf(NULL, "%d kbps",
500 (int) (sh_audio->i_bps * 8/1000));
501 case META_AUDIO_SAMPLES:
502 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
503 sh_audio->channels);
505 /* check for valid demuxer */
506 case META_INFO_TITLE:
507 return get_demuxer_info(mpctx, "Title");
509 case META_INFO_ARTIST:
510 return get_demuxer_info(mpctx, "Artist");
512 case META_INFO_ALBUM:
513 return get_demuxer_info(mpctx, "Album");
515 case META_INFO_YEAR:
516 return get_demuxer_info(mpctx, "Year");
518 case META_INFO_COMMENT:
519 return get_demuxer_info(mpctx, "Comment");
521 case META_INFO_TRACK:
522 return get_demuxer_info(mpctx, "Track");
524 case META_INFO_GENRE:
525 return get_demuxer_info(mpctx, "Genre");
527 default:
528 break;
531 return talloc_strdup(NULL, "");
534 static void print_file_properties(struct MPContext *mpctx, const char *filename)
536 double start_pts = MP_NOPTS_VALUE;
537 double video_start_pts = MP_NOPTS_VALUE;
538 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
539 filename_recode(filename));
540 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
541 if (mpctx->sh_video) {
542 /* Assume FOURCC if all bytes >= 0x20 (' ') */
543 if (mpctx->sh_video->format >= 0x20202020)
544 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
545 else
546 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
547 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
548 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
549 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
550 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
551 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
552 video_start_pts = ds_get_next_pts(mpctx->d_video);
554 if (mpctx->sh_audio) {
555 /* Assume FOURCC if all bytes >= 0x20 (' ') */
556 if (mpctx->sh_audio->format >= 0x20202020)
557 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
558 else
559 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
560 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
561 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
562 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
563 start_pts = ds_get_next_pts(mpctx->d_audio);
565 if (video_start_pts != MP_NOPTS_VALUE) {
566 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
567 (mpctx->sh_video && video_start_pts < start_pts))
568 start_pts = video_start_pts;
570 if (start_pts != MP_NOPTS_VALUE)
571 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
572 else
573 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
574 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
575 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
576 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
577 if (mpctx->demuxer) {
578 if (mpctx->demuxer->num_chapters == 0)
579 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
580 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
584 /// step size of mixer changes
585 int volstep = 3;
587 #ifdef CONFIG_DVDNAV
588 static void mp_dvdnav_context_free(MPContext *ctx){
589 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
590 ctx->nav_smpi = NULL;
591 free(ctx->nav_buffer);
592 ctx->nav_buffer = NULL;
593 ctx->nav_start = NULL;
594 ctx->nav_in_size = 0;
596 #endif
598 void uninit_player(struct MPContext *mpctx, unsigned int mask){
599 mask &= mpctx->initialized_flags;
601 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
603 if(mask&INITIALIZED_ACODEC){
604 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
605 current_module="uninit_acodec";
606 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
607 mpctx->sh_audio=NULL;
608 mpctx->mixer.afilter = NULL;
611 if(mask&INITIALIZED_VCODEC){
612 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
613 current_module="uninit_vcodec";
614 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
615 mpctx->sh_video=NULL;
616 #ifdef CONFIG_MENU
617 vf_menu=NULL;
618 #endif
621 if(mask&INITIALIZED_DEMUXER){
622 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
623 current_module="free_demuxer";
624 if (mpctx->num_sources) {
625 mpctx->demuxer = mpctx->sources[0].demuxer;
626 for (int i = 1; i < mpctx->num_sources; i++) {
627 free_stream(mpctx->sources[i].stream);
628 free_demuxer(mpctx->sources[i].demuxer);
631 talloc_free(mpctx->sources);
632 mpctx->sources = NULL;
633 mpctx->num_sources = 0;
634 talloc_free(mpctx->timeline);
635 mpctx->timeline = NULL;
636 mpctx->num_timeline_parts = 0;
637 talloc_free(mpctx->chapters);
638 mpctx->chapters = NULL;
639 mpctx->num_chapters = 0;
640 mpctx->video_offset = 0;
641 if(mpctx->demuxer){
642 mpctx->stream=mpctx->demuxer->stream;
643 free_demuxer(mpctx->demuxer);
645 mpctx->demuxer=NULL;
648 // kill the cache process:
649 if(mask&INITIALIZED_STREAM){
650 mpctx->initialized_flags&=~INITIALIZED_STREAM;
651 current_module="uninit_stream";
652 if(mpctx->stream) free_stream(mpctx->stream);
653 mpctx->stream=NULL;
656 if(mask&INITIALIZED_VO){
657 mpctx->initialized_flags&=~INITIALIZED_VO;
658 current_module="uninit_vo";
659 vo_destroy(mpctx->video_out);
660 mpctx->video_out=NULL;
661 #ifdef CONFIG_DVDNAV
662 mp_dvdnav_context_free(mpctx);
663 #endif
666 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
667 if(mask&INITIALIZED_GETCH2){
668 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
669 current_module="uninit_getch2";
670 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
671 // restore terminal:
672 getch2_disable();
675 if(mask&INITIALIZED_VOBSUB){
676 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
677 current_module="uninit_vobsub";
678 if(vo_vobsub) vobsub_close(vo_vobsub);
679 vo_vobsub=NULL;
682 if (mask&INITIALIZED_SPUDEC){
683 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
684 current_module="uninit_spudec";
685 spudec_free(vo_spudec);
686 vo_spudec=NULL;
689 if(mask&INITIALIZED_AO){
690 mpctx->initialized_flags&=~INITIALIZED_AO;
691 current_module="uninit_ao";
692 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
693 if (mpctx->audio_out)
694 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
695 mpctx->audio_out=NULL;
698 current_module=NULL;
701 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
703 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
704 uninit_player(mpctx, INITIALIZED_ALL);
705 #if defined(__MINGW32__) || defined(__CYGWIN__)
706 timeEndPeriod(1);
707 #endif
708 #ifdef CONFIG_X11
709 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
710 #endif
712 current_module="uninit_input";
713 mp_input_uninit(mpctx->input);
714 #ifdef CONFIG_MENU
715 if (use_menu)
716 menu_uninit();
717 #endif
719 #ifdef CONFIG_FREETYPE
720 current_module="uninit_font";
721 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
722 free_font_desc(mpctx->osd->sub_font);
723 free_font_desc(vo_font);
724 vo_font = NULL;
725 done_freetype();
726 #endif
727 osd_free(mpctx->osd);
729 #ifdef CONFIG_ASS
730 ass_library_done(ass_library);
731 ass_library = NULL;
732 #endif
734 current_module="exit_player";
736 // free mplayer config
737 if(mpctx->mconfig)
738 m_config_free(mpctx->mconfig);
739 mpctx->mconfig = NULL;
741 if(mpctx->playtree_iter)
742 play_tree_iter_free(mpctx->playtree_iter);
743 mpctx->playtree_iter = NULL;
744 if(mpctx->playtree)
745 play_tree_free(mpctx->playtree, 1);
746 mpctx->playtree = NULL;
748 talloc_free(mpctx->key_fifo);
750 free(edl_records); // free mem allocated for EDL
751 edl_records = NULL;
752 switch(how) {
753 case EXIT_QUIT:
754 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
755 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
756 break;
757 case EXIT_EOF:
758 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
759 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
760 break;
761 case EXIT_ERROR:
762 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
763 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
764 break;
765 default:
766 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
768 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
770 exit(rc);
773 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
775 exit_player_with_rc(mpctx, how, 1);
778 #ifndef __MINGW32__
779 static void child_sighandler(int x){
780 pid_t pid;
781 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
783 #endif
785 #ifdef CONFIG_CRASH_DEBUG
786 static char *prog_path;
787 static int crash_debug = 0;
788 #endif
790 static void exit_sighandler(int x){
791 static int sig_count=0;
792 #ifdef CONFIG_CRASH_DEBUG
793 if (!crash_debug || x != SIGTRAP)
794 #endif
795 ++sig_count;
796 if(sig_count==5)
798 /* We're crashing bad and can't uninit cleanly :(
799 * by popular request, we make one last (dirty)
800 * effort to restore the user's
801 * terminal. */
802 getch2_disable();
803 exit(1);
805 if(sig_count==6) exit(1);
806 if(sig_count>6){
807 // can't stop :(
808 #ifndef __MINGW32__
809 kill(getpid(),SIGKILL);
810 #endif
812 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
813 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
814 "\nMPlayer interrupted by signal %d in module: %s\n", x,
815 current_module ? current_module : "unknown");
816 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
817 if(sig_count<=1)
818 switch(x){
819 case SIGINT:
820 case SIGPIPE:
821 case SIGQUIT:
822 case SIGTERM:
823 case SIGKILL:
824 async_quit_request = 1;
825 return; // killed from keyboard (^C) or killed [-9]
826 case SIGILL:
827 #if CONFIG_RUNTIME_CPUDETECT
828 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
829 #else
830 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
831 #endif
832 case SIGFPE:
833 case SIGSEGV:
834 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
835 default:
836 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
837 #ifdef CONFIG_CRASH_DEBUG
838 if (crash_debug) {
839 int gdb_pid;
840 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
841 gdb_pid = fork();
842 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
843 if (gdb_pid == 0) { // We are the child
844 char spid[20];
845 snprintf(spid, sizeof(spid), "%i", getppid());
846 getch2_disable(); // allow terminal to work properly with gdb
847 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
848 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
849 } else if (gdb_pid < 0)
850 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
851 else {
852 waitpid(gdb_pid, NULL, 0);
854 if (x == SIGTRAP) return;
856 #endif
858 getch2_disable();
859 exit(1);
862 #include "cfg-mplayer.h"
864 static int cfg_include(m_option_t *conf, char *filename)
866 return m_config_parse_config_file(conf->priv, filename);
869 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
871 char *conffile;
872 int conffile_fd;
873 if (!disable_system_conf &&
874 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
875 exit_player(mpctx, EXIT_NONE);
876 if ((conffile = get_path("")) == NULL) {
877 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
878 } else {
879 #ifdef __MINGW32__
880 mkdir(conffile);
881 #else
882 mkdir(conffile, 0777);
883 #endif
884 free(conffile);
885 if ((conffile = get_path("config")) == NULL) {
886 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
887 } else {
888 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
889 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
890 write(conffile_fd, default_config, strlen(default_config));
891 close(conffile_fd);
893 if (!disable_user_conf &&
894 m_config_parse_config_file(conf, conffile) < 0)
895 exit_player(mpctx, EXIT_NONE);
896 free(conffile);
901 #define PROFILE_CFG_PROTOCOL "protocol."
903 static void load_per_protocol_config (m_config_t* conf, const char *const file)
905 char *str;
906 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
907 m_profile_t *p;
909 /* does filename actually uses a protocol ? */
910 str = strstr (file, "://");
911 if (!str)
912 return;
914 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
915 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
916 p = m_config_get_profile (conf, protocol);
917 if (p)
919 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
920 m_config_set_profile(conf,p);
924 #define PROFILE_CFG_EXTENSION "extension."
926 static void load_per_extension_config (m_config_t* conf, const char *const file)
928 char *str;
929 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
930 m_profile_t *p;
932 /* does filename actually have an extension ? */
933 str = strrchr (file, '.');
934 if (!str)
935 return;
937 sprintf (extension, PROFILE_CFG_EXTENSION);
938 strncat (extension, ++str, 7);
939 p = m_config_get_profile (conf, extension);
940 if (p)
942 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
943 m_config_set_profile(conf,p);
947 #define PROFILE_CFG_VO "vo."
948 #define PROFILE_CFG_AO "ao."
950 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
952 char profile[strlen (cfg) + strlen (out) + 1];
953 m_profile_t *p;
955 sprintf (profile, "%s%s", cfg, out);
956 p = m_config_get_profile (conf, profile);
957 if (p)
959 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
960 m_config_set_profile(conf,p);
965 * Tries to load a config file
966 * @return 0 if file was not found, 1 otherwise
968 static int try_load_config(m_config_t *conf, const char *file)
970 struct stat st;
971 if (stat(file, &st))
972 return 0;
973 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
974 m_config_parse_config_file (conf, file);
975 return 1;
978 static void load_per_file_config (m_config_t* conf, const char *const file)
980 char *confpath;
981 char cfg[PATH_MAX];
982 const char *name;
984 if (strlen(file) > PATH_MAX - 14) {
985 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
986 return;
988 sprintf (cfg, "%s.conf", file);
990 name = mp_basename(cfg);
991 if (use_filedir_conf) {
992 char dircfg[PATH_MAX];
993 strcpy(dircfg, cfg);
994 strcpy(dircfg + (name - cfg), "mplayer.conf");
995 try_load_config(conf, dircfg);
997 if (try_load_config(conf, cfg))
998 return;
1001 if ((confpath = get_path (name)) != NULL)
1003 try_load_config(conf, confpath);
1005 free (confpath);
1009 /* When libmpdemux performs a blocking operation (network connection or
1010 * cache filling) if the operation fails we use this function to check
1011 * if it was interrupted by the user.
1012 * The function returns a new value for eof. */
1013 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1015 mp_cmd_t* cmd;
1016 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1017 switch(cmd->id) {
1018 case MP_CMD_QUIT:
1019 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1020 case MP_CMD_PLAY_TREE_STEP: {
1021 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1022 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1023 } break;
1024 case MP_CMD_PLAY_TREE_UP_STEP: {
1025 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1026 } break;
1027 case MP_CMD_PLAY_ALT_SRC_STEP: {
1028 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1029 } break;
1031 mp_cmd_free(cmd);
1033 return stop_play;
1036 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1038 play_tree_add_bpf(entry,mpctx->filename);
1041 if(!entry) {
1042 entry = mpctx->playtree_iter->tree;
1043 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1044 return PT_NEXT_ENTRY;
1046 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1047 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1048 return PT_NEXT_ENTRY;
1051 play_tree_remove(entry,1,1);
1052 return PT_NEXT_SRC;
1054 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1055 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1056 entry = mpctx->playtree_iter->tree;
1057 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1058 return PT_NEXT_ENTRY;
1060 play_tree_remove(entry,1,1);
1062 return PT_NEXT_SRC;
1065 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1067 struct MPOpts *opts = &mpctx->opts;
1068 sub_data *subd = NULL;
1069 struct ass_track *asst = NULL;
1071 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1072 return;
1075 #ifdef CONFIG_ASS
1076 if (opts->ass_enabled) {
1077 #ifdef CONFIG_ICONV
1078 asst = ass_read_stream(ass_library, filename, sub_cp);
1079 #else
1080 asst = ass_read_stream(ass_library, filename, 0);
1081 #endif
1082 if (!asst) {
1083 subd = sub_read_file(filename, fps);
1084 if (subd) {
1085 asst = ass_read_subdata(ass_library, subd, fps);
1086 if (asst) {
1087 sub_free(subd);
1088 subd = NULL;
1092 } else
1093 #endif
1094 subd = sub_read_file(filename, fps);
1097 if (!asst && !subd) {
1098 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1099 "Cannot load subtitles: %s\n", filename_recode(filename));
1100 return;
1103 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1104 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1105 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1106 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1107 filename_recode(filename));
1108 ++mpctx->set_of_sub_size;
1109 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1110 filename_recode(filename));
1113 void init_vo_spudec(struct MPContext *mpctx)
1115 spudec_free(vo_spudec);
1116 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1117 vo_spudec = NULL;
1119 // we currently can't work without video stream
1120 if (!mpctx->sh_video)
1121 return;
1123 if (spudec_ifo) {
1124 unsigned int palette[16], width, height;
1125 current_module="spudec_init_vobsub";
1126 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1127 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1130 #ifdef CONFIG_DVDREAD
1131 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1132 current_module="spudec_init_dvdread";
1133 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1134 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1135 NULL, 0);
1137 #endif
1139 #ifdef CONFIG_DVDNAV
1140 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1141 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1142 current_module="spudec_init_dvdnav";
1143 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1145 #endif
1147 if (vo_spudec==NULL) {
1148 sh_sub_t *sh = mpctx->d_sub->sh;
1149 current_module="spudec_init_normal";
1150 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1151 spudec_set_font_factor(vo_spudec,font_factor);
1154 if (vo_spudec!=NULL) {
1155 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1156 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1161 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1162 * make it all work is to use the builtin SDL-bootstrap code, which
1163 * will be done automatically by replacing our main() if we include SDL.h.
1165 #if defined(__APPLE__) && defined(CONFIG_SDL)
1166 #ifdef CONFIG_SDL_SDL_H
1167 #include <SDL/SDL.h>
1168 #else
1169 #include <SDL.h>
1170 #endif
1171 #endif
1174 * \brief append a formatted string
1175 * \param buf buffer to print into
1176 * \param pos position of terminating 0 in buf
1177 * \param len maximum number of characters in buf, not including terminating 0
1178 * \param format printf format string
1180 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1182 va_list va;
1183 va_start(va, format);
1184 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1185 va_end(va);
1186 if (*pos >= len ) {
1187 buf[len] = 0;
1188 *pos = len;
1193 * \brief append time in the hh:mm:ss.f format
1194 * \param buf buffer to print into
1195 * \param pos position of terminating 0 in buf
1196 * \param len maximum number of characters in buf, not including terminating 0
1197 * \param time time value to convert/append
1199 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1200 int64_t tenths = 10 * time;
1201 int f1 = tenths % 10;
1202 int ss = (tenths / 10) % 60;
1203 int mm = (tenths / 600) % 60;
1204 int hh = tenths / 36000;
1205 if (time <= 0) {
1206 saddf(buf, pos, len, "unknown");
1207 return;
1209 if (hh > 0)
1210 saddf(buf, pos, len, "%2d:", hh);
1211 if (hh > 0 || mm > 0)
1212 saddf(buf, pos, len, "%02d:", mm);
1213 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1216 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1218 struct MPOpts *opts = &mpctx->opts;
1219 sh_video_t * const sh_video = mpctx->sh_video;
1221 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1222 a_pos = playing_audio_pts(mpctx);
1223 if (mpctx->sh_audio && sh_video && at_frame) {
1224 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1225 if (mpctx->time_frame > 0)
1226 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1227 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1228 && !mpctx->drop_message_shown) {
1229 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1230 mpctx->drop_message_shown = true;
1233 if (opts->quiet)
1234 return;
1237 int width;
1238 char *line;
1239 unsigned pos = 0;
1240 get_screen_size();
1241 if (screen_width > 0)
1242 width = screen_width;
1243 else
1244 width = 80;
1245 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1246 /* Windows command line is broken (MinGW's rxvt works, but we
1247 * should not depend on that). */
1248 width--;
1249 #endif
1250 line = malloc(width + 1); // one additional char for the terminating null
1252 // Audio time
1253 if (mpctx->sh_audio) {
1254 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1255 if (!sh_video) {
1256 float len = get_time_length(mpctx);
1257 saddf(line, &pos, width, "(");
1258 sadd_hhmmssf(line, &pos, width, a_pos);
1259 saddf(line, &pos, width, ") of %.1f (", len);
1260 sadd_hhmmssf(line, &pos, width, len);
1261 saddf(line, &pos, width, ") ");
1265 // Video time
1266 if (sh_video)
1267 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1269 // A-V sync
1270 if (mpctx->sh_audio && sh_video)
1271 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1272 mpctx->last_av_difference, mpctx->total_avsync_change);
1274 // Video stats
1275 if (sh_video)
1276 saddf(line, &pos, width, "%3d/%3d ",
1277 (int)sh_video->num_frames,
1278 (int)sh_video->num_frames_decoded);
1280 // CPU usage
1281 if (sh_video) {
1282 if (sh_video->timer > 0.5)
1283 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1284 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1285 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1286 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1287 else
1288 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1289 } else if (mpctx->sh_audio) {
1290 if (mpctx->delay > 0.5)
1291 saddf(line, &pos, width, "%4.1f%% ",
1292 100.0*audio_time_usage/(double)mpctx->delay);
1293 else
1294 saddf(line, &pos, width, "??,?%% ");
1297 // VO stats
1298 if (sh_video)
1299 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1301 #ifdef CONFIG_STREAM_CACHE
1302 // cache stats
1303 if (stream_cache_size > 0)
1304 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1305 #endif
1307 // other
1308 if (opts->playback_speed != 1)
1309 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1311 // end
1312 if (erase_to_end_of_line) {
1313 line[pos] = 0;
1314 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1315 } else {
1316 memset(&line[pos], ' ', width - pos);
1317 line[width] = 0;
1318 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1320 free(line);
1324 * \brief build a chain of audio filters that converts the input format
1325 * to the ao's format, taking into account the current playback_speed.
1326 * \param sh_audio describes the requested input format of the chain.
1327 * \param ao_data describes the requested output format of the chain.
1329 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1330 ao_data_t *ao_data)
1332 struct MPOpts *opts = &mpctx->opts;
1333 int new_srate;
1334 int result;
1335 if (!sh_audio)
1337 mpctx->mixer.afilter = NULL;
1338 return 0;
1340 if(af_control_any_rev(sh_audio->afilter,
1341 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1342 &opts->playback_speed)) {
1343 new_srate = sh_audio->samplerate;
1344 } else {
1345 new_srate = sh_audio->samplerate * opts->playback_speed;
1346 if (new_srate != ao_data->samplerate) {
1347 // limits are taken from libaf/af_resample.c
1348 if (new_srate < 8000)
1349 new_srate = 8000;
1350 if (new_srate > 192000)
1351 new_srate = 192000;
1352 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1355 result = init_audio_filters(sh_audio, new_srate,
1356 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1357 mpctx->mixer.afilter = sh_audio->afilter;
1358 return result;
1362 typedef struct mp_osd_msg mp_osd_msg_t;
1363 struct mp_osd_msg {
1364 /// Previous message on the stack.
1365 mp_osd_msg_t* prev;
1366 /// Message text.
1367 char msg[128];
1368 int id,level,started;
1369 /// Display duration in ms.
1370 unsigned time;
1373 /// OSD message stack.
1374 static mp_osd_msg_t* osd_msg_stack = NULL;
1377 * \brief Add a message on the OSD message stack
1379 * If a message with the same id is already present in the stack
1380 * it is pulled on top of the stack, otherwise a new message is created.
1383 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1384 va_list ap)
1386 mp_osd_msg_t *msg,*last=NULL;
1387 int r;
1389 // look if the id is already in the stack
1390 for(msg = osd_msg_stack ; msg && msg->id != id ;
1391 last = msg, msg = msg->prev);
1392 // not found: alloc it
1393 if(!msg) {
1394 msg = calloc(1,sizeof(mp_osd_msg_t));
1395 msg->prev = osd_msg_stack;
1396 osd_msg_stack = msg;
1397 } else if(last) { // found, but it's not on top of the stack
1398 last->prev = msg->prev;
1399 msg->prev = osd_msg_stack;
1400 osd_msg_stack = msg;
1402 // write the msg
1403 r = vsnprintf(msg->msg, 128, fmt, ap);
1404 if(r >= 128) msg->msg[127] = 0;
1405 // set id and time
1406 msg->id = id;
1407 msg->level = level;
1408 msg->time = time;
1412 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1414 va_list ap;
1415 va_start(ap, fmt);
1416 set_osd_msg_va(id, level, time, fmt, ap);
1417 va_end(ap);
1420 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1422 va_list ap;
1423 va_start(ap, fmt);
1424 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1425 va_end(ap);
1430 * \brief Remove a message from the OSD stack
1432 * This function can be used to get rid of a message right away.
1436 void rm_osd_msg(int id) {
1437 mp_osd_msg_t *msg,*last=NULL;
1439 // Search for the msg
1440 for(msg = osd_msg_stack ; msg && msg->id != id ;
1441 last = msg, msg = msg->prev);
1442 if(!msg) return;
1444 // Detach it from the stack and free it
1445 if(last)
1446 last->prev = msg->prev;
1447 else
1448 osd_msg_stack = msg->prev;
1449 free(msg);
1453 * \brief Remove all messages from the OSD stack
1457 static void clear_osd_msgs(void) {
1458 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1459 while(msg) {
1460 prev = msg->prev;
1461 free(msg);
1462 msg = prev;
1464 osd_msg_stack = NULL;
1468 * \brief Get the current message from the OSD stack.
1470 * This function decrements the message timer and destroys the old ones.
1471 * The message that should be displayed is returned (if any).
1475 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1477 struct MPOpts *opts = &mpctx->opts;
1478 mp_osd_msg_t *msg,*prev,*last = NULL;
1479 static unsigned last_update = 0;
1480 unsigned now = GetTimerMS();
1481 unsigned diff;
1482 char hidden_dec_done = 0;
1484 if (mpctx->osd_visible) {
1485 // 36000000 means max timed visibility is 1 hour into the future, if
1486 // the difference is greater assume it's wrapped around from below 0
1487 if (mpctx->osd_visible - now > 36000000) {
1488 mpctx->osd_visible = 0;
1489 vo_osd_progbar_type = -1; // disable
1490 vo_osd_changed(OSDTYPE_PROGBAR);
1491 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1494 if (mpctx->osd_show_percentage_until - now > 36000000)
1495 mpctx->osd_show_percentage_until = 0;
1497 if(!last_update) last_update = now;
1498 diff = now >= last_update ? now - last_update : 0;
1500 last_update = now;
1502 // Look for the first message in the stack with high enough level.
1503 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1504 prev = msg->prev;
1505 if (msg->level > opts->osd_level && hidden_dec_done)
1506 continue;
1507 // The message has a high enough level or it is the first hidden one
1508 // in both cases we decrement the timer or kill it.
1509 if(!msg->started || msg->time > diff) {
1510 if(msg->started) msg->time -= diff;
1511 else msg->started = 1;
1512 // display it
1513 if (msg->level <= opts->osd_level)
1514 return msg;
1515 hidden_dec_done = 1;
1516 continue;
1518 // kill the message
1519 free(msg);
1520 if(last) {
1521 last->prev = prev;
1522 msg = last;
1523 } else {
1524 osd_msg_stack = prev;
1525 msg = NULL;
1528 // Nothing found
1529 return NULL;
1533 * \brief Display the OSD bar.
1535 * Display the OSD bar or fall back on a simple message.
1539 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1540 struct MPOpts *opts = &mpctx->opts;
1541 if (opts->osd_level < 1)
1542 return;
1544 if(mpctx->sh_video) {
1545 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1546 vo_osd_progbar_type = type;
1547 vo_osd_progbar_value = 256*(val-min)/(max-min);
1548 vo_osd_changed(OSDTYPE_PROGBAR);
1549 return;
1552 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1553 name, ROUND(100*(val-min)/(max-min)));
1557 * \brief Display text subtitles on the OSD
1559 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1561 int i;
1562 vo_sub = subs;
1563 vo_osd_changed(OSDTYPE_SUBTITLE);
1564 if (!mpctx->sh_video) {
1565 // reverse order, since newest set_osd_msg is displayed first
1566 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1567 if (!subs || i >= subs->lines || !subs->text[i])
1568 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1569 else {
1570 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1571 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1572 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1579 * \brief Update the OSD message line.
1581 * This function displays the current message on the vo OSD or on the term.
1582 * If the stack is empty and the OSD level is high enough the timer
1583 * is displayed (only on the vo OSD).
1587 static void update_osd_msg(struct MPContext *mpctx)
1589 struct MPOpts *opts = &mpctx->opts;
1590 mp_osd_msg_t *msg;
1591 struct osd_state *osd = mpctx->osd;
1592 char osd_text_timer[128];
1594 if (mpctx->add_osd_seek_info) {
1595 double percentage = get_percent_pos(mpctx);
1596 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1597 if (mpctx->sh_video)
1598 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1599 mpctx->add_osd_seek_info = false;
1602 // Look if we have a msg
1603 if((msg = get_osd_msg(mpctx))) {
1604 if (strcmp(osd->osd_text, msg->msg)) {
1605 strncpy(osd->osd_text, msg->msg, 127);
1606 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1607 if(opts->term_osd)
1608 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1609 msg->msg);
1611 return;
1614 if(mpctx->sh_video) {
1615 // fallback on the timer
1616 if (opts->osd_level >= 2) {
1617 int len = get_time_length(mpctx);
1618 int percentage = -1;
1619 char percentage_text[10];
1620 int pts = get_current_time(mpctx);
1622 if (mpctx->osd_show_percentage_until)
1623 percentage = get_percent_pos(mpctx);
1625 if (percentage >= 0)
1626 snprintf(percentage_text, 9, " (%d%%)", percentage);
1627 else
1628 percentage_text[0] = 0;
1630 if (opts->osd_level == 3)
1631 snprintf(osd_text_timer, 63,
1632 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1633 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1634 len/3600,(len/60)%60,len%60,percentage_text);
1635 else
1636 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1637 mpctx->osd_function,pts/3600,(pts/60)%60,
1638 pts%60,percentage_text);
1639 } else
1640 osd_text_timer[0]=0;
1642 if (strcmp(osd->osd_text, osd_text_timer)) {
1643 strncpy(osd->osd_text, osd_text_timer, 63);
1644 vo_osd_changed(OSDTYPE_OSD);
1646 return;
1649 // Clear the term osd line
1650 if (opts->term_osd && osd->osd_text[0]) {
1651 osd->osd_text[0] = 0;
1652 printf("%s\n", opts->term_osd_esc);
1656 ///@}
1657 // OSDMsgStack
1660 void reinit_audio_chain(struct MPContext *mpctx)
1662 struct MPOpts *opts = &mpctx->opts;
1663 if (!mpctx->sh_audio)
1664 return;
1665 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1666 current_module="init_audio_codec";
1667 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1668 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1669 goto init_error;
1671 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1672 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1676 current_module="af_preinit";
1677 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1678 ao_data.samplerate=force_srate;
1679 ao_data.channels=0;
1680 ao_data.format = opts->audio_output_format;
1682 // first init to detect best values
1683 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1684 // input:
1685 mpctx->sh_audio->samplerate,
1686 // output:
1687 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1688 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1689 "pre-init!\n");
1690 exit_player(mpctx, EXIT_ERROR);
1692 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1693 current_module="ao2_init";
1694 ao_data.buffersize = opts->ao_buffersize;
1695 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1696 0, // plugin flag
1697 ao_data.samplerate,
1698 ao_data.channels,
1699 ao_data.format, 0);
1700 if(!mpctx->audio_out){
1701 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1702 goto init_error;
1704 mpctx->initialized_flags|=INITIALIZED_AO;
1705 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1706 mpctx->audio_out->info->short_name,
1707 ao_data.samplerate, ao_data.channels,
1708 af_fmt2str_short(ao_data.format),
1709 af_fmt2bits(ao_data.format)/8 );
1710 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1711 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1712 if(strlen(mpctx->audio_out->info->comment) > 0)
1713 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1716 // init audio filters:
1717 current_module="af_init";
1718 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1719 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1720 goto init_error;
1722 mpctx->mixer.audio_out = mpctx->audio_out;
1723 mpctx->mixer.volstep = volstep;
1724 mpctx->syncing_audio = true;
1725 return;
1727 init_error:
1728 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1729 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1730 mpctx->d_audio->id = -2;
1734 ///@}
1735 // Command2Property
1738 // Return pts value corresponding to the end point of audio written to the
1739 // ao so far.
1740 static double written_audio_pts(struct MPContext *mpctx)
1742 sh_audio_t *sh_audio = mpctx->sh_audio;
1743 demux_stream_t *d_audio = mpctx->d_audio;
1744 double buffered_output;
1745 // first calculate the end pts of audio that has been output by decoder
1746 double a_pts = sh_audio->pts;
1747 if (a_pts != MP_NOPTS_VALUE)
1748 // Good, decoder supports new way of calculating audio pts.
1749 // sh_audio->pts is the timestamp of the latest input packet with
1750 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1751 // the amount of bytes the decoder has written after that timestamp.
1752 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1753 else {
1754 // Decoder doesn't support new way of calculating pts (or we're
1755 // being called before it has decoded anything with known timestamp).
1756 // Use the old method of audio pts calculation: take the timestamp
1757 // of last packet with known pts the decoder has read data from,
1758 // and add amount of bytes read after the beginning of that packet
1759 // divided by input bps. This will be inaccurate if the input/output
1760 // ratio is not constant for every audio packet or if it is constant
1761 // but not accurately known in sh_audio->i_bps.
1763 a_pts = d_audio->pts;
1764 // ds_tell_pts returns bytes read after last timestamp from
1765 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1766 // it has read but not decoded
1767 if (sh_audio->i_bps)
1768 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1769 (double)sh_audio->i_bps;
1771 // Now a_pts hopefully holds the pts for end of audio from decoder.
1772 // Substract data in buffers between decoder and audio out.
1774 // Decoded but not filtered
1775 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1777 // Data buffered in audio filters, measured in bytes of "missing" output
1778 buffered_output = af_calc_delay(sh_audio->afilter);
1780 // Data that was ready for ao but was buffered because ao didn't fully
1781 // accept everything to internal buffers yet
1782 buffered_output += sh_audio->a_out_buffer_len;
1784 // Filters divide audio length by playback_speed, so multiply by it
1785 // to get the length in original units without speedup or slowdown
1786 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1788 return a_pts + mpctx->video_offset;
1791 // Return pts value corresponding to currently playing audio.
1792 double playing_audio_pts(struct MPContext *mpctx)
1794 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1795 mpctx->audio_out->get_delay();
1798 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1799 struct MPOpts *opts = &mpctx->opts;
1800 // check for frame-drop:
1801 current_module = "check_framedrop";
1802 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1803 static int dropped_frames;
1804 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1805 float d = delay-mpctx->delay;
1806 ++total_frame_cnt;
1807 // we should avoid dropping too many frames in sequence unless we
1808 // are too late. and we allow 100ms A-V delay here:
1809 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1810 && !mpctx->restart_playback) {
1811 ++drop_frame_cnt;
1812 ++dropped_frames;
1813 return frame_dropping;
1814 } else
1815 dropped_frames = 0;
1817 return 0;
1821 #ifdef HAVE_RTC
1822 int rtc_fd = -1;
1823 #endif
1825 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1827 #ifdef HAVE_RTC
1828 if (rtc_fd >= 0){
1829 // -------- RTC -----------
1830 current_module="sleep_rtc";
1831 while (time_frame > 0.000) {
1832 unsigned long rtc_ts;
1833 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1834 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1835 time_frame -= get_relative_time(mpctx);
1837 } else
1838 #endif
1840 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1841 // unnecessarily high CPU usage
1842 struct MPOpts *opts = &mpctx->opts;
1843 float margin = opts->softsleep ? 0.011 : 0;
1844 current_module = "sleep_timer";
1845 while (time_frame > margin) {
1846 usec_sleep(1000000 * (time_frame - margin));
1847 time_frame -= get_relative_time(mpctx);
1849 if (opts->softsleep){
1850 current_module = "sleep_soft";
1851 if (time_frame < 0)
1852 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1853 while (time_frame > 0)
1854 time_frame -= get_relative_time(mpctx); // burn the CPU
1857 return time_frame;
1860 static int select_subtitle(MPContext *mpctx)
1862 struct MPOpts *opts = &mpctx->opts;
1863 // find the best sub to use
1864 int id;
1865 int found = 0;
1866 mpctx->global_sub_pos = -1; // no subs by default
1867 if (vobsub_id >= 0) {
1868 // if user asks for a vobsub id, use that first.
1869 id = vobsub_id;
1870 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1873 if (!found && opts->sub_id >= 0) {
1874 // if user asks for a dvd sub id, use that next.
1875 id = opts->sub_id;
1876 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1879 if (!found) {
1880 // if there are text subs to use, use those. (autosubs come last here)
1881 id = 0;
1882 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1885 if (!found && opts->sub_id == -1) {
1886 // finally select subs by language and container hints
1887 if (opts->sub_id == -1)
1888 opts->sub_id =
1889 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
1890 opts->sub_lang);
1891 if (opts->sub_id >= 0) {
1892 id = opts->sub_id;
1893 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1896 return found;
1899 #ifdef CONFIG_DVDNAV
1900 #ifndef FF_B_TYPE
1901 #define FF_B_TYPE 3
1902 #endif
1903 /// store decoded video image
1904 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1905 mp_image_t *from_mpi) {
1906 mp_image_t *mpi;
1908 /// Do not store B-frames
1909 if (from_mpi->pict_type == FF_B_TYPE)
1910 return to_mpi;
1912 if (to_mpi &&
1913 to_mpi->w == from_mpi->w &&
1914 to_mpi->h == from_mpi->h &&
1915 to_mpi->imgfmt == from_mpi->imgfmt)
1916 mpi = to_mpi;
1917 else {
1918 if (to_mpi)
1919 free_mp_image(to_mpi);
1920 if (from_mpi->w == 0 || from_mpi->h == 0)
1921 return NULL;
1922 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1925 copy_mpi(mpi,from_mpi);
1926 return mpi;
1929 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1930 struct MPOpts *opts = &ctx->opts;
1931 if (ctx->sh_video) {
1932 /// clear video pts
1933 ctx->d_video->pts = 0.0f;
1934 ctx->sh_video->pts = 0.0f;
1935 ctx->sh_video->i_pts = 0.0f;
1936 ctx->sh_video->last_pts = 0.0f;
1937 ctx->sh_video->num_buffered_pts = 0;
1938 ctx->sh_video->num_frames = 0;
1939 ctx->sh_video->num_frames_decoded = 0;
1940 ctx->sh_video->timer = 0.0f;
1941 ctx->sh_video->stream_delay = 0.0f;
1942 ctx->sh_video->timer = 0;
1943 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1946 if (ctx->sh_audio) {
1947 /// free audio packets and reset
1948 ds_free_packs(ctx->d_audio);
1949 audio_delay -= ctx->sh_audio->stream_delay;
1950 ctx->delay =- audio_delay;
1951 ctx->audio_out->reset();
1952 resync_audio_stream(ctx->sh_audio);
1955 audio_delay = 0.0f;
1956 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
1957 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
1958 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
1959 if (dvdsub_lang_id != opts->sub_id) {
1960 opts->sub_id = dvdsub_lang_id;
1961 select_subtitle(ctx);
1965 /// clear all EOF related flags
1966 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1969 /// Restore last decoded DVDNAV (still frame)
1970 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
1971 int *in_size,
1972 unsigned char **start,
1973 mp_image_t *decoded_frame)
1975 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1976 return decoded_frame;
1978 /// a change occured in dvdnav stream
1979 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
1980 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
1981 mp_dvdnav_context_free(mpctx);
1982 mp_dvdnav_reset_stream(mpctx);
1983 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
1984 mp_dvdnav_cell_has_changed(mpctx->stream,1);
1987 if (*in_size < 0) {
1988 float len;
1990 /// Display still frame, if any
1991 if (mpctx->nav_smpi && !mpctx->nav_buffer)
1992 decoded_frame = mpctx->nav_smpi;
1994 /// increment video frame : continue playing after still frame
1995 len = get_time_length(mpctx);
1996 if (mpctx->sh_video->pts >= len &&
1997 mpctx->sh_video->pts > 0.0 && len > 0.0) {
1998 mp_dvdnav_skip_still(mpctx->stream);
1999 mp_dvdnav_skip_wait(mpctx->stream);
2001 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2003 if (mpctx->nav_buffer) {
2004 *start = mpctx->nav_start;
2005 *in_size = mpctx->nav_in_size;
2006 if (mpctx->nav_start)
2007 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2011 return decoded_frame;
2014 /// Save last decoded DVDNAV (still frame)
2015 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2016 unsigned char *start,
2017 mp_image_t *decoded_frame)
2019 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2020 return;
2022 free(mpctx->nav_buffer);
2024 mpctx->nav_buffer = malloc(in_size);
2025 mpctx->nav_start = start;
2026 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2027 if (mpctx->nav_buffer)
2028 memcpy(mpctx->nav_buffer,start,in_size);
2030 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2031 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2033 #endif /* CONFIG_DVDNAV */
2035 /* Modify video timing to match the audio timeline. There are two main
2036 * reasons this is needed. First, video and audio can start from different
2037 * positions at beginning of file or after a seek (MPlayer starts both
2038 * immediately even if they have different pts). Second, the file can have
2039 * audio timestamps that are inconsistent with the duration of the audio
2040 * packets, for example two consecutive timestamp values differing by
2041 * one second but only a packet with enough samples for half a second
2042 * of playback between them.
2044 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2046 current_module = "av_sync";
2048 if (!mpctx->sh_audio || mpctx->syncing_audio)
2049 return;
2051 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2052 double v_pts = mpctx->sh_video->pts;
2053 double av_delay = a_pts - v_pts;
2054 // Try to sync vo_flip() so it will *finish* at given time
2055 av_delay += mpctx->last_vo_flip_duration;
2056 av_delay -= audio_delay; // This much pts difference is desired
2058 double change = av_delay * 0.1;
2059 double max_change = default_max_pts_correction >= 0 ?
2060 default_max_pts_correction : frame_time * 0.1;
2061 if (change < -max_change)
2062 change = -max_change;
2063 else if (change > max_change)
2064 change = max_change;
2065 mpctx->delay += change;
2066 mpctx->total_avsync_change += change;
2069 #define ASYNC_PLAY_DONE -3
2070 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2072 struct MPOpts *opts = &mpctx->opts;
2073 sh_audio_t * const sh_audio = mpctx->sh_audio;
2074 int res;
2076 // Timing info may not be set without
2077 res = decode_audio(sh_audio, 1);
2078 if (res < 0)
2079 return res;
2081 int bytes;
2082 bool did_retry = false;
2083 while (1) {
2084 double written_pts = written_audio_pts(mpctx);
2085 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2086 - audio_delay;
2087 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2088 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2090 // ogg demuxers give packets without timing
2091 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2092 if (!did_retry) {
2093 // Try to read more data to see packets that have pts
2094 int res = decode_audio(sh_audio, ao_data.bps);
2095 if (res < 0)
2096 return res;
2097 did_retry = true;
2098 continue;
2100 bytes = 0;
2103 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2104 bytes = 0;
2106 if (bytes > 0)
2107 break;
2109 mpctx->syncing_audio = false;
2110 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2111 int res = decode_audio(sh_audio, a);
2112 bytes += sh_audio->a_out_buffer_len;
2113 if (bytes >= 0) {
2114 memmove(sh_audio->a_out_buffer,
2115 sh_audio->a_out_buffer +
2116 sh_audio->a_out_buffer_len - bytes,
2117 bytes);
2118 sh_audio->a_out_buffer_len = bytes;
2119 if (res < 0)
2120 return res;
2121 return decode_audio(sh_audio, playsize);
2123 sh_audio->a_out_buffer_len = 0;
2124 if (res < 0)
2125 return res;
2127 int fillbyte = 0;
2128 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2129 fillbyte = 0x80;
2130 if (bytes >= playsize) {
2131 /* This case could fall back to the one below with
2132 * bytes = playsize, but then silence would keep accumulating
2133 * in a_out_buffer if the AO accepts less data than it asks for
2134 * in playsize. */
2135 char *p = malloc(playsize);
2136 memset(p, fillbyte, playsize);
2137 playsize = mpctx->audio_out->play(p, playsize, 0);
2138 free(p);
2139 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2140 return ASYNC_PLAY_DONE;
2142 mpctx->syncing_audio = false;
2143 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2144 return decode_audio(sh_audio, playsize);
2147 static int fill_audio_out_buffers(struct MPContext *mpctx)
2149 struct MPOpts *opts = &mpctx->opts;
2150 unsigned int t;
2151 double tt;
2152 int playsize;
2153 int playflags=0;
2154 int audio_eof=0;
2155 bool format_change = false;
2156 sh_audio_t * const sh_audio = mpctx->sh_audio;
2158 current_module="play_audio";
2160 while (1) {
2161 int sleep_time;
2162 // all the current uses of ao_data.pts seem to be in aos that handle
2163 // sync completely wrong; there should be no need to use ao_data.pts
2164 // in get_space()
2165 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2166 playsize = mpctx->audio_out->get_space();
2167 if (mpctx->sh_video || playsize >= ao_data.outburst)
2168 break;
2170 // handle audio-only case:
2171 // this is where mplayer sleeps during audio-only playback
2172 // to avoid 100% CPU use
2173 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2174 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2175 usec_sleep(sleep_time * 1000);
2178 // Fill buffer if needed:
2179 current_module="decode_audio";
2180 t = GetTimer();
2182 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2183 mpctx->syncing_audio = false;
2185 int res;
2186 if (mpctx->syncing_audio && mpctx->sh_video)
2187 res = audio_start_sync(mpctx, playsize);
2188 else
2189 res = decode_audio(sh_audio, playsize);
2190 if (res < 0) { // EOF, error or format change
2191 if (res == -2)
2192 format_change = true;
2193 else if (res == ASYNC_PLAY_DONE)
2194 return 1;
2195 else if (mpctx->d_audio->eof) {
2196 audio_eof = 1;
2197 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2198 if (sh_audio->a_out_buffer_len < unitsize)
2199 return 0;
2202 t = GetTimer() - t;
2203 tt = t*0.000001f; audio_time_usage+=tt;
2204 if (playsize > sh_audio->a_out_buffer_len) {
2205 playsize = sh_audio->a_out_buffer_len;
2206 if (audio_eof)
2207 playflags |= AOPLAY_FINAL_CHUNK;
2209 if (!playsize)
2210 return 1;
2212 // play audio:
2213 current_module="play_audio";
2215 // Is this pts value actually useful for the aos that access it?
2216 // They're obviously badly broken in the way they handle av sync;
2217 // would not having access to this make them more broken?
2218 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2219 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2221 if (playsize > 0) {
2222 sh_audio->a_out_buffer_len -= playsize;
2223 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2224 sh_audio->a_out_buffer_len);
2225 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2226 } else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2227 // Sanity check to avoid hanging in case current ao doesn't output
2228 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2229 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2230 sh_audio->a_out_buffer_len = 0;
2233 /* The format change isn't handled too gracefully. A more precise
2234 * implementation would require draining buffered old-format audio
2235 * while displaying video, then doing the output format switch.
2237 if (format_change) {
2238 uninit_player(mpctx, INITIALIZED_AO);
2239 reinit_audio_chain(mpctx);
2242 return 1;
2245 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2246 float *aq_sleep_time)
2248 struct MPOpts *opts = &mpctx->opts;
2249 double audio_limit = 2;
2250 current_module="calc_sleep_time";
2252 if (mpctx->restart_playback)
2253 return 0;
2255 *time_frame -= get_relative_time(mpctx); // reset timer
2257 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2258 float delay = mpctx->audio_out->get_delay();
2259 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2261 if (opts->autosync) {
2263 * Adjust this raw delay value by calculating the expected
2264 * delay for this frame and generating a new value which is
2265 * weighted between the two. The higher autosync is, the
2266 * closer to the delay value gets to that which "-nosound"
2267 * would have used, and the longer it will take for A/V
2268 * sync to settle at the right value (but it eventually will.)
2269 * This settling time is very short for values below 100.
2271 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2272 float difference = delay - predicted;
2273 delay = predicted + difference / (float)opts->autosync;
2276 *time_frame = delay - mpctx->delay / opts->playback_speed;
2278 // delay = amount of audio buffered in soundcard/driver
2279 delay = FFMIN(delay, 0.5);
2280 delay = FFMAX(delay, 0.1);
2281 audio_limit = delay;
2282 } else {
2283 // If we're lagging more than 200 ms behind the right playback rate,
2284 // don't try to "catch up".
2285 // If benchmark is set always output frames as fast as possible
2286 // without sleeping.
2287 if (*time_frame < -0.2 || opts->benchmark)
2288 *time_frame = 0;
2291 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2293 if (t <= 0.05)
2294 return 0;
2296 t -= 0.05;
2297 if (t > audio_limit * 0.6)
2298 t = audio_limit * 0.5;
2299 *aq_sleep_time += t;
2300 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2301 return 1;
2304 int reinit_video_chain(struct MPContext *mpctx)
2306 struct MPOpts *opts = &mpctx->opts;
2307 sh_video_t * const sh_video = mpctx->sh_video;
2308 double ar=-1.0;
2309 //================== Init VIDEO (codec & libvo) ==========================
2310 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2311 current_module="preinit_libvo";
2313 //shouldn't we set dvideo->id=-2 when we fail?
2314 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2315 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2316 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2317 goto err_out;
2319 mpctx->initialized_flags|=INITIALIZED_VO;
2322 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2323 mpctx->sh_video->stream_aspect = ar;
2324 current_module="init_video_filters";
2326 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2327 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2329 #ifdef CONFIG_MENU
2330 if(use_menu) {
2331 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2332 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2333 if(!vf_menu) {
2334 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2335 use_menu = 0;
2338 if(vf_menu)
2339 sh_video->vfilter = vf_menu;
2340 #endif
2342 #ifdef CONFIG_ASS
2343 if(opts->ass_enabled) {
2344 int i;
2345 int insert = 1;
2346 if (opts->vf_settings)
2347 for (i = 0; opts->vf_settings[i].name; ++i)
2348 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2349 insert = 0;
2350 break;
2352 if (insert) {
2353 extern vf_info_t vf_info_ass;
2354 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2355 char* vf_arg[] = {"auto", "1", NULL};
2356 int retcode = 0;
2357 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2358 sh_video->vfilter,
2359 "ass", vf_arg,
2360 &retcode);
2361 if (vf_ass)
2362 sh_video->vfilter = vf_ass;
2363 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2364 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2365 else
2366 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2369 #endif
2371 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2373 #ifdef CONFIG_ASS
2374 if (opts->ass_enabled)
2375 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2376 #endif
2378 current_module="init_video_codec";
2380 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2381 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2382 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2384 if(!sh_video->initialized){
2385 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2386 goto err_out;
2389 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2391 if (sh_video->codec)
2392 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2394 sh_video->last_pts = MP_NOPTS_VALUE;
2395 sh_video->num_buffered_pts = 0;
2396 sh_video->next_frame_time = 0;
2398 if (opts->auto_quality > 0) {
2399 // Auto quality option enabled
2400 output_quality=get_video_quality_max(sh_video);
2401 if (opts->auto_quality > output_quality)
2402 opts->auto_quality = output_quality;
2403 else
2404 output_quality = opts->auto_quality;
2405 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2406 set_video_quality(sh_video,output_quality);
2409 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2411 current_module="init_vo";
2413 return 1;
2415 err_out:
2416 mpctx->sh_video = mpctx->d_video->sh = NULL;
2417 return 0;
2420 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2422 struct sh_video *sh_video = mpctx->sh_video;
2423 double frame_time = 0;
2424 struct vo *video_out = mpctx->video_out;
2425 while (1) {
2426 current_module = "filter_video";
2427 // In nocorrect-pts mode there is no way to properly time these frames
2428 if (vo_get_buffered_frame(video_out, 0) >= 0)
2429 break;
2430 if (vf_output_queued_frame(sh_video->vfilter))
2431 break;
2432 unsigned char *packet = NULL;
2433 frame_time = sh_video->next_frame_time;
2434 if (mpctx->restart_playback)
2435 frame_time = 0;
2436 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2437 &packet, force_fps);
2438 if (in_size < 0) {
2439 #ifdef CONFIG_DVDNAV
2440 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2441 if (mp_dvdnav_is_eof(mpctx->stream))
2442 return -1;
2443 if (mpctx->d_video)
2444 mpctx->d_video->eof = 0;
2445 if (mpctx->d_audio)
2446 mpctx->d_audio->eof = 0;
2447 mpctx->stream->eof = 0;
2448 } else
2449 #endif
2450 return -1;
2452 if (in_size > max_framesize)
2453 max_framesize = in_size;
2454 sh_video->timer += frame_time;
2455 if (mpctx->sh_audio)
2456 mpctx->delay -= frame_time;
2457 // video_read_frame can change fps (e.g. for ASF video)
2458 vo_fps = sh_video->fps;
2459 int framedrop_type = check_framedrop(mpctx, frame_time);
2460 current_module = "decode video";
2462 void *decoded_frame;
2463 #ifdef CONFIG_DVDNAV
2464 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2465 if (in_size >= 0 && !decoded_frame)
2466 #endif
2467 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2468 sh_video->pts);
2469 #ifdef CONFIG_DVDNAV
2470 // Save last still frame for future display
2471 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2472 #endif
2473 if (decoded_frame) {
2474 current_module = "filter video";
2475 filter_video(sh_video, decoded_frame, sh_video->pts);
2477 break;
2479 return frame_time;
2482 static void determine_frame_pts(struct MPContext *mpctx)
2484 struct sh_video *sh_video = mpctx->sh_video;
2485 struct MPOpts *opts = &mpctx->opts;
2487 if (opts->user_pts_assoc_mode) {
2488 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2489 } else if (sh_video->pts_assoc_mode == 0) {
2490 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2491 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2492 sh_video->pts_assoc_mode = 1;
2493 else
2494 sh_video->pts_assoc_mode = 2;
2495 } else {
2496 int probcount1 = sh_video->num_reordered_pts_problems;
2497 int probcount2 = sh_video->num_sorted_pts_problems;
2498 if (sh_video->pts_assoc_mode == 2) {
2499 int tmp = probcount1;
2500 probcount1 = probcount2;
2501 probcount2 = tmp;
2503 if (probcount1 >= probcount2 * 1.5 + 2) {
2504 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2505 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2506 "%d.\n", sh_video->pts_assoc_mode);
2509 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2510 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2513 static double update_video(struct MPContext *mpctx)
2515 struct sh_video *sh_video = mpctx->sh_video;
2516 struct vo *video_out = mpctx->video_out;
2517 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2518 mpctx->osd); // hack for vf_expand
2519 if (!mpctx->opts.correct_pts)
2520 return update_video_nocorrect_pts(mpctx);
2522 double pts;
2524 while (1) {
2525 current_module = "filter_video";
2526 if (!mpctx->hrseek_active
2527 && vo_get_buffered_frame(video_out, false) >= 0)
2528 break;
2529 // XXX Time used in this call is not counted in any performance
2530 // timer now
2531 if (vf_output_queued_frame(sh_video->vfilter))
2532 break;
2533 unsigned char *packet = NULL;
2534 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2535 if (pts != MP_NOPTS_VALUE)
2536 pts += mpctx->video_offset;
2537 bool hit_eof = false;
2538 if (in_size < 0) {
2539 // try to extract last frames in case of decoder lag
2540 in_size = 0;
2541 pts = MP_NOPTS_VALUE;
2542 hit_eof = true;
2544 if (in_size > max_framesize)
2545 max_framesize = in_size;
2546 current_module = "decode video";
2547 if (pts >= mpctx->hrseek_pts - .005)
2548 mpctx->hrseek_framedrop = false;
2549 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2550 check_framedrop(mpctx, sh_video->frametime);
2551 void *decoded_frame = decode_video(sh_video, packet, in_size,
2552 framedrop_type, pts);
2553 if (decoded_frame) {
2554 determine_frame_pts(mpctx);
2555 current_module = "filter video";
2556 filter_video(sh_video, decoded_frame, sh_video->pts);
2557 } else if (hit_eof) {
2558 if (vo_get_buffered_frame(video_out, true) < 0)
2559 return -1;
2561 break;
2564 if (!video_out->frame_loaded)
2565 return 0;
2567 pts = video_out->next_pts;
2568 if (pts == MP_NOPTS_VALUE) {
2569 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2570 // Try to use decoder pts from before filters
2571 pts = sh_video->pts;
2572 if (pts == MP_NOPTS_VALUE)
2573 pts = sh_video->last_pts;
2575 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005)
2576 return 0;
2577 mpctx->hrseek_active = false;
2578 sh_video->pts = pts;
2579 if (sh_video->last_pts == MP_NOPTS_VALUE)
2580 sh_video->last_pts = sh_video->pts;
2581 else if (sh_video->last_pts > sh_video->pts) {
2582 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2583 sh_video->pts, sh_video->last_pts);
2584 /* If the difference in pts is small treat it as jitter around the
2585 * right value (possibly caused by incorrect timestamp ordering) and
2586 * just show this frame immediately after the last one.
2587 * Treat bigger differences as timestamp resets and start counting
2588 * timing of later frames from the position of this one. */
2589 if (sh_video->last_pts - sh_video->pts > 0.5)
2590 sh_video->last_pts = sh_video->pts;
2591 else
2592 sh_video->pts = sh_video->last_pts;
2594 double frame_time = sh_video->pts - sh_video->last_pts;
2595 sh_video->last_pts = sh_video->pts;
2596 sh_video->timer += frame_time;
2597 if (mpctx->sh_audio)
2598 mpctx->delay -= frame_time;
2599 return frame_time;
2602 void pause_player(struct MPContext *mpctx)
2604 if (mpctx->paused)
2605 return;
2606 mpctx->paused = 1;
2607 mpctx->step_frames = 0;
2608 mpctx->time_frame -= get_relative_time(mpctx);
2610 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2611 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2613 if (mpctx->audio_out && mpctx->sh_audio)
2614 mpctx->audio_out->pause(); // pause audio, keep data if possible
2617 void unpause_player(struct MPContext *mpctx)
2619 if (!mpctx->paused)
2620 return;
2621 mpctx->paused = 0;
2623 if (mpctx->audio_out && mpctx->sh_audio)
2624 mpctx->audio_out->resume(); // resume audio
2625 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2626 && !mpctx->step_frames)
2627 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2628 (void)get_relative_time(mpctx); // ignore time that passed during pause
2631 void add_step_frame(struct MPContext *mpctx)
2633 mpctx->step_frames++;
2634 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2635 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2636 unpause_player(mpctx);
2639 static void pause_loop(struct MPContext *mpctx)
2641 struct MPOpts *opts = &mpctx->opts;
2642 mp_cmd_t* cmd;
2643 if (!opts->quiet) {
2644 // Small hack to display the pause message on the OSD line.
2645 // The pause string is: "\n == PAUSE == \r" so we need to
2646 // take the first and the last char out
2647 if (opts->term_osd && !mpctx->sh_video) {
2648 char msg[128] = _("\n ===== PAUSE =====\r");
2649 int mlen = strlen(msg);
2650 msg[mlen-1] = '\0';
2651 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2652 update_osd_msg(mpctx);
2653 } else
2654 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2655 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2658 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2659 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2660 if (cmd) {
2661 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2662 run_command(mpctx, cmd);
2663 mp_cmd_free(cmd);
2664 continue;
2666 if (mpctx->sh_video && mpctx->video_out)
2667 vo_check_events(mpctx->video_out);
2668 #ifdef CONFIG_MENU
2669 if (vf_menu)
2670 vf_menu_pause_update(vf_menu);
2671 #endif
2672 usec_sleep(20000);
2673 update_osd_msg(mpctx);
2674 int hack = vo_osd_changed(0);
2675 vo_osd_changed(hack);
2676 if (hack)
2677 break;
2682 // Find the right mute status and record position for new file position
2683 static void edl_seek_reset(MPContext *mpctx)
2685 mpctx->edl_muted = 0;
2686 next_edl_record = edl_records;
2688 while (next_edl_record) {
2689 if (next_edl_record->start_sec >= get_current_time(mpctx))
2690 break;
2692 if (next_edl_record->action == EDL_MUTE)
2693 mpctx->edl_muted = !mpctx->edl_muted;
2694 next_edl_record = next_edl_record->next;
2696 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2697 mixer_mute(&mpctx->mixer);
2701 // Execute EDL command for the current position if one exists
2702 static void edl_update(MPContext *mpctx)
2704 if (!next_edl_record)
2705 return;
2707 if (!mpctx->sh_video) {
2708 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2709 free_edl(edl_records);
2710 next_edl_record = NULL;
2711 edl_records = NULL;
2712 return;
2715 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2716 if (next_edl_record->action == EDL_SKIP) {
2717 mpctx->osd_function = OSD_FFW;
2718 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2719 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2720 "[%f], length [%f]\n", next_edl_record->start_sec,
2721 next_edl_record->stop_sec, next_edl_record->length_sec);
2723 else if (next_edl_record->action == EDL_MUTE) {
2724 mpctx->edl_muted = !mpctx->edl_muted;
2725 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2726 mixer_mute(&mpctx->mixer);
2727 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2728 next_edl_record->start_sec );
2730 next_edl_record = next_edl_record->next;
2734 static void reinit_decoders(struct MPContext *mpctx)
2736 reinit_video_chain(mpctx);
2737 reinit_audio_chain(mpctx);
2738 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2741 static void seek_reset(struct MPContext *mpctx)
2743 if (mpctx->sh_video) {
2744 current_module = "seek_video_reset";
2745 resync_video_stream(mpctx->sh_video);
2746 mpctx->sh_video->timer = 0;
2747 vo_seek_reset(mpctx->video_out);
2748 mpctx->sh_video->timer = 0;
2749 mpctx->sh_video->num_buffered_pts = 0;
2750 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2751 mpctx->delay = 0;
2752 mpctx->time_frame = 0;
2753 mpctx->restart_playback = true;
2754 // Not all demuxers set d_video->pts during seek, so this value
2755 // (which is used by at least vobsub and edl code below) may
2756 // be completely wrong (probably 0).
2757 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2758 mpctx->video_pts = mpctx->sh_video->pts;
2759 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2760 mpctx->sh_video->pts, mpctx->video_offset,
2761 mpctx->d_sub, 1);
2762 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2765 if (mpctx->sh_audio) {
2766 current_module = "seek_audio_reset";
2767 resync_audio_stream(mpctx->sh_audio);
2768 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2769 mpctx->sh_audio->a_buffer_len = 0;
2770 mpctx->sh_audio->a_out_buffer_len = 0;
2771 if (!mpctx->sh_video)
2772 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2773 mpctx->video_offset, mpctx->d_sub, 1);
2776 if (vo_vobsub && mpctx->sh_video) {
2777 current_module = "seek_vobsub_reset";
2778 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2781 edl_seek_reset(mpctx);
2783 mpctx->hrseek_active = false;
2784 mpctx->hrseek_framedrop = false;
2785 mpctx->total_avsync_change = 0;
2786 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2787 drop_frame_cnt = 0;
2789 current_module = NULL;
2792 static bool timeline_set_part(struct MPContext *mpctx, int i)
2794 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2795 struct timeline_part *n = mpctx->timeline + i;
2796 mpctx->timeline_part = i;
2797 mpctx->video_offset = n->start - n->source_start;
2798 if (n->source == p->source)
2799 return false;
2800 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2801 mpctx->demuxer = n->source->demuxer;
2802 mpctx->d_video = mpctx->demuxer->video;
2803 mpctx->d_audio = mpctx->demuxer->audio;
2804 mpctx->d_sub = mpctx->demuxer->sub;
2805 mpctx->sh_video = mpctx->d_video->sh;
2806 mpctx->sh_audio = mpctx->d_audio->sh;
2807 return true;
2810 // Given pts, switch playback to the corresponding part.
2811 // Return offset within that part.
2812 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2813 bool *need_reset)
2815 if (pts < 0)
2816 pts = 0;
2817 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2818 struct timeline_part *p = mpctx->timeline + i;
2819 if (pts < (p+1)->start) {
2820 *need_reset = timeline_set_part(mpctx, i);
2821 return pts - p->start + p->source_start;
2824 return -1;
2828 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2829 static int seek(MPContext *mpctx, struct seek_params seek)
2831 struct MPOpts *opts = &mpctx->opts;
2833 current_module = "seek";
2834 if (mpctx->stop_play == AT_END_OF_FILE)
2835 mpctx->stop_play = KEEP_PLAYING;
2836 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
2837 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
2838 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
2839 || opts->hr_seek > 0 || seek.exact > 0;
2840 if (seek.type == MPSEEK_FACTOR
2841 || seek.type == MPSEEK_ABSOLUTE
2842 && seek.amount < mpctx->last_chapter_pts
2843 || seek.amount < 0)
2844 mpctx->last_chapter_seek = -1;
2845 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
2846 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2847 seek.type = MPSEEK_ABSOLUTE;
2849 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
2850 && seek.type == MPSEEK_RELATIVE) {
2851 seek.type = MPSEEK_ABSOLUTE;
2852 seek.direction = seek.amount > 0 ? 1 : -1;
2853 seek.amount += get_current_time(mpctx);
2856 /* At least the liba52 decoder wants to read from the input stream
2857 * during initialization, so reinit must be done after the demux_seek()
2858 * call that clears possible stream EOF. */
2859 bool need_reset = false;
2860 double demuxer_amount = seek.amount;
2861 if (mpctx->timeline) {
2862 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
2863 &need_reset);
2864 if (demuxer_amount == -1) {
2865 mpctx->stop_play = AT_END_OF_FILE;
2866 // Clear audio from current position
2867 if (mpctx->sh_audio) {
2868 mpctx->audio_out->reset();
2869 mpctx->sh_audio->a_buffer_len = 0;
2870 mpctx->sh_audio->a_out_buffer_len = 0;
2872 return -1;
2875 int demuxer_style = 0;
2876 switch (seek.type) {
2877 case MPSEEK_FACTOR:
2878 demuxer_style |= SEEK_FACTOR; // fallthrough
2879 case MPSEEK_ABSOLUTE:
2880 demuxer_style |= SEEK_ABSOLUTE;
2882 if (hr_seek || seek.direction < 0)
2883 demuxer_style |= SEEK_BACKWARD;
2884 else if (seek.direction > 0)
2885 demuxer_style |= SEEK_FORWARD;
2887 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
2888 demuxer_style);
2889 if (need_reset)
2890 reinit_decoders(mpctx);
2891 if (seekresult == 0)
2892 return -1;
2894 seek_reset(mpctx);
2896 /* Use the target time as "current position" for further relative
2897 * seeks etc until a new video frame has been decoded */
2898 if (seek.type == MPSEEK_ABSOLUTE)
2899 mpctx->video_pts = seek.amount;
2901 if (hr_seek) {
2902 mpctx->hrseek_active = true;
2903 mpctx->hrseek_framedrop = true;
2904 mpctx->hrseek_pts = seek.amount;
2907 mpctx->start_timestamp = GetTimerMS();
2909 return 0;
2912 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
2913 int exact)
2915 struct seek_params *seek = &mpctx->seek;
2916 switch (type) {
2917 case MPSEEK_RELATIVE:
2918 if (seek->type == MPSEEK_FACTOR)
2919 return; // Well... not common enough to bother doing better
2920 seek->amount += amount;
2921 seek->exact = FFMAX(seek->exact, exact);
2922 if (seek->type == MPSEEK_NONE)
2923 seek->exact = exact;
2924 if (seek->type == MPSEEK_ABSOLUTE)
2925 return;
2926 if (seek->amount == 0) {
2927 *seek = (struct seek_params){0};
2928 return;
2930 seek->type = MPSEEK_RELATIVE;
2931 return;
2932 case MPSEEK_ABSOLUTE:
2933 case MPSEEK_FACTOR:
2934 *seek = (struct seek_params) {
2935 .type = type,
2936 .amount = amount,
2937 .exact = exact,
2939 return;
2940 case MPSEEK_NONE:
2941 *seek = (struct seek_params){0};
2942 return;
2944 abort();
2948 double get_time_length(struct MPContext *mpctx)
2950 if (mpctx->timeline)
2951 return mpctx->timeline[mpctx->num_timeline_parts].start;
2953 struct demuxer *demuxer = mpctx->demuxer;
2954 double get_time_ans;
2955 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
2956 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
2957 (void *) &get_time_ans) > 0)
2958 return get_time_ans;
2960 struct sh_video *sh_video = mpctx->d_video->sh;
2961 struct sh_audio *sh_audio = mpctx->d_audio->sh;
2962 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
2963 return (double) (demuxer->movi_end - demuxer->movi_start) /
2964 (sh_video->i_bps + sh_audio->i_bps);
2965 if (sh_video && sh_video->i_bps)
2966 return (double) (demuxer->movi_end - demuxer->movi_start) /
2967 sh_video->i_bps;
2968 if (sh_audio && sh_audio->i_bps)
2969 return (double) (demuxer->movi_end - demuxer->movi_start) /
2970 sh_audio->i_bps;
2971 return 0;
2974 /* If there are timestamps from stream level then use those (for example
2975 * DVDs can have consistent times there while the MPEG-level timestamps
2976 * reset). */
2977 double get_current_time(struct MPContext *mpctx)
2979 struct demuxer *demuxer = mpctx->demuxer;
2980 if (demuxer->stream_pts != MP_NOPTS_VALUE)
2981 return demuxer->stream_pts;
2982 struct sh_video *sh_video = demuxer->video->sh;
2983 if (sh_video)
2984 return mpctx->video_pts;
2985 return playing_audio_pts(mpctx);
2988 int get_percent_pos(struct MPContext *mpctx)
2990 struct demuxer *demuxer = mpctx->demuxer;
2991 int ans = 0;
2992 if (mpctx->timeline)
2993 ans = get_current_time(mpctx) * 100 /
2994 mpctx->timeline[mpctx->num_timeline_parts].start;
2995 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
2997 else {
2998 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
2999 off_t pos = demuxer->filepos > 0 ?
3000 demuxer->filepos : stream_tell(demuxer->stream);
3001 if (len > 0)
3002 ans = (pos - demuxer->movi_start) / len;
3003 else
3004 ans = 0;
3006 if (ans < 0)
3007 ans = 0;
3008 if (ans > 100)
3009 ans = 100;
3010 return ans;
3013 // -2 is no chapters, -1 is before first chapter
3014 int get_current_chapter(struct MPContext *mpctx)
3016 double current_pts = get_current_time(mpctx);
3017 if (!mpctx->chapters)
3018 return FFMAX(mpctx->last_chapter_seek,
3019 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3021 int i;
3022 for (i = 1; i < mpctx->num_chapters; i++)
3023 if (current_pts < mpctx->chapters[i].start)
3024 break;
3025 return FFMAX(mpctx->last_chapter_seek, i - 1);
3028 // currently returns a string allocated with malloc, not talloc
3029 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3031 if (!mpctx->chapters || !mpctx->sh_video)
3032 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3033 return strdup(mpctx->chapters[chapter].name);
3036 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3037 char **chapter_name)
3039 mpctx->last_chapter_seek = -1;
3040 if (!mpctx->chapters || !mpctx->sh_video) {
3041 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3042 chapter_name);
3043 if (res >= 0) {
3044 if (*seek_pts == -1)
3045 seek_reset(mpctx);
3046 else {
3047 mpctx->last_chapter_seek = res;
3048 mpctx->last_chapter_pts = *seek_pts;
3051 return res;
3054 if (chapter >= mpctx->num_chapters)
3055 return -1;
3056 if (chapter < 0)
3057 chapter = 0;
3058 *seek_pts = mpctx->chapters[chapter].start;
3059 mpctx->last_chapter_seek = chapter;
3060 mpctx->last_chapter_pts = *seek_pts;
3061 if (chapter_name)
3062 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3063 return chapter;
3067 static void run_playloop(struct MPContext *mpctx)
3069 struct MPOpts *opts = &mpctx->opts;
3070 float aq_sleep_time = 0;
3072 if (opts->chapterrange[1] > 0) {
3073 int cur_chapter = get_current_chapter(mpctx);
3074 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3075 mpctx->stop_play = PT_NEXT_ENTRY;
3078 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3079 mpctx->sh_audio = mpctx->d_audio->sh;
3080 mpctx->sh_audio->ds = mpctx->d_audio;
3081 reinit_audio_chain(mpctx);
3084 /*========================== PLAY AUDIO ============================*/
3086 if (mpctx->sh_audio && !mpctx->paused
3087 && (!mpctx->restart_playback || !mpctx->sh_video))
3088 if (!fill_audio_out_buffers(mpctx))
3089 // at eof, all audio at least written to ao
3090 if (!mpctx->sh_video)
3091 mpctx->stop_play = AT_END_OF_FILE;
3094 if (!mpctx->sh_video) {
3095 mpctx->restart_playback = false;
3096 if (mpctx->step_frames) {
3097 mpctx->step_frames = 0;
3098 pause_player(mpctx);
3100 // handle audio-only case:
3101 double a_pos = 0;
3102 // sh_audio can be NULL due to video stream switching
3103 // TODO: handle this better
3104 if (mpctx->sh_audio)
3105 a_pos = playing_audio_pts(mpctx);
3107 print_status(mpctx, a_pos, false);
3109 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3110 mpctx->stop_play = PT_NEXT_ENTRY;
3111 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
3112 mpctx->d_sub, 0);
3113 update_osd_msg(mpctx);
3114 } else {
3116 /*========================== PLAY VIDEO ============================*/
3118 vo_pts = mpctx->sh_video->timer * 90000.0;
3119 vo_fps = mpctx->sh_video->fps;
3121 bool blit_frame = mpctx->video_out->frame_loaded;
3122 if (!blit_frame || mpctx->hrseek_active) {
3123 double frame_time = update_video(mpctx);
3124 blit_frame = mpctx->video_out->frame_loaded;
3125 blit_frame &= !mpctx->hrseek_active;
3126 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3127 if (mpctx->sh_video->vf_initialized < 0) {
3128 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3129 "\nFATAL: Could not initialize video filters (-vf) "
3130 "or video output (-vo).\n");
3131 mpctx->stop_play = PT_NEXT_ENTRY;
3132 return;
3134 if (frame_time < 0)
3135 mpctx->stop_play = AT_END_OF_FILE;
3136 else if (!mpctx->restart_playback) {
3137 mpctx->time_frame += frame_time / opts->playback_speed;
3138 adjust_sync(mpctx, frame_time);
3141 if (mpctx->timeline) {
3142 struct timeline_part *next =
3143 mpctx->timeline + mpctx->timeline_part + 1;
3144 if (mpctx->sh_video->pts >= next->start
3145 || mpctx->stop_play == AT_END_OF_FILE
3146 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3147 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3148 .amount = next->start });
3149 return;
3153 // ==========================================================================
3155 current_module = "vo_check_events";
3156 vo_check_events(mpctx->video_out);
3158 #ifdef CONFIG_X11
3159 if (stop_xscreensaver) {
3160 current_module = "stop_xscreensaver";
3161 xscreensaver_heartbeat(mpctx->x11_state);
3163 #endif
3164 if (heartbeat_cmd) {
3165 static unsigned last_heartbeat;
3166 unsigned now = GetTimerMS();
3167 if (now - last_heartbeat > 30000) {
3168 last_heartbeat = now;
3169 system(heartbeat_cmd);
3173 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3174 &mpctx->time_frame,
3175 &aq_sleep_time);
3177 //====================== FLIP PAGE (VIDEO BLT): =========================
3179 current_module = "flip_page";
3180 if (!frame_time_remaining && blit_frame) {
3181 struct sh_video *sh_video = mpctx->sh_video;
3182 mpctx->video_pts = sh_video->pts;
3183 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
3184 mpctx->video_offset, mpctx->d_sub, 0);
3185 update_teletext(sh_video, mpctx->demuxer, 0);
3186 update_osd_msg(mpctx);
3187 struct vf_instance *vf = sh_video->vfilter;
3188 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3189 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3190 vo_osd_changed(0);
3192 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3193 aq_sleep_time += mpctx->time_frame;
3194 // flag 256 means: libvo driver does its timing (dvb card)
3195 if (mpctx->time_frame > 0.001
3196 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3197 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3198 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3200 unsigned int t2 = GetTimer();
3201 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
3202 int duration = -1;
3203 double pts2 = mpctx->video_out->next_pts2;
3204 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3205 && !mpctx->restart_playback) {
3206 // expected A/V sync correction is ignored
3207 double diff = (pts2 - mpctx->video_pts);
3208 diff /= opts->playback_speed;
3209 if (mpctx->time_frame < 0)
3210 diff += mpctx->time_frame;
3211 if (diff < 0)
3212 diff = 0;
3213 if (diff > 10)
3214 diff = 10;
3215 duration = diff * 1e6;
3217 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3219 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3220 vout_time_usage += mpctx->last_vo_flip_duration;
3221 if (mpctx->video_out->driver->flip_page_timed) {
3222 // No need to adjust sync based on flip speed
3223 mpctx->last_vo_flip_duration = 0;
3224 // For print_status - VO call finishing early is OK for sync
3225 mpctx->time_frame -= get_relative_time(mpctx);
3227 if (mpctx->restart_playback) {
3228 mpctx->syncing_audio = true;
3229 if (mpctx->sh_audio && !mpctx->paused)
3230 fill_audio_out_buffers(mpctx);
3231 mpctx->restart_playback = false;
3232 mpctx->time_frame = 0;
3233 get_relative_time(mpctx);
3235 print_status(mpctx, MP_NOPTS_VALUE, true);
3236 } else
3237 print_status(mpctx, MP_NOPTS_VALUE, false);
3239 //============================ Auto QUALITY ============================
3241 /*Output quality adjustments:*/
3242 if (opts->auto_quality > 0) {
3243 current_module = "autoq";
3244 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3245 ++output_quality;
3246 else
3247 if (output_quality>1 && aq_sleep_time<0)
3248 --output_quality;
3249 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3250 output_quality = 0;
3251 set_video_quality(mpctx->sh_video, output_quality);
3254 if (!frame_time_remaining && blit_frame) {
3255 if (play_n_frames >= 0) {
3256 --play_n_frames;
3257 if (play_n_frames <= 0)
3258 mpctx->stop_play = PT_NEXT_ENTRY;
3260 if (mpctx->step_frames > 0) {
3261 mpctx->step_frames--;
3262 if (mpctx->step_frames == 0)
3263 pause_player(mpctx);
3267 // FIXME: add size based support for -endpos
3268 if (end_at.type == END_AT_TIME &&
3269 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3270 mpctx->stop_play = PT_NEXT_ENTRY;
3272 } // end if(mpctx->sh_video)
3274 #ifdef CONFIG_DVDNAV
3275 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3276 nav_highlight_t hl;
3277 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3278 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3279 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3280 vo_osd_changed(OSDTYPE_DVDNAV);
3281 } else {
3282 osd_set_nav_box(0, 0, 0, 0);
3283 vo_osd_changed(OSDTYPE_DVDNAV);
3284 vo_osd_changed(OSDTYPE_SPU);
3287 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3288 double ar = -1.0;
3289 if (mpctx->sh_video &&
3290 stream_control(mpctx->demuxer->stream,
3291 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3292 != STREAM_UNSUPPORTED)
3293 mpctx->sh_video->stream_aspect = ar;
3296 #endif
3298 //================= Keyboard events, SEEKing ====================
3300 current_module = "key_events";
3302 while (1) {
3303 mp_cmd_t *cmd;
3304 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3305 /* Allow running consecutive seek commands to combine them,
3306 * but execute the seek before running other commands.
3307 * If the user seeks continuously (keeps arrow key down)
3308 * try to finish showing a frame from one location before doing
3309 * another seek (which could lead to unchanging display). */
3310 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3311 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3312 && GetTimerMS() - mpctx->start_timestamp < 300)
3313 break;
3314 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3315 run_command(mpctx, cmd);
3316 mp_cmd_free(cmd);
3317 if (mpctx->stop_play)
3318 break;
3320 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3321 || mpctx->restart_playback)
3322 break;
3323 if (mpctx->sh_video) {
3324 update_osd_msg(mpctx);
3325 int hack = vo_osd_changed(0);
3326 vo_osd_changed(hack);
3327 if (hack) {
3328 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3329 add_step_frame(mpctx);
3330 break;
3331 } else
3332 vo_osd_changed(0);
3335 pause_loop(mpctx);
3338 // handle -sstep
3339 if (step_sec > 0 && !mpctx->paused) {
3340 mpctx->osd_function = OSD_FFW;
3341 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3344 edl_update(mpctx);
3346 /* Looping. */
3347 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3348 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3350 if (opts->loop_times>1)
3351 opts->loop_times--;
3352 else if (opts->loop_times==1)
3353 opts->loop_times = -1;
3354 play_n_frames = play_n_frames_mf;
3355 mpctx->stop_play = 0;
3356 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3359 if (mpctx->seek.type) {
3360 seek(mpctx, mpctx->seek);
3361 mpctx->seek = (struct seek_params){0};
3366 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3367 struct content_source *sources,
3368 int num_sources,
3369 unsigned char uid_map[][16])
3371 int num_filenames = 0;
3372 char **filenames = NULL;
3373 if (num_sources > 1) {
3374 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3375 "other sources.\n");
3376 if (mpctx->stream->type != STREAMTYPE_FILE) {
3377 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3378 "normal disk file. Will not search for related files.\n");
3379 } else {
3380 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3381 "same directory to find referenced sources.\n");
3382 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3383 &num_filenames);
3387 int num_left = num_sources - 1;
3388 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3389 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3390 filename_recode(filenames[i]));
3391 int format;
3392 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3393 if (!s)
3394 continue;
3395 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3396 mpctx->opts.audio_id,
3397 mpctx->opts.video_id,
3398 mpctx->opts.sub_id, filenames[i]);
3399 if (!d) {
3400 free_stream(s);
3401 continue;
3403 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3404 for (int i = 1; i < num_sources; i++) {
3405 if (sources[i].demuxer)
3406 continue;
3407 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3408 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3409 i, filename_recode(d->filename));
3410 sources[i].stream = s;
3411 sources[i].demuxer = d;
3412 num_left--;
3413 goto match;
3417 free_demuxer(d);
3418 free_stream(s);
3419 continue;
3420 match:
3423 talloc_free(filenames);
3424 if (num_left) {
3425 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3426 "There will be parts MISSING from the video!\n");
3427 for (int i = 1, j = 1; i < num_sources; i++)
3428 if (sources[i].demuxer) {
3429 sources[j] = sources[i];
3430 memcpy(uid_map[j], uid_map[i], 16);
3431 j++;
3434 return num_sources - num_left;
3437 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3439 struct MPOpts *opts = &mpctx->opts;
3441 if (!opts->ordered_chapters) {
3442 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3443 "you have disabled support for them. Ignoring.\n");
3444 return;
3447 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3448 "edit timeline.\n");
3450 struct demuxer *demuxer = mpctx->demuxer;
3451 struct matroska_data *m = &demuxer->matroska_data;
3453 // +1 because sources/uid_map[0] is original file even if all chapters
3454 // actually use other sources and need separate entries
3455 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3456 m->num_ordered_chapters+1);
3457 sources[0].stream = mpctx->stream;
3458 sources[0].demuxer = mpctx->demuxer;
3459 unsigned char uid_map[m->num_ordered_chapters+1][16];
3460 int num_sources = 1;
3461 memcpy(uid_map[0], m->segment_uid, 16);
3463 for (int i = 0; i < m->num_ordered_chapters; i++) {
3464 struct matroska_chapter *c = m->ordered_chapters + i;
3465 if (!c->has_segment_uid)
3466 memcpy(c->segment_uid, m->segment_uid, 16);
3468 for (int j = 0; j < num_sources; j++)
3469 if (!memcmp(c->segment_uid, uid_map[j], 16))
3470 goto found1;
3471 memcpy(uid_map[num_sources], c->segment_uid, 16);
3472 sources[num_sources] = (struct content_source){};
3473 num_sources++;
3474 found1:
3478 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3479 uid_map);
3482 // +1 for terminating chapter with start time marking end of last real one
3483 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3484 m->num_ordered_chapters + 1);
3485 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3486 m->num_ordered_chapters);
3487 uint64_t starttime = 0;
3488 uint64_t missing_time = 0;
3489 int part_count = 0;
3490 int num_chapters = 0;
3491 uint64_t prev_part_offset = 0;
3492 for (int i = 0; i < m->num_ordered_chapters; i++) {
3493 struct matroska_chapter *c = m->ordered_chapters + i;
3495 int j;
3496 for (j = 0; j < num_sources; j++) {
3497 if (!memcmp(c->segment_uid, uid_map[j], 16))
3498 goto found2;
3500 missing_time += c->end - c->start;
3501 continue;
3502 found2:;
3503 /* Only add a separate part if the time or file actually changes.
3504 * Matroska files have chapter divisions that are redundant from
3505 * timeline point of view because the same chapter structure is used
3506 * both to specify the timeline and for normal chapter information.
3507 * Removing a missing inserted external chapter can also cause this.
3508 * We allow for a configurable fudge factor because of files which
3509 * specify chapter end times that are one frame too early;
3510 * we don't want to try seeking over a one frame gap. */
3511 int64_t join_diff = c->start - starttime - prev_part_offset;
3512 if (part_count == 0 || FFABS(join_diff) > opts->chapter_merge_threshold
3513 || sources + j != timeline[part_count - 1].source) {
3514 timeline[part_count].source = sources + j;
3515 timeline[part_count].start = starttime / 1000.;
3516 timeline[part_count].source_start = c->start / 1000.;
3517 prev_part_offset = c->start - starttime;
3518 part_count++;
3519 } else if (part_count > 0 && join_diff) {
3520 /* Chapter was merged at an inexact boundary;
3521 * adjust timestamps to match. */
3522 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3523 "offset %d ms.\n", i, (int) join_diff);
3524 starttime += join_diff;
3526 chapters[num_chapters].start = starttime / 1000.;
3527 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3528 starttime += c->end - c->start;
3529 num_chapters++;
3531 timeline[part_count].start = starttime / 1000.;
3533 if (!part_count) {
3534 // None of the parts come from the file itself???
3535 talloc_free(sources);
3536 talloc_free(timeline);
3537 talloc_free(chapters);
3538 return;
3541 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3542 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3543 timeline[part_count].start);
3544 if (missing_time)
3545 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3546 "from the timeline!\n", missing_time / 1000.);
3547 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3548 for (int i = 0; i < num_sources; i++)
3549 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3550 filename_recode(sources[i].demuxer->filename));
3551 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3552 "source_start, source):\n");
3553 for (int i = 0; i < part_count; i++) {
3554 struct timeline_part *p = timeline + i;
3555 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3556 p->source_start, p->source - sources);
3558 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3559 mpctx->sources = sources;
3560 mpctx->num_sources = num_sources;
3561 mpctx->timeline = timeline;
3562 mpctx->num_timeline_parts = part_count;
3563 mpctx->num_chapters = num_chapters;
3564 mpctx->chapters = chapters;
3566 mpctx->timeline_part = 0;
3567 mpctx->demuxer = timeline[0].source->demuxer;
3571 static int read_keys(void *ctx, int fd)
3573 getch2(ctx);
3574 return mplayer_get_key(ctx, 0);
3578 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3579 * file for some tools to link against. */
3580 #ifndef DISABLE_MAIN
3581 int main(int argc,char* argv[]){
3584 char * mem_ptr;
3586 // movie info:
3588 /* Flag indicating whether MPlayer should exit without playing anything. */
3589 int opt_exit = 0;
3590 int i;
3592 struct MPContext *mpctx = &(struct MPContext){
3593 .osd_function = OSD_PLAY,
3594 .begin_skip = MP_NOPTS_VALUE,
3595 .play_tree_step = 1,
3596 .global_sub_pos = -1,
3597 .set_of_sub_pos = -1,
3598 .file_format = DEMUXER_TYPE_UNKNOWN,
3599 .last_dvb_step = 1,
3602 InitTimer();
3603 srand(GetTimerMS());
3605 mp_msg_init();
3606 set_av_log_callback();
3608 #ifdef CONFIG_X11
3609 mpctx->x11_state = vo_x11_init_state();
3610 #endif
3611 struct MPOpts *opts = &mpctx->opts;
3612 set_default_mplayer_options(opts);
3613 // Create the config context and register the options
3614 mpctx->mconfig = m_config_new(opts, cfg_include);
3615 m_config_register_options(mpctx->mconfig,mplayer_opts);
3616 m_config_register_options(mpctx->mconfig, common_opts);
3617 mp_input_register_options(mpctx->mconfig);
3619 // Preparse the command line
3620 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3622 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3623 set_path_env();
3624 #endif
3626 #ifdef CONFIG_TV
3627 stream_tv_defaults.immediate = 1;
3628 #endif
3630 parse_cfgfiles(mpctx, mpctx->mconfig);
3632 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3633 if(mpctx->playtree == NULL)
3634 opt_exit = 1;
3635 else {
3636 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3637 if(mpctx->playtree) {
3638 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3639 if(mpctx->playtree_iter) {
3640 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3641 play_tree_iter_free(mpctx->playtree_iter);
3642 mpctx->playtree_iter = NULL;
3644 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3648 mpctx->key_fifo = mp_fifo_create(opts);
3650 print_version("MPlayer");
3652 #if defined(__MINGW32__) || defined(__CYGWIN__)
3654 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3655 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3656 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3657 if (kernel32) {
3658 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3659 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3661 if (setDEP) setDEP(3);
3662 if (setDllDir) setDllDir("");
3664 // stop Windows from showing all kinds of annoying error dialogs
3665 SetErrorMode(0x8003);
3666 // request 1ms timer resolution
3667 timeBeginPeriod(1);
3668 #endif
3670 #ifdef CONFIG_PRIORITY
3671 set_priority();
3672 #endif
3674 if (codec_path)
3675 set_codec_path(codec_path);
3677 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3678 list_video_out();
3679 opt_exit = 1;
3682 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3683 list_audio_out();
3684 opt_exit = 1;
3687 /* Check codecs.conf. */
3688 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3689 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3690 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3691 if(!parse_codec_cfg(NULL)){
3692 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3694 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3697 free( mem_ptr ); // release the buffer created by get_path()
3700 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3701 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3702 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3703 list_codecs(1);
3704 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3705 opt_exit = 1;
3707 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3708 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3709 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3710 list_codecs(0);
3711 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3712 opt_exit = 1;
3714 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3715 vfm_help();
3716 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3717 opt_exit = 1;
3719 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3720 afm_help();
3721 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3722 opt_exit = 1;
3724 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3725 af_help();
3726 printf("\n");
3727 opt_exit = 1;
3729 #ifdef CONFIG_X11
3730 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3731 fstype_help();
3732 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3733 opt_exit = 1;
3735 #endif
3736 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3737 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3738 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3739 demuxer_help();
3740 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3741 opt_exit = 1;
3743 if (opts->list_properties) {
3744 property_print_help();
3745 opt_exit = 1;
3748 if(opt_exit)
3749 exit_player(mpctx, EXIT_NONE);
3751 if (!mpctx->filename && !opts->player_idle_mode) {
3752 // no file/vcd/dvd -> show HELP:
3753 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3754 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3757 /* Display what configure line was used */
3758 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3760 // Many users forget to include command line in bugreports...
3761 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3762 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3763 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3764 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3767 //------ load global data first ------
3769 mpctx->osd = osd_create();
3771 // check font
3772 #ifdef CONFIG_FREETYPE
3773 init_freetype();
3774 #endif
3775 #ifdef CONFIG_FONTCONFIG
3776 if(font_fontconfig <= 0)
3778 #endif
3779 #ifdef CONFIG_BITMAP_FONT
3780 if(font_name){
3781 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3782 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3783 filename_recode(font_name));
3784 } else {
3785 // try default:
3786 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3787 free(mem_ptr); // release the buffer created by get_path()
3788 if(!vo_font)
3789 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3791 if (sub_font_name)
3792 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3793 else
3794 mpctx->osd->sub_font = vo_font;
3795 #endif
3796 #ifdef CONFIG_FONTCONFIG
3798 #endif
3800 #ifdef CONFIG_ASS
3801 ass_library = ass_init();
3802 #endif
3804 #ifdef HAVE_RTC
3805 if(opts->rtc)
3807 char *rtc_device = opts->rtc_device;
3808 // seteuid(0); /* Can't hurt to try to get root here */
3809 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3810 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3811 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3812 else {
3813 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3815 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3816 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3817 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3818 close (rtc_fd);
3819 rtc_fd = -1;
3820 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3821 /* variable only by the root */
3822 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3823 close (rtc_fd);
3824 rtc_fd = -1;
3825 } else
3826 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3829 if(rtc_fd<0)
3830 #endif /* HAVE_RTC */
3831 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3832 opts->softsleep ? "software" : timer_name);
3834 #ifdef HAVE_TERMCAP
3835 load_termcap(NULL); // load key-codes
3836 #endif
3838 // ========== Init keyboard FIFO (connection to libvo) ============
3840 // Init input system
3841 current_module = "init_input";
3842 mpctx->input = mp_input_init(&opts->input);
3843 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3844 if(slave_mode)
3845 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3846 else if (opts->consolecontrols)
3847 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3848 // Set the libstream interrupt callback
3849 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3851 #ifdef CONFIG_MENU
3852 if(use_menu) {
3853 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3854 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3855 else {
3856 menu_cfg = get_path("menu.conf");
3857 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3858 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3859 else {
3860 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3861 MPLAYER_CONFDIR "/menu.conf"))
3862 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3863 else {
3864 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3865 use_menu = 0;
3870 #endif
3872 current_module = NULL;
3874 /// Catch signals
3875 #ifndef __MINGW32__
3876 signal(SIGCHLD,child_sighandler);
3877 #endif
3879 #ifdef CONFIG_CRASH_DEBUG
3880 prog_path = argv[0];
3881 #endif
3882 //========= Catch terminate signals: ================
3883 // terminate requests:
3884 signal(SIGTERM,exit_sighandler); // kill
3885 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3887 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3889 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3890 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3891 #ifdef CONFIG_SIGHANDLER
3892 // fatal errors:
3893 signal(SIGBUS,exit_sighandler); // bus error
3894 signal(SIGSEGV,exit_sighandler); // segfault
3895 signal(SIGILL,exit_sighandler); // illegal instruction
3896 signal(SIGFPE,exit_sighandler); // floating point exc.
3897 signal(SIGABRT,exit_sighandler); // abort()
3898 #ifdef CONFIG_CRASH_DEBUG
3899 if (crash_debug)
3900 signal(SIGTRAP,exit_sighandler);
3901 #endif
3902 #endif
3904 // ******************* Now, let's see the per-file stuff ********************
3906 play_next_file:
3908 // init global sub numbers
3909 mpctx->global_sub_size = 0;
3910 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3912 if (mpctx->filename) {
3913 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3914 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3915 load_per_file_config (mpctx->mconfig, mpctx->filename);
3918 if (opts->video_driver_list)
3919 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3920 if (opts->audio_driver_list)
3921 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3923 // We must enable getch2 here to be able to interrupt network connection
3924 // or cache filling
3925 if (opts->consolecontrols && !slave_mode) {
3926 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3927 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3928 else
3929 getch2_enable(); // prepare stdin for hotkeys...
3930 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3931 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3934 // =================== GUI idle loop (STOP state) ===========================
3935 while (opts->player_idle_mode && !mpctx->filename) {
3936 play_tree_t * entry = NULL;
3937 mp_cmd_t * cmd;
3938 if (mpctx->video_out && mpctx->video_out->config_ok)
3939 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3940 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3941 if (mpctx->video_out)
3942 vo_check_events(mpctx->video_out);
3943 usec_sleep(20000);
3945 switch (cmd->id) {
3946 case MP_CMD_LOADFILE:
3947 // prepare a tree entry with the new filename
3948 entry = play_tree_new();
3949 play_tree_add_file(entry, cmd->args[0].v.s);
3950 // The entry is added to the main playtree after the switch().
3951 break;
3952 case MP_CMD_LOADLIST:
3953 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3954 break;
3955 case MP_CMD_QUIT:
3956 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3957 break;
3958 case MP_CMD_VO_FULLSCREEN:
3959 case MP_CMD_GET_PROPERTY:
3960 case MP_CMD_SET_PROPERTY:
3961 case MP_CMD_STEP_PROPERTY:
3962 run_command(mpctx, cmd);
3963 break;
3966 mp_cmd_free(cmd);
3968 if (entry) { // user entered a command that gave a valid entry
3969 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3970 play_tree_free_list(mpctx->playtree->child, 1);
3971 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3973 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3975 play_tree_set_child(mpctx->playtree, entry);
3977 /* Make iterator start at the top the of tree. */
3978 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3979 if (!mpctx->playtree_iter) continue;
3981 // find the first real item in the tree
3982 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3983 // no items!
3984 play_tree_iter_free(mpctx->playtree_iter);
3985 mpctx->playtree_iter = NULL;
3986 continue; // wait for next command
3988 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3991 //---------------------------------------------------------------------------
3993 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3994 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3996 if (mpctx->filename) {
3997 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3998 filename_recode(mpctx->filename));
3999 if(use_filename_title && opts->vo_wintitle == NULL)
4000 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4003 if (edl_filename) {
4004 if (edl_records) free_edl(edl_records);
4005 next_edl_record = edl_records = edl_parse_file();
4007 if (edl_output_filename) {
4008 if (edl_fd) fclose(edl_fd);
4009 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4011 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4012 filename_recode(edl_output_filename));
4016 //==================== Open VOB-Sub ============================
4018 current_module="vobsub";
4019 if (vobsub_name){
4020 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
4021 if(vo_vobsub==NULL)
4022 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4023 filename_recode(vobsub_name));
4024 } else if (sub_auto && mpctx->filename){
4025 /* try to autodetect vobsub from movie filename ::atmos */
4026 char *buf = strdup(mpctx->filename), *psub;
4027 char *pdot = strrchr(buf, '.');
4028 char *pslash = strrchr(buf, '/');
4029 #if defined(__MINGW32__) || defined(__CYGWIN__)
4030 if (!pslash) pslash = strrchr(buf, '\\');
4031 #endif
4032 if (pdot && (!pslash || pdot > pslash))
4033 *pdot = '\0';
4034 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4035 /* try from ~/.mplayer/sub */
4036 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4037 const char *bname = mp_basename(buf);
4038 int l;
4039 l = strlen(psub) + strlen(bname) + 1;
4040 psub = realloc(psub,l);
4041 strcat(psub,bname);
4042 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4043 free(psub);
4045 free(buf);
4047 if(vo_vobsub){
4048 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4049 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4050 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4052 // setup global sub numbering
4053 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4056 //============ Open & Sync STREAM --- fork cache2 ====================
4058 mpctx->stream=NULL;
4059 mpctx->demuxer=NULL;
4060 if (mpctx->d_audio) {
4061 //free_demuxer_stream(mpctx->d_audio);
4062 mpctx->d_audio=NULL;
4064 if (mpctx->d_video) {
4065 //free_demuxer_stream(d_video);
4066 mpctx->d_video=NULL;
4068 mpctx->sh_audio=NULL;
4069 mpctx->sh_video=NULL;
4071 current_module="open_stream";
4072 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4073 if(!mpctx->stream) { // error...
4074 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4075 goto goto_next_file;
4077 mpctx->initialized_flags|=INITIALIZED_STREAM;
4079 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4080 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4081 "playlist support will not be used automatically.\n"
4082 "MPlayer's playlist code is unsafe and should only be used with "
4083 "trusted sources.\nPlayback will probably fail.\n\n");
4084 #if 0
4085 play_tree_t* entry;
4086 // Handle playlist
4087 current_module="handle_playlist";
4088 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4089 filename_recode(mpctx->filename));
4090 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4091 mpctx->eof=playtree_add_playlist(mpctx, entry);
4092 goto goto_next_file;
4093 #endif
4095 mpctx->stream->start_pos+=seek_to_byte;
4097 if(stream_dump_type==5){
4098 unsigned char buf[4096];
4099 int len;
4100 FILE *f;
4101 current_module="dumpstream";
4102 stream_reset(mpctx->stream);
4103 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4104 f=fopen(opts->stream_dump_name,"wb");
4105 if(!f){
4106 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4107 exit_player(mpctx, EXIT_ERROR);
4109 if (opts->chapterrange[0] > 1) {
4110 int chapter = opts->chapterrange[0] - 1;
4111 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4113 while(!mpctx->stream->eof && !async_quit_request){
4114 len=stream_read(mpctx->stream,buf,4096);
4115 if(len>0) {
4116 if(fwrite(buf,len,1,f) != 1) {
4117 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4118 exit_player(mpctx, EXIT_ERROR);
4121 if (opts->chapterrange[1] > 0) {
4122 int chapter = -1;
4123 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4124 &chapter) == STREAM_OK
4125 && chapter + 1 > opts->chapterrange[1])
4126 break;
4129 if(fclose(f)) {
4130 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4131 exit_player(mpctx, EXIT_ERROR);
4133 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4134 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4137 #ifdef CONFIG_DVDREAD
4138 if(mpctx->stream->type==STREAMTYPE_DVD){
4139 current_module="dvd lang->id";
4140 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4141 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4142 // setup global sub numbering
4143 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4144 current_module=NULL;
4146 #endif
4148 #ifdef CONFIG_DVDNAV
4149 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4150 current_module="dvdnav lang->id";
4151 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4152 dvdsub_lang_id = -3;
4153 if(opts->sub_lang && opts->sub_id==-1)
4154 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4155 // setup global sub numbering
4156 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4157 current_module=NULL;
4159 #endif
4161 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4162 goto_enable_cache:
4163 if(stream_cache_size>0){
4164 int res;
4165 float stream_cache_min_percent = opts->stream_cache_min_percent;
4166 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4167 current_module="enable_cache";
4168 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4169 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4170 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4171 if(res == 0)
4172 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4175 //============ Open DEMUXERS --- DETECT file type =======================
4176 current_module="demux_open";
4178 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4180 // HACK to get MOV Reference Files working
4182 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4184 unsigned char* playlist_entry;
4185 play_tree_t *list = NULL, *entry = NULL;
4187 current_module="handle_demux_playlist";
4188 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4190 char *temp;
4191 const char *bname;
4193 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4194 filename_recode(playlist_entry));
4196 bname=mp_basename(playlist_entry);
4197 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4198 continue;
4200 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4201 continue;
4203 entry = play_tree_new();
4205 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4207 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4208 if (temp)
4210 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4211 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4212 strcat(temp, playlist_entry);
4213 if (!strcmp(temp, mpctx->filename)) {
4214 free(temp);
4215 continue;
4217 play_tree_add_file(entry,temp);
4218 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4219 free(temp);
4222 else
4223 play_tree_add_file(entry,playlist_entry);
4225 if(!list)
4226 list = entry;
4227 else
4228 play_tree_append_entry(list,entry);
4230 free_demuxer(mpctx->demuxer);
4231 mpctx->demuxer = NULL;
4233 if (list)
4235 entry = play_tree_new();
4236 play_tree_set_child(entry,list);
4237 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4238 goto goto_next_file;
4242 if(!mpctx->demuxer) {
4243 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4244 goto goto_next_file;
4247 if (mpctx->demuxer->matroska_data.ordered_chapters)
4248 build_ordered_chapter_timeline(mpctx);
4250 if (!mpctx->sources) {
4251 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4252 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4253 .demuxer = mpctx->demuxer};
4254 mpctx->num_sources = 1;
4257 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4259 #ifdef CONFIG_ASS
4260 if (opts->ass_enabled && ass_library) {
4261 for (int j = 0; j < mpctx->num_sources; j++) {
4262 struct demuxer *d = mpctx->sources[j].demuxer;
4263 for (int i = 0; i < d->num_attachments; i++) {
4264 struct demux_attachment *att = d->attachments + i;
4265 if (use_embedded_fonts && attachment_is_font(att))
4266 ass_add_font(ass_library, att->name, att->data, att->data_size);
4270 #endif
4272 current_module="demux_open2";
4274 mpctx->d_audio=mpctx->demuxer->audio;
4275 mpctx->d_video=mpctx->demuxer->video;
4276 mpctx->d_sub=mpctx->demuxer->sub;
4278 if (ts_prog) {
4279 int tmp = ts_prog;
4280 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4282 // select audio stream
4283 if (mpctx->num_sources)
4284 for (int i = 0; i < mpctx->num_sources; i++)
4285 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
4286 opts->audio_lang);
4287 else
4288 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
4290 // DUMP STREAMS:
4291 if((stream_dump_type)&&(stream_dump_type<4)){
4292 FILE *f;
4293 demux_stream_t *ds=NULL;
4294 current_module="dump";
4295 // select stream to dump
4296 switch(stream_dump_type){
4297 case 1: ds=mpctx->d_audio;break;
4298 case 2: ds=mpctx->d_video;break;
4299 case 3: ds=mpctx->d_sub;break;
4301 if(!ds){
4302 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4303 exit_player(mpctx, EXIT_ERROR);
4305 // disable other streams:
4306 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4307 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4308 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4309 // let's dump it!
4310 f=fopen(opts->stream_dump_name,"wb");
4311 if(!f){
4312 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4313 exit_player(mpctx, EXIT_ERROR);
4315 while(!ds->eof){
4316 unsigned char* start;
4317 int in_size=ds_get_packet(ds,&start);
4318 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4319 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4320 if(in_size>0) fwrite(start,in_size,1,f);
4321 if (opts->chapterrange[1] > 0) {
4322 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4323 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4324 break;
4327 fclose(f);
4328 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4329 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4332 mpctx->sh_audio=mpctx->d_audio->sh;
4333 mpctx->sh_video=mpctx->d_video->sh;
4335 if(mpctx->sh_video){
4337 current_module="video_read_properties";
4338 if(!video_read_properties(mpctx->sh_video)) {
4339 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4340 mpctx->sh_video=mpctx->d_video->sh=NULL;
4341 } else {
4342 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4343 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4344 mpctx->sh_video->fps,mpctx->sh_video->frametime
4347 /* need to set fps here for output encoders to pick it up in their init */
4348 if(force_fps){
4349 mpctx->sh_video->fps=force_fps;
4350 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4352 vo_fps = mpctx->sh_video->fps;
4354 if(!mpctx->sh_video->fps && !force_fps){
4355 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4356 mpctx->opts.correct_pts = 1;
4362 if(!mpctx->sh_video && !mpctx->sh_audio){
4363 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4364 #ifdef CONFIG_DVBIN
4365 if(mpctx->stream->type == STREAMTYPE_DVB)
4367 int dir;
4368 int v = mpctx->last_dvb_step;
4369 if(v > 0)
4370 dir = DVB_CHANNEL_HIGHER;
4371 else
4372 dir = DVB_CHANNEL_LOWER;
4374 if(dvb_step_channel(mpctx->stream, dir)) {
4375 mpctx->stop_play = PT_NEXT_ENTRY;
4376 mpctx->dvbin_reopen = 1;
4379 #endif
4380 goto goto_next_file; // exit_player(_("Fatal error"));
4383 /* display clip info */
4384 demux_info_print(mpctx->demuxer);
4386 //================== Read SUBTITLES (DVD & TEXT) ==========================
4387 if(vo_spudec==NULL &&
4388 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4389 init_vo_spudec(mpctx);
4392 // after reading video params we should load subtitles because
4393 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4394 // check .sub
4395 current_module="read_subtitles_file";
4396 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4397 if(sub_name){
4398 for (i = 0; sub_name[i] != NULL; ++i)
4399 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4401 if(sub_auto) { // auto load sub file ...
4402 char *psub = get_path( "sub/" );
4403 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4404 int i = 0;
4405 free(psub); // release the buffer created by get_path() above
4406 while (tmp[i]) {
4407 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4408 free(tmp[i++]);
4410 free(tmp);
4412 if (mpctx->set_of_sub_size > 0)
4413 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4415 if (select_subtitle(mpctx)) {
4416 if(subdata)
4417 switch (stream_dump_type) {
4418 case 3: list_sub_file(subdata); break;
4419 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
4420 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
4421 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
4422 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
4423 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
4427 print_file_properties(mpctx, mpctx->filename);
4429 if(!mpctx->sh_video) goto main; // audio-only
4431 if(!reinit_video_chain(mpctx)) {
4432 if(!mpctx->sh_video){
4433 if(!mpctx->sh_audio) goto goto_next_file;
4434 goto main; // exit_player(_("Fatal error"));
4438 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4439 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4441 #ifdef CONFIG_FREETYPE
4442 force_load_font = 1;
4443 #endif
4445 //================== MAIN: ==========================
4446 main:
4447 current_module="main";
4449 if (opts->playing_msg) {
4450 char* msg = property_expand_string(mpctx, opts->playing_msg);
4451 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4452 free(msg);
4456 // Disable the term OSD in verbose mode
4457 if (verbose)
4458 opts->term_osd = 0;
4462 // Make sure old OSD does not stay around,
4463 // e.g. with -fixed-vo and same-resolution files
4464 clear_osd_msgs();
4465 update_osd_msg(mpctx);
4467 //================ SETUP AUDIO ==========================
4469 if(mpctx->sh_audio){
4470 reinit_audio_chain(mpctx);
4471 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4472 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4475 current_module="av_init";
4477 if(mpctx->sh_video){
4478 mpctx->sh_video->timer=0;
4479 if (! ignore_start)
4480 audio_delay += mpctx->sh_video->stream_delay;
4482 if(mpctx->sh_audio){
4483 if (start_volume >= 0)
4484 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4485 if (! ignore_start)
4486 audio_delay -= mpctx->sh_audio->stream_delay;
4487 mpctx->delay=-audio_delay;
4490 if(!mpctx->sh_audio){
4491 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4492 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4493 ds_free_packs(mpctx->d_audio); // free buffered chunks
4494 //mpctx->d_audio->id=-2; // do not read audio chunks
4495 //uninit_player(mpctx, INITIALIZED_AO); // close device
4497 if(!mpctx->sh_video){
4498 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4499 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4500 ds_free_packs(mpctx->d_video);
4501 mpctx->d_video->id=-2;
4502 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4505 if (!mpctx->sh_video && !mpctx->sh_audio)
4506 goto goto_next_file;
4508 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4509 if(force_fps && mpctx->sh_video){
4510 vo_fps = mpctx->sh_video->fps=force_fps;
4511 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4512 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4515 mp_input_set_section(mpctx->input, NULL);
4516 //TODO: add desired (stream-based) sections here
4517 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4518 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4520 //==================== START PLAYING =======================
4522 if(opts->loop_times>1) opts->loop_times--; else
4523 if(opts->loop_times==1) opts->loop_times = -1;
4525 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4527 total_time_usage_start=GetTimer();
4528 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4529 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4530 play_n_frames=play_n_frames_mf;
4532 if(play_n_frames==0){
4533 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4536 mpctx->time_frame = 0;
4537 mpctx->drop_message_shown = 0;
4538 mpctx->restart_playback = true;
4539 mpctx->video_pts = 0;
4540 mpctx->hrseek_active = false;
4541 mpctx->hrseek_framedrop = false;
4542 mpctx->step_frames = 0;
4543 mpctx->total_avsync_change = 0;
4544 mpctx->last_chapter_seek = -1;
4546 // If there's a timeline force an absolute seek to initialize state
4547 if (seek_to_sec || mpctx->timeline) {
4548 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4549 seek(mpctx, mpctx->seek);
4550 end_at.pos += seek_to_sec;
4552 if (opts->chapterrange[0] > 0) {
4553 double pts;
4554 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4555 && pts > -1.0) {
4556 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4557 seek(mpctx, mpctx->seek);
4561 if (end_at.type == END_AT_SIZE) {
4562 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4563 end_at.type = END_AT_NONE;
4566 #ifdef CONFIG_DVDNAV
4567 mp_dvdnav_context_free(mpctx);
4568 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4569 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4570 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4572 #endif
4574 mpctx->seek = (struct seek_params){0};
4575 get_relative_time(mpctx); // reset current delta
4576 // Make sure VO knows current pause state
4577 if (mpctx->sh_video)
4578 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4579 NULL);
4581 while (!mpctx->stop_play)
4582 run_playloop(mpctx);
4584 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4586 #ifdef CONFIG_DVBIN
4587 if(mpctx->dvbin_reopen)
4589 mpctx->stop_play = 0;
4590 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4591 cache_uninit(mpctx->stream);
4592 mpctx->dvbin_reopen = 0;
4593 goto goto_enable_cache;
4595 #endif
4598 goto_next_file: // don't jump here after ao/vo/getch initialization!
4600 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4602 if (opts->benchmark) {
4603 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4604 double total_time_usage;
4605 total_time_usage_start=GetTimer()-total_time_usage_start;
4606 total_time_usage = (float)total_time_usage_start*0.000001;
4607 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4608 video_time_usage,vout_time_usage,audio_time_usage,
4609 total_time_usage-tot,total_time_usage);
4610 if(total_time_usage>0.0)
4611 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4612 100.0*video_time_usage/total_time_usage,
4613 100.0*vout_time_usage/total_time_usage,
4614 100.0*audio_time_usage/total_time_usage,
4615 100.0*(total_time_usage-tot)/total_time_usage,
4616 100.0);
4617 if(total_frame_cnt && frame_dropping)
4618 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4619 total_frame_cnt-drop_frame_cnt,
4620 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4621 drop_frame_cnt,
4622 100*drop_frame_cnt/total_frame_cnt,
4623 total_frame_cnt,
4624 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4627 // time to uninit all, except global stuff:
4628 int uninitialize_parts = INITIALIZED_ALL;
4629 if (opts->fixed_vo)
4630 uninitialize_parts -= INITIALIZED_VO;
4631 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4632 uninitialize_parts -= INITIALIZED_AO;
4633 uninit_player(mpctx, uninitialize_parts);
4635 if(mpctx->set_of_sub_size > 0) {
4636 current_module="sub_free";
4637 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4638 sub_free(mpctx->set_of_subtitles[i]);
4639 #ifdef CONFIG_ASS
4640 if(mpctx->set_of_ass_tracks[i])
4641 ass_free_track( mpctx->set_of_ass_tracks[i] );
4642 #endif
4644 mpctx->set_of_sub_size = 0;
4646 vo_sub_last = vo_sub=NULL;
4647 subdata=NULL;
4648 #ifdef CONFIG_ASS
4649 ass_track = NULL;
4650 if(ass_library)
4651 ass_clear_fonts(ass_library);
4652 #endif
4654 if (!mpctx->stop_play) // In case some goto jumped here...
4655 mpctx->stop_play = PT_NEXT_ENTRY;
4657 int playtree_direction = 1;
4659 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4660 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4661 play_tree_iter_free(mpctx->playtree_iter);
4662 mpctx->playtree_iter = NULL;
4664 mpctx->play_tree_step = 1;
4665 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4666 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4667 if(mpctx->playtree_iter) {
4668 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4669 play_tree_iter_free(mpctx->playtree_iter);
4670 mpctx->playtree_iter = NULL;
4673 } else if (mpctx->stop_play == PT_STOP) {
4674 play_tree_iter_free(mpctx->playtree_iter);
4675 mpctx->playtree_iter = NULL;
4676 } else { // NEXT PREV SRC
4677 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4680 while(mpctx->playtree_iter != NULL) {
4681 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4682 if(mpctx->filename == NULL) {
4683 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4684 play_tree_iter_free(mpctx->playtree_iter);
4685 mpctx->playtree_iter = NULL;
4687 } else
4688 break;
4691 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4692 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4693 mpctx->stop_play = 0;
4694 goto play_next_file;
4698 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4700 return 1;
4702 #endif /* DISABLE_MAIN */