Import libdvdnav / libdvdread4 from mplayerhq.hu (r1174)
[mplayer/kovensky.git] / mplayer.c
blobd9bd7666f45c617cd3094ae265fdaa24b78e43a8
2 /// \file
3 /// \ingroup Properties Command2Property OSDMsgStack
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdbool.h>
8 #include "config.h"
9 #include "talloc.h"
11 #if defined(__MINGW32__) || defined(__CYGWIN__)
12 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
13 #include <windows.h>
14 #endif
15 #include <string.h>
16 #include <unistd.h>
18 // #include <sys/mman.h>
19 #include <sys/types.h>
20 #ifndef __MINGW32__
21 #include <sys/ioctl.h>
22 #include <sys/wait.h>
23 #else
24 #define SIGHUP 1 /* hangup */
25 #define SIGQUIT 3 /* quit */
26 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
27 #define SIGBUS 10 /* bus error */
28 #define SIGPIPE 13 /* broken pipe */
29 #endif
31 #include <sys/time.h>
32 #include <sys/stat.h>
34 #include <signal.h>
35 #include <time.h>
36 #include <fcntl.h>
37 #include <limits.h>
39 #include <errno.h>
41 #include "mp_msg.h"
43 #define HELP_MP_DEFINE_STATIC
44 #include "help_mp.h"
46 #include "m_option.h"
47 #include "m_config.h"
48 #include "mplayer.h"
49 #include "access_mpcontext.h"
50 #include "m_property.h"
52 #include "cfg-mplayer-def.h"
54 #include "libavutil/intreadwrite.h"
56 #include "subreader.h"
58 #include "mp_osd.h"
59 #include "libvo/video_out.h"
61 #include "libvo/font_load.h"
62 #include "libvo/sub.h"
64 #ifdef CONFIG_X11
65 #include "libvo/x11_common.h"
66 #endif
68 #include "libao2/audio_out.h"
70 #include "codec-cfg.h"
72 #include "edl.h"
74 #include "spudec.h"
75 #include "vobsub.h"
77 #include "osdep/getch2.h"
78 #include "osdep/timer.h"
79 #include "osdep/findfiles.h"
81 #include "input/input.h"
83 const int under_mencoder = 0;
84 int slave_mode=0;
85 int player_idle_mode=0;
86 int quiet=0;
87 int enable_mouse_movements=0;
88 float start_volume = -1;
90 #include "osdep/priority.h"
92 char *heartbeat_cmd;
94 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
96 #ifdef HAVE_RTC
97 #ifdef __linux__
98 #include <linux/rtc.h>
99 #else
100 #include <rtc.h>
101 #define RTC_IRQP_SET RTCIO_IRQP_SET
102 #define RTC_PIE_ON RTCIO_PIE_ON
103 #endif /* __linux__ */
104 #endif /* HAVE_RTC */
106 #ifdef CONFIG_TV
107 #include "stream/tv.h"
108 #endif
109 #ifdef CONFIG_RADIO
110 #include "stream/stream_radio.h"
111 #endif
113 #ifdef CONFIG_DVBIN
114 #include "stream/dvbin.h"
115 #include "stream/cache2.h"
116 #endif
118 //**************************************************************************//
119 // Playtree
120 //**************************************************************************//
121 #include "playtree.h"
122 #include "playtreeparser.h"
124 //**************************************************************************//
125 // Config
126 //**************************************************************************//
127 #include "parser-cfg.h"
128 #include "parser-mpcmd.h"
130 //**************************************************************************//
131 // Config file
132 //**************************************************************************//
134 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
136 #include "get_path.h"
138 //**************************************************************************//
139 //**************************************************************************//
140 // Input media streaming & demultiplexer:
141 //**************************************************************************//
143 static int max_framesize=0;
145 #include "stream/stream.h"
146 #include "libmpdemux/demuxer.h"
147 #include "libmpdemux/stheader.h"
149 #ifdef CONFIG_DVDREAD
150 #include "stream/stream_dvd.h"
151 #endif
153 #ifdef CONFIG_DVDNAV
154 #include "stream/stream_dvdnav.h"
155 #endif
157 #include "libmpcodecs/dec_audio.h"
158 #include "libmpcodecs/dec_video.h"
159 #include "libmpcodecs/mp_image.h"
160 #include "libmpcodecs/vf.h"
161 #include "libmpcodecs/vd.h"
163 #include "mixer.h"
165 #include "mp_core.h"
166 #include "options.h"
167 #include "defaultopts.h"
169 #define Exit_SIGILL_RTCpuSel _(\
170 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
171 " It may be a bug in our new runtime CPU-detection code...\n"\
172 " Please read DOCS/HTML/en/bugreports.html.\n")
174 #define Exit_SIGILL _(\
175 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
176 " It usually happens when you run it on a CPU different than the one it was\n"\
177 " compiled/optimized for.\n"\
178 " Verify this!\n")
180 #define Exit_SIGSEGV_SIGFPE _(\
181 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
182 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
183 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
185 #define Exit_SIGCRASH _(\
186 "- MPlayer crashed. This shouldn't happen.\n"\
187 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
188 " gcc version. If you think it's MPlayer's fault, please read\n"\
189 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
190 " won't help unless you provide this information when reporting a possible bug.\n")
192 #define SystemTooSlow _("\n\n"\
193 " ************************************************\n"\
194 " **** Your system is too SLOW to play this! ****\n"\
195 " ************************************************\n\n"\
196 "Possible reasons, problems, workarounds:\n"\
197 "- Most common: broken/buggy _audio_ driver\n"\
198 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
199 " - Experiment with different values for -autosync, 30 is a good start.\n"\
200 "- Slow video output\n"\
201 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
202 "- Slow CPU\n"\
203 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
204 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
205 "- Broken file\n"\
206 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
207 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
208 " - Try -cache 8192.\n"\
209 "- Are you using -cache to play a non-interleaved AVI file?\n"\
210 " - Try -nocache.\n"\
211 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
212 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
215 //**************************************************************************//
216 //**************************************************************************//
218 // Common FIFO functions, and keyboard/event FIFO code
219 #include "mp_fifo.h"
220 int noconsolecontrols=0;
221 //**************************************************************************//
223 // benchmark:
224 double video_time_usage=0;
225 double vout_time_usage=0;
226 static double audio_time_usage=0;
227 static int total_time_usage_start=0;
228 static int total_frame_cnt=0;
229 static int drop_frame_cnt=0; // total number of dropped frames
230 int benchmark=0;
232 // options:
233 int auto_quality=0;
234 static int output_quality=0;
236 static int list_properties = 0;
238 int term_osd = 1;
239 static char* term_osd_esc = "\x1b[A\r\x1b[K";
240 static char* playing_msg = NULL;
241 // seek:
242 static double seek_to_sec;
243 static off_t seek_to_byte=0;
244 static off_t step_sec=0;
246 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
248 // A/V sync:
249 int autosync=0; // 30 might be a good default value.
251 // codecs:
252 char **audio_codec_list=NULL; // override audio codec
253 char **video_codec_list=NULL; // override video codec
254 char **audio_fm_list=NULL; // override audio codec family
255 char **video_fm_list=NULL; // override video codec family
257 // demuxer:
258 extern char *demuxer_name; // override demuxer
259 extern char *audio_demuxer_name; // override audio demuxer
260 extern char *sub_demuxer_name; // override sub demuxer
262 int vobsub_id=-1;
263 char* audio_lang=NULL;
264 char* dvdsub_lang=NULL;
265 static char* spudec_ifo=NULL;
266 int forced_subs_only=0;
267 int file_filter=1;
269 // cache2:
270 int stream_cache_size=-1;
271 #ifdef CONFIG_STREAM_CACHE
272 extern int cache_fill_status;
274 float stream_cache_min_percent=20.0;
275 float stream_cache_seek_min_percent=50.0;
276 #else
277 #define cache_fill_status 0
278 #endif
280 // dump:
281 static char *stream_dump_name="stream.dump";
282 int stream_dump_type=0;
284 // A-V sync:
285 static float default_max_pts_correction=-1;//0.01f;
286 float audio_delay=0;
287 static int ignore_start=0;
289 static int softsleep=0;
291 double force_fps=0;
292 static int force_srate=0;
293 static int audio_output_format=-1; // AF_FORMAT_UNKNOWN
294 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
295 static int play_n_frames=-1;
296 static int play_n_frames_mf=-1;
298 // sub:
299 char *font_name=NULL;
300 char *sub_font_name=NULL;
301 extern int font_fontconfig;
302 float font_factor=0.75;
303 char **sub_name=NULL;
304 float sub_delay=0;
305 float sub_fps=0;
306 int sub_auto = 1;
307 char *vobsub_name=NULL;
308 /*DSP!!char *dsp=NULL;*/
309 int subcc_enabled=0;
310 int suboverlap_enabled = 1;
312 #ifdef CONFIG_ASS
313 #include "libass/ass.h"
314 #include "libass/ass_mp.h"
315 #endif
317 char* current_module=NULL; // for debugging
320 // ---
322 #ifdef CONFIG_MENU
323 #include "m_struct.h"
324 #include "libmenu/menu.h"
325 void vf_menu_pause_update(struct vf_instance* vf);
326 extern vf_info_t vf_info_menu;
327 static const vf_info_t* const libmenu_vfs[] = {
328 &vf_info_menu,
329 NULL
331 static vf_instance_t* vf_menu = NULL;
332 int use_menu = 0;
333 static char* menu_cfg = NULL;
334 static char* menu_root = "main";
335 #endif
338 #ifdef HAVE_RTC
339 static int nortc = 1;
340 static char* rtc_device;
341 #endif
343 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
344 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
345 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
346 int use_filedir_conf;
348 #include "mpcommon.h"
349 #include "command.h"
351 #include "metadata.h"
353 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
355 const void *mpctx_get_video_out(MPContext *mpctx)
357 return mpctx->video_out;
360 const void *mpctx_get_audio_out(MPContext *mpctx)
362 return mpctx->audio_out;
365 void *mpctx_get_demuxer(MPContext *mpctx)
367 return mpctx->demuxer;
370 void *mpctx_get_playtree_iter(MPContext *mpctx)
372 return mpctx->playtree_iter;
375 void *mpctx_get_mixer(MPContext *mpctx)
377 return &mpctx->mixer;
380 int mpctx_get_global_sub_size(MPContext *mpctx)
382 return mpctx->global_sub_size;
385 int mpctx_get_osd_function(MPContext *mpctx)
387 return mpctx->osd_function;
390 static float get_relative_time(struct MPContext *mpctx)
392 unsigned int new_time = GetTimer();
393 unsigned int delta = new_time - mpctx->last_time;
394 mpctx->last_time = new_time;
395 return delta * 0.000001;
398 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
399 switch (type)
401 /* check for valid video stream */
402 case META_VIDEO_CODEC:
403 case META_VIDEO_BITRATE:
404 case META_VIDEO_RESOLUTION:
406 if (!mpctx->sh_video)
407 return 0;
408 break;
411 /* check for valid audio stream */
412 case META_AUDIO_CODEC:
413 case META_AUDIO_BITRATE:
414 case META_AUDIO_SAMPLES:
416 if (!mpctx->sh_audio)
417 return 0;
418 break;
421 /* check for valid demuxer */
422 case META_INFO_TITLE:
423 case META_INFO_ARTIST:
424 case META_INFO_ALBUM:
425 case META_INFO_YEAR:
426 case META_INFO_COMMENT:
427 case META_INFO_TRACK:
428 case META_INFO_GENRE:
430 if (!mpctx->demuxer)
431 return 0;
432 break;
435 default:
436 break;
439 return 1;
442 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
443 char **info = mpctx->demuxer->info;
444 int n;
446 if (!info || !tag)
447 return NULL;
449 for (n = 0; info[2*n] != NULL ; n++)
450 if (!strcasecmp (info[2*n], tag))
451 break;
453 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
456 char *get_metadata(struct MPContext *mpctx, metadata_t type)
458 char *meta = NULL;
459 sh_audio_t * const sh_audio = mpctx->sh_audio;
460 sh_video_t * const sh_video = mpctx->sh_video;
462 if (!is_valid_metadata_type(mpctx, type))
463 return NULL;
465 switch (type)
467 case META_NAME:
469 return strdup (mp_basename2 (mpctx->filename));
472 case META_VIDEO_CODEC:
474 if (sh_video->format == 0x10000001)
475 meta = strdup ("mpeg1");
476 else if (sh_video->format == 0x10000002)
477 meta = strdup ("mpeg2");
478 else if (sh_video->format == 0x10000004)
479 meta = strdup ("mpeg4");
480 else if (sh_video->format == 0x10000005)
481 meta = strdup ("h264");
482 else if (sh_video->format >= 0x20202020)
484 meta = malloc (8);
485 sprintf (meta, "%.4s", (char *) &sh_video->format);
487 else
489 meta = malloc (8);
490 sprintf (meta, "0x%08X", sh_video->format);
492 return meta;
495 case META_VIDEO_BITRATE:
497 meta = malloc (16);
498 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
499 return meta;
502 case META_VIDEO_RESOLUTION:
504 meta = malloc (16);
505 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
506 return meta;
509 case META_AUDIO_CODEC:
511 if (sh_audio->codec && sh_audio->codec->name)
512 meta = strdup (sh_audio->codec->name);
513 return meta;
516 case META_AUDIO_BITRATE:
518 meta = malloc (16);
519 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
520 return meta;
523 case META_AUDIO_SAMPLES:
525 meta = malloc (16);
526 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
527 return meta;
530 /* check for valid demuxer */
531 case META_INFO_TITLE:
532 return get_demuxer_info(mpctx, "Title");
534 case META_INFO_ARTIST:
535 return get_demuxer_info(mpctx, "Artist");
537 case META_INFO_ALBUM:
538 return get_demuxer_info(mpctx, "Album");
540 case META_INFO_YEAR:
541 return get_demuxer_info(mpctx, "Year");
543 case META_INFO_COMMENT:
544 return get_demuxer_info(mpctx, "Comment");
546 case META_INFO_TRACK:
547 return get_demuxer_info(mpctx, "Track");
549 case META_INFO_GENRE:
550 return get_demuxer_info(mpctx, "Genre");
552 default:
553 break;
556 return meta;
559 /// step size of mixer changes
560 int volstep = 3;
562 #ifdef CONFIG_DVDNAV
563 static void mp_dvdnav_context_free(MPContext *ctx){
564 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
565 ctx->nav_smpi = NULL;
566 if (ctx->nav_buffer) free(ctx->nav_buffer);
567 ctx->nav_buffer = NULL;
568 ctx->nav_start = NULL;
569 ctx->nav_in_size = 0;
571 #endif
573 void uninit_player(struct MPContext *mpctx, unsigned int mask){
574 mask=mpctx->initialized_flags&mask;
576 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
578 if(mask&INITIALIZED_ACODEC){
579 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
580 current_module="uninit_acodec";
581 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
582 mpctx->sh_audio=NULL;
583 mpctx->mixer.afilter = NULL;
586 if(mask&INITIALIZED_VCODEC){
587 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
588 current_module="uninit_vcodec";
589 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
590 mpctx->sh_video=NULL;
591 #ifdef CONFIG_MENU
592 vf_menu=NULL;
593 #endif
596 if(mask&INITIALIZED_DEMUXER){
597 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
598 current_module="free_demuxer";
599 if (mpctx->num_sources) {
600 mpctx->demuxer = mpctx->sources[0].demuxer;
601 for (int i = 1; i < mpctx->num_sources; i++) {
602 free_stream(mpctx->sources[i].stream);
603 free_demuxer(mpctx->sources[i].demuxer);
606 talloc_free(mpctx->sources);
607 mpctx->sources = NULL;
608 mpctx->num_sources = 0;
609 talloc_free(mpctx->timeline);
610 mpctx->timeline = NULL;
611 mpctx->num_timeline_parts = 0;
612 talloc_free(mpctx->chapters);
613 mpctx->chapters = NULL;
614 mpctx->num_chapters = 0;
615 mpctx->video_offset = 0;
616 if(mpctx->demuxer){
617 mpctx->stream=mpctx->demuxer->stream;
618 free_demuxer(mpctx->demuxer);
620 mpctx->demuxer=NULL;
623 // kill the cache process:
624 if(mask&INITIALIZED_STREAM){
625 mpctx->initialized_flags&=~INITIALIZED_STREAM;
626 current_module="uninit_stream";
627 if(mpctx->stream) free_stream(mpctx->stream);
628 mpctx->stream=NULL;
631 if(mask&INITIALIZED_VO){
632 mpctx->initialized_flags&=~INITIALIZED_VO;
633 current_module="uninit_vo";
634 vo_destroy(mpctx->video_out);
635 mpctx->video_out=NULL;
636 #ifdef CONFIG_DVDNAV
637 mp_dvdnav_context_free(mpctx);
638 #endif
641 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
642 if(mask&INITIALIZED_GETCH2){
643 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
644 current_module="uninit_getch2";
645 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
646 // restore terminal:
647 getch2_disable();
650 if(mask&INITIALIZED_VOBSUB){
651 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
652 current_module="uninit_vobsub";
653 if(vo_vobsub) vobsub_close(vo_vobsub);
654 vo_vobsub=NULL;
657 if (mask&INITIALIZED_SPUDEC){
658 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
659 current_module="uninit_spudec";
660 spudec_free(vo_spudec);
661 vo_spudec=NULL;
664 if(mask&INITIALIZED_AO){
665 mpctx->initialized_flags&=~INITIALIZED_AO;
666 current_module="uninit_ao";
667 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
668 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
669 mpctx->audio_out=NULL;
672 current_module=NULL;
675 void exit_player_with_rc(struct MPContext *mpctx, exit_reason_t how, int rc)
677 uninit_player(mpctx, INITIALIZED_ALL);
678 #if defined(__MINGW32__) || defined(__CYGWIN__)
679 timeEndPeriod(1);
680 #endif
681 #ifdef CONFIG_X11
682 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
683 #endif
685 current_module="uninit_input";
686 mp_input_uninit(mpctx->input);
687 #ifdef CONFIG_MENU
688 if (use_menu)
689 menu_uninit();
690 #endif
692 #ifdef CONFIG_FREETYPE
693 current_module="uninit_font";
694 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
695 free_font_desc(mpctx->osd->sub_font);
696 free_font_desc(vo_font);
697 vo_font = NULL;
698 done_freetype();
699 #endif
700 osd_free(mpctx->osd);
702 #ifdef CONFIG_ASS
703 ass_library_done(ass_library);
704 #endif
706 current_module="exit_player";
708 // free mplayer config
709 if(mpctx->mconfig)
710 m_config_free(mpctx->mconfig);
712 if(mpctx->playtree)
713 play_tree_free(mpctx->playtree, 1);
715 talloc_free(mpctx->key_fifo);
717 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
718 switch(how) {
719 case EXIT_QUIT:
720 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
721 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
722 break;
723 case EXIT_EOF:
724 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
725 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
726 break;
727 case EXIT_ERROR:
728 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
729 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
730 break;
731 default:
732 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
734 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
736 exit(rc);
739 static void exit_player(struct MPContext *mpctx, exit_reason_t how)
741 exit_player_with_rc(mpctx, how, 1);
744 #ifndef __MINGW32__
745 static void child_sighandler(int x){
746 pid_t pid;
747 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
749 #endif
751 #ifdef CONFIG_CRASH_DEBUG
752 static char *prog_path;
753 static int crash_debug = 0;
754 #endif
756 static void exit_sighandler(int x){
757 static int sig_count=0;
758 #ifdef CONFIG_CRASH_DEBUG
759 if (!crash_debug || x != SIGTRAP)
760 #endif
761 ++sig_count;
762 if(sig_count==5)
764 /* We're crashing bad and can't uninit cleanly :(
765 * by popular request, we make one last (dirty)
766 * effort to restore the user's
767 * terminal. */
768 getch2_disable();
769 exit(1);
771 if(sig_count==6) exit(1);
772 if(sig_count>6){
773 // can't stop :(
774 #ifndef __MINGW32__
775 kill(getpid(),SIGKILL);
776 #endif
778 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"\n" "\nMPlayer interrupted by signal %d in module: %s\n",x,
779 current_module?current_module:"unknown"
781 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
782 if(sig_count<=1)
783 switch(x){
784 case SIGINT:
785 case SIGQUIT:
786 case SIGTERM:
787 case SIGKILL:
788 async_quit_request = 1;
789 return; // killed from keyboard (^C) or killed [-9]
790 case SIGILL:
791 #if CONFIG_RUNTIME_CPUDETECT
792 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
793 #else
794 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
795 #endif
796 case SIGFPE:
797 case SIGSEGV:
798 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
799 default:
800 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
801 #ifdef CONFIG_CRASH_DEBUG
802 if (crash_debug) {
803 int gdb_pid;
804 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
805 gdb_pid = fork();
806 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
807 if (gdb_pid == 0) { // We are the child
808 char spid[20];
809 snprintf(spid, sizeof(spid), "%i", getppid());
810 getch2_disable(); // allow terminal to work properly with gdb
811 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
812 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
813 } else if (gdb_pid < 0)
814 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
815 else {
816 waitpid(gdb_pid, NULL, 0);
818 if (x == SIGTRAP) return;
820 #endif
822 getch2_disable();
823 exit(1);
826 #include "cfg-mplayer.h"
828 static int cfg_include(m_option_t *conf, char *filename)
830 return m_config_parse_config_file(conf->priv, filename);
833 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
835 char *conffile;
836 int conffile_fd;
837 if (!disable_system_conf &&
838 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
839 exit_player(mpctx, EXIT_NONE);
840 if ((conffile = get_path("")) == NULL) {
841 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
842 } else {
843 #ifdef __MINGW32__
844 mkdir(conffile);
845 #else
846 mkdir(conffile, 0777);
847 #endif
848 free(conffile);
849 if ((conffile = get_path("config")) == NULL) {
850 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
851 } else {
852 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
853 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
854 write(conffile_fd, default_config, strlen(default_config));
855 close(conffile_fd);
857 if (!disable_user_conf &&
858 m_config_parse_config_file(conf, conffile) < 0)
859 exit_player(mpctx, EXIT_NONE);
860 free(conffile);
865 #define PROFILE_CFG_PROTOCOL "protocol."
867 static void load_per_protocol_config (m_config_t* conf, const char *const file)
869 char *str;
870 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
871 m_profile_t *p;
873 /* does filename actually uses a protocol ? */
874 str = strstr (file, "://");
875 if (!str)
876 return;
878 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
879 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
880 p = m_config_get_profile (conf, protocol);
881 if (p)
883 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
884 m_config_set_profile(conf,p);
888 #define PROFILE_CFG_EXTENSION "extension."
890 static void load_per_extension_config (m_config_t* conf, const char *const file)
892 char *str;
893 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
894 m_profile_t *p;
896 /* does filename actually have an extension ? */
897 str = strrchr (file, '.');
898 if (!str)
899 return;
901 sprintf (extension, PROFILE_CFG_EXTENSION);
902 strncat (extension, ++str, 7);
903 p = m_config_get_profile (conf, extension);
904 if (p)
906 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
907 m_config_set_profile(conf,p);
911 #define PROFILE_CFG_VO "vo."
912 #define PROFILE_CFG_AO "ao."
914 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
916 char profile[strlen (cfg) + strlen (out) + 1];
917 m_profile_t *p;
919 sprintf (profile, "%s%s", cfg, out);
920 p = m_config_get_profile (conf, profile);
921 if (p)
923 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
924 m_config_set_profile(conf,p);
928 static void load_per_file_config (m_config_t* conf, const char *const file)
930 char *confpath;
931 char cfg[strlen(file)+10];
932 struct stat st;
933 char *name;
935 sprintf (cfg, "%s.conf", file);
937 if (use_filedir_conf && !stat (cfg, &st))
939 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading config '%s'\n", cfg);
940 m_config_parse_config_file (conf, cfg);
941 return;
944 if ((name = strrchr (cfg, '/')) == NULL)
945 name = cfg;
946 else
947 name++;
949 if ((confpath = get_path (name)) != NULL)
951 if (!stat (confpath, &st))
953 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading config '%s'\n", confpath);
954 m_config_parse_config_file (conf, confpath);
957 free (confpath);
961 /* When libmpdemux performs a blocking operation (network connection or
962 * cache filling) if the operation fails we use this function to check
963 * if it was interrupted by the user.
964 * The function returns a new value for eof. */
965 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
967 mp_cmd_t* cmd;
968 if((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
969 switch(cmd->id) {
970 case MP_CMD_QUIT:
971 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
972 case MP_CMD_PLAY_TREE_STEP: {
973 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
974 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
975 } break;
976 case MP_CMD_PLAY_TREE_UP_STEP: {
977 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
978 } break;
979 case MP_CMD_PLAY_ALT_SRC_STEP: {
980 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
981 } break;
983 mp_cmd_free(cmd);
985 return stop_play;
988 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
990 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
992 play_tree_add_bpf(entry,mpctx->filename);
995 if(!entry) {
996 entry = mpctx->playtree_iter->tree;
997 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
998 return PT_NEXT_ENTRY;
1000 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1001 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1002 return PT_NEXT_ENTRY;
1005 play_tree_remove(entry,1,1);
1006 return PT_NEXT_SRC;
1008 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1009 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1010 entry = mpctx->playtree_iter->tree;
1011 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1012 return PT_NEXT_ENTRY;
1014 play_tree_remove(entry,1,1);
1016 return PT_NEXT_SRC;
1019 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1021 sub_data *subd;
1022 #ifdef CONFIG_ASS
1023 ass_track_t *asst = 0;
1024 #endif
1026 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1027 return;
1030 subd = sub_read_file(filename, fps);
1031 #ifdef CONFIG_ASS
1032 if (ass_enabled)
1033 #ifdef CONFIG_ICONV
1034 asst = ass_read_file(ass_library, filename, sub_cp);
1035 #else
1036 asst = ass_read_file(ass_library, filename, 0);
1037 #endif
1038 if (ass_enabled && subd && !asst)
1039 asst = ass_read_subdata(ass_library, subd, fps);
1041 if (!asst && !subd)
1042 #else
1043 if(!subd)
1044 #endif
1045 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR, "Cannot load subtitles: %s\n",
1046 filename_recode(filename));
1048 #ifdef CONFIG_ASS
1049 if (!asst && !subd) return;
1050 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1051 #else
1052 if (!subd) return;
1053 #endif
1054 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1055 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1056 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1057 filename_recode(filename));
1058 ++mpctx->set_of_sub_size;
1059 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1060 filename_recode(filename));
1063 void init_vo_spudec(struct MPContext *mpctx)
1065 if (vo_spudec)
1066 spudec_free(vo_spudec);
1067 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1068 vo_spudec = NULL;
1069 if (spudec_ifo) {
1070 unsigned int palette[16], width, height;
1071 current_module="spudec_init_vobsub";
1072 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1073 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1076 #ifdef CONFIG_DVDREAD
1077 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1078 current_module="spudec_init_dvdread";
1079 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1080 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1081 NULL, 0);
1083 #endif
1085 #ifdef CONFIG_DVDNAV
1086 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1087 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1088 current_module="spudec_init_dvdnav";
1089 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1091 #endif
1093 if (vo_spudec==NULL) {
1094 sh_sub_t *sh = (sh_sub_t *)mpctx->d_sub->sh;
1095 current_module="spudec_init_normal";
1096 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1097 spudec_set_font_factor(vo_spudec,font_factor);
1100 if (vo_spudec!=NULL) {
1101 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1102 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1107 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1108 * make it all work is to use the builtin SDL-bootstrap code, which
1109 * will be done automatically by replacing our main() if we include SDL.h.
1111 #if defined(__APPLE__) && defined(CONFIG_SDL)
1112 #include <SDL.h>
1113 #endif
1116 * \brief append a formatted string
1117 * \param buf buffer to print into
1118 * \param pos position of terminating 0 in buf
1119 * \param len maximum number of characters in buf, not including terminating 0
1120 * \param format printf format string
1122 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1124 va_list va;
1125 va_start(va, format);
1126 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1127 va_end(va);
1128 if (*pos >= len ) {
1129 buf[len] = 0;
1130 *pos = len;
1135 * \brief append time in the hh:mm:ss.f format
1136 * \param buf buffer to print into
1137 * \param pos position of terminating 0 in buf
1138 * \param len maximum number of characters in buf, not including terminating 0
1139 * \param time time value to convert/append
1141 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1142 long tenths = 10 * time;
1143 int f1 = tenths % 10;
1144 int ss = (tenths / 10) % 60;
1145 int mm = (tenths / 600) % 60;
1146 int hh = tenths / 36000;
1147 if (time <= 0) {
1148 saddf(buf, pos, len, "unknown");
1149 return;
1151 if (hh > 0)
1152 saddf(buf, pos, len, "%2d:", hh);
1153 if (hh > 0 || mm > 0)
1154 saddf(buf, pos, len, "%02d:", mm);
1155 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1158 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1160 struct MPOpts *opts = &mpctx->opts;
1161 sh_video_t * const sh_video = mpctx->sh_video;
1163 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1164 a_pos = playing_audio_pts(mpctx);
1165 if (mpctx->sh_audio && sh_video && at_frame) {
1166 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1167 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1168 && !mpctx->drop_message_shown) {
1169 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1170 mpctx->drop_message_shown = true;
1173 if (quiet)
1174 return;
1177 int width;
1178 char *line;
1179 unsigned pos = 0;
1180 get_screen_size();
1181 if (screen_width > 0)
1182 width = screen_width;
1183 else
1184 width = 80;
1185 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1186 /* Windows command line is broken (MinGW's rxvt works, but we
1187 * should not depend on that). */
1188 width--;
1189 #endif
1190 line = malloc(width + 1); // one additional char for the terminating null
1192 // Audio time
1193 if (mpctx->sh_audio) {
1194 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1195 if (!sh_video) {
1196 float len = demuxer_get_time_length(mpctx->demuxer);
1197 saddf(line, &pos, width, "(");
1198 sadd_hhmmssf(line, &pos, width, a_pos);
1199 saddf(line, &pos, width, ") of %.1f (", len);
1200 sadd_hhmmssf(line, &pos, width, len);
1201 saddf(line, &pos, width, ") ");
1205 // Video time
1206 if (sh_video)
1207 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1209 // A-V sync
1210 if (mpctx->sh_audio && sh_video)
1211 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1212 mpctx->last_av_difference, mpctx->total_avsync_change);
1214 // Video stats
1215 if (sh_video)
1216 saddf(line, &pos, width, "%3d/%3d ",
1217 (int)sh_video->num_frames,
1218 (int)sh_video->num_frames_decoded);
1220 // CPU usage
1221 if (sh_video) {
1222 if (sh_video->timer > 0.5)
1223 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1224 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1225 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1226 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1227 else
1228 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1229 } else if (mpctx->sh_audio) {
1230 if (mpctx->delay > 0.5)
1231 saddf(line, &pos, width, "%4.1f%% ",
1232 100.0*audio_time_usage/(double)mpctx->delay);
1233 else
1234 saddf(line, &pos, width, "??,?%% ");
1237 // VO stats
1238 if (sh_video)
1239 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1241 #ifdef CONFIG_STREAM_CACHE
1242 // cache stats
1243 if (stream_cache_size > 0)
1244 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1245 #endif
1247 // other
1248 if (opts->playback_speed != 1)
1249 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1251 // end
1252 if (erase_to_end_of_line) {
1253 line[pos] = 0;
1254 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1255 } else {
1256 memset(&line[pos], ' ', width - pos);
1257 line[width] = 0;
1258 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1260 free(line);
1264 * \brief build a chain of audio filters that converts the input format
1265 * to the ao's format, taking into account the current playback_speed.
1266 * \param sh_audio describes the requested input format of the chain.
1267 * \param ao_data describes the requested output format of the chain.
1269 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1271 struct MPOpts *opts = &mpctx->opts;
1272 int new_srate;
1273 int result;
1274 if (!sh_audio)
1276 mpctx->mixer.afilter = NULL;
1277 return 0;
1279 if(af_control_any_rev(sh_audio->afilter,
1280 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1281 &opts->playback_speed)) {
1282 new_srate = sh_audio->samplerate;
1283 } else {
1284 new_srate = sh_audio->samplerate * opts->playback_speed;
1285 if (new_srate != ao_data->samplerate) {
1286 // limits are taken from libaf/af_resample.c
1287 if (new_srate < 8000)
1288 new_srate = 8000;
1289 if (new_srate > 192000)
1290 new_srate = 192000;
1291 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1294 result = init_audio_filters(sh_audio, new_srate,
1295 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1296 mpctx->mixer.afilter = sh_audio->afilter;
1297 return result;
1301 typedef struct mp_osd_msg mp_osd_msg_t;
1302 struct mp_osd_msg {
1303 /// Previous message on the stack.
1304 mp_osd_msg_t* prev;
1305 /// Message text.
1306 char msg[128];
1307 int id,level,started;
1308 /// Display duration in ms.
1309 unsigned time;
1312 /// OSD message stack.
1313 static mp_osd_msg_t* osd_msg_stack = NULL;
1316 * \brief Add a message on the OSD message stack
1318 * If a message with the same id is already present in the stack
1319 * it is pulled on top of the stack, otherwise a new message is created.
1323 void set_osd_msg(int id, int level, int time, const char* fmt, ...) {
1324 mp_osd_msg_t *msg,*last=NULL;
1325 va_list va;
1326 int r;
1328 // look if the id is already in the stack
1329 for(msg = osd_msg_stack ; msg && msg->id != id ;
1330 last = msg, msg = msg->prev);
1331 // not found: alloc it
1332 if(!msg) {
1333 msg = calloc(1,sizeof(mp_osd_msg_t));
1334 msg->prev = osd_msg_stack;
1335 osd_msg_stack = msg;
1336 } else if(last) { // found, but it's not on top of the stack
1337 last->prev = msg->prev;
1338 msg->prev = osd_msg_stack;
1339 osd_msg_stack = msg;
1341 // write the msg
1342 va_start(va,fmt);
1343 r = vsnprintf(msg->msg, 128, fmt, va);
1344 va_end(va);
1345 if(r >= 128) msg->msg[127] = 0;
1346 // set id and time
1347 msg->id = id;
1348 msg->level = level;
1349 msg->time = time;
1354 * \brief Remove a message from the OSD stack
1356 * This function can be used to get rid of a message right away.
1360 void rm_osd_msg(int id) {
1361 mp_osd_msg_t *msg,*last=NULL;
1363 // Search for the msg
1364 for(msg = osd_msg_stack ; msg && msg->id != id ;
1365 last = msg, msg = msg->prev);
1366 if(!msg) return;
1368 // Detach it from the stack and free it
1369 if(last)
1370 last->prev = msg->prev;
1371 else
1372 osd_msg_stack = msg->prev;
1373 free(msg);
1377 * \brief Remove all messages from the OSD stack
1381 static void clear_osd_msgs(void) {
1382 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1383 while(msg) {
1384 prev = msg->prev;
1385 free(msg);
1386 msg = prev;
1388 osd_msg_stack = NULL;
1392 * \brief Get the current message from the OSD stack.
1394 * This function decrements the message timer and destroys the old ones.
1395 * The message that should be displayed is returned (if any).
1399 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1401 struct MPOpts *opts = &mpctx->opts;
1402 mp_osd_msg_t *msg,*prev,*last = NULL;
1403 static unsigned last_update = 0;
1404 unsigned now = GetTimerMS();
1405 unsigned diff;
1406 char hidden_dec_done = 0;
1408 if (mpctx->osd_visible) {
1409 // 36000000 means max timed visibility is 1 hour into the future, if
1410 // the difference is greater assume it's wrapped around from below 0
1411 if (mpctx->osd_visible - now > 36000000) {
1412 mpctx->osd_visible = 0;
1413 vo_osd_progbar_type = -1; // disable
1414 vo_osd_changed(OSDTYPE_PROGBAR);
1415 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1418 if (mpctx->osd_show_percentage_until - now > 36000000)
1419 mpctx->osd_show_percentage_until = 0;
1421 if(!last_update) last_update = now;
1422 diff = now >= last_update ? now - last_update : 0;
1424 last_update = now;
1426 // Look for the first message in the stack with high enough level.
1427 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1428 prev = msg->prev;
1429 if (msg->level > opts->osd_level && hidden_dec_done)
1430 continue;
1431 // The message has a high enough level or it is the first hidden one
1432 // in both cases we decrement the timer or kill it.
1433 if(!msg->started || msg->time > diff) {
1434 if(msg->started) msg->time -= diff;
1435 else msg->started = 1;
1436 // display it
1437 if (msg->level <= opts->osd_level)
1438 return msg;
1439 hidden_dec_done = 1;
1440 continue;
1442 // kill the message
1443 free(msg);
1444 if(last) {
1445 last->prev = prev;
1446 msg = last;
1447 } else {
1448 osd_msg_stack = prev;
1449 msg = NULL;
1452 // Nothing found
1453 return NULL;
1457 * \brief Display the OSD bar.
1459 * Display the OSD bar or fall back on a simple message.
1463 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1464 struct MPOpts *opts = &mpctx->opts;
1465 if (opts->osd_level < 1)
1466 return;
1468 if(mpctx->sh_video) {
1469 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1470 vo_osd_progbar_type = type;
1471 vo_osd_progbar_value = 256*(val-min)/(max-min);
1472 vo_osd_changed(OSDTYPE_PROGBAR);
1473 return;
1476 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1477 name, ROUND(100*(val-min)/(max-min)));
1482 * \brief Update the OSD message line.
1484 * This function displays the current message on the vo OSD or on the term.
1485 * If the stack is empty and the OSD level is high enough the timer
1486 * is displayed (only on the vo OSD).
1490 static void update_osd_msg(struct MPContext *mpctx)
1492 struct MPOpts *opts = &mpctx->opts;
1493 mp_osd_msg_t *msg;
1494 struct osd_state *osd = mpctx->osd;
1495 char osd_text_timer[128];
1497 if (mpctx->add_osd_seek_info) {
1498 double percentage;
1499 if (mpctx->timeline && mpctx->sh_video)
1500 percentage = mpctx->sh_video->pts * 100 /
1501 mpctx->timeline[mpctx->num_timeline_parts].start;
1502 else
1503 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1504 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1505 if (mpctx->sh_video)
1506 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1507 mpctx->add_osd_seek_info = false;
1510 // Look if we have a msg
1511 if((msg = get_osd_msg(mpctx))) {
1512 if (strcmp(osd->osd_text, msg->msg)) {
1513 strncpy(osd->osd_text, msg->msg, 127);
1514 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1515 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1517 return;
1520 if(mpctx->sh_video) {
1521 // fallback on the timer
1522 if (opts->osd_level >= 2) {
1523 int len;
1524 if (mpctx->timeline)
1525 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1526 else
1527 len = demuxer_get_time_length(mpctx->demuxer);
1528 int percentage = -1;
1529 char percentage_text[10];
1530 int pts = demuxer_get_current_time(mpctx->demuxer);
1532 if (mpctx->osd_show_percentage_until)
1533 if (mpctx->timeline)
1534 percentage = mpctx->sh_video->pts * 100 /
1535 mpctx->timeline[mpctx->num_timeline_parts].start;
1536 else
1537 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1539 if (percentage >= 0)
1540 snprintf(percentage_text, 9, " (%d%%)", percentage);
1541 else
1542 percentage_text[0] = 0;
1544 if (opts->osd_level == 3)
1545 snprintf(osd_text_timer, 63,
1546 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1547 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1548 len/3600,(len/60)%60,len%60,percentage_text);
1549 else
1550 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1551 mpctx->osd_function,pts/3600,(pts/60)%60,
1552 pts%60,percentage_text);
1553 } else
1554 osd_text_timer[0]=0;
1556 if (strcmp(osd->osd_text, osd_text_timer)) {
1557 strncpy(osd->osd_text, osd_text_timer, 63);
1558 vo_osd_changed(OSDTYPE_OSD);
1560 return;
1563 // Clear the term osd line
1564 if (term_osd && osd->osd_text[0]) {
1565 osd->osd_text[0] = 0;
1566 printf("%s\n",term_osd_esc);
1570 ///@}
1571 // OSDMsgStack
1574 void reinit_audio_chain(struct MPContext *mpctx)
1576 struct MPOpts *opts = &mpctx->opts;
1577 if(mpctx->sh_audio){
1578 current_module="init_audio_codec";
1579 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1580 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1581 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // failed to init :(
1582 mpctx->d_audio->id = -2;
1583 return;
1584 } else
1585 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1586 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1589 //const ao_info_t *info=audio_out->info;
1590 current_module="af_preinit";
1591 ao_data.samplerate=force_srate;
1592 ao_data.channels=0;
1593 ao_data.format=audio_output_format;
1594 #if 1
1595 // first init to detect best values
1596 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1597 // input:
1598 mpctx->sh_audio->samplerate,
1599 // output:
1600 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1601 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Error at audio filter chain pre-init!\n");
1602 exit_player(mpctx, EXIT_ERROR);
1604 #endif
1605 current_module="ao2_init";
1606 if(!(mpctx->audio_out=init_best_audio_out(opts->audio_driver_list,
1607 0, // plugin flag
1608 ao_data.samplerate,
1609 ao_data.channels,
1610 ao_data.format,0))){
1611 // FAILED:
1612 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1613 uninit_player(mpctx, INITIALIZED_ACODEC); // close codec
1614 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1615 mpctx->d_audio->id = -2;
1616 return;
1617 } else {
1618 // SUCCESS:
1619 mpctx->initialized_flags|=INITIALIZED_AO;
1620 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1621 mpctx->audio_out->info->short_name,
1622 ao_data.samplerate, ao_data.channels,
1623 af_fmt2str_short(ao_data.format),
1624 af_fmt2bits(ao_data.format)/8 );
1625 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1626 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1627 if(strlen(mpctx->audio_out->info->comment) > 0)
1628 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1629 // init audio filters:
1630 #if 1
1631 current_module="af_init";
1632 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1633 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1634 // mp_msg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter / ao format! -> NOSOUND\n");
1635 // uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec & ao
1636 // sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1638 #endif
1640 mpctx->mixer.audio_out = mpctx->audio_out;
1641 mpctx->mixer.volstep = volstep;
1646 ///@}
1647 // Command2Property
1650 // Return pts value corresponding to the end point of audio written to the
1651 // ao so far.
1652 static double written_audio_pts(struct MPContext *mpctx)
1654 sh_audio_t *sh_audio = mpctx->sh_audio;
1655 demux_stream_t *d_audio = mpctx->d_audio;
1656 double buffered_output;
1657 // first calculate the end pts of audio that has been output by decoder
1658 double a_pts = sh_audio->pts;
1659 if (a_pts != MP_NOPTS_VALUE)
1660 // Good, decoder supports new way of calculating audio pts.
1661 // sh_audio->pts is the timestamp of the latest input packet with
1662 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1663 // the amount of bytes the decoder has written after that timestamp.
1664 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1665 else {
1666 // Decoder doesn't support new way of calculating pts (or we're
1667 // being called before it has decoded anything with known timestamp).
1668 // Use the old method of audio pts calculation: take the timestamp
1669 // of last packet with known pts the decoder has read data from,
1670 // and add amount of bytes read after the beginning of that packet
1671 // divided by input bps. This will be inaccurate if the input/output
1672 // ratio is not constant for every audio packet or if it is constant
1673 // but not accurately known in sh_audio->i_bps.
1675 a_pts = d_audio->pts;
1676 // ds_tell_pts returns bytes read after last timestamp from
1677 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1678 // it has read but not decoded
1679 if (sh_audio->i_bps)
1680 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1681 (double)sh_audio->i_bps;
1683 // Now a_pts hopefully holds the pts for end of audio from decoder.
1684 // Substract data in buffers between decoder and audio out.
1686 // Decoded but not filtered
1687 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1689 // Data buffered in audio filters, measured in bytes of "missing" output
1690 buffered_output = af_calc_delay(sh_audio->afilter);
1692 // Data that was ready for ao but was buffered because ao didn't fully
1693 // accept everything to internal buffers yet
1694 buffered_output += sh_audio->a_out_buffer_len;
1696 // Filters divide audio length by playback_speed, so multiply by it
1697 // to get the length in original units without speedup or slowdown
1698 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1700 return a_pts + mpctx->video_offset;
1703 // Return pts value corresponding to currently playing audio.
1704 double playing_audio_pts(struct MPContext *mpctx)
1706 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1707 mpctx->audio_out->get_delay();
1710 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1711 struct MPOpts *opts = &mpctx->opts;
1712 // check for frame-drop:
1713 current_module = "check_framedrop";
1714 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1715 static int dropped_frames;
1716 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1717 float d = delay-mpctx->delay;
1718 ++total_frame_cnt;
1719 // we should avoid dropping too many frames in sequence unless we
1720 // are too late. and we allow 100ms A-V delay here:
1721 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1722 && !mpctx->update_video_immediately) {
1723 ++drop_frame_cnt;
1724 ++dropped_frames;
1725 return frame_dropping;
1726 } else
1727 dropped_frames = 0;
1729 return 0;
1733 #ifdef HAVE_RTC
1734 int rtc_fd = -1;
1735 #endif
1737 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1739 #ifdef HAVE_RTC
1740 if (rtc_fd >= 0){
1741 // -------- RTC -----------
1742 current_module="sleep_rtc";
1743 while (time_frame > 0.000) {
1744 unsigned long rtc_ts;
1745 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1746 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1747 time_frame -= get_relative_time(mpctx);
1749 } else
1750 #endif
1752 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1753 // unnecessarily high CPU usage
1754 float margin = softsleep ? 0.011 : 0;
1755 current_module = "sleep_timer";
1756 while (time_frame > margin) {
1757 usec_sleep(1000000 * (time_frame - margin));
1758 time_frame -= get_relative_time(mpctx);
1760 if (softsleep){
1761 current_module = "sleep_soft";
1762 if (time_frame < 0)
1763 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1764 while (time_frame > 0)
1765 time_frame -= get_relative_time(mpctx); // burn the CPU
1768 return time_frame;
1771 #ifdef CONFIG_DVDNAV
1772 #ifndef FF_B_TYPE
1773 #define FF_B_TYPE 3
1774 #endif
1775 /// store decoded video image
1776 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1777 mp_image_t *from_mpi) {
1778 mp_image_t *mpi;
1780 /// Do not store B-frames
1781 if (from_mpi->pict_type == FF_B_TYPE)
1782 return to_mpi;
1784 if (to_mpi &&
1785 to_mpi->w == from_mpi->w &&
1786 to_mpi->h == from_mpi->h &&
1787 to_mpi->imgfmt == from_mpi->imgfmt)
1788 mpi = to_mpi;
1789 else {
1790 if (to_mpi)
1791 free_mp_image(to_mpi);
1792 if (from_mpi->w == 0 || from_mpi->h == 0)
1793 return NULL;
1794 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1797 copy_mpi(mpi,from_mpi);
1798 return mpi;
1801 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1802 struct MPOpts *opts = &ctx->opts;
1803 if (ctx->sh_video) {
1804 /// clear video pts
1805 ctx->d_video->pts = 0.0f;
1806 ctx->sh_video->pts = 0.0f;
1807 ctx->sh_video->i_pts = 0.0f;
1808 ctx->sh_video->last_pts = 0.0f;
1809 ctx->sh_video->num_buffered_pts = 0;
1810 ctx->sh_video->num_frames = 0;
1811 ctx->sh_video->num_frames_decoded = 0;
1812 ctx->sh_video->timer = 0.0f;
1813 ctx->sh_video->stream_delay = 0.0f;
1814 ctx->sh_video->timer = 0;
1815 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1818 if (ctx->sh_audio) {
1819 /// free audio packets and reset
1820 ds_free_packs(ctx->d_audio);
1821 audio_delay -= ctx->sh_audio->stream_delay;
1822 ctx->delay =- audio_delay;
1823 ctx->audio_out->reset();
1824 resync_audio_stream(ctx->sh_audio);
1827 if (ctx->d_sub) opts->sub_id = -2;
1829 audio_delay = 0.0f;
1831 /// clear all EOF related flags
1832 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1835 /// Restore last decoded DVDNAV (still frame)
1836 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
1837 int *in_size,
1838 unsigned char **start,
1839 mp_image_t *decoded_frame)
1841 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1842 return decoded_frame;
1844 /// a change occured in dvdnav stream
1845 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
1846 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
1847 mp_dvdnav_context_free(mpctx);
1848 mp_dvdnav_reset_stream(mpctx);
1849 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
1850 mp_dvdnav_cell_has_changed(mpctx->stream,1);
1853 if (*in_size < 0) {
1854 float len;
1856 /// Display still frame, if any
1857 if (mpctx->nav_smpi && !mpctx->nav_buffer)
1858 decoded_frame = mpctx->nav_smpi;
1860 /// increment video frame : continue playing after still frame
1861 len = demuxer_get_time_length(mpctx->demuxer);
1862 if (mpctx->sh_video->pts >= len &&
1863 mpctx->sh_video->pts > 0.0 && len > 0.0) {
1864 mp_dvdnav_skip_still(mpctx->stream);
1865 mp_dvdnav_skip_wait(mpctx->stream);
1867 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
1869 if (mpctx->nav_buffer) {
1870 *start = mpctx->nav_start;
1871 *in_size = mpctx->nav_in_size;
1872 if (mpctx->nav_start)
1873 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
1877 return decoded_frame;
1880 /// Save last decoded DVDNAV (still frame)
1881 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
1882 unsigned char *start,
1883 mp_image_t *decoded_frame)
1885 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1886 return;
1888 if (mpctx->nav_buffer)
1889 free(mpctx->nav_buffer);
1891 mpctx->nav_buffer = malloc(in_size);
1892 mpctx->nav_start = start;
1893 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
1894 if (mpctx->nav_buffer)
1895 memcpy(mpctx->nav_buffer,start,in_size);
1897 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
1898 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
1900 #endif /* CONFIG_DVDNAV */
1902 /* Modify video timing to match the audio timeline. There are two main
1903 * reasons this is needed. First, video and audio can start from different
1904 * positions at beginning of file or after a seek (MPlayer starts both
1905 * immediately even if they have different pts). Second, the file can have
1906 * audio timestamps that are inconsistent with the duration of the audio
1907 * packets, for example two consecutive timestamp values differing by
1908 * one second but only a packet with enough samples for half a second
1909 * of playback between them.
1911 static void adjust_sync(struct MPContext *mpctx, double frame_time)
1913 struct MPOpts *opts = &mpctx->opts;
1914 current_module = "av_sync";
1916 if (!mpctx->sh_audio)
1917 return;
1919 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
1920 double v_pts = mpctx->sh_video->pts;
1921 double av_delay = a_pts - v_pts;
1922 // Try to sync vo_flip() so it will *finish* at given time
1923 av_delay += mpctx->last_vo_flip_duration;
1924 av_delay -= audio_delay; // This much pts difference is desired
1926 double change = av_delay * 0.1;
1927 double max_change = default_max_pts_correction >= 0 ?
1928 default_max_pts_correction : frame_time * 0.1;
1929 if (change < -max_change)
1930 change = -max_change;
1931 else if (change > max_change)
1932 change = max_change;
1933 mpctx->delay += change;
1934 mpctx->total_avsync_change += change;
1937 static int fill_audio_out_buffers(struct MPContext *mpctx)
1939 struct MPOpts *opts = &mpctx->opts;
1940 unsigned int t;
1941 double tt;
1942 int playsize;
1943 int playflags=0;
1944 int audio_eof=0;
1945 int bytes_to_write;
1946 sh_audio_t * const sh_audio = mpctx->sh_audio;
1948 current_module="play_audio";
1950 while (1) {
1951 int sleep_time;
1952 // all the current uses of ao_data.pts seem to be in aos that handle
1953 // sync completely wrong; there should be no need to use ao_data.pts
1954 // in get_space()
1955 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
1956 bytes_to_write = mpctx->audio_out->get_space();
1957 if (mpctx->sh_video || bytes_to_write >= ao_data.outburst)
1958 break;
1960 // handle audio-only case:
1961 // this is where mplayer sleeps during audio-only playback
1962 // to avoid 100% CPU use
1963 sleep_time = (ao_data.outburst - bytes_to_write) * 1000 / ao_data.bps;
1964 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
1965 usec_sleep(sleep_time * 1000);
1968 while (bytes_to_write) {
1969 playsize = bytes_to_write;
1970 if (playsize > MAX_OUTBURST)
1971 playsize = MAX_OUTBURST;
1972 bytes_to_write -= playsize;
1974 // Fill buffer if needed:
1975 current_module="decode_audio";
1976 t = GetTimer();
1977 if (decode_audio(sh_audio, playsize) < 0) // EOF or error
1978 if (mpctx->d_audio->eof) {
1979 audio_eof = 1;
1980 if (sh_audio->a_out_buffer_len == 0)
1981 return 0;
1983 t = GetTimer() - t;
1984 tt = t*0.000001f; audio_time_usage+=tt;
1985 if (playsize > sh_audio->a_out_buffer_len) {
1986 playsize = sh_audio->a_out_buffer_len;
1987 if (audio_eof)
1988 playflags |= AOPLAY_FINAL_CHUNK;
1990 if (!playsize)
1991 break;
1993 // play audio:
1994 current_module="play_audio";
1996 // Is this pts value actually useful for the aos that access it?
1997 // They're obviously badly broken in the way they handle av sync;
1998 // would not having access to this make them more broken?
1999 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2000 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2002 if (playsize > 0) {
2003 sh_audio->a_out_buffer_len -= playsize;
2004 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2005 sh_audio->a_out_buffer_len);
2006 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2008 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2009 // Sanity check to avoid hanging in case current ao doesn't output
2010 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2011 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2012 sh_audio->a_out_buffer_len = 0;
2015 return 1;
2018 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2019 float *aq_sleep_time)
2021 struct MPOpts *opts = &mpctx->opts;
2022 int frame_time_remaining = 0;
2023 current_module="calc_sleep_time";
2025 *time_frame -= get_relative_time(mpctx); // reset timer
2027 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2028 float delay = mpctx->audio_out->get_delay();
2029 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2031 if (autosync) {
2033 * Adjust this raw delay value by calculating the expected
2034 * delay for this frame and generating a new value which is
2035 * weighted between the two. The higher autosync is, the
2036 * closer to the delay value gets to that which "-nosound"
2037 * would have used, and the longer it will take for A/V
2038 * sync to settle at the right value (but it eventually will.)
2039 * This settling time is very short for values below 100.
2041 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2042 float difference = delay - predicted;
2043 delay = predicted + difference / (float)autosync;
2046 *time_frame = delay - mpctx->delay / opts->playback_speed;
2048 // delay = amount of audio buffered in soundcard/driver
2049 if (delay > 0.25) delay=0.25; else
2050 if (delay < 0.10) delay=0.10;
2051 if (*time_frame > delay*0.6) {
2052 // sleep time too big - may cause audio drops (buffer underrun)
2053 frame_time_remaining = 1;
2054 *time_frame = delay*0.5;
2056 } else {
2057 // If we're lagging more than 200 ms behind the right playback rate,
2058 // don't try to "catch up".
2059 // If benchmark is set always output frames as fast as possible
2060 // without sleeping.
2061 if (*time_frame < -0.2 || benchmark)
2062 *time_frame = 0;
2065 *aq_sleep_time += *time_frame;
2068 //============================== SLEEP: ===================================
2070 // flag 256 means: libvo driver does its timing (dvb card)
2071 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2072 *time_frame = timing_sleep(mpctx, *time_frame);
2073 return frame_time_remaining;
2076 int reinit_video_chain(struct MPContext *mpctx)
2078 struct MPOpts *opts = &mpctx->opts;
2079 sh_video_t * const sh_video = mpctx->sh_video;
2080 double ar=-1.0;
2081 //================== Init VIDEO (codec & libvo) ==========================
2082 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2083 current_module="preinit_libvo";
2085 //shouldn't we set dvideo->id=-2 when we fail?
2086 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2087 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2088 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2089 goto err_out;
2091 mpctx->initialized_flags|=INITIALIZED_VO;
2094 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2095 mpctx->sh_video->stream_aspect = ar;
2096 current_module="init_video_filters";
2098 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2099 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2101 #ifdef CONFIG_MENU
2102 if(use_menu) {
2103 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2104 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2105 if(!vf_menu) {
2106 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2107 use_menu = 0;
2110 if(vf_menu)
2111 sh_video->vfilter = vf_menu;
2112 #endif
2114 #ifdef CONFIG_ASS
2115 if(ass_enabled) {
2116 int i;
2117 int insert = 1;
2118 if (opts->vf_settings)
2119 for (i = 0; opts->vf_settings[i].name; ++i)
2120 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2121 insert = 0;
2122 break;
2124 if (insert) {
2125 extern vf_info_t vf_info_ass;
2126 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2127 char* vf_arg[] = {"auto", "1", NULL};
2128 vf_instance_t* vf_ass = vf_open_plugin(opts, libass_vfs,sh_video->vfilter,"ass",vf_arg);
2129 if (vf_ass)
2130 sh_video->vfilter = vf_ass;
2131 else
2132 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2135 #endif
2137 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2139 #ifdef CONFIG_ASS
2140 if (ass_enabled)
2141 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2142 #endif
2144 current_module="init_video_codec";
2146 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2147 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2148 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2150 if(!sh_video->initialized){
2151 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2152 goto err_out;
2155 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2157 if (sh_video->codec)
2158 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2160 sh_video->last_pts = MP_NOPTS_VALUE;
2161 sh_video->num_buffered_pts = 0;
2162 sh_video->next_frame_time = 0;
2164 if(auto_quality>0){
2165 // Auto quality option enabled
2166 output_quality=get_video_quality_max(sh_video);
2167 if(auto_quality>output_quality) auto_quality=output_quality;
2168 else output_quality=auto_quality;
2169 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2170 set_video_quality(sh_video,output_quality);
2173 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2175 current_module="init_vo";
2177 return 1;
2179 err_out:
2180 mpctx->sh_video = mpctx->d_video->sh = NULL;
2181 return 0;
2184 static double update_video_nocorrect_pts(struct MPContext *mpctx,
2185 int *blit_frame)
2187 struct sh_video *sh_video = mpctx->sh_video;
2188 *blit_frame = 0;
2189 double frame_time = 0;
2190 while (1) {
2191 current_module = "filter_video";
2192 // In nocorrect-pts mode there is no way to properly time these frames
2193 if (vf_output_queued_frame(sh_video->vfilter))
2194 break;
2195 unsigned char *packet = NULL;
2196 frame_time = sh_video->next_frame_time;
2197 if (mpctx->update_video_immediately)
2198 frame_time = 0;
2199 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2200 &packet, force_fps);
2201 if (in_size < 0) {
2202 #ifdef CONFIG_DVDNAV
2203 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2204 if (mp_dvdnav_is_eof(mpctx->stream))
2205 return -1;
2206 if (mpctx->d_video)
2207 mpctx->d_video->eof = 0;
2208 if (mpctx->d_audio)
2209 mpctx->d_audio->eof = 0;
2210 mpctx->stream->eof = 0;
2211 } else
2212 #endif
2213 return -1;
2215 if (in_size > max_framesize)
2216 max_framesize = in_size;
2217 sh_video->timer += frame_time;
2218 if (mpctx->sh_audio)
2219 mpctx->delay -= frame_time;
2220 // video_read_frame can change fps (e.g. for ASF video)
2221 vo_fps = sh_video->fps;
2222 int framedrop_type = check_framedrop(mpctx, frame_time);
2223 current_module = "decode video";
2225 void *decoded_frame;
2226 #ifdef CONFIG_DVDNAV
2227 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2228 if (in_size >= 0 && !decoded_frame)
2229 #endif
2230 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2231 sh_video->pts);
2232 #ifdef CONFIG_DVDNAV
2233 // Save last still frame for future display
2234 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2235 #endif
2236 if (decoded_frame) {
2237 // These updates are done here for vf_expand OSD/subtitles
2238 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2239 update_teletext(sh_video, mpctx->demuxer, 0);
2240 update_osd_msg(mpctx);
2241 current_module = "filter video";
2242 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2243 break;
2246 *blit_frame = 1;
2247 return frame_time;
2250 static double update_video(struct MPContext *mpctx, int *blit_frame)
2252 struct sh_video *sh_video = mpctx->sh_video;
2253 *blit_frame = 0;
2254 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2255 mpctx->osd); // hack for vf_expand
2256 if (!mpctx->opts.correct_pts)
2257 return update_video_nocorrect_pts(mpctx, blit_frame);
2259 double pts;
2261 while (1) {
2262 current_module = "filter_video";
2263 // XXX Time used in this call is not counted in any performance
2264 // timer now, OSD time is not updated correctly for filter-added frames
2265 if (vf_output_queued_frame(sh_video->vfilter))
2266 break;
2267 unsigned char *packet = NULL;
2268 bool hit_eof = false;
2269 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2270 if (pts != MP_NOPTS_VALUE)
2271 pts += mpctx->video_offset;
2272 if (in_size < 0) {
2273 // try to extract last frames in case of decoder lag
2274 in_size = 0;
2275 pts = 1e300;
2276 hit_eof = true;
2278 if (in_size > max_framesize)
2279 max_framesize = in_size;
2280 current_module = "decode video";
2281 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2282 void *decoded_frame = decode_video(sh_video, packet, in_size,
2283 framedrop_type, pts);
2284 if (decoded_frame) {
2285 // These updates are done here for vf_expand OSD/subtitles
2286 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2287 update_teletext(sh_video, mpctx->demuxer, 0);
2288 update_osd_msg(mpctx);
2289 current_module = "filter video";
2290 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2291 break;
2292 } else if (hit_eof)
2293 return -1;
2296 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_GET_PTS, &pts);
2297 if (pts == MP_NOPTS_VALUE) {
2298 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2299 // Try to use decoder pts from before filters
2300 pts = sh_video->pts;
2301 if (pts == MP_NOPTS_VALUE)
2302 pts = sh_video->last_pts;
2304 sh_video->pts = pts;
2305 if (sh_video->last_pts == MP_NOPTS_VALUE)
2306 sh_video->last_pts = sh_video->pts;
2307 else if (sh_video->last_pts > sh_video->pts) {
2308 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2309 sh_video->pts, sh_video->last_pts);
2310 /* If the difference in pts is small treat it as jitter around the
2311 * right value (possibly caused by incorrect timestamp ordering) and
2312 * just show this frame immediately after the last one.
2313 * Treat bigger differences as timestamp resets and start counting
2314 * timing of later frames from the position of this one. */
2315 if (sh_video->last_pts - sh_video->pts > 0.5)
2316 sh_video->last_pts = sh_video->pts;
2317 else
2318 sh_video->pts = sh_video->last_pts;
2320 double frame_time = sh_video->pts - sh_video->last_pts;
2321 sh_video->last_pts = sh_video->pts;
2322 sh_video->timer += frame_time;
2323 if (mpctx->sh_audio)
2324 mpctx->delay -= frame_time;
2325 *blit_frame = 1;
2326 return frame_time;
2329 void pause_player(struct MPContext *mpctx)
2331 if (mpctx->paused)
2332 return;
2333 mpctx->paused = 1;
2334 mpctx->step_frames = 0;
2335 mpctx->time_frame -= get_relative_time(mpctx);
2337 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2338 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2340 if (mpctx->audio_out && mpctx->sh_audio)
2341 mpctx->audio_out->pause(); // pause audio, keep data if possible
2344 void unpause_player(struct MPContext *mpctx)
2346 if (!mpctx->paused)
2347 return;
2348 mpctx->paused = 0;
2350 if (mpctx->audio_out && mpctx->sh_audio)
2351 mpctx->audio_out->resume(); // resume audio
2352 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2353 && !mpctx->step_frames)
2354 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2355 (void)get_relative_time(mpctx); // ignore time that passed during pause
2358 void add_step_frame(struct MPContext *mpctx)
2360 mpctx->step_frames++;
2361 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2362 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2363 unpause_player(mpctx);
2366 static void pause_loop(struct MPContext *mpctx)
2368 mp_cmd_t* cmd;
2369 if (!quiet) {
2370 // Small hack to display the pause message on the OSD line.
2371 // The pause string is: "\n == PAUSE == \r" so we need to
2372 // take the first and the last char out
2373 if (term_osd && !mpctx->sh_video) {
2374 char msg[128] = _("\n ===== PAUSE =====\r");
2375 int mlen = strlen(msg);
2376 msg[mlen-1] = '\0';
2377 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2378 update_osd_msg(mpctx);
2379 } else
2380 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2381 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2384 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1, 1)) == NULL
2385 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2386 if (cmd) {
2387 cmd = mp_input_get_cmd(mpctx->input, 0,1,0);
2388 run_command(mpctx, cmd);
2389 mp_cmd_free(cmd);
2390 continue;
2392 if (mpctx->sh_video && mpctx->video_out)
2393 vo_check_events(mpctx->video_out);
2394 #ifdef CONFIG_MENU
2395 if (vf_menu)
2396 vf_menu_pause_update(vf_menu);
2397 #endif
2398 usec_sleep(20000);
2399 update_osd_msg(mpctx);
2400 int hack = vo_osd_changed(0);
2401 vo_osd_changed(hack);
2402 if (hack)
2403 break;
2408 // Find the right mute status and record position for new file position
2409 static void edl_seek_reset(MPContext *mpctx)
2411 mpctx->edl_muted = 0;
2412 next_edl_record = edl_records;
2414 while (next_edl_record) {
2415 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2416 break;
2418 if (next_edl_record->action == EDL_MUTE)
2419 mpctx->edl_muted = !mpctx->edl_muted;
2420 next_edl_record = next_edl_record->next;
2422 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2423 mixer_mute(&mpctx->mixer);
2427 // Execute EDL command for the current position if one exists
2428 static void edl_update(MPContext *mpctx)
2430 if (!next_edl_record)
2431 return;
2433 if (!mpctx->sh_video) {
2434 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2435 free_edl(edl_records);
2436 next_edl_record = NULL;
2437 edl_records = NULL;
2438 return;
2441 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2442 if (next_edl_record->action == EDL_SKIP) {
2443 mpctx->osd_function = OSD_FFW;
2444 mpctx->abs_seek_pos = 0;
2445 mpctx->rel_seek_secs = next_edl_record->length_sec;
2446 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2447 "[%f], length [%f]\n", next_edl_record->start_sec,
2448 next_edl_record->stop_sec, next_edl_record->length_sec);
2450 else if (next_edl_record->action == EDL_MUTE) {
2451 mpctx->edl_muted = !mpctx->edl_muted;
2452 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2453 mixer_mute(&mpctx->mixer);
2454 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2455 next_edl_record->start_sec );
2457 next_edl_record = next_edl_record->next;
2461 static void reinit_decoders(struct MPContext *mpctx)
2463 reinit_video_chain(mpctx);
2464 reinit_audio_chain(mpctx);
2465 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2468 static bool timeline_set_part(struct MPContext *mpctx, int i)
2470 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2471 struct timeline_part *n = mpctx->timeline + i;
2472 mpctx->timeline_part = i;
2473 mpctx->video_offset = n->start - n->source_start;
2474 if (n->source == p->source)
2475 return false;
2476 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2477 mpctx->demuxer = n->source->demuxer;
2478 mpctx->d_video = mpctx->demuxer->video;
2479 mpctx->d_audio = mpctx->demuxer->audio;
2480 mpctx->d_sub = mpctx->demuxer->sub;
2481 mpctx->sh_video = mpctx->d_video->sh;
2482 mpctx->sh_audio = mpctx->d_audio->sh;
2483 return true;
2486 // Given pts, switch playback to the corresponding part.
2487 // Return offset within that part.
2488 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2489 bool *need_reset)
2491 if (pts < 0)
2492 pts = 0;
2493 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2494 struct timeline_part *p = mpctx->timeline + i;
2495 if (pts < (p+1)->start) {
2496 *need_reset = timeline_set_part(mpctx, i);
2497 return pts - p->start + p->source_start;
2500 return -1;
2504 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2505 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2506 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2507 static int seek(MPContext *mpctx, double amount, int style)
2509 current_module = "seek";
2510 if (mpctx->stop_play == AT_END_OF_FILE)
2511 mpctx->stop_play = KEEP_PLAYING;
2512 if (mpctx->timeline && style & SEEK_FACTOR) {
2513 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2514 style &= ~SEEK_FACTOR;
2516 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2517 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2518 style |= SEEK_ABSOLUTE;
2519 if (amount > 0)
2520 style |= SEEK_FORWARD;
2521 else
2522 style |= SEEK_BACKWARD;
2523 amount += mpctx->sh_video->pts;
2526 /* At least the liba52 decoder wants to read from the input stream
2527 * during initialization, so reinit must be done after the demux_seek()
2528 * call that clears possible stream EOF. */
2529 bool need_reset = false;
2530 if (mpctx->timeline) {
2531 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2532 if (amount == -1) {
2533 mpctx->stop_play = AT_END_OF_FILE;
2534 // Clear audio from current position
2535 if (mpctx->sh_audio) {
2536 mpctx->audio_out->reset();
2537 mpctx->sh_audio->a_buffer_len = 0;
2538 mpctx->sh_audio->a_out_buffer_len = 0;
2540 return -1;
2543 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2544 if (need_reset)
2545 reinit_decoders(mpctx);
2546 if (seekresult == 0)
2547 return -1;
2549 if (mpctx->sh_video) {
2550 current_module = "seek_video_reset";
2551 resync_video_stream(mpctx->sh_video);
2552 if (mpctx->video_out->config_ok)
2553 vo_control(mpctx->video_out, VOCTRL_RESET, NULL);
2554 mpctx->sh_video->num_buffered_pts = 0;
2555 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2556 mpctx->num_buffered_frames = 0;
2557 mpctx->delay = 0;
2558 mpctx->time_frame = 0;
2559 mpctx->update_video_immediately = true;
2560 // Not all demuxers set d_video->pts during seek, so this value
2561 // (which is used by at least vobsub and edl code below) may
2562 // be completely wrong (probably 0).
2563 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2564 update_subtitles(mpctx->sh_video, mpctx->d_sub, mpctx->video_offset, 1);
2565 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2568 if (mpctx->sh_audio) {
2569 current_module = "seek_audio_reset";
2570 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2571 mpctx->sh_audio->a_buffer_len = 0;
2572 mpctx->sh_audio->a_out_buffer_len = 0;
2575 if (vo_vobsub && mpctx->sh_video) {
2576 current_module = "seek_vobsub_reset";
2577 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2580 edl_seek_reset(mpctx);
2582 mpctx->total_avsync_change = 0;
2583 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2584 drop_frame_cnt = 0;
2586 current_module = NULL;
2587 return 0;
2590 int get_current_chapter(struct MPContext *mpctx)
2592 if (!mpctx->chapters || !mpctx->sh_video)
2593 return demuxer_get_current_chapter(mpctx->demuxer);
2595 int i;
2596 double current_pts = mpctx->sh_video->pts;
2597 for (i = 1; i < mpctx->num_chapters; i++)
2598 if (current_pts < mpctx->chapters[i].start)
2599 break;
2600 return i - 1;
2603 // currently returns a string allocated with malloc, not talloc
2604 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2606 if (!mpctx->chapters || !mpctx->sh_video)
2607 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2608 return strdup(mpctx->chapters[chapter].name);
2611 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2612 char **chapter_name)
2614 if (!mpctx->chapters || !mpctx->sh_video)
2615 return demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2616 chapter_name);
2617 if (chapter >= mpctx->num_chapters)
2618 return -1;
2619 if (chapter < 0)
2620 chapter = 0;
2621 *seek_pts = mpctx->chapters[chapter].start;
2622 if (chapter_name)
2623 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2624 return chapter;
2627 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2628 struct content_source *sources,
2629 int num_sources,
2630 unsigned char uid_map[][16])
2632 int num_filenames = 0;
2633 char **filenames = NULL;
2634 if (num_sources > 1) {
2635 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2636 "other sources.\n");
2637 if (mpctx->stream->type != STREAMTYPE_FILE) {
2638 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2639 "normal disk file. Will not search for related files.\n");
2640 } else {
2641 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2642 "same directory to find referenced sources.\n");
2643 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2644 &num_filenames);
2648 int num_left = num_sources - 1;
2649 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2650 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2651 filename_recode(filenames[i]));
2652 int format;
2653 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2654 if (!s)
2655 continue;
2656 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2657 mpctx->opts.audio_id,
2658 mpctx->opts.video_id,
2659 mpctx->opts.sub_id, filenames[i]);
2660 if (!d) {
2661 free_stream(s);
2662 continue;
2664 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2665 for (int i = 1; i < num_sources; i++) {
2666 if (sources[i].demuxer)
2667 continue;
2668 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2669 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2670 i, filename_recode(d->filename));
2671 sources[i].stream = s;
2672 sources[i].demuxer = d;
2673 num_left--;
2674 goto match;
2678 free_demuxer(d);
2679 free_stream(s);
2680 continue;
2681 match:
2684 talloc_free(filenames);
2685 if (num_left) {
2686 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2687 "There will be parts MISSING from the video!\n");
2688 for (int i = 1, j = 1; i < num_sources; i++)
2689 if (sources[i].demuxer) {
2690 sources[j] = sources[i];
2691 memcpy(uid_map[j], uid_map[i], 16);
2692 j++;
2695 return num_sources - num_left;
2698 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2700 if (!mpctx->opts.ordered_chapters) {
2701 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
2702 "you have disabled support for them. Ignoring.\n");
2703 return;
2706 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
2707 "edit timeline.\n");
2709 struct demuxer *demuxer = mpctx->demuxer;
2710 struct matroska_data *m = &demuxer->matroska_data;
2712 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
2713 m->num_ordered_chapters);
2714 sources[0].stream = mpctx->stream;
2715 sources[0].demuxer = mpctx->demuxer;
2716 unsigned char uid_map[m->num_ordered_chapters][16];
2717 int num_sources = 1;
2718 memcpy(uid_map[0], m->segment_uid, 16);
2720 for (int i = 0; i < m->num_ordered_chapters; i++) {
2721 struct matroska_chapter *c = m->ordered_chapters + i;
2722 if (!c->has_segment_uid)
2723 memcpy(c->segment_uid, m->segment_uid, 16);
2725 for (int j = 0; j < num_sources; j++)
2726 if (!memcmp(c->segment_uid, uid_map[j], 16))
2727 goto found1;
2728 memcpy(uid_map[num_sources], c->segment_uid, 16);
2729 sources[num_sources] = (struct content_source){};
2730 num_sources++;
2731 found1:
2735 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
2736 uid_map);
2739 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
2740 m->num_ordered_chapters + 1);
2741 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
2742 m->num_ordered_chapters);
2743 uint64_t starttime = 0;
2744 uint64_t missing_time = 0;
2745 int part_count = 0;
2746 int num_chapters = 0;
2747 uint64_t prev_part_offset;
2748 for (int i = 0; i < m->num_ordered_chapters; i++) {
2749 struct matroska_chapter *c = m->ordered_chapters + i;
2751 int j;
2752 for (j = 0; j < num_sources; j++) {
2753 if (!memcmp(c->segment_uid, uid_map[j], 16))
2754 goto found2;
2756 missing_time += c->end - c->start;
2757 continue;
2758 found2:;
2759 chapters[num_chapters].start = starttime / 1000.;
2760 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
2761 /* Only add a separate part if the time or file actually changes.
2762 * Matroska files have chapter divisions that are redundant from
2763 * timeline point of view because the same chapter structure is used
2764 * both to specify the timeline and for normal chapter information.
2765 * Removing a missing inserted external chapter can also cause this. */
2766 if (part_count == 0 || c->start != starttime + prev_part_offset
2767 || sources + j != timeline[part_count - 1].source) {
2768 timeline[part_count].source = sources + j;
2769 timeline[part_count].start = chapters[num_chapters].start;
2770 timeline[part_count].source_start = c->start / 1000.;
2771 prev_part_offset = c->start - starttime;
2772 part_count++;
2774 starttime += c->end - c->start;
2775 num_chapters++;
2777 timeline[part_count].start = starttime / 1000.;
2779 if (!part_count) {
2780 // None of the parts come from the file itself???
2781 talloc_free(sources);
2782 talloc_free(timeline);
2783 talloc_free(chapters);
2784 return;
2787 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
2788 "sources. Total length %.3f seconds.\n", part_count, num_sources,
2789 timeline[part_count].start);
2790 if (missing_time)
2791 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
2792 "from the timeline!\n", missing_time / 1000.);
2793 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
2794 for (int i = 0; i < num_sources; i++)
2795 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
2796 filename_recode(sources[i].demuxer->filename));
2797 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
2798 "source_start, source):\n");
2799 for (int i = 0; i < part_count; i++) {
2800 struct timeline_part *p = timeline + i;
2801 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
2802 p->source_start, p->source - sources);
2804 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
2805 mpctx->sources = sources;
2806 mpctx->num_sources = num_sources;
2807 mpctx->timeline = timeline;
2808 mpctx->num_timeline_parts = part_count;
2809 mpctx->num_chapters = num_chapters;
2810 mpctx->chapters = chapters;
2812 mpctx->timeline_part = 0;
2813 mpctx->video_offset = timeline[0].source_start;
2814 mpctx->demuxer = timeline[0].source->demuxer;
2818 static int read_keys(void *ctx, int fd)
2820 getch2(ctx);
2821 return mplayer_get_key(ctx, 0);
2825 #ifdef PTW32_STATIC_LIB
2826 static void detach_ptw32(void)
2828 pthread_win32_thread_detach_np();
2829 pthread_win32_process_detach_np();
2831 #endif
2833 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
2834 * file for some tools to link against. */
2835 #ifndef DISABLE_MAIN
2836 int main(int argc,char* argv[]){
2839 char * mem_ptr;
2841 // movie info:
2843 /* Flag indicating whether MPlayer should exit without playing anything. */
2844 int opt_exit = 0;
2846 //float a_frame=0; // Audio
2848 int i;
2850 struct MPContext *mpctx = &(struct MPContext){
2851 .osd_function = OSD_PLAY,
2852 .begin_skip = MP_NOPTS_VALUE,
2853 .play_tree_step = 1,
2854 .global_sub_pos = -1,
2855 .set_of_sub_pos = -1,
2856 .file_format = DEMUXER_TYPE_UNKNOWN,
2857 .last_dvb_step = 1,
2860 #ifdef PTW32_STATIC_LIB
2861 pthread_win32_process_attach_np();
2862 pthread_win32_thread_attach_np();
2863 atexit(detach_ptw32);
2864 #endif
2866 InitTimer();
2867 srand(GetTimerMS());
2869 mp_msg_init();
2871 #ifdef CONFIG_X11
2872 mpctx->x11_state = vo_x11_init_state();
2873 #endif
2874 struct MPOpts *opts = &mpctx->opts;
2875 set_default_mplayer_options(opts);
2876 // Create the config context and register the options
2877 mpctx->mconfig = m_config_new(opts, cfg_include);
2878 m_config_register_options(mpctx->mconfig,mplayer_opts);
2879 mp_input_register_options(mpctx->mconfig);
2881 // Preparse the command line
2882 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
2884 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
2885 set_path_env();
2886 #endif
2888 #ifdef CONFIG_TV
2889 stream_tv_defaults.immediate = 1;
2890 #endif
2892 parse_cfgfiles(mpctx, mpctx->mconfig);
2894 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
2895 if(mpctx->playtree == NULL)
2896 opt_exit = 1;
2897 else {
2898 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
2899 if(mpctx->playtree) {
2900 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
2901 if(mpctx->playtree_iter) {
2902 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
2903 play_tree_iter_free(mpctx->playtree_iter);
2904 mpctx->playtree_iter = NULL;
2906 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
2910 mpctx->key_fifo = mp_fifo_create(opts);
2912 print_version("MPlayer");
2914 #if defined(__MINGW32__) || defined(__CYGWIN__)
2915 // stop Windows from showing all kinds of annoying error dialogs
2916 SetErrorMode(0x8003);
2917 // request 1ms timer resolution
2918 timeBeginPeriod(1);
2919 #endif
2921 #ifdef CONFIG_PRIORITY
2922 set_priority();
2923 #endif
2925 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
2926 list_video_out();
2927 opt_exit = 1;
2930 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
2931 list_audio_out();
2932 opt_exit = 1;
2935 /* Check codecs.conf. */
2936 if(!codecs_file || !parse_codec_cfg(codecs_file)){
2937 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
2938 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
2939 if(!parse_codec_cfg(NULL)){
2940 exit_player_with_rc(mpctx, EXIT_NONE, 0);
2942 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
2945 free( mem_ptr ); // release the buffer created by get_path()
2948 #if 0
2949 if(video_codec_list){
2950 int i;
2951 video_codec=video_codec_list[0];
2952 for(i=0;video_codec_list[i];i++)
2953 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
2955 #endif
2956 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
2957 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
2958 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
2959 list_codecs(1);
2960 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2961 opt_exit = 1;
2963 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
2964 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
2965 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
2966 list_codecs(0);
2967 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2968 opt_exit = 1;
2970 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
2971 vfm_help();
2972 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2973 opt_exit = 1;
2975 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
2976 afm_help();
2977 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2978 opt_exit = 1;
2980 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
2981 af_help();
2982 printf("\n");
2983 opt_exit = 1;
2985 #ifdef CONFIG_X11
2986 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
2987 fstype_help();
2988 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2989 opt_exit = 1;
2991 #endif
2992 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
2993 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
2994 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
2995 demuxer_help();
2996 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
2997 opt_exit = 1;
2999 if(list_properties) {
3000 property_print_help();
3001 opt_exit = 1;
3004 if(opt_exit)
3005 exit_player(mpctx, EXIT_NONE);
3007 if(!mpctx->filename && !player_idle_mode){
3008 // no file/vcd/dvd -> show HELP:
3009 mp_msg(MSGT_CPLAYER, MSGL_INFO, help_text);
3010 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3013 /* Display what configure line was used */
3014 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3016 // Many users forget to include command line in bugreports...
3017 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3018 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3019 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3020 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3023 //------ load global data first ------
3025 mpctx->osd = osd_create();
3027 // check font
3028 #ifdef CONFIG_FREETYPE
3029 init_freetype();
3030 #endif
3031 #ifdef CONFIG_FONTCONFIG
3032 if(font_fontconfig <= 0)
3034 #endif
3035 #ifdef CONFIG_BITMAP_FONT
3036 if(font_name){
3037 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3038 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3039 filename_recode(font_name));
3040 } else {
3041 // try default:
3042 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3043 free(mem_ptr); // release the buffer created by get_path()
3044 if(!vo_font)
3045 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3047 if (sub_font_name)
3048 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3049 else
3050 mpctx->osd->sub_font = vo_font;
3051 #endif
3052 #ifdef CONFIG_FONTCONFIG
3054 #endif
3056 #ifdef CONFIG_ASS
3057 ass_library = ass_init();
3058 #endif
3060 #ifdef HAVE_RTC
3061 if(!nortc)
3063 // seteuid(0); /* Can't hurt to try to get root here */
3064 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3065 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3066 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3067 else {
3068 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3070 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3071 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3072 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3073 close (rtc_fd);
3074 rtc_fd = -1;
3075 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3076 /* variable only by the root */
3077 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3078 close (rtc_fd);
3079 rtc_fd = -1;
3080 } else
3081 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3084 if(rtc_fd<0)
3085 #endif /* HAVE_RTC */
3086 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3087 softsleep?"software":timer_name);
3089 #ifdef HAVE_TERMCAP
3090 load_termcap(NULL); // load key-codes
3091 #endif
3093 // ========== Init keyboard FIFO (connection to libvo) ============
3095 // Init input system
3096 current_module = "init_input";
3097 mpctx->input = mp_input_init(&opts->input);
3098 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3099 if(slave_mode)
3100 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3101 else if(!noconsolecontrols)
3102 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3103 // Set the libstream interrupt callback
3104 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3106 #ifdef CONFIG_MENU
3107 if(use_menu) {
3108 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3109 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3110 else {
3111 menu_cfg = get_path("menu.conf");
3112 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3113 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3114 else {
3115 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3116 MPLAYER_CONFDIR "/menu.conf"))
3117 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3118 else {
3119 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3120 use_menu = 0;
3125 #endif
3127 current_module = NULL;
3129 /// Catch signals
3130 #ifndef __MINGW32__
3131 signal(SIGCHLD,child_sighandler);
3132 #endif
3134 #ifdef CONFIG_CRASH_DEBUG
3135 prog_path = argv[0];
3136 #endif
3137 //========= Catch terminate signals: ================
3138 // terminate requests:
3139 signal(SIGTERM,exit_sighandler); // kill
3140 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3142 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3144 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3145 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3146 #ifdef CONFIG_SIGHANDLER
3147 // fatal errors:
3148 signal(SIGBUS,exit_sighandler); // bus error
3149 signal(SIGSEGV,exit_sighandler); // segfault
3150 signal(SIGILL,exit_sighandler); // illegal instruction
3151 signal(SIGFPE,exit_sighandler); // floating point exc.
3152 signal(SIGABRT,exit_sighandler); // abort()
3153 #ifdef CONFIG_CRASH_DEBUG
3154 if (crash_debug)
3155 signal(SIGTRAP,exit_sighandler);
3156 #endif
3157 #endif
3159 // ******************* Now, let's see the per-file stuff ********************
3161 play_next_file:
3163 // init global sub numbers
3164 mpctx->global_sub_size = 0;
3165 { int i; for (i = 0; i < SUB_SOURCES; i++) mpctx->global_sub_indices[i] = -1; }
3167 if (mpctx->filename) {
3168 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3169 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3170 load_per_file_config (mpctx->mconfig, mpctx->filename);
3173 if (opts->video_driver_list)
3174 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3175 if (opts->audio_driver_list)
3176 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3178 // We must enable getch2 here to be able to interrupt network connection
3179 // or cache filling
3180 if(!noconsolecontrols && !slave_mode){
3181 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3182 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3183 else
3184 getch2_enable(); // prepare stdin for hotkeys...
3185 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3186 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3189 // =================== GUI idle loop (STOP state) ===========================
3190 while (player_idle_mode && !mpctx->filename) {
3191 play_tree_t * entry = NULL;
3192 mp_cmd_t * cmd;
3193 while (!(cmd = mp_input_get_cmd(mpctx->input, 0,1,0))) { // wait for command
3194 if (mpctx->video_out)
3195 vo_check_events(mpctx->video_out);
3196 usec_sleep(20000);
3198 switch (cmd->id) {
3199 case MP_CMD_LOADFILE:
3200 // prepare a tree entry with the new filename
3201 entry = play_tree_new();
3202 play_tree_add_file(entry, cmd->args[0].v.s);
3203 // The entry is added to the main playtree after the switch().
3204 break;
3205 case MP_CMD_LOADLIST:
3206 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3207 break;
3208 case MP_CMD_QUIT:
3209 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3210 break;
3211 case MP_CMD_GET_PROPERTY:
3212 case MP_CMD_SET_PROPERTY:
3213 case MP_CMD_STEP_PROPERTY:
3214 run_command(mpctx, cmd);
3215 break;
3218 mp_cmd_free(cmd);
3220 if (entry) { // user entered a command that gave a valid entry
3221 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3222 play_tree_free_list(mpctx->playtree->child, 1);
3223 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3225 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3227 play_tree_set_child(mpctx->playtree, entry);
3229 /* Make iterator start at the top the of tree. */
3230 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3231 if (!mpctx->playtree_iter) continue;
3233 // find the first real item in the tree
3234 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3235 // no items!
3236 play_tree_iter_free(mpctx->playtree_iter);
3237 mpctx->playtree_iter = NULL;
3238 continue; // wait for next command
3240 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3243 //---------------------------------------------------------------------------
3245 if(mpctx->filename)
3246 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3247 filename_recode(mpctx->filename));
3249 if (edl_filename) {
3250 if (edl_records) free_edl(edl_records);
3251 next_edl_record = edl_records = edl_parse_file();
3253 if (edl_output_filename) {
3254 if (edl_fd) fclose(edl_fd);
3255 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3257 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3258 filename_recode(edl_output_filename));
3262 //==================== Open VOB-Sub ============================
3264 current_module="vobsub";
3265 if (vobsub_name){
3266 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3267 if(vo_vobsub==NULL)
3268 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3269 filename_recode(vobsub_name));
3270 } else if (sub_auto && mpctx->filename){
3271 /* try to autodetect vobsub from movie filename ::atmos */
3272 char *buf = strdup(mpctx->filename), *psub;
3273 char *pdot = strrchr(buf, '.');
3274 char *pslash = strrchr(buf, '/');
3275 #if defined(__MINGW32__) || defined(__CYGWIN__)
3276 if (!pslash) pslash = strrchr(buf, '\\');
3277 #endif
3278 if (pdot && (!pslash || pdot > pslash))
3279 *pdot = '\0';
3280 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3281 /* try from ~/.mplayer/sub */
3282 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3283 char *bname;
3284 int l;
3285 bname = strrchr(buf,'/');
3286 #if defined(__MINGW32__) || defined(__CYGWIN__)
3287 if(!bname) bname = strrchr(buf,'\\');
3288 #endif
3289 if(bname) bname++;
3290 else bname = buf;
3291 l = strlen(psub) + strlen(bname) + 1;
3292 psub = realloc(psub,l);
3293 strcat(psub,bname);
3294 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3295 free(psub);
3297 free(buf);
3299 if(vo_vobsub){
3300 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3301 vobsub_set_from_lang(vo_vobsub, dvdsub_lang);
3302 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3304 // setup global sub numbering
3305 mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] = mpctx->global_sub_size; // the global # of the first vobsub.
3306 mpctx->global_sub_size += vobsub_get_indexes_count(vo_vobsub);
3309 //============ Open & Sync STREAM --- fork cache2 ====================
3311 mpctx->stream=NULL;
3312 mpctx->demuxer=NULL;
3313 if (mpctx->d_audio) {
3314 //free_demuxer_stream(mpctx->d_audio);
3315 mpctx->d_audio=NULL;
3317 if (mpctx->d_video) {
3318 //free_demuxer_stream(d_video);
3319 mpctx->d_video=NULL;
3321 mpctx->sh_audio=NULL;
3322 mpctx->sh_video=NULL;
3324 current_module="open_stream";
3325 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3326 if(!mpctx->stream) { // error...
3327 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3328 goto goto_next_file;
3330 mpctx->initialized_flags|=INITIALIZED_STREAM;
3332 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3333 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3334 "playlist support will not be used automatically.\n"
3335 "MPlayer's playlist code is unsafe and should only be used with "
3336 "trusted sources.\nPlayback will probably fail.\n\n");
3337 #if 0
3338 play_tree_t* entry;
3339 // Handle playlist
3340 current_module="handle_playlist";
3341 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3342 filename_recode(mpctx->filename));
3343 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3344 mpctx->eof=playtree_add_playlist(mpctx, entry);
3345 goto goto_next_file;
3346 #endif
3348 mpctx->stream->start_pos+=seek_to_byte;
3350 if(stream_dump_type==5){
3351 unsigned char buf[4096];
3352 int len;
3353 FILE *f;
3354 current_module="dumpstream";
3355 if(mpctx->stream->type==STREAMTYPE_STREAM && mpctx->stream->fd<0){
3356 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot dump this stream - no file descriptor available.\n");
3357 exit_player(mpctx, EXIT_ERROR);
3359 stream_reset(mpctx->stream);
3360 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3361 f=fopen(stream_dump_name,"wb");
3362 if(!f){
3363 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3364 exit_player(mpctx, EXIT_ERROR);
3366 if (dvd_chapter > 1) {
3367 int chapter = dvd_chapter - 1;
3368 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3370 while(!mpctx->stream->eof && !async_quit_request){
3371 len=stream_read(mpctx->stream,buf,4096);
3372 if(len>0) {
3373 if(fwrite(buf,len,1,f) != 1) {
3374 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3375 exit_player(mpctx, EXIT_ERROR);
3378 if(dvd_last_chapter > 0) {
3379 int chapter = -1;
3380 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3381 &chapter) == STREAM_OK && chapter + 1 > dvd_last_chapter)
3382 break;
3385 if(fclose(f)) {
3386 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3387 exit_player(mpctx, EXIT_ERROR);
3389 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3390 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3393 #ifdef CONFIG_DVDREAD
3394 if(mpctx->stream->type==STREAMTYPE_DVD){
3395 current_module="dvd lang->id";
3396 if(opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,audio_lang);
3397 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3398 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,dvdsub_lang);
3399 // setup global sub numbering
3400 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3401 mpctx->global_sub_size += dvd_number_of_subs(mpctx->stream);
3402 current_module=NULL;
3404 #endif
3406 #ifdef CONFIG_DVDNAV
3407 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3408 current_module="dvdnav lang->id";
3409 if(opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,audio_lang);
3410 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3411 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=mp_dvdnav_sid_from_lang(mpctx->stream,dvdsub_lang);
3412 // setup global sub numbering
3413 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3414 mpctx->global_sub_size += mp_dvdnav_number_of_subs(mpctx->stream);
3415 current_module=NULL;
3417 #endif
3419 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3420 goto_enable_cache:
3421 if(stream_cache_size>0){
3422 current_module="enable_cache";
3423 if(!stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3424 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3425 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0)))
3426 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3429 //============ Open DEMUXERS --- DETECT file type =======================
3430 current_module="demux_open";
3432 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3434 // HACK to get MOV Reference Files working
3436 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3438 unsigned char* playlist_entry;
3439 play_tree_t *list = NULL, *entry = NULL;
3441 current_module="handle_demux_playlist";
3442 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3444 char *temp, *bname;
3446 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3447 filename_recode(playlist_entry));
3449 bname=mp_basename(playlist_entry);
3450 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3451 continue;
3453 if (!strncmp(bname,mp_basename(mpctx->filename),strlen(bname))) // ignoring self-reference
3454 continue;
3456 entry = play_tree_new();
3458 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3460 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3461 if (temp)
3463 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3464 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3465 strcat(temp, playlist_entry);
3466 play_tree_add_file(entry,temp);
3467 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3468 free(temp);
3471 else
3472 play_tree_add_file(entry,playlist_entry);
3474 if(!list)
3475 list = entry;
3476 else
3477 play_tree_append_entry(list,entry);
3479 free_demuxer(mpctx->demuxer);
3480 mpctx->demuxer = NULL;
3482 if (list)
3484 entry = play_tree_new();
3485 play_tree_set_child(entry,list);
3486 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3487 goto goto_next_file;
3491 if(!mpctx->demuxer)
3492 goto goto_next_file;
3494 if (mpctx->demuxer->matroska_data.ordered_chapters)
3495 build_ordered_chapter_timeline(mpctx);
3497 if (!mpctx->sources) {
3498 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3499 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3500 .demuxer = mpctx->demuxer};
3501 mpctx->num_sources = 1;
3504 if(dvd_chapter>1) {
3505 double pts;
3506 if (seek_chapter(mpctx, dvd_chapter-1, &pts, NULL) >= 0 && pts > -1.0)
3507 seek(mpctx, pts, SEEK_ABSOLUTE);
3510 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3512 if (mpctx->stream->type != STREAMTYPE_DVD && mpctx->stream->type != STREAMTYPE_DVDNAV) {
3513 int i;
3514 int maxid = -1;
3515 // setup global sub numbering
3516 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3517 for (i = 0; i < MAX_S_STREAMS; i++)
3518 if (mpctx->demuxer->s_streams[i])
3519 maxid = FFMAX(maxid, mpctx->demuxer->s_streams[i]->sid);
3520 mpctx->global_sub_size += maxid + 1;
3522 // Make opts->sub_id always selectable if set.
3523 if (mpctx->global_sub_size <= mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id)
3524 mpctx->global_sub_size = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id + 1;
3526 #ifdef CONFIG_ASS
3527 if (ass_enabled && ass_library) {
3528 for (int j = 0; j < mpctx->num_sources; j++) {
3529 struct demuxer *d = mpctx->sources[j].demuxer;
3530 for (int i = 0; i < d->num_attachments; i++) {
3531 struct demux_attachment *att = d->attachments + i;
3532 if (extract_embedded_fonts
3533 && att->name && att->type && att->data && att->data_size
3534 && (strcmp(att->type, "application/x-truetype-font") == 0
3535 || strcmp(att->type, "application/x-font") == 0))
3536 ass_add_font(ass_library, att->name, att->data, att->data_size);
3540 #endif
3542 current_module="demux_open2";
3544 //file_format=demuxer->file_format;
3546 mpctx->d_audio=mpctx->demuxer->audio;
3547 mpctx->d_video=mpctx->demuxer->video;
3548 mpctx->d_sub=mpctx->demuxer->sub;
3550 // select audio stream
3551 select_audio(mpctx->demuxer, opts->audio_id, audio_lang);
3553 // DUMP STREAMS:
3554 if((stream_dump_type)&&(stream_dump_type<4)){
3555 FILE *f;
3556 demux_stream_t *ds=NULL;
3557 current_module="dump";
3558 // select stream to dump
3559 switch(stream_dump_type){
3560 case 1: ds=mpctx->d_audio;break;
3561 case 2: ds=mpctx->d_video;break;
3562 case 3: ds=mpctx->d_sub;break;
3564 if(!ds){
3565 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3566 exit_player(mpctx, EXIT_ERROR);
3568 // disable other streams:
3569 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3570 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3571 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3572 // let's dump it!
3573 f=fopen(stream_dump_name,"wb");
3574 if(!f){
3575 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3576 exit_player(mpctx, EXIT_ERROR);
3578 while(!ds->eof){
3579 unsigned char* start;
3580 int in_size=ds_get_packet(ds,&start);
3581 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3582 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3583 if(in_size>0) fwrite(start,in_size,1,f);
3584 if(dvd_last_chapter>0) {
3585 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3586 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3587 break;
3590 fclose(f);
3591 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3592 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3595 mpctx->sh_audio=mpctx->d_audio->sh;
3596 mpctx->sh_video=mpctx->d_video->sh;
3598 if(mpctx->sh_video){
3600 current_module="video_read_properties";
3601 if(!video_read_properties(mpctx->sh_video)) {
3602 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3603 mpctx->sh_video=mpctx->d_video->sh=NULL;
3604 } else {
3605 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3606 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3607 mpctx->sh_video->fps,mpctx->sh_video->frametime
3610 /* need to set fps here for output encoders to pick it up in their init */
3611 if(force_fps){
3612 mpctx->sh_video->fps=force_fps;
3613 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3615 vo_fps = mpctx->sh_video->fps;
3617 if(!mpctx->sh_video->fps && !force_fps){
3618 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3619 mpctx->sh_video=mpctx->d_video->sh=NULL;
3625 if(!mpctx->sh_video && !mpctx->sh_audio){
3626 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3627 #ifdef CONFIG_DVBIN
3628 if(mpctx->stream->type == STREAMTYPE_DVB)
3630 int dir;
3631 int v = mpctx->last_dvb_step;
3632 if(v > 0)
3633 dir = DVB_CHANNEL_HIGHER;
3634 else
3635 dir = DVB_CHANNEL_LOWER;
3637 if(dvb_step_channel(mpctx->stream, dir)) {
3638 mpctx->stop_play = PT_NEXT_ENTRY;
3639 mpctx->dvbin_reopen = 1;
3642 #endif
3643 goto goto_next_file; // exit_player(_("Fatal error"));
3646 /* display clip info */
3647 demux_info_print(mpctx->demuxer);
3649 //================== Read SUBTITLES (DVD & TEXT) ==========================
3650 if(vo_spudec==NULL && mpctx->sh_video &&
3651 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3652 init_vo_spudec(mpctx);
3655 if(mpctx->sh_video) {
3656 // after reading video params we should load subtitles because
3657 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3658 // check .sub
3659 current_module="read_subtitles_file";
3660 if(sub_name){
3661 for (i = 0; sub_name[i] != NULL; ++i)
3662 add_subtitles(mpctx, sub_name[i], mpctx->sh_video->fps, 0);
3664 if(sub_auto) { // auto load sub file ...
3665 char *psub = get_path( "sub/" );
3666 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3667 int i = 0;
3668 free(psub); // release the buffer created by get_path() above
3669 while (tmp[i]) {
3670 add_subtitles(mpctx, tmp[i], mpctx->sh_video->fps, 1);
3671 free(tmp[i++]);
3673 free(tmp);
3675 if (mpctx->set_of_sub_size > 0) {
3676 // setup global sub numbering
3677 mpctx->global_sub_indices[SUB_SOURCE_SUBS] = mpctx->global_sub_size; // the global # of the first sub.
3678 mpctx->global_sub_size += mpctx->set_of_sub_size;
3682 if (mpctx->global_sub_size) {
3683 // find the best sub to use
3684 int vobsub_index_id = vobsub_get_index_by_id(vo_vobsub, vobsub_id);
3685 mpctx->global_sub_pos = -1; // no subs by default
3686 if (vobsub_index_id >= 0) {
3687 // if user asks for a vobsub id, use that first.
3688 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] + vobsub_index_id;
3689 } else if (opts->sub_id >= 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3690 // if user asks for a dvd sub id, use that next.
3691 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3692 } else if (mpctx->global_sub_indices[SUB_SOURCE_SUBS] >= 0) {
3693 // if there are text subs to use, use those. (autosubs come last here)
3694 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_SUBS];
3695 } else if (opts->sub_id < 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3696 // finally select subs by language and container hints
3697 if (opts->sub_id < 0 && dvdsub_lang)
3698 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, dvdsub_lang);
3699 if (opts->sub_id < 0)
3700 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
3701 if (opts->sub_id >= 0)
3702 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3704 // rather than duplicate code, use the SUB_SELECT handler to init the right one.
3705 mpctx->global_sub_pos--;
3706 mp_property_do("sub",M_PROPERTY_STEP_UP,NULL, mpctx);
3707 if(subdata)
3708 switch (stream_dump_type) {
3709 case 3: list_sub_file(subdata); break;
3710 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3711 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3712 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3713 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3714 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3718 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
3719 filename_recode(mpctx->filename));
3720 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
3721 if (mpctx->sh_video) {
3722 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3723 if (mpctx->sh_video->format >= 0x20202020)
3724 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
3725 else
3726 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
3727 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
3728 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
3729 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
3730 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
3731 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
3733 if (mpctx->sh_audio) {
3734 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3735 if (mpctx->sh_audio->format >= 0x20202020)
3736 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
3737 else
3738 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
3739 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
3740 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
3741 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
3743 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2lf\n", demuxer_get_time_length(mpctx->demuxer));
3744 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
3745 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
3746 if (mpctx->demuxer) {
3747 if (mpctx->demuxer->num_chapters == 0)
3748 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
3749 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
3752 if(!mpctx->sh_video) goto main; // audio-only
3754 if(!reinit_video_chain(mpctx)) {
3755 if(!mpctx->sh_video){
3756 if(!mpctx->sh_audio) goto goto_next_file;
3757 goto main; // exit_player(_("Fatal error"));
3761 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
3762 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3764 #ifdef CONFIG_FREETYPE
3765 force_load_font = 1;
3766 #endif
3768 //================== MAIN: ==========================
3769 main:
3770 current_module="main";
3772 if(playing_msg) {
3773 char* msg = property_expand_string(mpctx, playing_msg);
3774 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
3775 free(msg);
3779 // Disable the term OSD in verbose mode
3780 if(verbose) term_osd = 0;
3783 //int frame_corr_num=0; //
3784 //float v_frame=0; // Video
3785 //float num_frames=0; // number of frames played
3787 int frame_time_remaining=0; // flag
3788 int blit_frame=0;
3789 mpctx->num_buffered_frames=0;
3791 // Make sure old OSD does not stay around,
3792 // e.g. with -fixed-vo and same-resolution files
3793 clear_osd_msgs();
3794 update_osd_msg(mpctx);
3796 //================ SETUP AUDIO ==========================
3798 if(mpctx->sh_audio){
3799 reinit_audio_chain(mpctx);
3800 if (mpctx->sh_audio && mpctx->sh_audio->codec)
3801 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
3804 current_module="av_init";
3806 if(mpctx->sh_video){
3807 mpctx->sh_video->timer=0;
3808 if (! ignore_start)
3809 audio_delay += mpctx->sh_video->stream_delay;
3811 if(mpctx->sh_audio){
3812 if (start_volume >= 0)
3813 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
3814 if (! ignore_start)
3815 audio_delay -= mpctx->sh_audio->stream_delay;
3816 mpctx->delay=-audio_delay;
3819 if(!mpctx->sh_audio){
3820 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
3821 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
3822 ds_free_packs(mpctx->d_audio); // free buffered chunks
3823 //mpctx->d_audio->id=-2; // do not read audio chunks
3824 //uninit_player(mpctx, INITIALIZED_AO); // close device
3826 if(!mpctx->sh_video){
3827 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
3828 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
3829 ds_free_packs(mpctx->d_video);
3830 mpctx->d_video->id=-2;
3831 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
3834 if (!mpctx->sh_video && !mpctx->sh_audio)
3835 goto goto_next_file;
3837 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
3838 if(force_fps && mpctx->sh_video){
3839 vo_fps = mpctx->sh_video->fps=force_fps;
3840 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3841 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
3844 mp_input_set_section(mpctx->input, NULL);
3845 //TODO: add desired (stream-based) sections here
3846 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
3847 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
3849 //==================== START PLAYING =======================
3851 if(opts->loop_times>1) opts->loop_times--; else
3852 if(opts->loop_times==1) opts->loop_times = -1;
3854 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
3856 total_time_usage_start=GetTimer();
3857 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
3858 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
3859 play_n_frames=play_n_frames_mf;
3861 if(play_n_frames==0){
3862 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
3865 if (seek_to_sec) {
3866 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
3867 end_at.pos += seek_to_sec;
3870 if (end_at.type == END_AT_SIZE) {
3871 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
3872 end_at.type = END_AT_NONE;
3875 #ifdef CONFIG_DVDNAV
3876 mp_dvdnav_context_free(mpctx);
3877 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3878 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
3879 mp_dvdnav_cell_has_changed(mpctx->stream,1);
3881 #endif
3883 get_relative_time(mpctx); // reset current delta
3884 mpctx->time_frame = 0;
3885 mpctx->drop_message_shown = 0;
3886 mpctx->update_video_immediately = true;
3887 mpctx->total_avsync_change = 0;
3888 // Make sure VO knows current pause state
3889 if (mpctx->sh_video)
3890 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
3891 NULL);
3893 while(!mpctx->stop_play){
3894 float aq_sleep_time=0;
3896 if(dvd_last_chapter>0) {
3897 int cur_chapter = get_current_chapter(mpctx);
3898 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3899 goto goto_next_file;
3902 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
3903 mpctx->sh_audio = mpctx->d_audio->sh;
3904 mpctx->sh_audio->ds = mpctx->d_audio;
3905 reinit_audio_chain(mpctx);
3908 /*========================== PLAY AUDIO ============================*/
3910 if (mpctx->sh_audio && !mpctx->paused)
3911 if (!fill_audio_out_buffers(mpctx))
3912 // at eof, all audio at least written to ao
3913 if (!mpctx->sh_video)
3914 mpctx->stop_play = AT_END_OF_FILE;
3917 if(!mpctx->sh_video) {
3918 // handle audio-only case:
3919 double a_pos=0;
3920 // sh_audio can be NULL due to video stream switching
3921 // TODO: handle this better
3922 if (mpctx->sh_audio)
3923 a_pos = playing_audio_pts(mpctx);
3925 print_status(mpctx, a_pos, false);
3927 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
3928 mpctx->stop_play = PT_NEXT_ENTRY;
3929 update_osd_msg(mpctx);
3931 } else {
3933 /*========================== PLAY VIDEO ============================*/
3935 vo_pts=mpctx->sh_video->timer*90000.0;
3936 vo_fps=mpctx->sh_video->fps;
3938 if (!mpctx->num_buffered_frames) {
3939 double frame_time = update_video(mpctx, &blit_frame);
3940 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
3941 if (mpctx->sh_video->vf_initialized < 0) {
3942 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
3943 mpctx->stop_play = PT_NEXT_ENTRY;
3944 goto goto_next_file;
3946 if (blit_frame) {
3947 struct vf_instance *vf = mpctx->sh_video->vfilter;
3948 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3949 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3950 vo_osd_changed(0);
3952 if (frame_time < 0)
3953 mpctx->stop_play = AT_END_OF_FILE;
3954 else {
3955 // might return with !eof && !blit_frame if !correct_pts
3956 mpctx->num_buffered_frames += blit_frame;
3957 if (mpctx->update_video_immediately) {
3958 // Show this frame immediately, rest normally
3959 mpctx->update_video_immediately = false;
3960 } else {
3961 mpctx->time_frame += frame_time / opts->playback_speed;
3962 adjust_sync(mpctx, frame_time);
3966 if (mpctx->timeline) {
3967 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
3968 if (mpctx->sh_video->pts >= next->start
3969 || mpctx->stop_play == AT_END_OF_FILE
3970 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3971 seek(mpctx, next->start, SEEK_ABSOLUTE);
3972 continue;
3976 // ==========================================================================
3978 // current_module="draw_osd";
3979 // if(vo_config_count) mpctx->video_out->draw_osd();
3981 current_module="vo_check_events";
3982 vo_check_events(mpctx->video_out);
3984 #ifdef CONFIG_X11
3985 if (stop_xscreensaver) {
3986 current_module = "stop_xscreensaver";
3987 xscreensaver_heartbeat(mpctx->x11_state);
3989 #endif
3990 if (heartbeat_cmd) {
3991 static unsigned last_heartbeat;
3992 unsigned now = GetTimerMS();
3993 if (now - last_heartbeat > 30000) {
3994 last_heartbeat = now;
3995 system(heartbeat_cmd);
3999 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4001 //====================== FLIP PAGE (VIDEO BLT): =========================
4003 current_module="flip_page";
4004 if (!frame_time_remaining && blit_frame) {
4005 unsigned int t2=GetTimer();
4007 vo_flip_page(mpctx->video_out);
4008 mpctx->num_buffered_frames--;
4010 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4011 vout_time_usage += mpctx->last_vo_flip_duration;
4012 print_status(mpctx, MP_NOPTS_VALUE, true);
4014 else
4015 print_status(mpctx, MP_NOPTS_VALUE, false);
4017 //============================ Auto QUALITY ============================
4019 /*Output quality adjustments:*/
4020 if(auto_quality>0){
4021 current_module="autoq";
4022 // float total=0.000001f * (GetTimer()-aq_total_time);
4023 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4024 if(output_quality<auto_quality && aq_sleep_time>0)
4025 ++output_quality;
4026 else
4027 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4028 if(output_quality>1 && aq_sleep_time<0)
4029 --output_quality;
4030 else
4031 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4032 output_quality=0;
4033 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4034 set_video_quality(mpctx->sh_video,output_quality);
4037 if (!frame_time_remaining && blit_frame) {
4038 if (play_n_frames >= 0) {
4039 --play_n_frames;
4040 if (play_n_frames <= 0)
4041 mpctx->stop_play = PT_NEXT_ENTRY;
4043 if (mpctx->step_frames > 0) {
4044 mpctx->step_frames--;
4045 if (mpctx->step_frames == 0)
4046 pause_player(mpctx);
4051 // FIXME: add size based support for -endpos
4052 if (end_at.type == END_AT_TIME &&
4053 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4054 mpctx->stop_play = PT_NEXT_ENTRY;
4056 } // end if(mpctx->sh_video)
4058 #ifdef CONFIG_DVDNAV
4059 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4060 nav_highlight_t hl;
4061 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4062 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4063 vo_osd_changed (OSDTYPE_DVDNAV);
4065 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4066 double ar = -1.0;
4067 if (stream_control (mpctx->demuxer->stream,
4068 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4069 != STREAM_UNSUPPORTED)
4070 mpctx->sh_video->stream_aspect = ar;
4073 #endif
4075 //================= Keyboard events, SEEKing ====================
4077 current_module="key_events";
4080 while (1) {
4081 mp_cmd_t* cmd;
4082 while ((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
4083 run_command(mpctx, cmd);
4084 mp_cmd_free(cmd);
4085 if (mpctx->stop_play)
4086 break;
4088 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4089 || mpctx->abs_seek_pos)
4090 break;
4091 if (mpctx->sh_video) {
4092 update_osd_msg(mpctx);
4093 int hack = vo_osd_changed(0);
4094 vo_osd_changed(hack);
4095 if (hack)
4096 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4097 add_step_frame(mpctx);
4098 break;
4100 else
4101 vo_osd_changed(0);
4103 pause_loop(mpctx);
4107 // handle -sstep
4108 if (step_sec > 0 && !mpctx->paused) {
4109 mpctx->osd_function=OSD_FFW;
4110 mpctx->rel_seek_secs+=step_sec;
4113 edl_update(mpctx);
4115 /* Looping. */
4116 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4117 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4119 if(opts->loop_times>1) opts->loop_times--; else
4120 if(opts->loop_times==1) opts->loop_times=-1;
4121 play_n_frames=play_n_frames_mf;
4122 mpctx->stop_play=0;
4123 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4126 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4127 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4129 mpctx->rel_seek_secs=0;
4130 mpctx->abs_seek_pos=0;
4133 } // while(!mpctx->stop_play)
4135 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4137 #ifdef CONFIG_DVBIN
4138 if(mpctx->dvbin_reopen)
4140 mpctx->stop_play = 0;
4141 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4142 cache_uninit(mpctx->stream);
4143 mpctx->dvbin_reopen = 0;
4144 goto goto_enable_cache;
4146 #endif
4149 goto_next_file: // don't jump here after ao/vo/getch initialization!
4151 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4153 if(benchmark){
4154 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4155 double total_time_usage;
4156 total_time_usage_start=GetTimer()-total_time_usage_start;
4157 total_time_usage = (float)total_time_usage_start*0.000001;
4158 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4159 video_time_usage,vout_time_usage,audio_time_usage,
4160 total_time_usage-tot,total_time_usage);
4161 if(total_time_usage>0.0)
4162 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4163 100.0*video_time_usage/total_time_usage,
4164 100.0*vout_time_usage/total_time_usage,
4165 100.0*audio_time_usage/total_time_usage,
4166 100.0*(total_time_usage-tot)/total_time_usage,
4167 100.0);
4168 if(total_frame_cnt && frame_dropping)
4169 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4170 total_frame_cnt-drop_frame_cnt,
4171 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4172 drop_frame_cnt,
4173 100*drop_frame_cnt/total_frame_cnt,
4174 total_frame_cnt,
4175 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4178 // time to uninit all, except global stuff:
4179 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4181 if(mpctx->set_of_sub_size > 0) {
4182 current_module="sub_free";
4183 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4184 sub_free(mpctx->set_of_subtitles[i]);
4185 #ifdef CONFIG_ASS
4186 if(mpctx->set_of_ass_tracks[i])
4187 ass_free_track( mpctx->set_of_ass_tracks[i] );
4188 #endif
4190 mpctx->set_of_sub_size = 0;
4192 vo_sub_last = vo_sub=NULL;
4193 subdata=NULL;
4194 #ifdef CONFIG_ASS
4195 ass_track = NULL;
4196 if(ass_library)
4197 ass_clear_fonts(ass_library);
4198 #endif
4200 if (!mpctx->stop_play) // In case some goto jumped here...
4201 mpctx->stop_play = PT_NEXT_ENTRY;
4203 int playtree_direction = 1;
4205 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4206 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4207 play_tree_iter_free(mpctx->playtree_iter);
4208 mpctx->playtree_iter = NULL;
4210 mpctx->play_tree_step = 1;
4211 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4212 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4213 if(mpctx->playtree_iter) {
4214 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4215 play_tree_iter_free(mpctx->playtree_iter);
4216 mpctx->playtree_iter = NULL;
4219 } else if (mpctx->stop_play == PT_STOP) {
4220 play_tree_iter_free(mpctx->playtree_iter);
4221 mpctx->playtree_iter = NULL;
4222 } else { // NEXT PREV SRC
4223 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4226 while(mpctx->playtree_iter != NULL) {
4227 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4228 if(mpctx->filename == NULL) {
4229 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4230 play_tree_iter_free(mpctx->playtree_iter);
4231 mpctx->playtree_iter = NULL;
4233 } else
4234 break;
4237 if(mpctx->playtree_iter != NULL || player_idle_mode){
4238 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4239 mpctx->stop_play = 0;
4240 goto play_next_file;
4244 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4246 return 1;
4248 #endif /* DISABLE_MAIN */