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