demux_mkv: support V_MJPEG video tag
[mplayer/glamo.git] / mplayer.c
blob53ee3ba199dc0e27058ef0814a2d9401c278b0ad
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 "config.h"
26 #include "talloc.h"
28 #if defined(__MINGW32__) || defined(__CYGWIN__)
29 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
30 #include <windows.h>
31 #endif
32 #include <string.h>
33 #include <unistd.h>
35 // #include <sys/mman.h>
36 #include <sys/types.h>
37 #ifndef __MINGW32__
38 #include <sys/ioctl.h>
39 #include <sys/wait.h>
40 #else
41 #define SIGHUP 1 /* hangup */
42 #define SIGQUIT 3 /* quit */
43 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
44 #define SIGBUS 10 /* bus error */
45 #define SIGPIPE 13 /* broken pipe */
46 #endif
48 #include <sys/time.h>
49 #include <sys/stat.h>
51 #include <signal.h>
52 #include <time.h>
53 #include <fcntl.h>
54 #include <limits.h>
56 #include <errno.h>
58 #include "mp_msg.h"
59 #include "av_log.h"
62 #include "m_option.h"
63 #include "m_config.h"
64 #include "mplayer.h"
65 #include "access_mpcontext.h"
66 #include "m_property.h"
68 #include "cfg-mplayer-def.h"
70 #include "libavutil/avstring.h"
72 #include "subreader.h"
74 #include "mp_osd.h"
75 #include "libvo/video_out.h"
77 #include "libvo/font_load.h"
78 #include "libvo/sub.h"
80 #ifdef CONFIG_X11
81 #include "libvo/x11_common.h"
82 #endif
84 #include "libao2/audio_out.h"
86 #include "codec-cfg.h"
88 #include "edl.h"
90 #include "spudec.h"
91 #include "vobsub.h"
93 #include "osdep/getch2.h"
94 #include "osdep/timer.h"
95 #include "osdep/findfiles.h"
97 #include "input/input.h"
99 const int under_mencoder = 0;
100 int slave_mode=0;
101 int player_idle_mode=0;
102 int quiet=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 // Common FIFO functions, and keyboard/event FIFO code
268 #include "mp_fifo.h"
269 int noconsolecontrols=0;
270 //**************************************************************************//
272 // benchmark:
273 double video_time_usage=0;
274 double vout_time_usage=0;
275 static double audio_time_usage=0;
276 static int total_time_usage_start=0;
277 static int total_frame_cnt=0;
278 static int drop_frame_cnt=0; // total number of dropped frames
279 int benchmark=0;
281 // options:
282 int auto_quality=0;
283 static int output_quality=0;
285 static int list_properties = 0;
287 int term_osd = 1;
288 static char* term_osd_esc = "\x1b[A\r\x1b[K";
289 static char* playing_msg = NULL;
290 // seek:
291 static double seek_to_sec;
292 static off_t seek_to_byte=0;
293 static off_t step_sec=0;
295 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
297 // A/V sync:
298 int autosync=0; // 30 might be a good default value.
300 // codecs:
301 char **audio_codec_list=NULL; // override audio codec
302 char **video_codec_list=NULL; // override video codec
303 char **audio_fm_list=NULL; // override audio codec family
304 char **video_fm_list=NULL; // override video codec family
306 // demuxer:
307 extern char *demuxer_name; // override demuxer
308 extern char *audio_demuxer_name; // override audio demuxer
309 extern char *sub_demuxer_name; // override sub demuxer
311 // this dvdsub_id was selected via slang
312 // use this to allow dvdnav to follow -slang across stream resets,
313 // in particular the subtitle ID for a language changes
314 int dvdsub_lang_id;
315 int vobsub_id=-1;
316 static char* spudec_ifo=NULL;
317 int forced_subs_only=0;
318 int file_filter=1;
320 // cache2:
321 int stream_cache_size=-1;
322 #ifdef CONFIG_STREAM_CACHE
323 extern int cache_fill_status;
325 float stream_cache_min_percent=20.0;
326 float stream_cache_seek_min_percent=50.0;
327 #else
328 #define cache_fill_status 0
329 #endif
331 // dump:
332 static char *stream_dump_name="stream.dump";
333 int stream_dump_type=0;
335 // A-V sync:
336 static float default_max_pts_correction=-1;//0.01f;
337 float audio_delay=0;
338 static int ignore_start=0;
340 static int softsleep=0;
342 double force_fps=0;
343 static int force_srate=0;
344 static int audio_output_format=-1; // AF_FORMAT_UNKNOWN
345 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
346 static int play_n_frames=-1;
347 static int play_n_frames_mf=-1;
349 // sub:
350 char *font_name=NULL;
351 char *sub_font_name=NULL;
352 extern int font_fontconfig;
353 float font_factor=0.75;
354 char **sub_name=NULL;
355 float sub_delay=0;
356 float sub_fps=0;
357 int sub_auto = 1;
358 char *vobsub_name=NULL;
359 /*DSP!!char *dsp=NULL;*/
360 int subcc_enabled=0;
361 int suboverlap_enabled = 1;
363 #include "ass_mp.h"
365 char* current_module=NULL; // for debugging
368 // ---
370 #ifdef CONFIG_MENU
371 #include "m_struct.h"
372 #include "libmenu/menu.h"
373 extern vf_info_t vf_info_menu;
374 static const vf_info_t* const libmenu_vfs[] = {
375 &vf_info_menu,
376 NULL
378 static vf_instance_t* vf_menu = NULL;
379 int use_menu = 0;
380 static char* menu_cfg = NULL;
381 static char* menu_root = "main";
382 #endif
385 #ifdef HAVE_RTC
386 static int nortc = 1;
387 static char* rtc_device;
388 #endif
390 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
391 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
392 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
393 int use_filedir_conf;
394 int use_filename_title;
396 #include "mpcommon.h"
397 #include "command.h"
399 #include "metadata.h"
401 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
403 const void *mpctx_get_video_out(MPContext *mpctx)
405 return mpctx->video_out;
408 const void *mpctx_get_audio_out(MPContext *mpctx)
410 return mpctx->audio_out;
413 void *mpctx_get_demuxer(MPContext *mpctx)
415 return mpctx->demuxer;
418 void *mpctx_get_playtree_iter(MPContext *mpctx)
420 return mpctx->playtree_iter;
423 void *mpctx_get_mixer(MPContext *mpctx)
425 return &mpctx->mixer;
428 int mpctx_get_global_sub_size(MPContext *mpctx)
430 return mpctx->global_sub_size;
433 int mpctx_get_osd_function(MPContext *mpctx)
435 return mpctx->osd_function;
438 static float get_relative_time(struct MPContext *mpctx)
440 unsigned int new_time = GetTimer();
441 unsigned int delta = new_time - mpctx->last_time;
442 mpctx->last_time = new_time;
443 return delta * 0.000001;
446 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
447 switch (type)
449 /* check for valid video stream */
450 case META_VIDEO_CODEC:
451 case META_VIDEO_BITRATE:
452 case META_VIDEO_RESOLUTION:
454 if (!mpctx->sh_video)
455 return 0;
456 break;
459 /* check for valid audio stream */
460 case META_AUDIO_CODEC:
461 case META_AUDIO_BITRATE:
462 case META_AUDIO_SAMPLES:
464 if (!mpctx->sh_audio)
465 return 0;
466 break;
469 /* check for valid demuxer */
470 case META_INFO_TITLE:
471 case META_INFO_ARTIST:
472 case META_INFO_ALBUM:
473 case META_INFO_YEAR:
474 case META_INFO_COMMENT:
475 case META_INFO_TRACK:
476 case META_INFO_GENRE:
478 if (!mpctx->demuxer)
479 return 0;
480 break;
483 default:
484 break;
487 return 1;
490 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
491 char **info = mpctx->demuxer->info;
492 int n;
494 if (!info || !tag)
495 return NULL;
497 for (n = 0; info[2*n] != NULL ; n++)
498 if (!strcasecmp (info[2*n], tag))
499 break;
501 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
504 char *get_metadata(struct MPContext *mpctx, metadata_t type)
506 char *meta = NULL;
507 sh_audio_t * const sh_audio = mpctx->sh_audio;
508 sh_video_t * const sh_video = mpctx->sh_video;
510 if (!is_valid_metadata_type(mpctx, type))
511 return NULL;
513 switch (type)
515 case META_NAME:
517 return strdup (mp_basename2 (mpctx->filename));
520 case META_VIDEO_CODEC:
522 if (sh_video->format == 0x10000001)
523 meta = strdup ("mpeg1");
524 else if (sh_video->format == 0x10000002)
525 meta = strdup ("mpeg2");
526 else if (sh_video->format == 0x10000004)
527 meta = strdup ("mpeg4");
528 else if (sh_video->format == 0x10000005)
529 meta = strdup ("h264");
530 else if (sh_video->format >= 0x20202020)
532 meta = malloc (8);
533 sprintf (meta, "%.4s", (char *) &sh_video->format);
535 else
537 meta = malloc (8);
538 sprintf (meta, "0x%08X", sh_video->format);
540 return meta;
543 case META_VIDEO_BITRATE:
545 meta = malloc (16);
546 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
547 return meta;
550 case META_VIDEO_RESOLUTION:
552 meta = malloc (16);
553 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
554 return meta;
557 case META_AUDIO_CODEC:
559 if (sh_audio->codec && sh_audio->codec->name)
560 meta = strdup (sh_audio->codec->name);
561 return meta;
564 case META_AUDIO_BITRATE:
566 meta = malloc (16);
567 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
568 return meta;
571 case META_AUDIO_SAMPLES:
573 meta = malloc (16);
574 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
575 return meta;
578 /* check for valid demuxer */
579 case META_INFO_TITLE:
580 return get_demuxer_info(mpctx, "Title");
582 case META_INFO_ARTIST:
583 return get_demuxer_info(mpctx, "Artist");
585 case META_INFO_ALBUM:
586 return get_demuxer_info(mpctx, "Album");
588 case META_INFO_YEAR:
589 return get_demuxer_info(mpctx, "Year");
591 case META_INFO_COMMENT:
592 return get_demuxer_info(mpctx, "Comment");
594 case META_INFO_TRACK:
595 return get_demuxer_info(mpctx, "Track");
597 case META_INFO_GENRE:
598 return get_demuxer_info(mpctx, "Genre");
600 default:
601 break;
604 return meta;
607 /// step size of mixer changes
608 int volstep = 3;
610 #ifdef CONFIG_DVDNAV
611 static void mp_dvdnav_context_free(MPContext *ctx){
612 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
613 ctx->nav_smpi = NULL;
614 if (ctx->nav_buffer) free(ctx->nav_buffer);
615 ctx->nav_buffer = NULL;
616 ctx->nav_start = NULL;
617 ctx->nav_in_size = 0;
619 #endif
621 void uninit_player(struct MPContext *mpctx, unsigned int mask){
622 mask &= mpctx->initialized_flags;
624 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
626 if(mask&INITIALIZED_ACODEC){
627 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
628 current_module="uninit_acodec";
629 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
630 mpctx->sh_audio=NULL;
631 mpctx->mixer.afilter = NULL;
634 if(mask&INITIALIZED_VCODEC){
635 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
636 current_module="uninit_vcodec";
637 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
638 mpctx->sh_video=NULL;
639 #ifdef CONFIG_MENU
640 vf_menu=NULL;
641 #endif
644 if(mask&INITIALIZED_DEMUXER){
645 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
646 current_module="free_demuxer";
647 if (mpctx->num_sources) {
648 mpctx->demuxer = mpctx->sources[0].demuxer;
649 for (int i = 1; i < mpctx->num_sources; i++) {
650 free_stream(mpctx->sources[i].stream);
651 free_demuxer(mpctx->sources[i].demuxer);
654 talloc_free(mpctx->sources);
655 mpctx->sources = NULL;
656 mpctx->num_sources = 0;
657 talloc_free(mpctx->timeline);
658 mpctx->timeline = NULL;
659 mpctx->num_timeline_parts = 0;
660 talloc_free(mpctx->chapters);
661 mpctx->chapters = NULL;
662 mpctx->num_chapters = 0;
663 mpctx->video_offset = 0;
664 if(mpctx->demuxer){
665 mpctx->stream=mpctx->demuxer->stream;
666 free_demuxer(mpctx->demuxer);
668 mpctx->demuxer=NULL;
671 // kill the cache process:
672 if(mask&INITIALIZED_STREAM){
673 mpctx->initialized_flags&=~INITIALIZED_STREAM;
674 current_module="uninit_stream";
675 if(mpctx->stream) free_stream(mpctx->stream);
676 mpctx->stream=NULL;
679 if(mask&INITIALIZED_VO){
680 mpctx->initialized_flags&=~INITIALIZED_VO;
681 current_module="uninit_vo";
682 vo_destroy(mpctx->video_out);
683 mpctx->video_out=NULL;
684 #ifdef CONFIG_DVDNAV
685 mp_dvdnav_context_free(mpctx);
686 #endif
689 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
690 if(mask&INITIALIZED_GETCH2){
691 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
692 current_module="uninit_getch2";
693 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
694 // restore terminal:
695 getch2_disable();
698 if(mask&INITIALIZED_VOBSUB){
699 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
700 current_module="uninit_vobsub";
701 if(vo_vobsub) vobsub_close(vo_vobsub);
702 vo_vobsub=NULL;
705 if (mask&INITIALIZED_SPUDEC){
706 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
707 current_module="uninit_spudec";
708 spudec_free(vo_spudec);
709 vo_spudec=NULL;
712 if(mask&INITIALIZED_AO){
713 mpctx->initialized_flags&=~INITIALIZED_AO;
714 current_module="uninit_ao";
715 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
716 if (mpctx->audio_out)
717 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
718 mpctx->audio_out=NULL;
721 current_module=NULL;
724 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
726 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
727 uninit_player(mpctx, INITIALIZED_ALL);
728 #if defined(__MINGW32__) || defined(__CYGWIN__)
729 timeEndPeriod(1);
730 #endif
731 #ifdef CONFIG_X11
732 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
733 #endif
735 current_module="uninit_input";
736 mp_input_uninit(mpctx->input);
737 #ifdef CONFIG_MENU
738 if (use_menu)
739 menu_uninit();
740 #endif
742 #ifdef CONFIG_FREETYPE
743 current_module="uninit_font";
744 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
745 free_font_desc(mpctx->osd->sub_font);
746 free_font_desc(vo_font);
747 vo_font = NULL;
748 done_freetype();
749 #endif
750 osd_free(mpctx->osd);
752 #ifdef CONFIG_ASS
753 ass_library_done(ass_library);
754 ass_library = NULL;
755 #endif
757 current_module="exit_player";
759 // free mplayer config
760 if(mpctx->mconfig)
761 m_config_free(mpctx->mconfig);
762 mpctx->mconfig = NULL;
764 if(mpctx->playtree_iter)
765 play_tree_iter_free(mpctx->playtree_iter);
766 mpctx->playtree_iter = NULL;
767 if(mpctx->playtree)
768 play_tree_free(mpctx->playtree, 1);
769 mpctx->playtree = NULL;
771 talloc_free(mpctx->key_fifo);
773 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
774 edl_records = NULL;
775 switch(how) {
776 case EXIT_QUIT:
777 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
778 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
779 break;
780 case EXIT_EOF:
781 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
782 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
783 break;
784 case EXIT_ERROR:
785 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
786 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
787 break;
788 default:
789 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
791 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
793 exit(rc);
796 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
798 exit_player_with_rc(mpctx, how, 1);
801 #ifndef __MINGW32__
802 static void child_sighandler(int x){
803 pid_t pid;
804 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
806 #endif
808 #ifdef CONFIG_CRASH_DEBUG
809 static char *prog_path;
810 static int crash_debug = 0;
811 #endif
813 static void exit_sighandler(int x){
814 static int sig_count=0;
815 #ifdef CONFIG_CRASH_DEBUG
816 if (!crash_debug || x != SIGTRAP)
817 #endif
818 ++sig_count;
819 if(sig_count==5)
821 /* We're crashing bad and can't uninit cleanly :(
822 * by popular request, we make one last (dirty)
823 * effort to restore the user's
824 * terminal. */
825 getch2_disable();
826 exit(1);
828 if(sig_count==6) exit(1);
829 if(sig_count>6){
830 // can't stop :(
831 #ifndef __MINGW32__
832 kill(getpid(),SIGKILL);
833 #endif
835 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
836 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
837 "\nMPlayer interrupted by signal %d in module: %s\n", x,
838 current_module ? current_module : "unknown");
839 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
840 if(sig_count<=1)
841 switch(x){
842 case SIGINT:
843 case SIGQUIT:
844 case SIGTERM:
845 case SIGKILL:
846 async_quit_request = 1;
847 return; // killed from keyboard (^C) or killed [-9]
848 case SIGILL:
849 #if CONFIG_RUNTIME_CPUDETECT
850 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
851 #else
852 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
853 #endif
854 case SIGFPE:
855 case SIGSEGV:
856 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
857 default:
858 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
859 #ifdef CONFIG_CRASH_DEBUG
860 if (crash_debug) {
861 int gdb_pid;
862 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
863 gdb_pid = fork();
864 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
865 if (gdb_pid == 0) { // We are the child
866 char spid[20];
867 snprintf(spid, sizeof(spid), "%i", getppid());
868 getch2_disable(); // allow terminal to work properly with gdb
869 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
870 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
871 } else if (gdb_pid < 0)
872 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
873 else {
874 waitpid(gdb_pid, NULL, 0);
876 if (x == SIGTRAP) return;
878 #endif
880 getch2_disable();
881 exit(1);
884 #include "cfg-mplayer.h"
886 static int cfg_include(m_option_t *conf, char *filename)
888 return m_config_parse_config_file(conf->priv, filename);
891 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
893 char *conffile;
894 int conffile_fd;
895 if (!disable_system_conf &&
896 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
897 exit_player(mpctx, EXIT_NONE);
898 if ((conffile = get_path("")) == NULL) {
899 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
900 } else {
901 #ifdef __MINGW32__
902 mkdir(conffile);
903 #else
904 mkdir(conffile, 0777);
905 #endif
906 free(conffile);
907 if ((conffile = get_path("config")) == NULL) {
908 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
909 } else {
910 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
911 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
912 write(conffile_fd, default_config, strlen(default_config));
913 close(conffile_fd);
915 if (!disable_user_conf &&
916 m_config_parse_config_file(conf, conffile) < 0)
917 exit_player(mpctx, EXIT_NONE);
918 free(conffile);
923 #define PROFILE_CFG_PROTOCOL "protocol."
925 static void load_per_protocol_config (m_config_t* conf, const char *const file)
927 char *str;
928 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
929 m_profile_t *p;
931 /* does filename actually uses a protocol ? */
932 str = strstr (file, "://");
933 if (!str)
934 return;
936 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
937 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
938 p = m_config_get_profile (conf, protocol);
939 if (p)
941 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
942 m_config_set_profile(conf,p);
946 #define PROFILE_CFG_EXTENSION "extension."
948 static void load_per_extension_config (m_config_t* conf, const char *const file)
950 char *str;
951 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
952 m_profile_t *p;
954 /* does filename actually have an extension ? */
955 str = strrchr (file, '.');
956 if (!str)
957 return;
959 sprintf (extension, PROFILE_CFG_EXTENSION);
960 strncat (extension, ++str, 7);
961 p = m_config_get_profile (conf, extension);
962 if (p)
964 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
965 m_config_set_profile(conf,p);
969 #define PROFILE_CFG_VO "vo."
970 #define PROFILE_CFG_AO "ao."
972 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
974 char profile[strlen (cfg) + strlen (out) + 1];
975 m_profile_t *p;
977 sprintf (profile, "%s%s", cfg, out);
978 p = m_config_get_profile (conf, profile);
979 if (p)
981 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
982 m_config_set_profile(conf,p);
987 * Tries to load a config file
988 * @return 0 if file was not found, 1 otherwise
990 static int try_load_config(m_config_t *conf, const char *file)
992 struct stat st;
993 if (stat(file, &st))
994 return 0;
995 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
996 m_config_parse_config_file (conf, file);
997 return 1;
1000 static void load_per_file_config (m_config_t* conf, const char *const file)
1002 char *confpath;
1003 char cfg[PATH_MAX];
1004 char *name;
1006 if (strlen(file) > PATH_MAX - 14) {
1007 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1008 return;
1010 sprintf (cfg, "%s.conf", file);
1012 name = strrchr(cfg, '/');
1013 if (HAVE_DOS_PATHS) {
1014 char *tmp = strrchr(cfg, '\\');
1015 if (!name || tmp > name)
1016 name = tmp;
1017 tmp = strrchr(cfg, ':');
1018 if (!name || tmp > name)
1019 name = tmp;
1021 if (!name)
1022 name = cfg;
1023 else
1024 name++;
1026 if (use_filedir_conf) {
1027 char dircfg[PATH_MAX];
1028 strcpy(dircfg, cfg);
1029 strcpy(dircfg + (name - cfg), "mplayer.conf");
1030 try_load_config(conf, dircfg);
1032 if (try_load_config(conf, cfg))
1033 return;
1036 if ((confpath = get_path (name)) != NULL)
1038 try_load_config(conf, confpath);
1040 free (confpath);
1044 /* When libmpdemux performs a blocking operation (network connection or
1045 * cache filling) if the operation fails we use this function to check
1046 * if it was interrupted by the user.
1047 * The function returns a new value for eof. */
1048 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1050 mp_cmd_t* cmd;
1051 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1052 switch(cmd->id) {
1053 case MP_CMD_QUIT:
1054 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1055 case MP_CMD_PLAY_TREE_STEP: {
1056 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1057 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1058 } break;
1059 case MP_CMD_PLAY_TREE_UP_STEP: {
1060 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1061 } break;
1062 case MP_CMD_PLAY_ALT_SRC_STEP: {
1063 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1064 } break;
1066 mp_cmd_free(cmd);
1068 return stop_play;
1071 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1073 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1075 play_tree_add_bpf(entry,mpctx->filename);
1078 if(!entry) {
1079 entry = mpctx->playtree_iter->tree;
1080 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1081 return PT_NEXT_ENTRY;
1083 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1084 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1085 return PT_NEXT_ENTRY;
1088 play_tree_remove(entry,1,1);
1089 return PT_NEXT_SRC;
1091 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1092 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1093 entry = mpctx->playtree_iter->tree;
1094 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1095 return PT_NEXT_ENTRY;
1097 play_tree_remove(entry,1,1);
1099 return PT_NEXT_SRC;
1102 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1104 struct MPOpts *opts = &mpctx->opts;
1105 sub_data *subd = NULL;
1106 struct ass_track *asst = NULL;
1108 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1109 return;
1112 #ifdef CONFIG_ASS
1113 if (opts->ass_enabled) {
1114 #ifdef CONFIG_ICONV
1115 asst = ass_read_stream(ass_library, filename, sub_cp);
1116 #else
1117 asst = ass_read_stream(ass_library, filename, 0);
1118 #endif
1119 if (!asst) {
1120 subd = sub_read_file(filename, fps);
1121 if (subd) {
1122 asst = ass_read_subdata(ass_library, subd, fps);
1123 if (asst) {
1124 sub_free(subd);
1125 subd = NULL;
1129 } else
1130 #endif
1131 subd = sub_read_file(filename, fps);
1134 if (!asst && !subd) {
1135 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1136 "Cannot load subtitles: %s\n", filename_recode(filename));
1137 return;
1140 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1141 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1142 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1143 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1144 filename_recode(filename));
1145 ++mpctx->set_of_sub_size;
1146 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1147 filename_recode(filename));
1150 void init_vo_spudec(struct MPContext *mpctx)
1152 if (vo_spudec)
1153 spudec_free(vo_spudec);
1154 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1155 vo_spudec = NULL;
1157 // we currently can't work without video stream
1158 if (!mpctx->sh_video)
1159 return;
1161 if (spudec_ifo) {
1162 unsigned int palette[16], width, height;
1163 current_module="spudec_init_vobsub";
1164 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1165 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1168 #ifdef CONFIG_DVDREAD
1169 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1170 current_module="spudec_init_dvdread";
1171 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1172 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1173 NULL, 0);
1175 #endif
1177 #ifdef CONFIG_DVDNAV
1178 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1179 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1180 current_module="spudec_init_dvdnav";
1181 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1183 #endif
1185 if (vo_spudec==NULL) {
1186 sh_sub_t *sh = (sh_sub_t *)mpctx->d_sub->sh;
1187 current_module="spudec_init_normal";
1188 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1189 spudec_set_font_factor(vo_spudec,font_factor);
1192 if (vo_spudec!=NULL) {
1193 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1194 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1199 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1200 * make it all work is to use the builtin SDL-bootstrap code, which
1201 * will be done automatically by replacing our main() if we include SDL.h.
1203 #if defined(__APPLE__) && defined(CONFIG_SDL)
1204 #ifdef CONFIG_SDL_SDL_H
1205 #include <SDL/SDL.h>
1206 #else
1207 #include <SDL.h>
1208 #endif
1209 #endif
1212 * \brief append a formatted string
1213 * \param buf buffer to print into
1214 * \param pos position of terminating 0 in buf
1215 * \param len maximum number of characters in buf, not including terminating 0
1216 * \param format printf format string
1218 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1220 va_list va;
1221 va_start(va, format);
1222 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1223 va_end(va);
1224 if (*pos >= len ) {
1225 buf[len] = 0;
1226 *pos = len;
1231 * \brief append time in the hh:mm:ss.f format
1232 * \param buf buffer to print into
1233 * \param pos position of terminating 0 in buf
1234 * \param len maximum number of characters in buf, not including terminating 0
1235 * \param time time value to convert/append
1237 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1238 int64_t tenths = 10 * time;
1239 int f1 = tenths % 10;
1240 int ss = (tenths / 10) % 60;
1241 int mm = (tenths / 600) % 60;
1242 int hh = tenths / 36000;
1243 if (time <= 0) {
1244 saddf(buf, pos, len, "unknown");
1245 return;
1247 if (hh > 0)
1248 saddf(buf, pos, len, "%2d:", hh);
1249 if (hh > 0 || mm > 0)
1250 saddf(buf, pos, len, "%02d:", mm);
1251 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1254 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1256 struct MPOpts *opts = &mpctx->opts;
1257 sh_video_t * const sh_video = mpctx->sh_video;
1259 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1260 a_pos = playing_audio_pts(mpctx);
1261 if (mpctx->sh_audio && sh_video && at_frame) {
1262 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1263 if (mpctx->time_frame > 0)
1264 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1265 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1266 && !mpctx->drop_message_shown) {
1267 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1268 mpctx->drop_message_shown = true;
1271 if (quiet)
1272 return;
1275 int width;
1276 char *line;
1277 unsigned pos = 0;
1278 get_screen_size();
1279 if (screen_width > 0)
1280 width = screen_width;
1281 else
1282 width = 80;
1283 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1284 /* Windows command line is broken (MinGW's rxvt works, but we
1285 * should not depend on that). */
1286 width--;
1287 #endif
1288 line = malloc(width + 1); // one additional char for the terminating null
1290 // Audio time
1291 if (mpctx->sh_audio) {
1292 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1293 if (!sh_video) {
1294 float len = demuxer_get_time_length(mpctx->demuxer);
1295 saddf(line, &pos, width, "(");
1296 sadd_hhmmssf(line, &pos, width, a_pos);
1297 saddf(line, &pos, width, ") of %.1f (", len);
1298 sadd_hhmmssf(line, &pos, width, len);
1299 saddf(line, &pos, width, ") ");
1303 // Video time
1304 if (sh_video)
1305 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1307 // A-V sync
1308 if (mpctx->sh_audio && sh_video)
1309 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1310 mpctx->last_av_difference, mpctx->total_avsync_change);
1312 // Video stats
1313 if (sh_video)
1314 saddf(line, &pos, width, "%3d/%3d ",
1315 (int)sh_video->num_frames,
1316 (int)sh_video->num_frames_decoded);
1318 // CPU usage
1319 if (sh_video) {
1320 if (sh_video->timer > 0.5)
1321 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1322 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1323 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1324 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1325 else
1326 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1327 } else if (mpctx->sh_audio) {
1328 if (mpctx->delay > 0.5)
1329 saddf(line, &pos, width, "%4.1f%% ",
1330 100.0*audio_time_usage/(double)mpctx->delay);
1331 else
1332 saddf(line, &pos, width, "??,?%% ");
1335 // VO stats
1336 if (sh_video)
1337 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1339 #ifdef CONFIG_STREAM_CACHE
1340 // cache stats
1341 if (stream_cache_size > 0)
1342 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1343 #endif
1345 // other
1346 if (opts->playback_speed != 1)
1347 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1349 // end
1350 if (erase_to_end_of_line) {
1351 line[pos] = 0;
1352 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1353 } else {
1354 memset(&line[pos], ' ', width - pos);
1355 line[width] = 0;
1356 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1358 free(line);
1362 * \brief build a chain of audio filters that converts the input format
1363 * to the ao's format, taking into account the current playback_speed.
1364 * \param sh_audio describes the requested input format of the chain.
1365 * \param ao_data describes the requested output format of the chain.
1367 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1369 struct MPOpts *opts = &mpctx->opts;
1370 int new_srate;
1371 int result;
1372 if (!sh_audio)
1374 mpctx->mixer.afilter = NULL;
1375 return 0;
1377 if(af_control_any_rev(sh_audio->afilter,
1378 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1379 &opts->playback_speed)) {
1380 new_srate = sh_audio->samplerate;
1381 } else {
1382 new_srate = sh_audio->samplerate * opts->playback_speed;
1383 if (new_srate != ao_data->samplerate) {
1384 // limits are taken from libaf/af_resample.c
1385 if (new_srate < 8000)
1386 new_srate = 8000;
1387 if (new_srate > 192000)
1388 new_srate = 192000;
1389 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1392 result = init_audio_filters(sh_audio, new_srate,
1393 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1394 mpctx->mixer.afilter = sh_audio->afilter;
1395 return result;
1399 typedef struct mp_osd_msg mp_osd_msg_t;
1400 struct mp_osd_msg {
1401 /// Previous message on the stack.
1402 mp_osd_msg_t* prev;
1403 /// Message text.
1404 char msg[128];
1405 int id,level,started;
1406 /// Display duration in ms.
1407 unsigned time;
1410 /// OSD message stack.
1411 static mp_osd_msg_t* osd_msg_stack = NULL;
1414 * \brief Add a message on the OSD message stack
1416 * If a message with the same id is already present in the stack
1417 * it is pulled on top of the stack, otherwise a new message is created.
1420 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1421 va_list ap)
1423 mp_osd_msg_t *msg,*last=NULL;
1424 int r;
1426 // look if the id is already in the stack
1427 for(msg = osd_msg_stack ; msg && msg->id != id ;
1428 last = msg, msg = msg->prev);
1429 // not found: alloc it
1430 if(!msg) {
1431 msg = calloc(1,sizeof(mp_osd_msg_t));
1432 msg->prev = osd_msg_stack;
1433 osd_msg_stack = msg;
1434 } else if(last) { // found, but it's not on top of the stack
1435 last->prev = msg->prev;
1436 msg->prev = osd_msg_stack;
1437 osd_msg_stack = msg;
1439 // write the msg
1440 r = vsnprintf(msg->msg, 128, fmt, ap);
1441 if(r >= 128) msg->msg[127] = 0;
1442 // set id and time
1443 msg->id = id;
1444 msg->level = level;
1445 msg->time = time;
1449 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1451 va_list ap;
1452 va_start(ap, fmt);
1453 set_osd_msg_va(id, level, time, fmt, ap);
1454 va_end(ap);
1457 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1459 va_list ap;
1460 va_start(ap, fmt);
1461 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1462 va_end(ap);
1467 * \brief Remove a message from the OSD stack
1469 * This function can be used to get rid of a message right away.
1473 void rm_osd_msg(int id) {
1474 mp_osd_msg_t *msg,*last=NULL;
1476 // Search for the msg
1477 for(msg = osd_msg_stack ; msg && msg->id != id ;
1478 last = msg, msg = msg->prev);
1479 if(!msg) return;
1481 // Detach it from the stack and free it
1482 if(last)
1483 last->prev = msg->prev;
1484 else
1485 osd_msg_stack = msg->prev;
1486 free(msg);
1490 * \brief Remove all messages from the OSD stack
1494 static void clear_osd_msgs(void) {
1495 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1496 while(msg) {
1497 prev = msg->prev;
1498 free(msg);
1499 msg = prev;
1501 osd_msg_stack = NULL;
1505 * \brief Get the current message from the OSD stack.
1507 * This function decrements the message timer and destroys the old ones.
1508 * The message that should be displayed is returned (if any).
1512 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1514 struct MPOpts *opts = &mpctx->opts;
1515 mp_osd_msg_t *msg,*prev,*last = NULL;
1516 static unsigned last_update = 0;
1517 unsigned now = GetTimerMS();
1518 unsigned diff;
1519 char hidden_dec_done = 0;
1521 if (mpctx->osd_visible) {
1522 // 36000000 means max timed visibility is 1 hour into the future, if
1523 // the difference is greater assume it's wrapped around from below 0
1524 if (mpctx->osd_visible - now > 36000000) {
1525 mpctx->osd_visible = 0;
1526 vo_osd_progbar_type = -1; // disable
1527 vo_osd_changed(OSDTYPE_PROGBAR);
1528 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1531 if (mpctx->osd_show_percentage_until - now > 36000000)
1532 mpctx->osd_show_percentage_until = 0;
1534 if(!last_update) last_update = now;
1535 diff = now >= last_update ? now - last_update : 0;
1537 last_update = now;
1539 // Look for the first message in the stack with high enough level.
1540 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1541 prev = msg->prev;
1542 if (msg->level > opts->osd_level && hidden_dec_done)
1543 continue;
1544 // The message has a high enough level or it is the first hidden one
1545 // in both cases we decrement the timer or kill it.
1546 if(!msg->started || msg->time > diff) {
1547 if(msg->started) msg->time -= diff;
1548 else msg->started = 1;
1549 // display it
1550 if (msg->level <= opts->osd_level)
1551 return msg;
1552 hidden_dec_done = 1;
1553 continue;
1555 // kill the message
1556 free(msg);
1557 if(last) {
1558 last->prev = prev;
1559 msg = last;
1560 } else {
1561 osd_msg_stack = prev;
1562 msg = NULL;
1565 // Nothing found
1566 return NULL;
1570 * \brief Display the OSD bar.
1572 * Display the OSD bar or fall back on a simple message.
1576 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1577 struct MPOpts *opts = &mpctx->opts;
1578 if (opts->osd_level < 1)
1579 return;
1581 if(mpctx->sh_video) {
1582 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1583 vo_osd_progbar_type = type;
1584 vo_osd_progbar_value = 256*(val-min)/(max-min);
1585 vo_osd_changed(OSDTYPE_PROGBAR);
1586 return;
1589 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1590 name, ROUND(100*(val-min)/(max-min)));
1594 * \brief Display text subtitles on the OSD
1596 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1598 int i;
1599 vo_sub = subs;
1600 vo_osd_changed(OSDTYPE_SUBTITLE);
1601 if (!mpctx->sh_video) {
1602 // reverse order, since newest set_osd_msg is displayed first
1603 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1604 if (!subs || i >= subs->lines || !subs->text[i])
1605 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1606 else {
1607 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1608 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1609 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1616 * \brief Update the OSD message line.
1618 * This function displays the current message on the vo OSD or on the term.
1619 * If the stack is empty and the OSD level is high enough the timer
1620 * is displayed (only on the vo OSD).
1624 static void update_osd_msg(struct MPContext *mpctx)
1626 struct MPOpts *opts = &mpctx->opts;
1627 mp_osd_msg_t *msg;
1628 struct osd_state *osd = mpctx->osd;
1629 char osd_text_timer[128];
1631 if (mpctx->add_osd_seek_info) {
1632 double percentage;
1633 if (mpctx->timeline && mpctx->sh_video)
1634 percentage = mpctx->sh_video->pts * 100 /
1635 mpctx->timeline[mpctx->num_timeline_parts].start;
1636 else
1637 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1638 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1639 if (mpctx->sh_video)
1640 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1641 mpctx->add_osd_seek_info = false;
1644 // Look if we have a msg
1645 if((msg = get_osd_msg(mpctx))) {
1646 if (strcmp(osd->osd_text, msg->msg)) {
1647 strncpy(osd->osd_text, msg->msg, 127);
1648 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1649 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1651 return;
1654 if(mpctx->sh_video) {
1655 // fallback on the timer
1656 if (opts->osd_level >= 2) {
1657 int len;
1658 if (mpctx->timeline)
1659 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1660 else
1661 len = demuxer_get_time_length(mpctx->demuxer);
1662 int percentage = -1;
1663 char percentage_text[10];
1664 int pts = demuxer_get_current_time(mpctx->demuxer);
1666 if (mpctx->osd_show_percentage_until) {
1667 if (mpctx->timeline)
1668 percentage = mpctx->sh_video->pts * 100 /
1669 mpctx->timeline[mpctx->num_timeline_parts].start;
1670 else
1671 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1674 if (percentage >= 0)
1675 snprintf(percentage_text, 9, " (%d%%)", percentage);
1676 else
1677 percentage_text[0] = 0;
1679 if (opts->osd_level == 3)
1680 snprintf(osd_text_timer, 63,
1681 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1682 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1683 len/3600,(len/60)%60,len%60,percentage_text);
1684 else
1685 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1686 mpctx->osd_function,pts/3600,(pts/60)%60,
1687 pts%60,percentage_text);
1688 } else
1689 osd_text_timer[0]=0;
1691 if (strcmp(osd->osd_text, osd_text_timer)) {
1692 strncpy(osd->osd_text, osd_text_timer, 63);
1693 vo_osd_changed(OSDTYPE_OSD);
1695 return;
1698 // Clear the term osd line
1699 if (term_osd && osd->osd_text[0]) {
1700 osd->osd_text[0] = 0;
1701 printf("%s\n",term_osd_esc);
1705 ///@}
1706 // OSDMsgStack
1709 void reinit_audio_chain(struct MPContext *mpctx)
1711 struct MPOpts *opts = &mpctx->opts;
1712 if (!mpctx->sh_audio)
1713 return;
1714 current_module="init_audio_codec";
1715 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1716 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1717 goto init_error;
1719 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1720 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1723 current_module="af_preinit";
1724 ao_data.samplerate=force_srate;
1725 ao_data.channels=0;
1726 ao_data.format=audio_output_format;
1727 // first init to detect best values
1728 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1729 // input:
1730 mpctx->sh_audio->samplerate,
1731 // output:
1732 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1733 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1734 "pre-init!\n");
1735 exit_player(mpctx, EXIT_ERROR);
1737 current_module="ao2_init";
1738 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1739 0, // plugin flag
1740 ao_data.samplerate,
1741 ao_data.channels,
1742 ao_data.format, 0);
1743 if(!mpctx->audio_out){
1744 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1745 goto init_error;
1747 mpctx->initialized_flags|=INITIALIZED_AO;
1748 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1749 mpctx->audio_out->info->short_name,
1750 ao_data.samplerate, ao_data.channels,
1751 af_fmt2str_short(ao_data.format),
1752 af_fmt2bits(ao_data.format)/8 );
1753 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1754 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1755 if(strlen(mpctx->audio_out->info->comment) > 0)
1756 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1757 // init audio filters:
1758 current_module="af_init";
1759 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1760 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1761 goto init_error;
1763 mpctx->mixer.audio_out = mpctx->audio_out;
1764 mpctx->mixer.volstep = volstep;
1765 return;
1767 init_error:
1768 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1769 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1770 mpctx->d_audio->id = -2;
1774 ///@}
1775 // Command2Property
1778 // Return pts value corresponding to the end point of audio written to the
1779 // ao so far.
1780 static double written_audio_pts(struct MPContext *mpctx)
1782 sh_audio_t *sh_audio = mpctx->sh_audio;
1783 demux_stream_t *d_audio = mpctx->d_audio;
1784 double buffered_output;
1785 // first calculate the end pts of audio that has been output by decoder
1786 double a_pts = sh_audio->pts;
1787 if (a_pts != MP_NOPTS_VALUE)
1788 // Good, decoder supports new way of calculating audio pts.
1789 // sh_audio->pts is the timestamp of the latest input packet with
1790 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1791 // the amount of bytes the decoder has written after that timestamp.
1792 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1793 else {
1794 // Decoder doesn't support new way of calculating pts (or we're
1795 // being called before it has decoded anything with known timestamp).
1796 // Use the old method of audio pts calculation: take the timestamp
1797 // of last packet with known pts the decoder has read data from,
1798 // and add amount of bytes read after the beginning of that packet
1799 // divided by input bps. This will be inaccurate if the input/output
1800 // ratio is not constant for every audio packet or if it is constant
1801 // but not accurately known in sh_audio->i_bps.
1803 a_pts = d_audio->pts;
1804 // ds_tell_pts returns bytes read after last timestamp from
1805 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1806 // it has read but not decoded
1807 if (sh_audio->i_bps)
1808 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1809 (double)sh_audio->i_bps;
1811 // Now a_pts hopefully holds the pts for end of audio from decoder.
1812 // Substract data in buffers between decoder and audio out.
1814 // Decoded but not filtered
1815 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1817 // Data buffered in audio filters, measured in bytes of "missing" output
1818 buffered_output = af_calc_delay(sh_audio->afilter);
1820 // Data that was ready for ao but was buffered because ao didn't fully
1821 // accept everything to internal buffers yet
1822 buffered_output += sh_audio->a_out_buffer_len;
1824 // Filters divide audio length by playback_speed, so multiply by it
1825 // to get the length in original units without speedup or slowdown
1826 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1828 return a_pts + mpctx->video_offset;
1831 // Return pts value corresponding to currently playing audio.
1832 double playing_audio_pts(struct MPContext *mpctx)
1834 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1835 mpctx->audio_out->get_delay();
1838 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1839 struct MPOpts *opts = &mpctx->opts;
1840 // check for frame-drop:
1841 current_module = "check_framedrop";
1842 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1843 static int dropped_frames;
1844 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1845 float d = delay-mpctx->delay;
1846 ++total_frame_cnt;
1847 // we should avoid dropping too many frames in sequence unless we
1848 // are too late. and we allow 100ms A-V delay here:
1849 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1850 && !mpctx->update_video_immediately) {
1851 ++drop_frame_cnt;
1852 ++dropped_frames;
1853 return frame_dropping;
1854 } else
1855 dropped_frames = 0;
1857 return 0;
1861 #ifdef HAVE_RTC
1862 int rtc_fd = -1;
1863 #endif
1865 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1867 #ifdef HAVE_RTC
1868 if (rtc_fd >= 0){
1869 // -------- RTC -----------
1870 current_module="sleep_rtc";
1871 while (time_frame > 0.000) {
1872 unsigned long rtc_ts;
1873 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1874 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1875 time_frame -= get_relative_time(mpctx);
1877 } else
1878 #endif
1880 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1881 // unnecessarily high CPU usage
1882 float margin = softsleep ? 0.011 : 0;
1883 current_module = "sleep_timer";
1884 while (time_frame > margin) {
1885 usec_sleep(1000000 * (time_frame - margin));
1886 time_frame -= get_relative_time(mpctx);
1888 if (softsleep){
1889 current_module = "sleep_soft";
1890 if (time_frame < 0)
1891 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1892 while (time_frame > 0)
1893 time_frame -= get_relative_time(mpctx); // burn the CPU
1896 return time_frame;
1899 static void select_subtitle(MPContext *mpctx)
1901 struct MPOpts *opts = &mpctx->opts;
1902 // find the best sub to use
1903 int vobsub_index_id = vobsub_get_index_by_id(vo_vobsub, vobsub_id);
1904 mpctx->global_sub_pos = -1; // no subs by default
1905 if (vobsub_index_id >= 0) {
1906 // if user asks for a vobsub id, use that first.
1907 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] + vobsub_index_id;
1908 } else if (opts->sub_id >= 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
1909 // if user asks for a dvd sub id, use that next.
1910 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
1911 } else if (mpctx->global_sub_indices[SUB_SOURCE_SUBS] >= 0) {
1912 // if there are text subs to use, use those. (autosubs come last here)
1913 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_SUBS];
1914 } else if (opts->sub_id == -1 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
1915 // finally select subs by language and container hints
1916 if (opts->sub_id == -1 && opts->sub_lang)
1917 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, opts->sub_lang);
1918 if (opts->sub_id == -1)
1919 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
1920 if (opts->sub_id >= 0)
1921 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
1923 // rather than duplicate code, use the SUB_SELECT handler to init the right one.
1924 mpctx->global_sub_pos--;
1925 mp_property_do("sub",M_PROPERTY_STEP_UP,NULL, mpctx);
1928 #ifdef CONFIG_DVDNAV
1929 #ifndef FF_B_TYPE
1930 #define FF_B_TYPE 3
1931 #endif
1932 /// store decoded video image
1933 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1934 mp_image_t *from_mpi) {
1935 mp_image_t *mpi;
1937 /// Do not store B-frames
1938 if (from_mpi->pict_type == FF_B_TYPE)
1939 return to_mpi;
1941 if (to_mpi &&
1942 to_mpi->w == from_mpi->w &&
1943 to_mpi->h == from_mpi->h &&
1944 to_mpi->imgfmt == from_mpi->imgfmt)
1945 mpi = to_mpi;
1946 else {
1947 if (to_mpi)
1948 free_mp_image(to_mpi);
1949 if (from_mpi->w == 0 || from_mpi->h == 0)
1950 return NULL;
1951 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1954 copy_mpi(mpi,from_mpi);
1955 return mpi;
1958 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1959 struct MPOpts *opts = &ctx->opts;
1960 if (ctx->sh_video) {
1961 /// clear video pts
1962 ctx->d_video->pts = 0.0f;
1963 ctx->sh_video->pts = 0.0f;
1964 ctx->sh_video->i_pts = 0.0f;
1965 ctx->sh_video->last_pts = 0.0f;
1966 ctx->sh_video->num_buffered_pts = 0;
1967 ctx->sh_video->num_frames = 0;
1968 ctx->sh_video->num_frames_decoded = 0;
1969 ctx->sh_video->timer = 0.0f;
1970 ctx->sh_video->stream_delay = 0.0f;
1971 ctx->sh_video->timer = 0;
1972 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1975 if (ctx->sh_audio) {
1976 /// free audio packets and reset
1977 ds_free_packs(ctx->d_audio);
1978 audio_delay -= ctx->sh_audio->stream_delay;
1979 ctx->delay =- audio_delay;
1980 ctx->audio_out->reset();
1981 resync_audio_stream(ctx->sh_audio);
1984 audio_delay = 0.0f;
1985 ctx->global_sub_size = ctx->global_sub_indices[SUB_SOURCE_DEMUX] + mp_dvdnav_number_of_subs(ctx->stream);
1986 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
1987 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
1988 if (dvdsub_lang_id != opts->sub_id) {
1989 opts->sub_id = dvdsub_lang_id;
1990 select_subtitle(ctx);
1994 /// clear all EOF related flags
1995 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1998 /// Restore last decoded DVDNAV (still frame)
1999 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2000 int *in_size,
2001 unsigned char **start,
2002 mp_image_t *decoded_frame)
2004 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2005 return decoded_frame;
2007 /// a change occured in dvdnav stream
2008 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2009 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2010 mp_dvdnav_context_free(mpctx);
2011 mp_dvdnav_reset_stream(mpctx);
2012 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2013 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2016 if (*in_size < 0) {
2017 float len;
2019 /// Display still frame, if any
2020 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2021 decoded_frame = mpctx->nav_smpi;
2023 /// increment video frame : continue playing after still frame
2024 len = demuxer_get_time_length(mpctx->demuxer);
2025 if (mpctx->sh_video->pts >= len &&
2026 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2027 mp_dvdnav_skip_still(mpctx->stream);
2028 mp_dvdnav_skip_wait(mpctx->stream);
2030 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2032 if (mpctx->nav_buffer) {
2033 *start = mpctx->nav_start;
2034 *in_size = mpctx->nav_in_size;
2035 if (mpctx->nav_start)
2036 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2040 return decoded_frame;
2043 /// Save last decoded DVDNAV (still frame)
2044 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2045 unsigned char *start,
2046 mp_image_t *decoded_frame)
2048 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2049 return;
2051 if (mpctx->nav_buffer)
2052 free(mpctx->nav_buffer);
2054 mpctx->nav_buffer = malloc(in_size);
2055 mpctx->nav_start = start;
2056 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2057 if (mpctx->nav_buffer)
2058 memcpy(mpctx->nav_buffer,start,in_size);
2060 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2061 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2063 #endif /* CONFIG_DVDNAV */
2065 /* Modify video timing to match the audio timeline. There are two main
2066 * reasons this is needed. First, video and audio can start from different
2067 * positions at beginning of file or after a seek (MPlayer starts both
2068 * immediately even if they have different pts). Second, the file can have
2069 * audio timestamps that are inconsistent with the duration of the audio
2070 * packets, for example two consecutive timestamp values differing by
2071 * one second but only a packet with enough samples for half a second
2072 * of playback between them.
2074 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2076 current_module = "av_sync";
2078 if (!mpctx->sh_audio)
2079 return;
2081 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2082 double v_pts = mpctx->sh_video->pts;
2083 double av_delay = a_pts - v_pts;
2084 // Try to sync vo_flip() so it will *finish* at given time
2085 av_delay += mpctx->last_vo_flip_duration;
2086 av_delay -= audio_delay; // This much pts difference is desired
2088 double change = av_delay * 0.1;
2089 double max_change = default_max_pts_correction >= 0 ?
2090 default_max_pts_correction : frame_time * 0.1;
2091 if (change < -max_change)
2092 change = -max_change;
2093 else if (change > max_change)
2094 change = max_change;
2095 mpctx->delay += change;
2096 mpctx->total_avsync_change += change;
2099 static int fill_audio_out_buffers(struct MPContext *mpctx)
2101 struct MPOpts *opts = &mpctx->opts;
2102 unsigned int t;
2103 double tt;
2104 int playsize;
2105 int playflags=0;
2106 int audio_eof=0;
2107 sh_audio_t * const sh_audio = mpctx->sh_audio;
2109 current_module="play_audio";
2111 while (1) {
2112 int sleep_time;
2113 // all the current uses of ao_data.pts seem to be in aos that handle
2114 // sync completely wrong; there should be no need to use ao_data.pts
2115 // in get_space()
2116 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2117 playsize = mpctx->audio_out->get_space();
2118 if (mpctx->sh_video || playsize >= ao_data.outburst)
2119 break;
2121 // handle audio-only case:
2122 // this is where mplayer sleeps during audio-only playback
2123 // to avoid 100% CPU use
2124 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2125 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2126 usec_sleep(sleep_time * 1000);
2129 // Fill buffer if needed:
2130 current_module="decode_audio";
2131 t = GetTimer();
2132 if (decode_audio(sh_audio, playsize) < 0) // EOF or error
2133 if (mpctx->d_audio->eof) {
2134 audio_eof = 1;
2135 if (sh_audio->a_out_buffer_len == 0)
2136 return 0;
2138 t = GetTimer() - t;
2139 tt = t*0.000001f; audio_time_usage+=tt;
2140 if (playsize > sh_audio->a_out_buffer_len) {
2141 playsize = sh_audio->a_out_buffer_len;
2142 if (audio_eof)
2143 playflags |= AOPLAY_FINAL_CHUNK;
2145 if (!playsize)
2146 return 1;
2148 // play audio:
2149 current_module="play_audio";
2151 // Is this pts value actually useful for the aos that access it?
2152 // They're obviously badly broken in the way they handle av sync;
2153 // would not having access to this make them more broken?
2154 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2155 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2157 if (playsize > 0) {
2158 sh_audio->a_out_buffer_len -= playsize;
2159 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2160 sh_audio->a_out_buffer_len);
2161 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2163 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2164 // Sanity check to avoid hanging in case current ao doesn't output
2165 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2166 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2167 sh_audio->a_out_buffer_len = 0;
2170 return 1;
2173 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2174 float *aq_sleep_time)
2176 struct MPOpts *opts = &mpctx->opts;
2177 int frame_time_remaining = 0;
2178 current_module="calc_sleep_time";
2180 *time_frame -= get_relative_time(mpctx); // reset timer
2182 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2183 float delay = mpctx->audio_out->get_delay();
2184 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2186 if (autosync) {
2188 * Adjust this raw delay value by calculating the expected
2189 * delay for this frame and generating a new value which is
2190 * weighted between the two. The higher autosync is, the
2191 * closer to the delay value gets to that which "-nosound"
2192 * would have used, and the longer it will take for A/V
2193 * sync to settle at the right value (but it eventually will.)
2194 * This settling time is very short for values below 100.
2196 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2197 float difference = delay - predicted;
2198 delay = predicted + difference / (float)autosync;
2201 *time_frame = delay - mpctx->delay / opts->playback_speed;
2202 *time_frame -= mpctx->video_out->flip_queue_offset;
2204 // delay = amount of audio buffered in soundcard/driver
2205 if (delay > 0.25) delay=0.25; else
2206 if (delay < 0.10) delay=0.10;
2208 if (*time_frame > delay*0.6) {
2209 // sleep time too big - may cause audio drops (buffer underrun)
2210 frame_time_remaining = 1;
2211 *time_frame = delay*0.5;
2213 } else {
2214 // If we're lagging more than 200 ms behind the right playback rate,
2215 // don't try to "catch up".
2216 // If benchmark is set always output frames as fast as possible
2217 // without sleeping.
2218 if (*time_frame < -0.2 || benchmark)
2219 *time_frame = 0;
2220 *time_frame -= mpctx->video_out->flip_queue_offset;
2223 *aq_sleep_time += *time_frame;
2226 //============================== SLEEP: ===================================
2228 // flag 256 means: libvo driver does its timing (dvb card)
2229 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2230 *time_frame = timing_sleep(mpctx, *time_frame);
2231 *time_frame += mpctx->video_out->flip_queue_offset;
2232 return frame_time_remaining;
2235 int reinit_video_chain(struct MPContext *mpctx)
2237 struct MPOpts *opts = &mpctx->opts;
2238 sh_video_t * const sh_video = mpctx->sh_video;
2239 double ar=-1.0;
2240 //================== Init VIDEO (codec & libvo) ==========================
2241 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2242 current_module="preinit_libvo";
2244 //shouldn't we set dvideo->id=-2 when we fail?
2245 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2246 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2247 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2248 goto err_out;
2250 mpctx->initialized_flags|=INITIALIZED_VO;
2253 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2254 mpctx->sh_video->stream_aspect = ar;
2255 current_module="init_video_filters";
2257 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2258 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2260 #ifdef CONFIG_MENU
2261 if(use_menu) {
2262 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2263 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2264 if(!vf_menu) {
2265 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2266 use_menu = 0;
2269 if(vf_menu)
2270 sh_video->vfilter = vf_menu;
2271 #endif
2273 #ifdef CONFIG_ASS
2274 if(opts->ass_enabled) {
2275 int i;
2276 int insert = 1;
2277 if (opts->vf_settings)
2278 for (i = 0; opts->vf_settings[i].name; ++i)
2279 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2280 insert = 0;
2281 break;
2283 if (insert) {
2284 extern vf_info_t vf_info_ass;
2285 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2286 char* vf_arg[] = {"auto", "1", NULL};
2287 int retcode = 0;
2288 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2289 sh_video->vfilter,
2290 "ass", vf_arg,
2291 &retcode);
2292 if (vf_ass)
2293 sh_video->vfilter = vf_ass;
2294 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2295 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2296 else
2297 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2300 #endif
2302 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2304 #ifdef CONFIG_ASS
2305 if (opts->ass_enabled)
2306 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2307 #endif
2309 current_module="init_video_codec";
2311 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2312 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2313 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2315 if(!sh_video->initialized){
2316 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2317 goto err_out;
2320 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2322 if (sh_video->codec)
2323 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2325 sh_video->last_pts = MP_NOPTS_VALUE;
2326 sh_video->num_buffered_pts = 0;
2327 sh_video->next_frame_time = 0;
2329 if(auto_quality>0){
2330 // Auto quality option enabled
2331 output_quality=get_video_quality_max(sh_video);
2332 if(auto_quality>output_quality) auto_quality=output_quality;
2333 else output_quality=auto_quality;
2334 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2335 set_video_quality(sh_video,output_quality);
2338 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2340 current_module="init_vo";
2342 return 1;
2344 err_out:
2345 mpctx->sh_video = mpctx->d_video->sh = NULL;
2346 return 0;
2349 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2351 struct sh_video *sh_video = mpctx->sh_video;
2352 double frame_time = 0;
2353 struct vo *video_out = mpctx->video_out;
2354 while (!video_out->frame_loaded) {
2355 current_module = "filter_video";
2356 // In nocorrect-pts mode there is no way to properly time these frames
2357 if (vo_get_buffered_frame(video_out, 0) >= 0)
2358 break;
2359 if (vf_output_queued_frame(sh_video->vfilter))
2360 continue;
2361 unsigned char *packet = NULL;
2362 frame_time = sh_video->next_frame_time;
2363 if (mpctx->update_video_immediately)
2364 frame_time = 0;
2365 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2366 &packet, force_fps);
2367 if (in_size < 0) {
2368 #ifdef CONFIG_DVDNAV
2369 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2370 if (mp_dvdnav_is_eof(mpctx->stream))
2371 return -1;
2372 if (mpctx->d_video)
2373 mpctx->d_video->eof = 0;
2374 if (mpctx->d_audio)
2375 mpctx->d_audio->eof = 0;
2376 mpctx->stream->eof = 0;
2377 } else
2378 #endif
2379 return -1;
2381 if (in_size > max_framesize)
2382 max_framesize = in_size;
2383 sh_video->timer += frame_time;
2384 if (mpctx->sh_audio)
2385 mpctx->delay -= frame_time;
2386 // video_read_frame can change fps (e.g. for ASF video)
2387 vo_fps = sh_video->fps;
2388 int framedrop_type = check_framedrop(mpctx, frame_time);
2389 current_module = "decode video";
2391 void *decoded_frame;
2392 #ifdef CONFIG_DVDNAV
2393 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2394 if (in_size >= 0 && !decoded_frame)
2395 #endif
2396 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2397 sh_video->pts);
2398 #ifdef CONFIG_DVDNAV
2399 // Save last still frame for future display
2400 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2401 #endif
2402 if (decoded_frame) {
2403 current_module = "filter video";
2404 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2405 if (!video_out->config_ok)
2406 break;
2409 return frame_time;
2412 static void determine_frame_pts(struct MPContext *mpctx)
2414 struct sh_video *sh_video = mpctx->sh_video;
2415 struct MPOpts *opts = &mpctx->opts;
2417 if (opts->user_pts_assoc_mode) {
2418 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2419 } else if (sh_video->pts_assoc_mode == 0) {
2420 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2421 sh_video->pts_assoc_mode = 1;
2422 else
2423 sh_video->pts_assoc_mode = 2;
2424 } else {
2425 int probcount1 = sh_video->num_reordered_pts_problems;
2426 int probcount2 = sh_video->num_sorted_pts_problems;
2427 if (sh_video->pts_assoc_mode == 2) {
2428 int tmp = probcount1;
2429 probcount1 = probcount2;
2430 probcount2 = tmp;
2432 if (probcount1 >= probcount2 * 1.5 + 2) {
2433 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2434 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2435 "%d.\n", sh_video->pts_assoc_mode);
2438 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2439 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2442 static double update_video(struct MPContext *mpctx)
2444 struct sh_video *sh_video = mpctx->sh_video;
2445 struct vo *video_out = mpctx->video_out;
2446 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2447 mpctx->osd); // hack for vf_expand
2448 if (!mpctx->opts.correct_pts)
2449 return update_video_nocorrect_pts(mpctx);
2451 double pts;
2453 bool hit_eof = false;
2454 while (!video_out->frame_loaded) {
2455 current_module = "filter_video";
2456 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2457 break;
2458 // XXX Time used in this call is not counted in any performance
2459 // timer now, OSD time is not updated correctly for filter-added frames
2460 if (vf_output_queued_frame(sh_video->vfilter))
2461 continue;
2462 if (hit_eof)
2463 return -1;
2464 unsigned char *packet = NULL;
2465 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2466 if (pts != MP_NOPTS_VALUE)
2467 pts += mpctx->video_offset;
2468 if (in_size < 0) {
2469 // try to extract last frames in case of decoder lag
2470 in_size = 0;
2471 pts = MP_NOPTS_VALUE;
2472 hit_eof = true;
2474 if (in_size > max_framesize)
2475 max_framesize = in_size;
2476 current_module = "decode video";
2477 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2478 void *decoded_frame = decode_video(sh_video, packet, in_size,
2479 framedrop_type, pts);
2480 if (decoded_frame) {
2481 determine_frame_pts(mpctx);
2482 current_module = "filter video";
2483 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2484 if (!video_out->config_ok)
2485 break; // We'd likely hang in this loop otherwise
2489 pts = video_out->next_pts;
2490 if (pts == MP_NOPTS_VALUE) {
2491 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2492 // Try to use decoder pts from before filters
2493 pts = sh_video->pts;
2494 if (pts == MP_NOPTS_VALUE)
2495 pts = sh_video->last_pts;
2497 sh_video->pts = pts;
2498 if (sh_video->last_pts == MP_NOPTS_VALUE)
2499 sh_video->last_pts = sh_video->pts;
2500 else if (sh_video->last_pts > sh_video->pts) {
2501 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2502 sh_video->pts, sh_video->last_pts);
2503 /* If the difference in pts is small treat it as jitter around the
2504 * right value (possibly caused by incorrect timestamp ordering) and
2505 * just show this frame immediately after the last one.
2506 * Treat bigger differences as timestamp resets and start counting
2507 * timing of later frames from the position of this one. */
2508 if (sh_video->last_pts - sh_video->pts > 0.5)
2509 sh_video->last_pts = sh_video->pts;
2510 else
2511 sh_video->pts = sh_video->last_pts;
2513 double frame_time = sh_video->pts - sh_video->last_pts;
2514 sh_video->last_pts = sh_video->pts;
2515 sh_video->timer += frame_time;
2516 if (mpctx->sh_audio)
2517 mpctx->delay -= frame_time;
2518 return frame_time;
2521 void pause_player(struct MPContext *mpctx)
2523 if (mpctx->paused)
2524 return;
2525 mpctx->paused = 1;
2526 mpctx->step_frames = 0;
2527 mpctx->time_frame -= get_relative_time(mpctx);
2529 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2530 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2532 if (mpctx->audio_out && mpctx->sh_audio)
2533 mpctx->audio_out->pause(); // pause audio, keep data if possible
2536 void unpause_player(struct MPContext *mpctx)
2538 if (!mpctx->paused)
2539 return;
2540 mpctx->paused = 0;
2542 if (mpctx->audio_out && mpctx->sh_audio)
2543 mpctx->audio_out->resume(); // resume audio
2544 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2545 && !mpctx->step_frames)
2546 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2547 (void)get_relative_time(mpctx); // ignore time that passed during pause
2550 void add_step_frame(struct MPContext *mpctx)
2552 mpctx->step_frames++;
2553 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2554 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2555 unpause_player(mpctx);
2558 static void pause_loop(struct MPContext *mpctx)
2560 mp_cmd_t* cmd;
2561 if (!quiet) {
2562 // Small hack to display the pause message on the OSD line.
2563 // The pause string is: "\n == PAUSE == \r" so we need to
2564 // take the first and the last char out
2565 if (term_osd && !mpctx->sh_video) {
2566 char msg[128] = _("\n ===== PAUSE =====\r");
2567 int mlen = strlen(msg);
2568 msg[mlen-1] = '\0';
2569 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2570 update_osd_msg(mpctx);
2571 } else
2572 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2573 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2576 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2577 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2578 if (cmd) {
2579 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2580 run_command(mpctx, cmd);
2581 mp_cmd_free(cmd);
2582 continue;
2584 if (mpctx->sh_video && mpctx->video_out)
2585 vo_check_events(mpctx->video_out);
2586 #ifdef CONFIG_MENU
2587 if (vf_menu)
2588 vf_menu_pause_update(vf_menu);
2589 #endif
2590 usec_sleep(20000);
2591 update_osd_msg(mpctx);
2592 int hack = vo_osd_changed(0);
2593 vo_osd_changed(hack);
2594 if (hack)
2595 break;
2600 // Find the right mute status and record position for new file position
2601 static void edl_seek_reset(MPContext *mpctx)
2603 mpctx->edl_muted = 0;
2604 next_edl_record = edl_records;
2606 while (next_edl_record) {
2607 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2608 break;
2610 if (next_edl_record->action == EDL_MUTE)
2611 mpctx->edl_muted = !mpctx->edl_muted;
2612 next_edl_record = next_edl_record->next;
2614 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2615 mixer_mute(&mpctx->mixer);
2619 // Execute EDL command for the current position if one exists
2620 static void edl_update(MPContext *mpctx)
2622 if (!next_edl_record)
2623 return;
2625 if (!mpctx->sh_video) {
2626 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2627 free_edl(edl_records);
2628 next_edl_record = NULL;
2629 edl_records = NULL;
2630 return;
2633 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2634 if (next_edl_record->action == EDL_SKIP) {
2635 mpctx->osd_function = OSD_FFW;
2636 mpctx->abs_seek_pos = 0;
2637 mpctx->rel_seek_secs = next_edl_record->length_sec;
2638 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2639 "[%f], length [%f]\n", next_edl_record->start_sec,
2640 next_edl_record->stop_sec, next_edl_record->length_sec);
2642 else if (next_edl_record->action == EDL_MUTE) {
2643 mpctx->edl_muted = !mpctx->edl_muted;
2644 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2645 mixer_mute(&mpctx->mixer);
2646 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2647 next_edl_record->start_sec );
2649 next_edl_record = next_edl_record->next;
2653 static void reinit_decoders(struct MPContext *mpctx)
2655 reinit_video_chain(mpctx);
2656 reinit_audio_chain(mpctx);
2657 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2660 static void seek_reset(struct MPContext *mpctx)
2662 if (mpctx->sh_video) {
2663 current_module = "seek_video_reset";
2664 resync_video_stream(mpctx->sh_video);
2665 mpctx->sh_video->timer = 0;
2666 vo_seek_reset(mpctx->video_out);
2667 mpctx->sh_video->timer = 0;
2668 mpctx->sh_video->num_buffered_pts = 0;
2669 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2670 mpctx->delay = 0;
2671 mpctx->time_frame = 0;
2672 mpctx->update_video_immediately = true;
2673 // Not all demuxers set d_video->pts during seek, so this value
2674 // (which is used by at least vobsub and edl code below) may
2675 // be completely wrong (probably 0).
2676 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2677 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2678 mpctx->sh_video->pts, mpctx->video_offset,
2679 mpctx->d_sub, 1);
2680 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2683 if (mpctx->sh_audio) {
2684 current_module = "seek_audio_reset";
2685 resync_audio_stream(mpctx->sh_audio);
2686 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2687 mpctx->sh_audio->a_buffer_len = 0;
2688 mpctx->sh_audio->a_out_buffer_len = 0;
2689 if (!mpctx->sh_video)
2690 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2691 mpctx->video_offset, mpctx->d_sub, 1);
2694 if (vo_vobsub && mpctx->sh_video) {
2695 current_module = "seek_vobsub_reset";
2696 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2699 edl_seek_reset(mpctx);
2701 mpctx->total_avsync_change = 0;
2702 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2703 drop_frame_cnt = 0;
2705 current_module = NULL;
2708 static bool timeline_set_part(struct MPContext *mpctx, int i)
2710 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2711 struct timeline_part *n = mpctx->timeline + i;
2712 mpctx->timeline_part = i;
2713 mpctx->video_offset = n->start - n->source_start;
2714 if (n->source == p->source)
2715 return false;
2716 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2717 mpctx->demuxer = n->source->demuxer;
2718 mpctx->d_video = mpctx->demuxer->video;
2719 mpctx->d_audio = mpctx->demuxer->audio;
2720 mpctx->d_sub = mpctx->demuxer->sub;
2721 mpctx->sh_video = mpctx->d_video->sh;
2722 mpctx->sh_audio = mpctx->d_audio->sh;
2723 return true;
2726 // Given pts, switch playback to the corresponding part.
2727 // Return offset within that part.
2728 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2729 bool *need_reset)
2731 if (pts < 0)
2732 pts = 0;
2733 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2734 struct timeline_part *p = mpctx->timeline + i;
2735 if (pts < (p+1)->start) {
2736 *need_reset = timeline_set_part(mpctx, i);
2737 return pts - p->start + p->source_start;
2740 return -1;
2744 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2745 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2746 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2747 static int seek(MPContext *mpctx, double amount, int style)
2749 current_module = "seek";
2750 if (mpctx->stop_play == AT_END_OF_FILE)
2751 mpctx->stop_play = KEEP_PLAYING;
2752 if (style & SEEK_FACTOR
2753 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2754 || amount < 0)
2755 mpctx->last_chapter_seek = -1;
2756 if (mpctx->timeline && style & SEEK_FACTOR) {
2757 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2758 style &= ~SEEK_FACTOR;
2760 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2761 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2762 style |= SEEK_ABSOLUTE;
2763 if (amount > 0)
2764 style |= SEEK_FORWARD;
2765 else
2766 style |= SEEK_BACKWARD;
2767 amount += mpctx->sh_video->pts;
2770 /* At least the liba52 decoder wants to read from the input stream
2771 * during initialization, so reinit must be done after the demux_seek()
2772 * call that clears possible stream EOF. */
2773 bool need_reset = false;
2774 if (mpctx->timeline) {
2775 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2776 if (amount == -1) {
2777 mpctx->stop_play = AT_END_OF_FILE;
2778 // Clear audio from current position
2779 if (mpctx->sh_audio) {
2780 mpctx->audio_out->reset();
2781 mpctx->sh_audio->a_buffer_len = 0;
2782 mpctx->sh_audio->a_out_buffer_len = 0;
2784 return -1;
2787 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2788 if (need_reset)
2789 reinit_decoders(mpctx);
2790 if (seekresult == 0)
2791 return -1;
2793 seek_reset(mpctx);
2794 return 0;
2797 // -2 is no chapters, -1 is before first chapter
2798 int get_current_chapter(struct MPContext *mpctx)
2800 if (!mpctx->chapters || !mpctx->sh_video)
2801 return FFMAX(mpctx->last_chapter_seek,
2802 demuxer_get_current_chapter(mpctx->demuxer));
2804 int i;
2805 double current_pts = mpctx->sh_video->pts;
2806 for (i = 1; i < mpctx->num_chapters; i++)
2807 if (current_pts < mpctx->chapters[i].start)
2808 break;
2809 return FFMAX(mpctx->last_chapter_seek, i - 1);
2812 // currently returns a string allocated with malloc, not talloc
2813 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2815 if (!mpctx->chapters || !mpctx->sh_video)
2816 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2817 return strdup(mpctx->chapters[chapter].name);
2820 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2821 char **chapter_name)
2823 mpctx->last_chapter_seek = -1;
2824 if (!mpctx->chapters || !mpctx->sh_video) {
2825 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2826 chapter_name);
2827 if (res >= 0) {
2828 if (*seek_pts == -1)
2829 seek_reset(mpctx);
2830 else {
2831 mpctx->last_chapter_seek = res;
2832 mpctx->last_chapter_pts = *seek_pts;
2835 return res;
2838 if (chapter >= mpctx->num_chapters)
2839 return -1;
2840 if (chapter < 0)
2841 chapter = 0;
2842 *seek_pts = mpctx->chapters[chapter].start;
2843 mpctx->last_chapter_seek = chapter;
2844 mpctx->last_chapter_pts = *seek_pts;
2845 if (chapter_name)
2846 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2847 return chapter;
2850 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2851 struct content_source *sources,
2852 int num_sources,
2853 unsigned char uid_map[][16])
2855 int num_filenames = 0;
2856 char **filenames = NULL;
2857 if (num_sources > 1) {
2858 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2859 "other sources.\n");
2860 if (mpctx->stream->type != STREAMTYPE_FILE) {
2861 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2862 "normal disk file. Will not search for related files.\n");
2863 } else {
2864 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2865 "same directory to find referenced sources.\n");
2866 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2867 &num_filenames);
2871 int num_left = num_sources - 1;
2872 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2873 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2874 filename_recode(filenames[i]));
2875 int format;
2876 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2877 if (!s)
2878 continue;
2879 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2880 mpctx->opts.audio_id,
2881 mpctx->opts.video_id,
2882 mpctx->opts.sub_id, filenames[i]);
2883 if (!d) {
2884 free_stream(s);
2885 continue;
2887 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2888 for (int i = 1; i < num_sources; i++) {
2889 if (sources[i].demuxer)
2890 continue;
2891 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2892 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2893 i, filename_recode(d->filename));
2894 sources[i].stream = s;
2895 sources[i].demuxer = d;
2896 num_left--;
2897 goto match;
2901 free_demuxer(d);
2902 free_stream(s);
2903 continue;
2904 match:
2907 talloc_free(filenames);
2908 if (num_left) {
2909 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2910 "There will be parts MISSING from the video!\n");
2911 for (int i = 1, j = 1; i < num_sources; i++)
2912 if (sources[i].demuxer) {
2913 sources[j] = sources[i];
2914 memcpy(uid_map[j], uid_map[i], 16);
2915 j++;
2918 return num_sources - num_left;
2921 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2923 if (!mpctx->opts.ordered_chapters) {
2924 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
2925 "you have disabled support for them. Ignoring.\n");
2926 return;
2929 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
2930 "edit timeline.\n");
2932 struct demuxer *demuxer = mpctx->demuxer;
2933 struct matroska_data *m = &demuxer->matroska_data;
2935 // +1 because sources/uid_map[0] is original file even if all chapters
2936 // actually use other sources and need separate entries
2937 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
2938 m->num_ordered_chapters+1);
2939 sources[0].stream = mpctx->stream;
2940 sources[0].demuxer = mpctx->demuxer;
2941 unsigned char uid_map[m->num_ordered_chapters+1][16];
2942 int num_sources = 1;
2943 memcpy(uid_map[0], m->segment_uid, 16);
2945 for (int i = 0; i < m->num_ordered_chapters; i++) {
2946 struct matroska_chapter *c = m->ordered_chapters + i;
2947 if (!c->has_segment_uid)
2948 memcpy(c->segment_uid, m->segment_uid, 16);
2950 for (int j = 0; j < num_sources; j++)
2951 if (!memcmp(c->segment_uid, uid_map[j], 16))
2952 goto found1;
2953 memcpy(uid_map[num_sources], c->segment_uid, 16);
2954 sources[num_sources] = (struct content_source){};
2955 num_sources++;
2956 found1:
2960 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
2961 uid_map);
2964 // +1 for terminating chapter with start time marking end of last real one
2965 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
2966 m->num_ordered_chapters + 1);
2967 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
2968 m->num_ordered_chapters);
2969 uint64_t starttime = 0;
2970 uint64_t missing_time = 0;
2971 int part_count = 0;
2972 int num_chapters = 0;
2973 uint64_t prev_part_offset = 0;
2974 for (int i = 0; i < m->num_ordered_chapters; i++) {
2975 struct matroska_chapter *c = m->ordered_chapters + i;
2977 int j;
2978 for (j = 0; j < num_sources; j++) {
2979 if (!memcmp(c->segment_uid, uid_map[j], 16))
2980 goto found2;
2982 missing_time += c->end - c->start;
2983 continue;
2984 found2:;
2985 chapters[num_chapters].start = starttime / 1000.;
2986 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
2987 /* Only add a separate part if the time or file actually changes.
2988 * Matroska files have chapter divisions that are redundant from
2989 * timeline point of view because the same chapter structure is used
2990 * both to specify the timeline and for normal chapter information.
2991 * Removing a missing inserted external chapter can also cause this. */
2992 if (part_count == 0 || c->start != starttime + prev_part_offset
2993 || sources + j != timeline[part_count - 1].source) {
2994 timeline[part_count].source = sources + j;
2995 timeline[part_count].start = chapters[num_chapters].start;
2996 timeline[part_count].source_start = c->start / 1000.;
2997 prev_part_offset = c->start - starttime;
2998 part_count++;
3000 starttime += c->end - c->start;
3001 num_chapters++;
3003 timeline[part_count].start = starttime / 1000.;
3005 if (!part_count) {
3006 // None of the parts come from the file itself???
3007 talloc_free(sources);
3008 talloc_free(timeline);
3009 talloc_free(chapters);
3010 return;
3013 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3014 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3015 timeline[part_count].start);
3016 if (missing_time)
3017 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3018 "from the timeline!\n", missing_time / 1000.);
3019 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3020 for (int i = 0; i < num_sources; i++)
3021 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3022 filename_recode(sources[i].demuxer->filename));
3023 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3024 "source_start, source):\n");
3025 for (int i = 0; i < part_count; i++) {
3026 struct timeline_part *p = timeline + i;
3027 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3028 p->source_start, p->source - sources);
3030 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3031 mpctx->sources = sources;
3032 mpctx->num_sources = num_sources;
3033 mpctx->timeline = timeline;
3034 mpctx->num_timeline_parts = part_count;
3035 mpctx->num_chapters = num_chapters;
3036 mpctx->chapters = chapters;
3038 mpctx->timeline_part = 0;
3039 mpctx->demuxer = timeline[0].source->demuxer;
3043 static int read_keys(void *ctx, int fd)
3045 getch2(ctx);
3046 return mplayer_get_key(ctx, 0);
3050 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3051 * file for some tools to link against. */
3052 #ifndef DISABLE_MAIN
3053 int main(int argc,char* argv[]){
3056 char * mem_ptr;
3058 // movie info:
3060 /* Flag indicating whether MPlayer should exit without playing anything. */
3061 int opt_exit = 0;
3063 //float a_frame=0; // Audio
3065 int i;
3067 struct MPContext *mpctx = &(struct MPContext){
3068 .osd_function = OSD_PLAY,
3069 .begin_skip = MP_NOPTS_VALUE,
3070 .play_tree_step = 1,
3071 .global_sub_pos = -1,
3072 .set_of_sub_pos = -1,
3073 .file_format = DEMUXER_TYPE_UNKNOWN,
3074 .last_dvb_step = 1,
3077 InitTimer();
3078 srand(GetTimerMS());
3080 mp_msg_init();
3081 set_av_log_callback();
3083 #ifdef CONFIG_X11
3084 mpctx->x11_state = vo_x11_init_state();
3085 #endif
3086 struct MPOpts *opts = &mpctx->opts;
3087 set_default_mplayer_options(opts);
3088 // Create the config context and register the options
3089 mpctx->mconfig = m_config_new(opts, cfg_include);
3090 m_config_register_options(mpctx->mconfig,mplayer_opts);
3091 mp_input_register_options(mpctx->mconfig);
3093 // Preparse the command line
3094 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3096 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3097 set_path_env();
3098 #endif
3100 #ifdef CONFIG_TV
3101 stream_tv_defaults.immediate = 1;
3102 #endif
3104 parse_cfgfiles(mpctx, mpctx->mconfig);
3106 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3107 if(mpctx->playtree == NULL)
3108 opt_exit = 1;
3109 else {
3110 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3111 if(mpctx->playtree) {
3112 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3113 if(mpctx->playtree_iter) {
3114 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3115 play_tree_iter_free(mpctx->playtree_iter);
3116 mpctx->playtree_iter = NULL;
3118 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3122 mpctx->key_fifo = mp_fifo_create(opts);
3124 print_version("MPlayer");
3126 #if defined(__MINGW32__) || defined(__CYGWIN__)
3128 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3129 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3130 if (kernel32)
3131 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3132 if (setDEP) setDEP(3);
3134 // stop Windows from showing all kinds of annoying error dialogs
3135 SetErrorMode(0x8003);
3136 // request 1ms timer resolution
3137 timeBeginPeriod(1);
3138 #endif
3140 #ifdef CONFIG_PRIORITY
3141 set_priority();
3142 #endif
3144 if (codec_path)
3145 set_codec_path(codec_path);
3147 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3148 list_video_out();
3149 opt_exit = 1;
3152 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3153 list_audio_out();
3154 opt_exit = 1;
3157 /* Check codecs.conf. */
3158 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3159 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3160 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3161 if(!parse_codec_cfg(NULL)){
3162 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3164 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3167 free( mem_ptr ); // release the buffer created by get_path()
3170 #if 0
3171 if(video_codec_list){
3172 int i;
3173 video_codec=video_codec_list[0];
3174 for(i=0;video_codec_list[i];i++)
3175 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
3177 #endif
3178 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3179 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3180 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3181 list_codecs(1);
3182 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3183 opt_exit = 1;
3185 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3186 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3187 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3188 list_codecs(0);
3189 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3190 opt_exit = 1;
3192 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3193 vfm_help();
3194 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3195 opt_exit = 1;
3197 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3198 afm_help();
3199 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3200 opt_exit = 1;
3202 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3203 af_help();
3204 printf("\n");
3205 opt_exit = 1;
3207 #ifdef CONFIG_X11
3208 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3209 fstype_help();
3210 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3211 opt_exit = 1;
3213 #endif
3214 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3215 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3216 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3217 demuxer_help();
3218 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3219 opt_exit = 1;
3221 if(list_properties) {
3222 property_print_help();
3223 opt_exit = 1;
3226 if(opt_exit)
3227 exit_player(mpctx, EXIT_NONE);
3229 if(!mpctx->filename && !player_idle_mode){
3230 // no file/vcd/dvd -> show HELP:
3231 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3232 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3235 /* Display what configure line was used */
3236 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3238 // Many users forget to include command line in bugreports...
3239 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3240 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3241 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3242 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3245 //------ load global data first ------
3247 mpctx->osd = osd_create();
3249 // check font
3250 #ifdef CONFIG_FREETYPE
3251 init_freetype();
3252 #endif
3253 #ifdef CONFIG_FONTCONFIG
3254 if(font_fontconfig <= 0)
3256 #endif
3257 #ifdef CONFIG_BITMAP_FONT
3258 if(font_name){
3259 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3260 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3261 filename_recode(font_name));
3262 } else {
3263 // try default:
3264 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3265 free(mem_ptr); // release the buffer created by get_path()
3266 if(!vo_font)
3267 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3269 if (sub_font_name)
3270 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3271 else
3272 mpctx->osd->sub_font = vo_font;
3273 #endif
3274 #ifdef CONFIG_FONTCONFIG
3276 #endif
3278 #ifdef CONFIG_ASS
3279 ass_library = ass_init();
3280 #endif
3282 #ifdef HAVE_RTC
3283 if(!nortc)
3285 // seteuid(0); /* Can't hurt to try to get root here */
3286 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3287 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3288 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3289 else {
3290 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3292 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3293 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3294 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3295 close (rtc_fd);
3296 rtc_fd = -1;
3297 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3298 /* variable only by the root */
3299 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3300 close (rtc_fd);
3301 rtc_fd = -1;
3302 } else
3303 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3306 if(rtc_fd<0)
3307 #endif /* HAVE_RTC */
3308 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3309 softsleep?"software":timer_name);
3311 #ifdef HAVE_TERMCAP
3312 load_termcap(NULL); // load key-codes
3313 #endif
3315 // ========== Init keyboard FIFO (connection to libvo) ============
3317 // Init input system
3318 current_module = "init_input";
3319 mpctx->input = mp_input_init(&opts->input);
3320 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3321 if(slave_mode)
3322 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3323 else if(!noconsolecontrols)
3324 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3325 // Set the libstream interrupt callback
3326 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3328 #ifdef CONFIG_MENU
3329 if(use_menu) {
3330 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3331 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3332 else {
3333 menu_cfg = get_path("menu.conf");
3334 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3335 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3336 else {
3337 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3338 MPLAYER_CONFDIR "/menu.conf"))
3339 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3340 else {
3341 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3342 use_menu = 0;
3347 #endif
3349 current_module = NULL;
3351 /// Catch signals
3352 #ifndef __MINGW32__
3353 signal(SIGCHLD,child_sighandler);
3354 #endif
3356 #ifdef CONFIG_CRASH_DEBUG
3357 prog_path = argv[0];
3358 #endif
3359 //========= Catch terminate signals: ================
3360 // terminate requests:
3361 signal(SIGTERM,exit_sighandler); // kill
3362 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3364 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3366 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3367 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3368 #ifdef CONFIG_SIGHANDLER
3369 // fatal errors:
3370 signal(SIGBUS,exit_sighandler); // bus error
3371 signal(SIGSEGV,exit_sighandler); // segfault
3372 signal(SIGILL,exit_sighandler); // illegal instruction
3373 signal(SIGFPE,exit_sighandler); // floating point exc.
3374 signal(SIGABRT,exit_sighandler); // abort()
3375 #ifdef CONFIG_CRASH_DEBUG
3376 if (crash_debug)
3377 signal(SIGTRAP,exit_sighandler);
3378 #endif
3379 #endif
3381 // ******************* Now, let's see the per-file stuff ********************
3383 play_next_file:
3385 // init global sub numbers
3386 mpctx->global_sub_size = 0;
3387 { int i; for (i = 0; i < SUB_SOURCES; i++) mpctx->global_sub_indices[i] = -1; }
3389 if (mpctx->filename) {
3390 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3391 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3392 load_per_file_config (mpctx->mconfig, mpctx->filename);
3395 if (opts->video_driver_list)
3396 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3397 if (opts->audio_driver_list)
3398 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3400 // We must enable getch2 here to be able to interrupt network connection
3401 // or cache filling
3402 if(!noconsolecontrols && !slave_mode){
3403 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3404 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3405 else
3406 getch2_enable(); // prepare stdin for hotkeys...
3407 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3408 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3411 // =================== GUI idle loop (STOP state) ===========================
3412 while (player_idle_mode && !mpctx->filename) {
3413 play_tree_t * entry = NULL;
3414 mp_cmd_t * cmd;
3415 if (mpctx->video_out && mpctx->video_out->config_ok)
3416 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3417 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3418 if (mpctx->video_out)
3419 vo_check_events(mpctx->video_out);
3420 usec_sleep(20000);
3422 switch (cmd->id) {
3423 case MP_CMD_LOADFILE:
3424 // prepare a tree entry with the new filename
3425 entry = play_tree_new();
3426 play_tree_add_file(entry, cmd->args[0].v.s);
3427 // The entry is added to the main playtree after the switch().
3428 break;
3429 case MP_CMD_LOADLIST:
3430 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3431 break;
3432 case MP_CMD_QUIT:
3433 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3434 break;
3435 case MP_CMD_GET_PROPERTY:
3436 case MP_CMD_SET_PROPERTY:
3437 case MP_CMD_STEP_PROPERTY:
3438 run_command(mpctx, cmd);
3439 break;
3442 mp_cmd_free(cmd);
3444 if (entry) { // user entered a command that gave a valid entry
3445 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3446 play_tree_free_list(mpctx->playtree->child, 1);
3447 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3449 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3451 play_tree_set_child(mpctx->playtree, entry);
3453 /* Make iterator start at the top the of tree. */
3454 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3455 if (!mpctx->playtree_iter) continue;
3457 // find the first real item in the tree
3458 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3459 // no items!
3460 play_tree_iter_free(mpctx->playtree_iter);
3461 mpctx->playtree_iter = NULL;
3462 continue; // wait for next command
3464 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3467 //---------------------------------------------------------------------------
3469 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3470 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3472 if (mpctx->filename) {
3473 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3474 filename_recode(mpctx->filename));
3475 if(use_filename_title && vo_wintitle == NULL)
3476 vo_wintitle = strdup(mp_basename2(mpctx->filename));
3479 if (edl_filename) {
3480 if (edl_records) free_edl(edl_records);
3481 next_edl_record = edl_records = edl_parse_file();
3483 if (edl_output_filename) {
3484 if (edl_fd) fclose(edl_fd);
3485 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3487 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3488 filename_recode(edl_output_filename));
3492 //==================== Open VOB-Sub ============================
3494 current_module="vobsub";
3495 if (vobsub_name){
3496 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3497 if(vo_vobsub==NULL)
3498 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3499 filename_recode(vobsub_name));
3500 } else if (sub_auto && mpctx->filename){
3501 /* try to autodetect vobsub from movie filename ::atmos */
3502 char *buf = strdup(mpctx->filename), *psub;
3503 char *pdot = strrchr(buf, '.');
3504 char *pslash = strrchr(buf, '/');
3505 #if defined(__MINGW32__) || defined(__CYGWIN__)
3506 if (!pslash) pslash = strrchr(buf, '\\');
3507 #endif
3508 if (pdot && (!pslash || pdot > pslash))
3509 *pdot = '\0';
3510 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3511 /* try from ~/.mplayer/sub */
3512 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3513 char *bname;
3514 int l;
3515 bname = strrchr(buf,'/');
3516 #if defined(__MINGW32__) || defined(__CYGWIN__)
3517 if(!bname) bname = strrchr(buf,'\\');
3518 #endif
3519 if(bname) bname++;
3520 else bname = buf;
3521 l = strlen(psub) + strlen(bname) + 1;
3522 psub = realloc(psub,l);
3523 strcat(psub,bname);
3524 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3525 free(psub);
3527 free(buf);
3529 if(vo_vobsub){
3530 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3531 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3532 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3534 // setup global sub numbering
3535 mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] = mpctx->global_sub_size; // the global # of the first vobsub.
3536 mpctx->global_sub_size += vobsub_get_indexes_count(vo_vobsub);
3539 //============ Open & Sync STREAM --- fork cache2 ====================
3541 mpctx->stream=NULL;
3542 mpctx->demuxer=NULL;
3543 if (mpctx->d_audio) {
3544 //free_demuxer_stream(mpctx->d_audio);
3545 mpctx->d_audio=NULL;
3547 if (mpctx->d_video) {
3548 //free_demuxer_stream(d_video);
3549 mpctx->d_video=NULL;
3551 mpctx->sh_audio=NULL;
3552 mpctx->sh_video=NULL;
3554 current_module="open_stream";
3555 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3556 if(!mpctx->stream) { // error...
3557 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3558 goto goto_next_file;
3560 mpctx->initialized_flags|=INITIALIZED_STREAM;
3562 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3563 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3564 "playlist support will not be used automatically.\n"
3565 "MPlayer's playlist code is unsafe and should only be used with "
3566 "trusted sources.\nPlayback will probably fail.\n\n");
3567 #if 0
3568 play_tree_t* entry;
3569 // Handle playlist
3570 current_module="handle_playlist";
3571 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3572 filename_recode(mpctx->filename));
3573 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3574 mpctx->eof=playtree_add_playlist(mpctx, entry);
3575 goto goto_next_file;
3576 #endif
3578 mpctx->stream->start_pos+=seek_to_byte;
3580 if(stream_dump_type==5){
3581 unsigned char buf[4096];
3582 int len;
3583 FILE *f;
3584 current_module="dumpstream";
3585 stream_reset(mpctx->stream);
3586 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3587 f=fopen(stream_dump_name,"wb");
3588 if(!f){
3589 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3590 exit_player(mpctx, EXIT_ERROR);
3592 if (opts->chapterrange[0] > 1) {
3593 int chapter = opts->chapterrange[0] - 1;
3594 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3596 while(!mpctx->stream->eof && !async_quit_request){
3597 len=stream_read(mpctx->stream,buf,4096);
3598 if(len>0) {
3599 if(fwrite(buf,len,1,f) != 1) {
3600 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3601 exit_player(mpctx, EXIT_ERROR);
3604 if (opts->chapterrange[1] > 0) {
3605 int chapter = -1;
3606 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3607 &chapter) == STREAM_OK
3608 && chapter + 1 > opts->chapterrange[1])
3609 break;
3612 if(fclose(f)) {
3613 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3614 exit_player(mpctx, EXIT_ERROR);
3616 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3617 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3620 #ifdef CONFIG_DVDREAD
3621 if(mpctx->stream->type==STREAMTYPE_DVD){
3622 current_module="dvd lang->id";
3623 if(opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3624 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3625 // setup global sub numbering
3626 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3627 mpctx->global_sub_size += dvd_number_of_subs(mpctx->stream);
3628 current_module=NULL;
3630 #endif
3632 #ifdef CONFIG_DVDNAV
3633 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3634 current_module="dvdnav lang->id";
3635 if(opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3636 dvdsub_lang_id = -3;
3637 if(opts->sub_lang && opts->sub_id==-1)
3638 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3639 // setup global sub numbering
3640 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3641 mpctx->global_sub_size += mp_dvdnav_number_of_subs(mpctx->stream);
3642 current_module=NULL;
3644 #endif
3646 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3647 goto_enable_cache:
3648 if(stream_cache_size>0){
3649 int res;
3650 current_module="enable_cache";
3651 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3652 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3653 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3654 if(res == 0)
3655 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3658 //============ Open DEMUXERS --- DETECT file type =======================
3659 current_module="demux_open";
3661 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3663 // HACK to get MOV Reference Files working
3665 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3667 unsigned char* playlist_entry;
3668 play_tree_t *list = NULL, *entry = NULL;
3670 current_module="handle_demux_playlist";
3671 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3673 char *temp, *bname;
3675 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3676 filename_recode(playlist_entry));
3678 bname=mp_basename(playlist_entry);
3679 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3680 continue;
3682 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3683 continue;
3685 entry = play_tree_new();
3687 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3689 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3690 if (temp)
3692 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3693 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3694 strcat(temp, playlist_entry);
3695 if (!strcmp(temp, mpctx->filename)) {
3696 free(temp);
3697 continue;
3699 play_tree_add_file(entry,temp);
3700 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3701 free(temp);
3704 else
3705 play_tree_add_file(entry,playlist_entry);
3707 if(!list)
3708 list = entry;
3709 else
3710 play_tree_append_entry(list,entry);
3712 free_demuxer(mpctx->demuxer);
3713 mpctx->demuxer = NULL;
3715 if (list)
3717 entry = play_tree_new();
3718 play_tree_set_child(entry,list);
3719 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3720 goto goto_next_file;
3724 if(!mpctx->demuxer)
3725 goto goto_next_file;
3727 if (mpctx->demuxer->matroska_data.ordered_chapters)
3728 build_ordered_chapter_timeline(mpctx);
3730 if (!mpctx->sources) {
3731 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3732 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3733 .demuxer = mpctx->demuxer};
3734 mpctx->num_sources = 1;
3737 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3739 if (mpctx->stream->type != STREAMTYPE_DVD && mpctx->stream->type != STREAMTYPE_DVDNAV) {
3740 int i;
3741 int maxid = -1;
3742 // setup global sub numbering
3743 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3744 for (i = 0; i < MAX_S_STREAMS; i++)
3745 if (mpctx->demuxer->s_streams[i])
3746 maxid = FFMAX(maxid, mpctx->demuxer->s_streams[i]->sid);
3747 mpctx->global_sub_size += maxid + 1;
3749 // Make opts->sub_id always selectable if set.
3750 if (mpctx->global_sub_size <= mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id)
3751 mpctx->global_sub_size = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id + 1;
3753 #ifdef CONFIG_ASS
3754 if (opts->ass_enabled && ass_library) {
3755 for (int j = 0; j < mpctx->num_sources; j++) {
3756 struct demuxer *d = mpctx->sources[j].demuxer;
3757 for (int i = 0; i < d->num_attachments; i++) {
3758 struct demux_attachment *att = d->attachments + i;
3759 if (use_embedded_fonts && attachment_is_font(att))
3760 ass_add_font(ass_library, att->name, att->data, att->data_size);
3764 #endif
3766 current_module="demux_open2";
3768 //file_format=demuxer->file_format;
3770 mpctx->d_audio=mpctx->demuxer->audio;
3771 mpctx->d_video=mpctx->demuxer->video;
3772 mpctx->d_sub=mpctx->demuxer->sub;
3774 if (ts_prog) {
3775 int tmp = ts_prog;
3776 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3778 // select audio stream
3779 if (mpctx->num_sources)
3780 for (int i = 0; i < mpctx->num_sources; i++)
3781 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3782 opts->audio_lang);
3783 else
3784 select_audio(mpctx->demuxer, opts->audio_id, opts->audio_lang);
3786 // DUMP STREAMS:
3787 if((stream_dump_type)&&(stream_dump_type<4)){
3788 FILE *f;
3789 demux_stream_t *ds=NULL;
3790 current_module="dump";
3791 // select stream to dump
3792 switch(stream_dump_type){
3793 case 1: ds=mpctx->d_audio;break;
3794 case 2: ds=mpctx->d_video;break;
3795 case 3: ds=mpctx->d_sub;break;
3797 if(!ds){
3798 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3799 exit_player(mpctx, EXIT_ERROR);
3801 // disable other streams:
3802 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3803 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3804 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3805 // let's dump it!
3806 f=fopen(stream_dump_name,"wb");
3807 if(!f){
3808 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3809 exit_player(mpctx, EXIT_ERROR);
3811 while(!ds->eof){
3812 unsigned char* start;
3813 int in_size=ds_get_packet(ds,&start);
3814 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3815 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3816 if(in_size>0) fwrite(start,in_size,1,f);
3817 if (opts->chapterrange[1] > 0) {
3818 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3819 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3820 break;
3823 fclose(f);
3824 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3825 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3828 mpctx->sh_audio=mpctx->d_audio->sh;
3829 mpctx->sh_video=mpctx->d_video->sh;
3831 if(mpctx->sh_video){
3833 current_module="video_read_properties";
3834 if(!video_read_properties(mpctx->sh_video)) {
3835 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3836 mpctx->sh_video=mpctx->d_video->sh=NULL;
3837 } else {
3838 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3839 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3840 mpctx->sh_video->fps,mpctx->sh_video->frametime
3843 /* need to set fps here for output encoders to pick it up in their init */
3844 if(force_fps){
3845 mpctx->sh_video->fps=force_fps;
3846 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3848 vo_fps = mpctx->sh_video->fps;
3850 if(!mpctx->sh_video->fps && !force_fps){
3851 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3852 mpctx->opts.correct_pts = 1;
3858 if(!mpctx->sh_video && !mpctx->sh_audio){
3859 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3860 #ifdef CONFIG_DVBIN
3861 if(mpctx->stream->type == STREAMTYPE_DVB)
3863 int dir;
3864 int v = mpctx->last_dvb_step;
3865 if(v > 0)
3866 dir = DVB_CHANNEL_HIGHER;
3867 else
3868 dir = DVB_CHANNEL_LOWER;
3870 if(dvb_step_channel(mpctx->stream, dir)) {
3871 mpctx->stop_play = PT_NEXT_ENTRY;
3872 mpctx->dvbin_reopen = 1;
3875 #endif
3876 goto goto_next_file; // exit_player(_("Fatal error"));
3879 /* display clip info */
3880 demux_info_print(mpctx->demuxer);
3882 //================== Read SUBTITLES (DVD & TEXT) ==========================
3883 if(vo_spudec==NULL &&
3884 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3885 init_vo_spudec(mpctx);
3888 // after reading video params we should load subtitles because
3889 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3890 // check .sub
3891 current_module="read_subtitles_file";
3892 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3893 if(sub_name){
3894 for (i = 0; sub_name[i] != NULL; ++i)
3895 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
3897 if(sub_auto) { // auto load sub file ...
3898 char *psub = get_path( "sub/" );
3899 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3900 int i = 0;
3901 free(psub); // release the buffer created by get_path() above
3902 while (tmp[i]) {
3903 add_subtitles(mpctx, tmp[i], sub_fps, 1);
3904 free(tmp[i++]);
3906 free(tmp);
3908 if (mpctx->set_of_sub_size > 0) {
3909 // setup global sub numbering
3910 mpctx->global_sub_indices[SUB_SOURCE_SUBS] = mpctx->global_sub_size; // the global # of the first sub.
3911 mpctx->global_sub_size += mpctx->set_of_sub_size;
3915 if (mpctx->global_sub_size) {
3916 select_subtitle(mpctx);
3917 if(subdata)
3918 switch (stream_dump_type) {
3919 case 3: list_sub_file(subdata); break;
3920 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3921 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3922 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3923 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3924 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3928 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
3929 filename_recode(mpctx->filename));
3930 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
3931 if (mpctx->sh_video) {
3932 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3933 if (mpctx->sh_video->format >= 0x20202020)
3934 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
3935 else
3936 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
3937 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
3938 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
3939 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
3940 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
3941 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
3943 if (mpctx->sh_audio) {
3944 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3945 if (mpctx->sh_audio->format >= 0x20202020)
3946 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
3947 else
3948 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
3949 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
3950 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
3951 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
3953 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", mpctx->timeline ?
3954 mpctx->timeline[mpctx->num_timeline_parts].start :
3955 demuxer_get_time_length(mpctx->demuxer));
3956 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
3957 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
3958 if (mpctx->demuxer) {
3959 if (mpctx->demuxer->num_chapters == 0)
3960 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
3961 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
3964 if(!mpctx->sh_video) goto main; // audio-only
3966 if(!reinit_video_chain(mpctx)) {
3967 if(!mpctx->sh_video){
3968 if(!mpctx->sh_audio) goto goto_next_file;
3969 goto main; // exit_player(_("Fatal error"));
3973 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
3974 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3976 #ifdef CONFIG_FREETYPE
3977 force_load_font = 1;
3978 #endif
3980 //================== MAIN: ==========================
3981 main:
3982 current_module="main";
3984 if(playing_msg) {
3985 char* msg = property_expand_string(mpctx, playing_msg);
3986 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
3987 free(msg);
3991 // Disable the term OSD in verbose mode
3992 if(verbose) term_osd = 0;
3995 //int frame_corr_num=0; //
3996 //float v_frame=0; // Video
3997 //float num_frames=0; // number of frames played
3999 int frame_time_remaining=0; // flag
4000 int blit_frame=0;
4002 // Make sure old OSD does not stay around,
4003 // e.g. with -fixed-vo and same-resolution files
4004 clear_osd_msgs();
4005 update_osd_msg(mpctx);
4007 //================ SETUP AUDIO ==========================
4009 if(mpctx->sh_audio){
4010 reinit_audio_chain(mpctx);
4011 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4012 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4015 current_module="av_init";
4017 if(mpctx->sh_video){
4018 mpctx->sh_video->timer=0;
4019 if (! ignore_start)
4020 audio_delay += mpctx->sh_video->stream_delay;
4022 if(mpctx->sh_audio){
4023 if (start_volume >= 0)
4024 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4025 if (! ignore_start)
4026 audio_delay -= mpctx->sh_audio->stream_delay;
4027 mpctx->delay=-audio_delay;
4030 if(!mpctx->sh_audio){
4031 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4032 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4033 ds_free_packs(mpctx->d_audio); // free buffered chunks
4034 //mpctx->d_audio->id=-2; // do not read audio chunks
4035 //uninit_player(mpctx, INITIALIZED_AO); // close device
4037 if(!mpctx->sh_video){
4038 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4039 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4040 ds_free_packs(mpctx->d_video);
4041 mpctx->d_video->id=-2;
4042 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4045 if (!mpctx->sh_video && !mpctx->sh_audio)
4046 goto goto_next_file;
4048 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4049 if(force_fps && mpctx->sh_video){
4050 vo_fps = mpctx->sh_video->fps=force_fps;
4051 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4052 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4055 mp_input_set_section(mpctx->input, NULL);
4056 //TODO: add desired (stream-based) sections here
4057 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4058 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4060 //==================== START PLAYING =======================
4062 if(opts->loop_times>1) opts->loop_times--; else
4063 if(opts->loop_times==1) opts->loop_times = -1;
4065 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4067 total_time_usage_start=GetTimer();
4068 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4069 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4070 play_n_frames=play_n_frames_mf;
4072 if(play_n_frames==0){
4073 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4076 // If there's a timeline force an absolute seek to initialize state
4077 if (seek_to_sec || mpctx->timeline) {
4078 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4079 end_at.pos += seek_to_sec;
4081 if (opts->chapterrange[0] > 0) {
4082 double pts;
4083 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4084 && pts > -1.0)
4085 seek(mpctx, pts, SEEK_ABSOLUTE);
4088 if (end_at.type == END_AT_SIZE) {
4089 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4090 end_at.type = END_AT_NONE;
4093 #ifdef CONFIG_DVDNAV
4094 mp_dvdnav_context_free(mpctx);
4095 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4096 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4097 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4099 #endif
4101 get_relative_time(mpctx); // reset current delta
4102 mpctx->time_frame = 0;
4103 mpctx->drop_message_shown = 0;
4104 mpctx->update_video_immediately = true;
4105 mpctx->total_avsync_change = 0;
4106 mpctx->last_chapter_seek = -1;
4107 // Make sure VO knows current pause state
4108 if (mpctx->sh_video)
4109 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4110 NULL);
4112 while(!mpctx->stop_play){
4113 float aq_sleep_time=0;
4115 if (opts->chapterrange[1] > 0) {
4116 int cur_chapter = get_current_chapter(mpctx);
4117 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4118 goto goto_next_file;
4121 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4122 mpctx->sh_audio = mpctx->d_audio->sh;
4123 mpctx->sh_audio->ds = mpctx->d_audio;
4124 reinit_audio_chain(mpctx);
4127 /*========================== PLAY AUDIO ============================*/
4129 if (mpctx->sh_audio && !mpctx->paused)
4130 if (!fill_audio_out_buffers(mpctx))
4131 // at eof, all audio at least written to ao
4132 if (!mpctx->sh_video)
4133 mpctx->stop_play = AT_END_OF_FILE;
4136 if(!mpctx->sh_video) {
4137 // handle audio-only case:
4138 double a_pos=0;
4139 // sh_audio can be NULL due to video stream switching
4140 // TODO: handle this better
4141 if (mpctx->sh_audio)
4142 a_pos = playing_audio_pts(mpctx);
4144 print_status(mpctx, a_pos, false);
4146 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4147 mpctx->stop_play = PT_NEXT_ENTRY;
4148 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4149 mpctx->d_sub, 0);
4150 update_osd_msg(mpctx);
4152 } else {
4154 /*========================== PLAY VIDEO ============================*/
4156 vo_pts=mpctx->sh_video->timer*90000.0;
4157 vo_fps=mpctx->sh_video->fps;
4159 blit_frame = mpctx->video_out->frame_loaded;
4160 if (!blit_frame) {
4161 double frame_time = update_video(mpctx);
4162 blit_frame = mpctx->video_out->frame_loaded;
4163 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4164 if (mpctx->sh_video->vf_initialized < 0) {
4165 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4166 mpctx->stop_play = PT_NEXT_ENTRY;
4167 goto goto_next_file;
4169 if (blit_frame) {
4170 struct sh_video *sh_video = mpctx->sh_video;
4171 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4172 mpctx->video_offset, mpctx->d_sub, 0);
4173 update_teletext(sh_video, mpctx->demuxer, 0);
4174 update_osd_msg(mpctx);
4175 struct vf_instance *vf = mpctx->sh_video->vfilter;
4176 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4177 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4178 vo_osd_changed(0);
4180 if (frame_time < 0)
4181 mpctx->stop_play = AT_END_OF_FILE;
4182 else {
4183 if (mpctx->update_video_immediately) {
4184 // Show this frame immediately, rest normally
4185 mpctx->update_video_immediately = false;
4186 } else {
4187 mpctx->time_frame += frame_time / opts->playback_speed;
4188 adjust_sync(mpctx, frame_time);
4192 if (mpctx->timeline) {
4193 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4194 if (mpctx->sh_video->pts >= next->start
4195 || mpctx->stop_play == AT_END_OF_FILE
4196 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4197 seek(mpctx, next->start, SEEK_ABSOLUTE);
4198 continue;
4202 // ==========================================================================
4204 // current_module="draw_osd";
4205 // if(vo_config_count) mpctx->video_out->draw_osd();
4207 current_module="vo_check_events";
4208 vo_check_events(mpctx->video_out);
4210 #ifdef CONFIG_X11
4211 if (stop_xscreensaver) {
4212 current_module = "stop_xscreensaver";
4213 xscreensaver_heartbeat(mpctx->x11_state);
4215 #endif
4216 if (heartbeat_cmd) {
4217 static unsigned last_heartbeat;
4218 unsigned now = GetTimerMS();
4219 if (now - last_heartbeat > 30000) {
4220 last_heartbeat = now;
4221 system(heartbeat_cmd);
4225 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4227 //====================== FLIP PAGE (VIDEO BLT): =========================
4229 current_module="flip_page";
4230 if (!frame_time_remaining && blit_frame) {
4231 unsigned int t2=GetTimer();
4232 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4233 int duration = -1;
4234 double pts2 = mpctx->video_out->next_pts2;
4235 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts) {
4236 // expected A/V sync correction is ignored
4237 double diff = (pts2 - mpctx->sh_video->pts);
4238 diff /= opts->playback_speed;
4239 if (mpctx->time_frame < 0)
4240 diff += mpctx->time_frame;
4241 if (diff < 0)
4242 diff = 0;
4243 if (diff > 10)
4244 diff = 10;
4245 duration = diff * 1e6;
4247 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4249 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4250 vout_time_usage += mpctx->last_vo_flip_duration;
4251 if (mpctx->video_out->driver->flip_page_timed) {
4252 // No need to adjust sync based on flip speed
4253 mpctx->last_vo_flip_duration = 0;
4254 // For print_status - VO call finishing early is OK for sync
4255 mpctx->time_frame -= get_relative_time(mpctx);
4257 print_status(mpctx, MP_NOPTS_VALUE, true);
4259 else
4260 print_status(mpctx, MP_NOPTS_VALUE, false);
4262 //============================ Auto QUALITY ============================
4264 /*Output quality adjustments:*/
4265 if(auto_quality>0){
4266 current_module="autoq";
4267 // float total=0.000001f * (GetTimer()-aq_total_time);
4268 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4269 if(output_quality<auto_quality && aq_sleep_time>0)
4270 ++output_quality;
4271 else
4272 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4273 if(output_quality>1 && aq_sleep_time<0)
4274 --output_quality;
4275 else
4276 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4277 output_quality=0;
4278 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4279 set_video_quality(mpctx->sh_video,output_quality);
4282 if (!frame_time_remaining && blit_frame) {
4283 if (play_n_frames >= 0) {
4284 --play_n_frames;
4285 if (play_n_frames <= 0)
4286 mpctx->stop_play = PT_NEXT_ENTRY;
4288 if (mpctx->step_frames > 0) {
4289 mpctx->step_frames--;
4290 if (mpctx->step_frames == 0)
4291 pause_player(mpctx);
4296 // FIXME: add size based support for -endpos
4297 if (end_at.type == END_AT_TIME &&
4298 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4299 mpctx->stop_play = PT_NEXT_ENTRY;
4301 } // end if(mpctx->sh_video)
4303 #ifdef CONFIG_DVDNAV
4304 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4305 nav_highlight_t hl;
4306 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4307 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4308 vo_osd_changed (OSDTYPE_DVDNAV);
4310 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4311 double ar = -1.0;
4312 if (mpctx->sh_video &&
4313 stream_control (mpctx->demuxer->stream,
4314 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4315 != STREAM_UNSUPPORTED)
4316 mpctx->sh_video->stream_aspect = ar;
4319 #endif
4321 //================= Keyboard events, SEEKing ====================
4323 current_module="key_events";
4326 while (1) {
4327 mp_cmd_t* cmd;
4328 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4329 run_command(mpctx, cmd);
4330 mp_cmd_free(cmd);
4331 if (mpctx->stop_play)
4332 break;
4333 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4334 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4335 /* Allow seek commands to be combined, but execute the real seek
4336 * before processing other commands */
4337 if (!cmd || cmd->id != MP_CMD_SEEK)
4338 break;
4341 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4342 || mpctx->abs_seek_pos)
4343 break;
4344 if (mpctx->sh_video) {
4345 update_osd_msg(mpctx);
4346 int hack = vo_osd_changed(0);
4347 vo_osd_changed(hack);
4348 if (hack) {
4349 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4350 add_step_frame(mpctx);
4351 break;
4353 else
4354 vo_osd_changed(0);
4357 pause_loop(mpctx);
4361 // handle -sstep
4362 if (step_sec > 0 && !mpctx->paused) {
4363 mpctx->osd_function=OSD_FFW;
4364 mpctx->rel_seek_secs+=step_sec;
4367 edl_update(mpctx);
4369 /* Looping. */
4370 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4371 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4373 if(opts->loop_times>1) opts->loop_times--; else
4374 if(opts->loop_times==1) opts->loop_times=-1;
4375 play_n_frames=play_n_frames_mf;
4376 mpctx->stop_play=0;
4377 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4380 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4381 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4383 mpctx->rel_seek_secs=0;
4384 mpctx->abs_seek_pos=0;
4387 } // while(!mpctx->stop_play)
4389 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4391 #ifdef CONFIG_DVBIN
4392 if(mpctx->dvbin_reopen)
4394 mpctx->stop_play = 0;
4395 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4396 cache_uninit(mpctx->stream);
4397 mpctx->dvbin_reopen = 0;
4398 goto goto_enable_cache;
4400 #endif
4403 goto_next_file: // don't jump here after ao/vo/getch initialization!
4405 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4407 if(benchmark){
4408 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4409 double total_time_usage;
4410 total_time_usage_start=GetTimer()-total_time_usage_start;
4411 total_time_usage = (float)total_time_usage_start*0.000001;
4412 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4413 video_time_usage,vout_time_usage,audio_time_usage,
4414 total_time_usage-tot,total_time_usage);
4415 if(total_time_usage>0.0)
4416 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4417 100.0*video_time_usage/total_time_usage,
4418 100.0*vout_time_usage/total_time_usage,
4419 100.0*audio_time_usage/total_time_usage,
4420 100.0*(total_time_usage-tot)/total_time_usage,
4421 100.0);
4422 if(total_frame_cnt && frame_dropping)
4423 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4424 total_frame_cnt-drop_frame_cnt,
4425 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4426 drop_frame_cnt,
4427 100*drop_frame_cnt/total_frame_cnt,
4428 total_frame_cnt,
4429 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4432 // time to uninit all, except global stuff:
4433 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4435 if(mpctx->set_of_sub_size > 0) {
4436 current_module="sub_free";
4437 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4438 sub_free(mpctx->set_of_subtitles[i]);
4439 #ifdef CONFIG_ASS
4440 if(mpctx->set_of_ass_tracks[i])
4441 ass_free_track( mpctx->set_of_ass_tracks[i] );
4442 #endif
4444 mpctx->set_of_sub_size = 0;
4446 vo_sub_last = vo_sub=NULL;
4447 subdata=NULL;
4448 #ifdef CONFIG_ASS
4449 ass_track = NULL;
4450 if(ass_library)
4451 ass_clear_fonts(ass_library);
4452 #endif
4454 if (!mpctx->stop_play) // In case some goto jumped here...
4455 mpctx->stop_play = PT_NEXT_ENTRY;
4457 int playtree_direction = 1;
4459 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4460 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4461 play_tree_iter_free(mpctx->playtree_iter);
4462 mpctx->playtree_iter = NULL;
4464 mpctx->play_tree_step = 1;
4465 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4466 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4467 if(mpctx->playtree_iter) {
4468 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4469 play_tree_iter_free(mpctx->playtree_iter);
4470 mpctx->playtree_iter = NULL;
4473 } else if (mpctx->stop_play == PT_STOP) {
4474 play_tree_iter_free(mpctx->playtree_iter);
4475 mpctx->playtree_iter = NULL;
4476 } else { // NEXT PREV SRC
4477 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4480 while(mpctx->playtree_iter != NULL) {
4481 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4482 if(mpctx->filename == NULL) {
4483 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4484 play_tree_iter_free(mpctx->playtree_iter);
4485 mpctx->playtree_iter = NULL;
4487 } else
4488 break;
4491 if(mpctx->playtree_iter != NULL || player_idle_mode){
4492 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4493 mpctx->stop_play = 0;
4494 goto play_next_file;
4498 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4500 return 1;
4502 #endif /* DISABLE_MAIN */