Fix the update script
[mplayer/kovensky.git] / mplayer.c
blobf6bdb6ae4b1c66fdd1c78329769cf9ba3274d7a0
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 "ffmpeg_files/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 #include "ass_mp.h"
314 char* current_module=NULL; // for debugging
317 // ---
319 #ifdef CONFIG_MENU
320 #include "m_struct.h"
321 #include "libmenu/menu.h"
322 void vf_menu_pause_update(struct vf_instance* vf);
323 extern vf_info_t vf_info_menu;
324 static const vf_info_t* const libmenu_vfs[] = {
325 &vf_info_menu,
326 NULL
328 static vf_instance_t* vf_menu = NULL;
329 int use_menu = 0;
330 static char* menu_cfg = NULL;
331 static char* menu_root = "main";
332 #endif
335 #ifdef HAVE_RTC
336 static int nortc = 1;
337 static char* rtc_device;
338 #endif
340 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
341 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
342 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
343 int use_filedir_conf;
345 #include "mpcommon.h"
346 #include "command.h"
348 #include "metadata.h"
350 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
352 const void *mpctx_get_video_out(MPContext *mpctx)
354 return mpctx->video_out;
357 const void *mpctx_get_audio_out(MPContext *mpctx)
359 return mpctx->audio_out;
362 void *mpctx_get_demuxer(MPContext *mpctx)
364 return mpctx->demuxer;
367 void *mpctx_get_playtree_iter(MPContext *mpctx)
369 return mpctx->playtree_iter;
372 void *mpctx_get_mixer(MPContext *mpctx)
374 return &mpctx->mixer;
377 int mpctx_get_global_sub_size(MPContext *mpctx)
379 return mpctx->global_sub_size;
382 int mpctx_get_osd_function(MPContext *mpctx)
384 return mpctx->osd_function;
387 static float get_relative_time(struct MPContext *mpctx)
389 unsigned int new_time = GetTimer();
390 unsigned int delta = new_time - mpctx->last_time;
391 mpctx->last_time = new_time;
392 return delta * 0.000001;
395 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
396 switch (type)
398 /* check for valid video stream */
399 case META_VIDEO_CODEC:
400 case META_VIDEO_BITRATE:
401 case META_VIDEO_RESOLUTION:
403 if (!mpctx->sh_video)
404 return 0;
405 break;
408 /* check for valid audio stream */
409 case META_AUDIO_CODEC:
410 case META_AUDIO_BITRATE:
411 case META_AUDIO_SAMPLES:
413 if (!mpctx->sh_audio)
414 return 0;
415 break;
418 /* check for valid demuxer */
419 case META_INFO_TITLE:
420 case META_INFO_ARTIST:
421 case META_INFO_ALBUM:
422 case META_INFO_YEAR:
423 case META_INFO_COMMENT:
424 case META_INFO_TRACK:
425 case META_INFO_GENRE:
427 if (!mpctx->demuxer)
428 return 0;
429 break;
432 default:
433 break;
436 return 1;
439 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
440 char **info = mpctx->demuxer->info;
441 int n;
443 if (!info || !tag)
444 return NULL;
446 for (n = 0; info[2*n] != NULL ; n++)
447 if (!strcasecmp (info[2*n], tag))
448 break;
450 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
453 char *get_metadata(struct MPContext *mpctx, metadata_t type)
455 char *meta = NULL;
456 sh_audio_t * const sh_audio = mpctx->sh_audio;
457 sh_video_t * const sh_video = mpctx->sh_video;
459 if (!is_valid_metadata_type(mpctx, type))
460 return NULL;
462 switch (type)
464 case META_NAME:
466 return strdup (mp_basename2 (mpctx->filename));
469 case META_VIDEO_CODEC:
471 if (sh_video->format == 0x10000001)
472 meta = strdup ("mpeg1");
473 else if (sh_video->format == 0x10000002)
474 meta = strdup ("mpeg2");
475 else if (sh_video->format == 0x10000004)
476 meta = strdup ("mpeg4");
477 else if (sh_video->format == 0x10000005)
478 meta = strdup ("h264");
479 else if (sh_video->format >= 0x20202020)
481 meta = malloc (8);
482 sprintf (meta, "%.4s", (char *) &sh_video->format);
484 else
486 meta = malloc (8);
487 sprintf (meta, "0x%08X", sh_video->format);
489 return meta;
492 case META_VIDEO_BITRATE:
494 meta = malloc (16);
495 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
496 return meta;
499 case META_VIDEO_RESOLUTION:
501 meta = malloc (16);
502 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
503 return meta;
506 case META_AUDIO_CODEC:
508 if (sh_audio->codec && sh_audio->codec->name)
509 meta = strdup (sh_audio->codec->name);
510 return meta;
513 case META_AUDIO_BITRATE:
515 meta = malloc (16);
516 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
517 return meta;
520 case META_AUDIO_SAMPLES:
522 meta = malloc (16);
523 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
524 return meta;
527 /* check for valid demuxer */
528 case META_INFO_TITLE:
529 return get_demuxer_info(mpctx, "Title");
531 case META_INFO_ARTIST:
532 return get_demuxer_info(mpctx, "Artist");
534 case META_INFO_ALBUM:
535 return get_demuxer_info(mpctx, "Album");
537 case META_INFO_YEAR:
538 return get_demuxer_info(mpctx, "Year");
540 case META_INFO_COMMENT:
541 return get_demuxer_info(mpctx, "Comment");
543 case META_INFO_TRACK:
544 return get_demuxer_info(mpctx, "Track");
546 case META_INFO_GENRE:
547 return get_demuxer_info(mpctx, "Genre");
549 default:
550 break;
553 return meta;
556 /// step size of mixer changes
557 int volstep = 3;
559 #ifdef CONFIG_DVDNAV
560 static void mp_dvdnav_context_free(MPContext *ctx){
561 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
562 ctx->nav_smpi = NULL;
563 if (ctx->nav_buffer) free(ctx->nav_buffer);
564 ctx->nav_buffer = NULL;
565 ctx->nav_start = NULL;
566 ctx->nav_in_size = 0;
568 #endif
570 void uninit_player(struct MPContext *mpctx, unsigned int mask){
571 mask=mpctx->initialized_flags&mask;
573 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
575 if(mask&INITIALIZED_ACODEC){
576 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
577 current_module="uninit_acodec";
578 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
579 mpctx->sh_audio=NULL;
580 mpctx->mixer.afilter = NULL;
583 if(mask&INITIALIZED_VCODEC){
584 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
585 current_module="uninit_vcodec";
586 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
587 mpctx->sh_video=NULL;
588 #ifdef CONFIG_MENU
589 vf_menu=NULL;
590 #endif
593 if(mask&INITIALIZED_DEMUXER){
594 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
595 current_module="free_demuxer";
596 if (mpctx->num_sources) {
597 mpctx->demuxer = mpctx->sources[0].demuxer;
598 for (int i = 1; i < mpctx->num_sources; i++) {
599 free_stream(mpctx->sources[i].stream);
600 free_demuxer(mpctx->sources[i].demuxer);
603 talloc_free(mpctx->sources);
604 mpctx->sources = NULL;
605 mpctx->num_sources = 0;
606 talloc_free(mpctx->timeline);
607 mpctx->timeline = NULL;
608 mpctx->num_timeline_parts = 0;
609 talloc_free(mpctx->chapters);
610 mpctx->chapters = NULL;
611 mpctx->num_chapters = 0;
612 mpctx->video_offset = 0;
613 if(mpctx->demuxer){
614 mpctx->stream=mpctx->demuxer->stream;
615 free_demuxer(mpctx->demuxer);
617 mpctx->demuxer=NULL;
620 // kill the cache process:
621 if(mask&INITIALIZED_STREAM){
622 mpctx->initialized_flags&=~INITIALIZED_STREAM;
623 current_module="uninit_stream";
624 if(mpctx->stream) free_stream(mpctx->stream);
625 mpctx->stream=NULL;
628 if(mask&INITIALIZED_VO){
629 mpctx->initialized_flags&=~INITIALIZED_VO;
630 current_module="uninit_vo";
631 vo_destroy(mpctx->video_out);
632 mpctx->video_out=NULL;
633 #ifdef CONFIG_DVDNAV
634 mp_dvdnav_context_free(mpctx);
635 #endif
638 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
639 if(mask&INITIALIZED_GETCH2){
640 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
641 current_module="uninit_getch2";
642 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
643 // restore terminal:
644 getch2_disable();
647 if(mask&INITIALIZED_VOBSUB){
648 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
649 current_module="uninit_vobsub";
650 if(vo_vobsub) vobsub_close(vo_vobsub);
651 vo_vobsub=NULL;
654 if (mask&INITIALIZED_SPUDEC){
655 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
656 current_module="uninit_spudec";
657 spudec_free(vo_spudec);
658 vo_spudec=NULL;
661 if(mask&INITIALIZED_AO){
662 mpctx->initialized_flags&=~INITIALIZED_AO;
663 current_module="uninit_ao";
664 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
665 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
666 mpctx->audio_out=NULL;
669 current_module=NULL;
672 void exit_player_with_rc(struct MPContext *mpctx, exit_reason_t how, int rc)
674 uninit_player(mpctx, INITIALIZED_ALL);
675 #if defined(__MINGW32__) || defined(__CYGWIN__)
676 timeEndPeriod(1);
677 #endif
678 #ifdef CONFIG_X11
679 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
680 #endif
682 current_module="uninit_input";
683 mp_input_uninit(mpctx->input);
684 #ifdef CONFIG_MENU
685 if (use_menu)
686 menu_uninit();
687 #endif
689 #ifdef CONFIG_FREETYPE
690 current_module="uninit_font";
691 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
692 free_font_desc(mpctx->osd->sub_font);
693 free_font_desc(vo_font);
694 vo_font = NULL;
695 done_freetype();
696 #endif
697 osd_free(mpctx->osd);
699 #ifdef CONFIG_ASS
700 ass_library_done(ass_library);
701 #endif
703 current_module="exit_player";
705 // free mplayer config
706 if(mpctx->mconfig)
707 m_config_free(mpctx->mconfig);
709 if(mpctx->playtree)
710 play_tree_free(mpctx->playtree, 1);
712 talloc_free(mpctx->key_fifo);
714 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
715 switch(how) {
716 case EXIT_QUIT:
717 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
718 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
719 break;
720 case EXIT_EOF:
721 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
722 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
723 break;
724 case EXIT_ERROR:
725 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
726 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
727 break;
728 default:
729 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
731 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
733 exit(rc);
736 static void exit_player(struct MPContext *mpctx, exit_reason_t how)
738 exit_player_with_rc(mpctx, how, 1);
741 #ifndef __MINGW32__
742 static void child_sighandler(int x){
743 pid_t pid;
744 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
746 #endif
748 #ifdef CONFIG_CRASH_DEBUG
749 static char *prog_path;
750 static int crash_debug = 0;
751 #endif
753 static void exit_sighandler(int x){
754 static int sig_count=0;
755 #ifdef CONFIG_CRASH_DEBUG
756 if (!crash_debug || x != SIGTRAP)
757 #endif
758 ++sig_count;
759 if(sig_count==5)
761 /* We're crashing bad and can't uninit cleanly :(
762 * by popular request, we make one last (dirty)
763 * effort to restore the user's
764 * terminal. */
765 getch2_disable();
766 exit(1);
768 if(sig_count==6) exit(1);
769 if(sig_count>6){
770 // can't stop :(
771 #ifndef __MINGW32__
772 kill(getpid(),SIGKILL);
773 #endif
775 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"\n" "\nMPlayer interrupted by signal %d in module: %s\n",x,
776 current_module?current_module:"unknown"
778 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
779 if(sig_count<=1)
780 switch(x){
781 case SIGINT:
782 case SIGQUIT:
783 case SIGTERM:
784 case SIGKILL:
785 async_quit_request = 1;
786 return; // killed from keyboard (^C) or killed [-9]
787 case SIGILL:
788 #if CONFIG_RUNTIME_CPUDETECT
789 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
790 #else
791 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
792 #endif
793 case SIGFPE:
794 case SIGSEGV:
795 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
796 default:
797 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
798 #ifdef CONFIG_CRASH_DEBUG
799 if (crash_debug) {
800 int gdb_pid;
801 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
802 gdb_pid = fork();
803 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
804 if (gdb_pid == 0) { // We are the child
805 char spid[20];
806 snprintf(spid, sizeof(spid), "%i", getppid());
807 getch2_disable(); // allow terminal to work properly with gdb
808 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
809 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
810 } else if (gdb_pid < 0)
811 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
812 else {
813 waitpid(gdb_pid, NULL, 0);
815 if (x == SIGTRAP) return;
817 #endif
819 getch2_disable();
820 exit(1);
823 #include "cfg-mplayer.h"
825 static int cfg_include(m_option_t *conf, char *filename)
827 return m_config_parse_config_file(conf->priv, filename);
830 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
832 char *conffile;
833 int conffile_fd;
834 if (!disable_system_conf &&
835 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
836 exit_player(mpctx, EXIT_NONE);
837 if ((conffile = get_path("")) == NULL) {
838 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
839 } else {
840 #ifdef __MINGW32__
841 mkdir(conffile);
842 #else
843 mkdir(conffile, 0777);
844 #endif
845 free(conffile);
846 if ((conffile = get_path("config")) == NULL) {
847 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
848 } else {
849 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
850 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
851 write(conffile_fd, default_config, strlen(default_config));
852 close(conffile_fd);
854 if (!disable_user_conf &&
855 m_config_parse_config_file(conf, conffile) < 0)
856 exit_player(mpctx, EXIT_NONE);
857 free(conffile);
862 #define PROFILE_CFG_PROTOCOL "protocol."
864 static void load_per_protocol_config (m_config_t* conf, const char *const file)
866 char *str;
867 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
868 m_profile_t *p;
870 /* does filename actually uses a protocol ? */
871 str = strstr (file, "://");
872 if (!str)
873 return;
875 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
876 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
877 p = m_config_get_profile (conf, protocol);
878 if (p)
880 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
881 m_config_set_profile(conf,p);
885 #define PROFILE_CFG_EXTENSION "extension."
887 static void load_per_extension_config (m_config_t* conf, const char *const file)
889 char *str;
890 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
891 m_profile_t *p;
893 /* does filename actually have an extension ? */
894 str = strrchr (file, '.');
895 if (!str)
896 return;
898 sprintf (extension, PROFILE_CFG_EXTENSION);
899 strncat (extension, ++str, 7);
900 p = m_config_get_profile (conf, extension);
901 if (p)
903 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
904 m_config_set_profile(conf,p);
908 #define PROFILE_CFG_VO "vo."
909 #define PROFILE_CFG_AO "ao."
911 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
913 char profile[strlen (cfg) + strlen (out) + 1];
914 m_profile_t *p;
916 sprintf (profile, "%s%s", cfg, out);
917 p = m_config_get_profile (conf, profile);
918 if (p)
920 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
921 m_config_set_profile(conf,p);
925 static void load_per_file_config (m_config_t* conf, const char *const file)
927 char *confpath;
928 char cfg[strlen(file)+10];
929 struct stat st;
930 char *name;
932 sprintf (cfg, "%s.conf", file);
934 if (use_filedir_conf && !stat (cfg, &st))
936 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading config '%s'\n", cfg);
937 m_config_parse_config_file (conf, cfg);
938 return;
941 if ((name = strrchr (cfg, '/')) == NULL)
942 name = cfg;
943 else
944 name++;
946 if ((confpath = get_path (name)) != NULL)
948 if (!stat (confpath, &st))
950 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading config '%s'\n", confpath);
951 m_config_parse_config_file (conf, confpath);
954 free (confpath);
958 /* When libmpdemux performs a blocking operation (network connection or
959 * cache filling) if the operation fails we use this function to check
960 * if it was interrupted by the user.
961 * The function returns a new value for eof. */
962 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
964 mp_cmd_t* cmd;
965 if((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
966 switch(cmd->id) {
967 case MP_CMD_QUIT:
968 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
969 case MP_CMD_PLAY_TREE_STEP: {
970 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
971 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
972 } break;
973 case MP_CMD_PLAY_TREE_UP_STEP: {
974 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
975 } break;
976 case MP_CMD_PLAY_ALT_SRC_STEP: {
977 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
978 } break;
980 mp_cmd_free(cmd);
982 return stop_play;
985 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
987 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
989 play_tree_add_bpf(entry,mpctx->filename);
992 if(!entry) {
993 entry = mpctx->playtree_iter->tree;
994 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
995 return PT_NEXT_ENTRY;
997 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
998 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
999 return PT_NEXT_ENTRY;
1002 play_tree_remove(entry,1,1);
1003 return PT_NEXT_SRC;
1005 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1006 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1007 entry = mpctx->playtree_iter->tree;
1008 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1009 return PT_NEXT_ENTRY;
1011 play_tree_remove(entry,1,1);
1013 return PT_NEXT_SRC;
1016 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1018 sub_data *subd;
1019 #ifdef CONFIG_ASS
1020 ASS_Track *asst = 0;
1021 #endif
1023 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1024 return;
1027 subd = sub_read_file(filename, fps);
1028 #ifdef CONFIG_ASS
1029 if (ass_enabled)
1030 #ifdef CONFIG_ICONV
1031 asst = ass_read_file(ass_library, filename, sub_cp);
1032 #else
1033 asst = ass_read_file(ass_library, filename, 0);
1034 #endif
1035 if (ass_enabled && subd && !asst)
1036 asst = ass_read_subdata(ass_library, subd, fps);
1038 if (!asst && !subd)
1039 #else
1040 if(!subd)
1041 #endif
1042 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR, "Cannot load subtitles: %s\n",
1043 filename_recode(filename));
1044 #if defined(_WIN32) && !defined(HAVE_NEW_GUI)
1045 if(filename) {
1046 static char message[MAX_PATH + 1];
1047 char *s = strrchr(filename, '\\');
1048 if (!s) s = strrchr(filename, '/');
1049 if (s) s++; else s = filename;
1050 message[0] = 0;
1051 snprintf(message, MAX_PATH, "MPlayer: %s", filename_recode(s));
1052 message[MAX_PATH] = 0;
1053 SetConsoleTitle(message);
1055 #endif
1057 #ifdef CONFIG_ASS
1058 if (!asst && !subd) return;
1059 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1060 #else
1061 if (!subd) return;
1062 #endif
1063 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1064 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1065 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1066 filename_recode(filename));
1067 ++mpctx->set_of_sub_size;
1068 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1069 filename_recode(filename));
1072 void init_vo_spudec(struct MPContext *mpctx)
1074 if (vo_spudec)
1075 spudec_free(vo_spudec);
1076 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1077 vo_spudec = NULL;
1078 if (spudec_ifo) {
1079 unsigned int palette[16], width, height;
1080 current_module="spudec_init_vobsub";
1081 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1082 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1085 #ifdef CONFIG_DVDREAD
1086 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1087 current_module="spudec_init_dvdread";
1088 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1089 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1090 NULL, 0);
1092 #endif
1094 #ifdef CONFIG_DVDNAV
1095 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1096 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1097 current_module="spudec_init_dvdnav";
1098 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1100 #endif
1102 if (vo_spudec==NULL) {
1103 sh_sub_t *sh = (sh_sub_t *)mpctx->d_sub->sh;
1104 current_module="spudec_init_normal";
1105 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1106 spudec_set_font_factor(vo_spudec,font_factor);
1109 if (vo_spudec!=NULL) {
1110 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1111 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1116 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1117 * make it all work is to use the builtin SDL-bootstrap code, which
1118 * will be done automatically by replacing our main() if we include SDL.h.
1120 #if defined(__APPLE__) && defined(CONFIG_SDL)
1121 #include <SDL.h>
1122 #endif
1125 * \brief append a formatted string
1126 * \param buf buffer to print into
1127 * \param pos position of terminating 0 in buf
1128 * \param len maximum number of characters in buf, not including terminating 0
1129 * \param format printf format string
1131 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1133 va_list va;
1134 va_start(va, format);
1135 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1136 va_end(va);
1137 if (*pos >= len ) {
1138 buf[len] = 0;
1139 *pos = len;
1144 * \brief append time in the hh:mm:ss.f format
1145 * \param buf buffer to print into
1146 * \param pos position of terminating 0 in buf
1147 * \param len maximum number of characters in buf, not including terminating 0
1148 * \param time time value to convert/append
1150 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1151 long tenths = 10 * time;
1152 int f1 = tenths % 10;
1153 int ss = (tenths / 10) % 60;
1154 int mm = (tenths / 600) % 60;
1155 int hh = tenths / 36000;
1156 if (time <= 0) {
1157 saddf(buf, pos, len, "unknown");
1158 return;
1160 if (hh > 0)
1161 saddf(buf, pos, len, "%2d:", hh);
1162 if (hh > 0 || mm > 0)
1163 saddf(buf, pos, len, "%02d:", mm);
1164 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1167 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1169 struct MPOpts *opts = &mpctx->opts;
1170 sh_video_t * const sh_video = mpctx->sh_video;
1172 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1173 a_pos = playing_audio_pts(mpctx);
1174 if (mpctx->sh_audio && sh_video && at_frame) {
1175 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1176 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1177 && !mpctx->drop_message_shown) {
1178 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1179 mpctx->drop_message_shown = true;
1182 if (quiet)
1183 return;
1186 int width;
1187 char *line;
1188 unsigned pos = 0;
1189 get_screen_size();
1190 if (screen_width > 0)
1191 width = screen_width;
1192 else
1193 width = 80;
1194 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1195 /* Windows command line is broken (MinGW's rxvt works, but we
1196 * should not depend on that). */
1197 width--;
1198 #endif
1199 line = malloc(width + 1); // one additional char for the terminating null
1201 // Audio time
1202 if (mpctx->sh_audio) {
1203 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1204 if (!sh_video) {
1205 float len = demuxer_get_time_length(mpctx->demuxer);
1206 saddf(line, &pos, width, "(");
1207 sadd_hhmmssf(line, &pos, width, a_pos);
1208 saddf(line, &pos, width, ") of %.1f (", len);
1209 sadd_hhmmssf(line, &pos, width, len);
1210 saddf(line, &pos, width, ") ");
1214 // Video time
1215 if (sh_video)
1216 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1218 // A-V sync
1219 if (mpctx->sh_audio && sh_video)
1220 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1221 mpctx->last_av_difference, mpctx->total_avsync_change);
1223 // Video stats
1224 if (sh_video)
1225 saddf(line, &pos, width, "%3d/%3d ",
1226 (int)sh_video->num_frames,
1227 (int)sh_video->num_frames_decoded);
1229 // CPU usage
1230 if (sh_video) {
1231 if (sh_video->timer > 0.5)
1232 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1233 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1234 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1235 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1236 else
1237 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1238 } else if (mpctx->sh_audio) {
1239 if (mpctx->delay > 0.5)
1240 saddf(line, &pos, width, "%4.1f%% ",
1241 100.0*audio_time_usage/(double)mpctx->delay);
1242 else
1243 saddf(line, &pos, width, "??,?%% ");
1246 // VO stats
1247 if (sh_video)
1248 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1250 #ifdef CONFIG_STREAM_CACHE
1251 // cache stats
1252 if (stream_cache_size > 0)
1253 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1254 #endif
1256 // other
1257 if (opts->playback_speed != 1)
1258 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1260 // end
1261 if (erase_to_end_of_line) {
1262 line[pos] = 0;
1263 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1264 } else {
1265 memset(&line[pos], ' ', width - pos);
1266 line[width] = 0;
1267 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1269 free(line);
1273 * \brief build a chain of audio filters that converts the input format
1274 * to the ao's format, taking into account the current playback_speed.
1275 * \param sh_audio describes the requested input format of the chain.
1276 * \param ao_data describes the requested output format of the chain.
1278 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1280 struct MPOpts *opts = &mpctx->opts;
1281 int new_srate;
1282 int result;
1283 if (!sh_audio)
1285 mpctx->mixer.afilter = NULL;
1286 return 0;
1288 if(af_control_any_rev(sh_audio->afilter,
1289 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1290 &opts->playback_speed)) {
1291 new_srate = sh_audio->samplerate;
1292 } else {
1293 new_srate = sh_audio->samplerate * opts->playback_speed;
1294 if (new_srate != ao_data->samplerate) {
1295 // limits are taken from libaf/af_resample.c
1296 if (new_srate < 8000)
1297 new_srate = 8000;
1298 if (new_srate > 192000)
1299 new_srate = 192000;
1300 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1303 result = init_audio_filters(sh_audio, new_srate,
1304 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1305 mpctx->mixer.afilter = sh_audio->afilter;
1306 return result;
1310 typedef struct mp_osd_msg mp_osd_msg_t;
1311 struct mp_osd_msg {
1312 /// Previous message on the stack.
1313 mp_osd_msg_t* prev;
1314 /// Message text.
1315 char msg[128];
1316 int id,level,started;
1317 /// Display duration in ms.
1318 unsigned time;
1321 /// OSD message stack.
1322 static mp_osd_msg_t* osd_msg_stack = NULL;
1325 * \brief Add a message on the OSD message stack
1327 * If a message with the same id is already present in the stack
1328 * it is pulled on top of the stack, otherwise a new message is created.
1332 void set_osd_msg(int id, int level, int time, const char* fmt, ...) {
1333 mp_osd_msg_t *msg,*last=NULL;
1334 va_list va;
1335 int r;
1337 // look if the id is already in the stack
1338 for(msg = osd_msg_stack ; msg && msg->id != id ;
1339 last = msg, msg = msg->prev);
1340 // not found: alloc it
1341 if(!msg) {
1342 msg = calloc(1,sizeof(mp_osd_msg_t));
1343 msg->prev = osd_msg_stack;
1344 osd_msg_stack = msg;
1345 } else if(last) { // found, but it's not on top of the stack
1346 last->prev = msg->prev;
1347 msg->prev = osd_msg_stack;
1348 osd_msg_stack = msg;
1350 // write the msg
1351 va_start(va,fmt);
1352 r = vsnprintf(msg->msg, 128, fmt, va);
1353 va_end(va);
1354 if(r >= 128) msg->msg[127] = 0;
1355 // set id and time
1356 msg->id = id;
1357 msg->level = level;
1358 msg->time = time;
1363 * \brief Remove a message from the OSD stack
1365 * This function can be used to get rid of a message right away.
1369 void rm_osd_msg(int id) {
1370 mp_osd_msg_t *msg,*last=NULL;
1372 // Search for the msg
1373 for(msg = osd_msg_stack ; msg && msg->id != id ;
1374 last = msg, msg = msg->prev);
1375 if(!msg) return;
1377 // Detach it from the stack and free it
1378 if(last)
1379 last->prev = msg->prev;
1380 else
1381 osd_msg_stack = msg->prev;
1382 free(msg);
1386 * \brief Remove all messages from the OSD stack
1390 static void clear_osd_msgs(void) {
1391 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1392 while(msg) {
1393 prev = msg->prev;
1394 free(msg);
1395 msg = prev;
1397 osd_msg_stack = NULL;
1401 * \brief Get the current message from the OSD stack.
1403 * This function decrements the message timer and destroys the old ones.
1404 * The message that should be displayed is returned (if any).
1408 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1410 struct MPOpts *opts = &mpctx->opts;
1411 mp_osd_msg_t *msg,*prev,*last = NULL;
1412 static unsigned last_update = 0;
1413 unsigned now = GetTimerMS();
1414 unsigned diff;
1415 char hidden_dec_done = 0;
1417 if (mpctx->osd_visible) {
1418 // 36000000 means max timed visibility is 1 hour into the future, if
1419 // the difference is greater assume it's wrapped around from below 0
1420 if (mpctx->osd_visible - now > 36000000) {
1421 mpctx->osd_visible = 0;
1422 vo_osd_progbar_type = -1; // disable
1423 vo_osd_changed(OSDTYPE_PROGBAR);
1424 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1427 if (mpctx->osd_show_percentage_until - now > 36000000)
1428 mpctx->osd_show_percentage_until = 0;
1430 if(!last_update) last_update = now;
1431 diff = now >= last_update ? now - last_update : 0;
1433 last_update = now;
1435 // Look for the first message in the stack with high enough level.
1436 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1437 prev = msg->prev;
1438 if (msg->level > opts->osd_level && hidden_dec_done)
1439 continue;
1440 // The message has a high enough level or it is the first hidden one
1441 // in both cases we decrement the timer or kill it.
1442 if(!msg->started || msg->time > diff) {
1443 if(msg->started) msg->time -= diff;
1444 else msg->started = 1;
1445 // display it
1446 if (msg->level <= opts->osd_level)
1447 return msg;
1448 hidden_dec_done = 1;
1449 continue;
1451 // kill the message
1452 free(msg);
1453 if(last) {
1454 last->prev = prev;
1455 msg = last;
1456 } else {
1457 osd_msg_stack = prev;
1458 msg = NULL;
1461 // Nothing found
1462 return NULL;
1466 * \brief Display the OSD bar.
1468 * Display the OSD bar or fall back on a simple message.
1472 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1473 struct MPOpts *opts = &mpctx->opts;
1474 if (opts->osd_level < 1)
1475 return;
1477 if(mpctx->sh_video) {
1478 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1479 vo_osd_progbar_type = type;
1480 vo_osd_progbar_value = 256*(val-min)/(max-min);
1481 vo_osd_changed(OSDTYPE_PROGBAR);
1482 return;
1485 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1486 name, ROUND(100*(val-min)/(max-min)));
1491 * \brief Update the OSD message line.
1493 * This function displays the current message on the vo OSD or on the term.
1494 * If the stack is empty and the OSD level is high enough the timer
1495 * is displayed (only on the vo OSD).
1499 static void update_osd_msg(struct MPContext *mpctx)
1501 struct MPOpts *opts = &mpctx->opts;
1502 mp_osd_msg_t *msg;
1503 struct osd_state *osd = mpctx->osd;
1504 char osd_text_timer[128];
1506 if (mpctx->add_osd_seek_info) {
1507 double percentage;
1508 if (mpctx->timeline && mpctx->sh_video)
1509 percentage = mpctx->sh_video->pts * 100 /
1510 mpctx->timeline[mpctx->num_timeline_parts].start;
1511 else
1512 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1513 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1514 if (mpctx->sh_video)
1515 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1516 mpctx->add_osd_seek_info = false;
1519 // Look if we have a msg
1520 if((msg = get_osd_msg(mpctx))) {
1521 if (strcmp(osd->osd_text, msg->msg)) {
1522 strncpy(osd->osd_text, msg->msg, 127);
1523 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1524 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1526 return;
1529 if(mpctx->sh_video) {
1530 // fallback on the timer
1531 if (opts->osd_level >= 2) {
1532 int len;
1533 if (mpctx->timeline)
1534 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1535 else
1536 len = demuxer_get_time_length(mpctx->demuxer);
1537 int percentage = -1;
1538 char percentage_text[10];
1539 int pts = demuxer_get_current_time(mpctx->demuxer);
1541 if (mpctx->osd_show_percentage_until)
1542 if (mpctx->timeline)
1543 percentage = mpctx->sh_video->pts * 100 /
1544 mpctx->timeline[mpctx->num_timeline_parts].start;
1545 else
1546 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1548 if (percentage >= 0)
1549 snprintf(percentage_text, 9, " (%d%%)", percentage);
1550 else
1551 percentage_text[0] = 0;
1553 if (opts->osd_level == 3)
1554 snprintf(osd_text_timer, 63,
1555 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1556 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1557 len/3600,(len/60)%60,len%60,percentage_text);
1558 else
1559 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1560 mpctx->osd_function,pts/3600,(pts/60)%60,
1561 pts%60,percentage_text);
1562 } else
1563 osd_text_timer[0]=0;
1565 if (strcmp(osd->osd_text, osd_text_timer)) {
1566 strncpy(osd->osd_text, osd_text_timer, 63);
1567 vo_osd_changed(OSDTYPE_OSD);
1569 return;
1572 // Clear the term osd line
1573 if (term_osd && osd->osd_text[0]) {
1574 osd->osd_text[0] = 0;
1575 printf("%s\n",term_osd_esc);
1579 ///@}
1580 // OSDMsgStack
1583 void reinit_audio_chain(struct MPContext *mpctx)
1585 struct MPOpts *opts = &mpctx->opts;
1586 if(mpctx->sh_audio){
1587 current_module="init_audio_codec";
1588 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1589 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1590 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // failed to init :(
1591 mpctx->d_audio->id = -2;
1592 return;
1593 } else
1594 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1595 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1598 //const ao_info_t *info=audio_out->info;
1599 current_module="af_preinit";
1600 ao_data.samplerate=force_srate;
1601 ao_data.channels=0;
1602 ao_data.format=audio_output_format;
1603 #if 1
1604 // first init to detect best values
1605 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1606 // input:
1607 mpctx->sh_audio->samplerate,
1608 // output:
1609 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1610 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Error at audio filter chain pre-init!\n");
1611 exit_player(mpctx, EXIT_ERROR);
1613 #endif
1614 current_module="ao2_init";
1615 if(!(mpctx->audio_out=init_best_audio_out(opts->audio_driver_list,
1616 0, // plugin flag
1617 ao_data.samplerate,
1618 ao_data.channels,
1619 ao_data.format,0))){
1620 // FAILED:
1621 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1622 uninit_player(mpctx, INITIALIZED_ACODEC); // close codec
1623 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1624 mpctx->d_audio->id = -2;
1625 return;
1626 } else {
1627 // SUCCESS:
1628 mpctx->initialized_flags|=INITIALIZED_AO;
1629 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1630 mpctx->audio_out->info->short_name,
1631 ao_data.samplerate, ao_data.channels,
1632 af_fmt2str_short(ao_data.format),
1633 af_fmt2bits(ao_data.format)/8 );
1634 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1635 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1636 if(strlen(mpctx->audio_out->info->comment) > 0)
1637 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1638 // init audio filters:
1639 #if 1
1640 current_module="af_init";
1641 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1642 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1643 // mp_msg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter / ao format! -> NOSOUND\n");
1644 // uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec & ao
1645 // sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1647 #endif
1649 mpctx->mixer.audio_out = mpctx->audio_out;
1650 mpctx->mixer.volstep = volstep;
1655 ///@}
1656 // Command2Property
1659 // Return pts value corresponding to the end point of audio written to the
1660 // ao so far.
1661 static double written_audio_pts(struct MPContext *mpctx)
1663 sh_audio_t *sh_audio = mpctx->sh_audio;
1664 demux_stream_t *d_audio = mpctx->d_audio;
1665 double buffered_output;
1666 // first calculate the end pts of audio that has been output by decoder
1667 double a_pts = sh_audio->pts;
1668 if (a_pts != MP_NOPTS_VALUE)
1669 // Good, decoder supports new way of calculating audio pts.
1670 // sh_audio->pts is the timestamp of the latest input packet with
1671 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1672 // the amount of bytes the decoder has written after that timestamp.
1673 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1674 else {
1675 // Decoder doesn't support new way of calculating pts (or we're
1676 // being called before it has decoded anything with known timestamp).
1677 // Use the old method of audio pts calculation: take the timestamp
1678 // of last packet with known pts the decoder has read data from,
1679 // and add amount of bytes read after the beginning of that packet
1680 // divided by input bps. This will be inaccurate if the input/output
1681 // ratio is not constant for every audio packet or if it is constant
1682 // but not accurately known in sh_audio->i_bps.
1684 a_pts = d_audio->pts;
1685 // ds_tell_pts returns bytes read after last timestamp from
1686 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1687 // it has read but not decoded
1688 if (sh_audio->i_bps)
1689 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1690 (double)sh_audio->i_bps;
1692 // Now a_pts hopefully holds the pts for end of audio from decoder.
1693 // Substract data in buffers between decoder and audio out.
1695 // Decoded but not filtered
1696 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1698 // Data buffered in audio filters, measured in bytes of "missing" output
1699 buffered_output = af_calc_delay(sh_audio->afilter);
1701 // Data that was ready for ao but was buffered because ao didn't fully
1702 // accept everything to internal buffers yet
1703 buffered_output += sh_audio->a_out_buffer_len;
1705 // Filters divide audio length by playback_speed, so multiply by it
1706 // to get the length in original units without speedup or slowdown
1707 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1709 return a_pts + mpctx->video_offset;
1712 // Return pts value corresponding to currently playing audio.
1713 double playing_audio_pts(struct MPContext *mpctx)
1715 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1716 mpctx->audio_out->get_delay();
1719 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1720 struct MPOpts *opts = &mpctx->opts;
1721 // check for frame-drop:
1722 current_module = "check_framedrop";
1723 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1724 static int dropped_frames;
1725 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1726 float d = delay-mpctx->delay;
1727 ++total_frame_cnt;
1728 // we should avoid dropping too many frames in sequence unless we
1729 // are too late. and we allow 100ms A-V delay here:
1730 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1731 && !mpctx->update_video_immediately) {
1732 ++drop_frame_cnt;
1733 ++dropped_frames;
1734 return frame_dropping;
1735 } else
1736 dropped_frames = 0;
1738 return 0;
1742 #ifdef HAVE_RTC
1743 int rtc_fd = -1;
1744 #endif
1746 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1748 #ifdef HAVE_RTC
1749 if (rtc_fd >= 0){
1750 // -------- RTC -----------
1751 current_module="sleep_rtc";
1752 while (time_frame > 0.000) {
1753 unsigned long rtc_ts;
1754 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1755 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1756 time_frame -= get_relative_time(mpctx);
1758 } else
1759 #endif
1761 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1762 // unnecessarily high CPU usage
1763 float margin = softsleep ? 0.011 : 0;
1764 current_module = "sleep_timer";
1765 while (time_frame > margin) {
1766 usec_sleep(1000000 * (time_frame - margin));
1767 time_frame -= get_relative_time(mpctx);
1769 if (softsleep){
1770 current_module = "sleep_soft";
1771 if (time_frame < 0)
1772 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1773 while (time_frame > 0)
1774 time_frame -= get_relative_time(mpctx); // burn the CPU
1777 return time_frame;
1780 #ifdef CONFIG_DVDNAV
1781 #ifndef FF_B_TYPE
1782 #define FF_B_TYPE 3
1783 #endif
1784 /// store decoded video image
1785 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1786 mp_image_t *from_mpi) {
1787 mp_image_t *mpi;
1789 /// Do not store B-frames
1790 if (from_mpi->pict_type == FF_B_TYPE)
1791 return to_mpi;
1793 if (to_mpi &&
1794 to_mpi->w == from_mpi->w &&
1795 to_mpi->h == from_mpi->h &&
1796 to_mpi->imgfmt == from_mpi->imgfmt)
1797 mpi = to_mpi;
1798 else {
1799 if (to_mpi)
1800 free_mp_image(to_mpi);
1801 if (from_mpi->w == 0 || from_mpi->h == 0)
1802 return NULL;
1803 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1806 copy_mpi(mpi,from_mpi);
1807 return mpi;
1810 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1811 struct MPOpts *opts = &ctx->opts;
1812 if (ctx->sh_video) {
1813 /// clear video pts
1814 ctx->d_video->pts = 0.0f;
1815 ctx->sh_video->pts = 0.0f;
1816 ctx->sh_video->i_pts = 0.0f;
1817 ctx->sh_video->last_pts = 0.0f;
1818 ctx->sh_video->num_buffered_pts = 0;
1819 ctx->sh_video->num_frames = 0;
1820 ctx->sh_video->num_frames_decoded = 0;
1821 ctx->sh_video->timer = 0.0f;
1822 ctx->sh_video->stream_delay = 0.0f;
1823 ctx->sh_video->timer = 0;
1824 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1827 if (ctx->sh_audio) {
1828 /// free audio packets and reset
1829 ds_free_packs(ctx->d_audio);
1830 audio_delay -= ctx->sh_audio->stream_delay;
1831 ctx->delay =- audio_delay;
1832 ctx->audio_out->reset();
1833 resync_audio_stream(ctx->sh_audio);
1836 if (ctx->d_sub) opts->sub_id = -2;
1838 audio_delay = 0.0f;
1840 /// clear all EOF related flags
1841 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1844 /// Restore last decoded DVDNAV (still frame)
1845 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
1846 int *in_size,
1847 unsigned char **start,
1848 mp_image_t *decoded_frame)
1850 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1851 return decoded_frame;
1853 /// a change occured in dvdnav stream
1854 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
1855 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
1856 mp_dvdnav_context_free(mpctx);
1857 mp_dvdnav_reset_stream(mpctx);
1858 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
1859 mp_dvdnav_cell_has_changed(mpctx->stream,1);
1862 if (*in_size < 0) {
1863 float len;
1865 /// Display still frame, if any
1866 if (mpctx->nav_smpi && !mpctx->nav_buffer)
1867 decoded_frame = mpctx->nav_smpi;
1869 /// increment video frame : continue playing after still frame
1870 len = demuxer_get_time_length(mpctx->demuxer);
1871 if (mpctx->sh_video->pts >= len &&
1872 mpctx->sh_video->pts > 0.0 && len > 0.0) {
1873 mp_dvdnav_skip_still(mpctx->stream);
1874 mp_dvdnav_skip_wait(mpctx->stream);
1876 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
1878 if (mpctx->nav_buffer) {
1879 *start = mpctx->nav_start;
1880 *in_size = mpctx->nav_in_size;
1881 if (mpctx->nav_start)
1882 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
1886 return decoded_frame;
1889 /// Save last decoded DVDNAV (still frame)
1890 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
1891 unsigned char *start,
1892 mp_image_t *decoded_frame)
1894 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1895 return;
1897 if (mpctx->nav_buffer)
1898 free(mpctx->nav_buffer);
1900 mpctx->nav_buffer = malloc(in_size);
1901 mpctx->nav_start = start;
1902 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
1903 if (mpctx->nav_buffer)
1904 memcpy(mpctx->nav_buffer,start,in_size);
1906 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
1907 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
1909 #endif /* CONFIG_DVDNAV */
1911 /* Modify video timing to match the audio timeline. There are two main
1912 * reasons this is needed. First, video and audio can start from different
1913 * positions at beginning of file or after a seek (MPlayer starts both
1914 * immediately even if they have different pts). Second, the file can have
1915 * audio timestamps that are inconsistent with the duration of the audio
1916 * packets, for example two consecutive timestamp values differing by
1917 * one second but only a packet with enough samples for half a second
1918 * of playback between them.
1920 static void adjust_sync(struct MPContext *mpctx, double frame_time)
1922 struct MPOpts *opts = &mpctx->opts;
1923 current_module = "av_sync";
1925 if (!mpctx->sh_audio)
1926 return;
1928 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
1929 double v_pts = mpctx->sh_video->pts;
1930 double av_delay = a_pts - v_pts;
1931 // Try to sync vo_flip() so it will *finish* at given time
1932 av_delay += mpctx->last_vo_flip_duration;
1933 av_delay -= audio_delay; // This much pts difference is desired
1935 double change = av_delay * 0.1;
1936 double max_change = default_max_pts_correction >= 0 ?
1937 default_max_pts_correction : frame_time * 0.1;
1938 if (change < -max_change)
1939 change = -max_change;
1940 else if (change > max_change)
1941 change = max_change;
1942 mpctx->delay += change;
1943 mpctx->total_avsync_change += change;
1946 static int fill_audio_out_buffers(struct MPContext *mpctx)
1948 struct MPOpts *opts = &mpctx->opts;
1949 unsigned int t;
1950 double tt;
1951 int playsize;
1952 int playflags=0;
1953 int audio_eof=0;
1954 int bytes_to_write;
1955 sh_audio_t * const sh_audio = mpctx->sh_audio;
1957 current_module="play_audio";
1959 while (1) {
1960 int sleep_time;
1961 // all the current uses of ao_data.pts seem to be in aos that handle
1962 // sync completely wrong; there should be no need to use ao_data.pts
1963 // in get_space()
1964 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
1965 bytes_to_write = mpctx->audio_out->get_space();
1966 if (mpctx->sh_video || bytes_to_write >= ao_data.outburst)
1967 break;
1969 // handle audio-only case:
1970 // this is where mplayer sleeps during audio-only playback
1971 // to avoid 100% CPU use
1972 sleep_time = (ao_data.outburst - bytes_to_write) * 1000 / ao_data.bps;
1973 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
1974 usec_sleep(sleep_time * 1000);
1977 while (bytes_to_write) {
1978 playsize = bytes_to_write;
1979 if (playsize > MAX_OUTBURST)
1980 playsize = MAX_OUTBURST;
1981 bytes_to_write -= playsize;
1983 // Fill buffer if needed:
1984 current_module="decode_audio";
1985 t = GetTimer();
1986 if (decode_audio(sh_audio, playsize) < 0) // EOF or error
1987 if (mpctx->d_audio->eof) {
1988 audio_eof = 1;
1989 if (sh_audio->a_out_buffer_len == 0)
1990 return 0;
1992 t = GetTimer() - t;
1993 tt = t*0.000001f; audio_time_usage+=tt;
1994 if (playsize > sh_audio->a_out_buffer_len) {
1995 playsize = sh_audio->a_out_buffer_len;
1996 if (audio_eof)
1997 playflags |= AOPLAY_FINAL_CHUNK;
1999 if (!playsize)
2000 break;
2002 // play audio:
2003 current_module="play_audio";
2005 // Is this pts value actually useful for the aos that access it?
2006 // They're obviously badly broken in the way they handle av sync;
2007 // would not having access to this make them more broken?
2008 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2009 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2011 if (playsize > 0) {
2012 sh_audio->a_out_buffer_len -= playsize;
2013 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2014 sh_audio->a_out_buffer_len);
2015 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2017 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2018 // Sanity check to avoid hanging in case current ao doesn't output
2019 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2020 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2021 sh_audio->a_out_buffer_len = 0;
2024 return 1;
2027 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2028 float *aq_sleep_time)
2030 struct MPOpts *opts = &mpctx->opts;
2031 int frame_time_remaining = 0;
2032 current_module="calc_sleep_time";
2034 *time_frame -= get_relative_time(mpctx); // reset timer
2036 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2037 float delay = mpctx->audio_out->get_delay();
2038 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2040 if (autosync) {
2042 * Adjust this raw delay value by calculating the expected
2043 * delay for this frame and generating a new value which is
2044 * weighted between the two. The higher autosync is, the
2045 * closer to the delay value gets to that which "-nosound"
2046 * would have used, and the longer it will take for A/V
2047 * sync to settle at the right value (but it eventually will.)
2048 * This settling time is very short for values below 100.
2050 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2051 float difference = delay - predicted;
2052 delay = predicted + difference / (float)autosync;
2055 *time_frame = delay - mpctx->delay / opts->playback_speed;
2057 // delay = amount of audio buffered in soundcard/driver
2058 if (delay > 0.25) delay=0.25; else
2059 if (delay < 0.10) delay=0.10;
2060 if (*time_frame > delay*0.6) {
2061 // sleep time too big - may cause audio drops (buffer underrun)
2062 frame_time_remaining = 1;
2063 *time_frame = delay*0.5;
2065 } else {
2066 // If we're lagging more than 200 ms behind the right playback rate,
2067 // don't try to "catch up".
2068 // If benchmark is set always output frames as fast as possible
2069 // without sleeping.
2070 if (*time_frame < -0.2 || benchmark)
2071 *time_frame = 0;
2074 *aq_sleep_time += *time_frame;
2077 //============================== SLEEP: ===================================
2079 // flag 256 means: libvo driver does its timing (dvb card)
2080 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2081 *time_frame = timing_sleep(mpctx, *time_frame);
2082 return frame_time_remaining;
2085 int reinit_video_chain(struct MPContext *mpctx)
2087 struct MPOpts *opts = &mpctx->opts;
2088 sh_video_t * const sh_video = mpctx->sh_video;
2089 double ar=-1.0;
2090 //================== Init VIDEO (codec & libvo) ==========================
2091 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2092 current_module="preinit_libvo";
2094 //shouldn't we set dvideo->id=-2 when we fail?
2095 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2096 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2097 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2098 goto err_out;
2100 mpctx->initialized_flags|=INITIALIZED_VO;
2103 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2104 mpctx->sh_video->stream_aspect = ar;
2105 current_module="init_video_filters";
2107 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2108 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2110 #ifdef CONFIG_MENU
2111 if(use_menu) {
2112 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2113 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2114 if(!vf_menu) {
2115 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2116 use_menu = 0;
2119 if(vf_menu)
2120 sh_video->vfilter = vf_menu;
2121 #endif
2123 #ifdef CONFIG_ASS
2124 if(ass_enabled) {
2125 int i;
2126 int insert = 1;
2127 if (opts->vf_settings)
2128 for (i = 0; opts->vf_settings[i].name; ++i)
2129 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2130 insert = 0;
2131 break;
2133 if (insert) {
2134 extern vf_info_t vf_info_ass;
2135 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2136 char* vf_arg[] = {"auto", "1", NULL};
2137 vf_instance_t* vf_ass = vf_open_plugin(opts, libass_vfs,sh_video->vfilter,"ass",vf_arg);
2138 if (vf_ass)
2139 sh_video->vfilter = vf_ass;
2140 else
2141 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2144 #endif
2146 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2148 #ifdef CONFIG_ASS
2149 if (ass_enabled)
2150 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2151 #endif
2153 current_module="init_video_codec";
2155 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2156 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2157 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2159 if(!sh_video->initialized){
2160 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2161 goto err_out;
2164 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2166 if (sh_video->codec)
2167 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2169 sh_video->last_pts = MP_NOPTS_VALUE;
2170 sh_video->num_buffered_pts = 0;
2171 sh_video->next_frame_time = 0;
2173 if(auto_quality>0){
2174 // Auto quality option enabled
2175 output_quality=get_video_quality_max(sh_video);
2176 if(auto_quality>output_quality) auto_quality=output_quality;
2177 else output_quality=auto_quality;
2178 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2179 set_video_quality(sh_video,output_quality);
2182 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2184 current_module="init_vo";
2186 return 1;
2188 err_out:
2189 mpctx->sh_video = mpctx->d_video->sh = NULL;
2190 return 0;
2193 static double update_video_nocorrect_pts(struct MPContext *mpctx,
2194 int *blit_frame)
2196 struct sh_video *sh_video = mpctx->sh_video;
2197 *blit_frame = 0;
2198 double frame_time = 0;
2199 while (1) {
2200 current_module = "filter_video";
2201 // In nocorrect-pts mode there is no way to properly time these frames
2202 if (vf_output_queued_frame(sh_video->vfilter))
2203 break;
2204 unsigned char *packet = NULL;
2205 frame_time = sh_video->next_frame_time;
2206 if (mpctx->update_video_immediately)
2207 frame_time = 0;
2208 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2209 &packet, force_fps);
2210 if (in_size < 0) {
2211 #ifdef CONFIG_DVDNAV
2212 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2213 if (mp_dvdnav_is_eof(mpctx->stream))
2214 return -1;
2215 if (mpctx->d_video)
2216 mpctx->d_video->eof = 0;
2217 if (mpctx->d_audio)
2218 mpctx->d_audio->eof = 0;
2219 mpctx->stream->eof = 0;
2220 } else
2221 #endif
2222 return -1;
2224 if (in_size > max_framesize)
2225 max_framesize = in_size;
2226 sh_video->timer += frame_time;
2227 if (mpctx->sh_audio)
2228 mpctx->delay -= frame_time;
2229 // video_read_frame can change fps (e.g. for ASF video)
2230 vo_fps = sh_video->fps;
2231 int framedrop_type = check_framedrop(mpctx, frame_time);
2232 current_module = "decode video";
2234 void *decoded_frame;
2235 #ifdef CONFIG_DVDNAV
2236 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2237 if (in_size >= 0 && !decoded_frame)
2238 #endif
2239 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2240 sh_video->pts);
2241 #ifdef CONFIG_DVDNAV
2242 // Save last still frame for future display
2243 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2244 #endif
2245 if (decoded_frame) {
2246 // These updates are done here for vf_expand OSD/subtitles
2247 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2248 update_teletext(sh_video, mpctx->demuxer, 0);
2249 update_osd_msg(mpctx);
2250 current_module = "filter video";
2251 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2252 break;
2255 *blit_frame = 1;
2256 return frame_time;
2259 static double update_video(struct MPContext *mpctx, int *blit_frame)
2261 struct sh_video *sh_video = mpctx->sh_video;
2262 *blit_frame = 0;
2263 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2264 mpctx->osd); // hack for vf_expand
2265 if (!mpctx->opts.correct_pts)
2266 return update_video_nocorrect_pts(mpctx, blit_frame);
2268 double pts;
2270 while (1) {
2271 current_module = "filter_video";
2272 // XXX Time used in this call is not counted in any performance
2273 // timer now, OSD time is not updated correctly for filter-added frames
2274 if (vf_output_queued_frame(sh_video->vfilter))
2275 break;
2276 unsigned char *packet = NULL;
2277 bool hit_eof = false;
2278 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2279 if (pts != MP_NOPTS_VALUE)
2280 pts += mpctx->video_offset;
2281 if (in_size < 0) {
2282 // try to extract last frames in case of decoder lag
2283 in_size = 0;
2284 pts = 1e300;
2285 hit_eof = true;
2287 if (in_size > max_framesize)
2288 max_framesize = in_size;
2289 current_module = "decode video";
2290 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2291 void *decoded_frame = decode_video(sh_video, packet, in_size,
2292 framedrop_type, pts);
2293 if (decoded_frame) {
2294 // These updates are done here for vf_expand OSD/subtitles
2295 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2296 update_teletext(sh_video, mpctx->demuxer, 0);
2297 update_osd_msg(mpctx);
2298 current_module = "filter video";
2299 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2300 break;
2301 } else if (hit_eof)
2302 return -1;
2305 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_GET_PTS, &pts);
2306 if (pts == MP_NOPTS_VALUE) {
2307 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2308 // Try to use decoder pts from before filters
2309 pts = sh_video->pts;
2310 if (pts == MP_NOPTS_VALUE)
2311 pts = sh_video->last_pts;
2313 sh_video->pts = pts;
2314 if (sh_video->last_pts == MP_NOPTS_VALUE)
2315 sh_video->last_pts = sh_video->pts;
2316 else if (sh_video->last_pts > sh_video->pts) {
2317 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2318 sh_video->pts, sh_video->last_pts);
2319 /* If the difference in pts is small treat it as jitter around the
2320 * right value (possibly caused by incorrect timestamp ordering) and
2321 * just show this frame immediately after the last one.
2322 * Treat bigger differences as timestamp resets and start counting
2323 * timing of later frames from the position of this one. */
2324 if (sh_video->last_pts - sh_video->pts > 0.5)
2325 sh_video->last_pts = sh_video->pts;
2326 else
2327 sh_video->pts = sh_video->last_pts;
2329 double frame_time = sh_video->pts - sh_video->last_pts;
2330 sh_video->last_pts = sh_video->pts;
2331 sh_video->timer += frame_time;
2332 if (mpctx->sh_audio)
2333 mpctx->delay -= frame_time;
2334 *blit_frame = 1;
2335 return frame_time;
2338 void pause_player(struct MPContext *mpctx)
2340 if (mpctx->paused)
2341 return;
2342 mpctx->paused = 1;
2343 mpctx->step_frames = 0;
2344 mpctx->time_frame -= get_relative_time(mpctx);
2346 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2347 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2349 if (mpctx->audio_out && mpctx->sh_audio)
2350 mpctx->audio_out->pause(); // pause audio, keep data if possible
2353 void unpause_player(struct MPContext *mpctx)
2355 if (!mpctx->paused)
2356 return;
2357 mpctx->paused = 0;
2359 if (mpctx->audio_out && mpctx->sh_audio)
2360 mpctx->audio_out->resume(); // resume audio
2361 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2362 && !mpctx->step_frames)
2363 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2364 (void)get_relative_time(mpctx); // ignore time that passed during pause
2367 void add_step_frame(struct MPContext *mpctx)
2369 mpctx->step_frames++;
2370 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2371 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2372 unpause_player(mpctx);
2375 static void pause_loop(struct MPContext *mpctx)
2377 mp_cmd_t* cmd;
2378 if (!quiet) {
2379 // Small hack to display the pause message on the OSD line.
2380 // The pause string is: "\n == PAUSE == \r" so we need to
2381 // take the first and the last char out
2382 if (term_osd && !mpctx->sh_video) {
2383 char msg[128] = _("\n ===== PAUSE =====\r");
2384 int mlen = strlen(msg);
2385 msg[mlen-1] = '\0';
2386 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2387 update_osd_msg(mpctx);
2388 } else
2389 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2390 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2393 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1, 1)) == NULL
2394 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2395 if (cmd) {
2396 cmd = mp_input_get_cmd(mpctx->input, 0,1,0);
2397 run_command(mpctx, cmd);
2398 mp_cmd_free(cmd);
2399 continue;
2401 if (mpctx->sh_video && mpctx->video_out)
2402 vo_check_events(mpctx->video_out);
2403 #ifdef CONFIG_MENU
2404 if (vf_menu)
2405 vf_menu_pause_update(vf_menu);
2406 #endif
2407 usec_sleep(20000);
2408 update_osd_msg(mpctx);
2409 int hack = vo_osd_changed(0);
2410 vo_osd_changed(hack);
2411 if (hack)
2412 break;
2417 // Find the right mute status and record position for new file position
2418 static void edl_seek_reset(MPContext *mpctx)
2420 mpctx->edl_muted = 0;
2421 next_edl_record = edl_records;
2423 while (next_edl_record) {
2424 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2425 break;
2427 if (next_edl_record->action == EDL_MUTE)
2428 mpctx->edl_muted = !mpctx->edl_muted;
2429 next_edl_record = next_edl_record->next;
2431 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2432 mixer_mute(&mpctx->mixer);
2436 // Execute EDL command for the current position if one exists
2437 static void edl_update(MPContext *mpctx)
2439 if (!next_edl_record)
2440 return;
2442 if (!mpctx->sh_video) {
2443 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2444 free_edl(edl_records);
2445 next_edl_record = NULL;
2446 edl_records = NULL;
2447 return;
2450 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2451 if (next_edl_record->action == EDL_SKIP) {
2452 mpctx->osd_function = OSD_FFW;
2453 mpctx->abs_seek_pos = 0;
2454 mpctx->rel_seek_secs = next_edl_record->length_sec;
2455 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2456 "[%f], length [%f]\n", next_edl_record->start_sec,
2457 next_edl_record->stop_sec, next_edl_record->length_sec);
2459 else if (next_edl_record->action == EDL_MUTE) {
2460 mpctx->edl_muted = !mpctx->edl_muted;
2461 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2462 mixer_mute(&mpctx->mixer);
2463 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2464 next_edl_record->start_sec );
2466 next_edl_record = next_edl_record->next;
2470 static void reinit_decoders(struct MPContext *mpctx)
2472 reinit_video_chain(mpctx);
2473 reinit_audio_chain(mpctx);
2474 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2477 static bool timeline_set_part(struct MPContext *mpctx, int i)
2479 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2480 struct timeline_part *n = mpctx->timeline + i;
2481 mpctx->timeline_part = i;
2482 mpctx->video_offset = n->start - n->source_start;
2483 if (n->source == p->source)
2484 return false;
2485 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2486 mpctx->demuxer = n->source->demuxer;
2487 mpctx->d_video = mpctx->demuxer->video;
2488 mpctx->d_audio = mpctx->demuxer->audio;
2489 mpctx->d_sub = mpctx->demuxer->sub;
2490 mpctx->sh_video = mpctx->d_video->sh;
2491 mpctx->sh_audio = mpctx->d_audio->sh;
2492 return true;
2495 // Given pts, switch playback to the corresponding part.
2496 // Return offset within that part.
2497 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2498 bool *need_reset)
2500 if (pts < 0)
2501 pts = 0;
2502 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2503 struct timeline_part *p = mpctx->timeline + i;
2504 if (pts < (p+1)->start) {
2505 *need_reset = timeline_set_part(mpctx, i);
2506 return pts - p->start + p->source_start;
2509 return -1;
2513 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2514 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2515 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2516 static int seek(MPContext *mpctx, double amount, int style)
2518 current_module = "seek";
2519 if (mpctx->stop_play == AT_END_OF_FILE)
2520 mpctx->stop_play = KEEP_PLAYING;
2521 if (mpctx->timeline && style & SEEK_FACTOR) {
2522 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2523 style &= ~SEEK_FACTOR;
2525 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2526 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2527 style |= SEEK_ABSOLUTE;
2528 if (amount > 0)
2529 style |= SEEK_FORWARD;
2530 else
2531 style |= SEEK_BACKWARD;
2532 amount += mpctx->sh_video->pts;
2535 /* At least the liba52 decoder wants to read from the input stream
2536 * during initialization, so reinit must be done after the demux_seek()
2537 * call that clears possible stream EOF. */
2538 bool need_reset = false;
2539 if (mpctx->timeline) {
2540 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2541 if (amount == -1) {
2542 mpctx->stop_play = AT_END_OF_FILE;
2543 // Clear audio from current position
2544 if (mpctx->sh_audio) {
2545 mpctx->audio_out->reset();
2546 mpctx->sh_audio->a_buffer_len = 0;
2547 mpctx->sh_audio->a_out_buffer_len = 0;
2549 return -1;
2552 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2553 if (need_reset)
2554 reinit_decoders(mpctx);
2555 if (seekresult == 0)
2556 return -1;
2558 if (mpctx->sh_video) {
2559 current_module = "seek_video_reset";
2560 resync_video_stream(mpctx->sh_video);
2561 if (mpctx->video_out->config_ok)
2562 vo_control(mpctx->video_out, VOCTRL_RESET, NULL);
2563 mpctx->sh_video->num_buffered_pts = 0;
2564 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2565 mpctx->num_buffered_frames = 0;
2566 mpctx->delay = 0;
2567 mpctx->time_frame = 0;
2568 mpctx->update_video_immediately = true;
2569 // Not all demuxers set d_video->pts during seek, so this value
2570 // (which is used by at least vobsub and edl code below) may
2571 // be completely wrong (probably 0).
2572 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2573 update_subtitles(mpctx->sh_video, mpctx->d_sub, mpctx->video_offset, 1);
2574 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2577 if (mpctx->sh_audio) {
2578 current_module = "seek_audio_reset";
2579 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2580 mpctx->sh_audio->a_buffer_len = 0;
2581 mpctx->sh_audio->a_out_buffer_len = 0;
2584 if (vo_vobsub && mpctx->sh_video) {
2585 current_module = "seek_vobsub_reset";
2586 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2589 edl_seek_reset(mpctx);
2591 mpctx->total_avsync_change = 0;
2592 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2593 drop_frame_cnt = 0;
2595 current_module = NULL;
2596 return 0;
2599 int get_current_chapter(struct MPContext *mpctx)
2601 if (!mpctx->chapters || !mpctx->sh_video)
2602 return demuxer_get_current_chapter(mpctx->demuxer);
2604 int i;
2605 double current_pts = mpctx->sh_video->pts;
2606 for (i = 1; i < mpctx->num_chapters; i++)
2607 if (current_pts < mpctx->chapters[i].start)
2608 break;
2609 return i - 1;
2612 // currently returns a string allocated with malloc, not talloc
2613 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2615 if (!mpctx->chapters || !mpctx->sh_video)
2616 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2617 return strdup(mpctx->chapters[chapter].name);
2620 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2621 char **chapter_name)
2623 if (!mpctx->chapters || !mpctx->sh_video)
2624 return demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2625 chapter_name);
2626 if (chapter >= mpctx->num_chapters)
2627 return -1;
2628 if (chapter < 0)
2629 chapter = 0;
2630 *seek_pts = mpctx->chapters[chapter].start;
2631 if (chapter_name)
2632 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2633 return chapter;
2636 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2637 struct content_source *sources,
2638 int num_sources,
2639 unsigned char uid_map[][16])
2641 int num_filenames = 0;
2642 char **filenames = NULL;
2643 if (num_sources > 1) {
2644 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2645 "other sources.\n");
2646 if (mpctx->stream->type != STREAMTYPE_FILE) {
2647 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2648 "normal disk file. Will not search for related files.\n");
2649 } else {
2650 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2651 "same directory to find referenced sources.\n");
2652 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2653 &num_filenames);
2657 int num_left = num_sources - 1;
2658 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2659 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2660 filename_recode(filenames[i]));
2661 int format;
2662 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2663 if (!s)
2664 continue;
2665 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2666 mpctx->opts.audio_id,
2667 mpctx->opts.video_id,
2668 mpctx->opts.sub_id, filenames[i]);
2669 if (!d) {
2670 free_stream(s);
2671 continue;
2673 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2674 for (int i = 1; i < num_sources; i++) {
2675 if (sources[i].demuxer)
2676 continue;
2677 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2678 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2679 i, filename_recode(d->filename));
2680 sources[i].stream = s;
2681 sources[i].demuxer = d;
2682 num_left--;
2683 goto match;
2687 free_demuxer(d);
2688 free_stream(s);
2689 continue;
2690 match:
2693 talloc_free(filenames);
2694 if (num_left) {
2695 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2696 "There will be parts MISSING from the video!\n");
2697 for (int i = 1, j = 1; i < num_sources; i++)
2698 if (sources[i].demuxer) {
2699 sources[j] = sources[i];
2700 memcpy(uid_map[j], uid_map[i], 16);
2701 j++;
2704 return num_sources - num_left;
2707 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2709 if (!mpctx->opts.ordered_chapters) {
2710 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
2711 "you have disabled support for them. Ignoring.\n");
2712 return;
2715 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
2716 "edit timeline.\n");
2718 struct demuxer *demuxer = mpctx->demuxer;
2719 struct matroska_data *m = &demuxer->matroska_data;
2721 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
2722 m->num_ordered_chapters);
2723 sources[0].stream = mpctx->stream;
2724 sources[0].demuxer = mpctx->demuxer;
2725 unsigned char uid_map[m->num_ordered_chapters][16];
2726 int num_sources = 1;
2727 memcpy(uid_map[0], m->segment_uid, 16);
2729 for (int i = 0; i < m->num_ordered_chapters; i++) {
2730 struct matroska_chapter *c = m->ordered_chapters + i;
2731 if (!c->has_segment_uid)
2732 memcpy(c->segment_uid, m->segment_uid, 16);
2734 for (int j = 0; j < num_sources; j++)
2735 if (!memcmp(c->segment_uid, uid_map[j], 16))
2736 goto found1;
2737 memcpy(uid_map[num_sources], c->segment_uid, 16);
2738 sources[num_sources] = (struct content_source){};
2739 num_sources++;
2740 found1:
2744 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
2745 uid_map);
2748 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
2749 m->num_ordered_chapters + 1);
2750 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
2751 m->num_ordered_chapters);
2752 uint64_t starttime = 0;
2753 uint64_t missing_time = 0;
2754 int part_count = 0;
2755 int num_chapters = 0;
2756 uint64_t prev_part_offset;
2757 for (int i = 0; i < m->num_ordered_chapters; i++) {
2758 struct matroska_chapter *c = m->ordered_chapters + i;
2760 int j;
2761 for (j = 0; j < num_sources; j++) {
2762 if (!memcmp(c->segment_uid, uid_map[j], 16))
2763 goto found2;
2765 missing_time += c->end - c->start;
2766 continue;
2767 found2:;
2768 chapters[num_chapters].start = starttime / 1000.;
2769 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
2770 /* Only add a separate part if the time or file actually changes.
2771 * Matroska files have chapter divisions that are redundant from
2772 * timeline point of view because the same chapter structure is used
2773 * both to specify the timeline and for normal chapter information.
2774 * Removing a missing inserted external chapter can also cause this. */
2775 if (part_count == 0 || c->start != starttime + prev_part_offset
2776 || sources + j != timeline[part_count - 1].source) {
2777 timeline[part_count].source = sources + j;
2778 timeline[part_count].start = chapters[num_chapters].start;
2779 timeline[part_count].source_start = c->start / 1000.;
2780 prev_part_offset = c->start - starttime;
2781 part_count++;
2783 starttime += c->end - c->start;
2784 num_chapters++;
2786 timeline[part_count].start = starttime / 1000.;
2788 if (!part_count) {
2789 // None of the parts come from the file itself???
2790 talloc_free(sources);
2791 talloc_free(timeline);
2792 talloc_free(chapters);
2793 return;
2796 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
2797 "sources. Total length %.3f seconds.\n", part_count, num_sources,
2798 timeline[part_count].start);
2799 if (missing_time)
2800 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
2801 "from the timeline!\n", missing_time / 1000.);
2802 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
2803 for (int i = 0; i < num_sources; i++)
2804 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
2805 filename_recode(sources[i].demuxer->filename));
2806 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
2807 "source_start, source):\n");
2808 for (int i = 0; i < part_count; i++) {
2809 struct timeline_part *p = timeline + i;
2810 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
2811 p->source_start, p->source - sources);
2813 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
2814 mpctx->sources = sources;
2815 mpctx->num_sources = num_sources;
2816 mpctx->timeline = timeline;
2817 mpctx->num_timeline_parts = part_count;
2818 mpctx->num_chapters = num_chapters;
2819 mpctx->chapters = chapters;
2821 mpctx->timeline_part = 0;
2822 mpctx->video_offset = timeline[0].source_start;
2823 mpctx->demuxer = timeline[0].source->demuxer;
2827 static int read_keys(void *ctx, int fd)
2829 getch2(ctx);
2830 return mplayer_get_key(ctx, 0);
2834 #ifdef PTW32_STATIC_LIB
2835 static void detach_ptw32(void)
2837 pthread_win32_thread_detach_np();
2838 pthread_win32_process_detach_np();
2840 #endif
2842 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
2843 * file for some tools to link against. */
2844 #ifndef DISABLE_MAIN
2845 int main(int argc,char* argv[]){
2848 char * mem_ptr;
2850 // movie info:
2852 /* Flag indicating whether MPlayer should exit without playing anything. */
2853 int opt_exit = 0;
2855 //float a_frame=0; // Audio
2857 int i;
2859 struct MPContext *mpctx = &(struct MPContext){
2860 .osd_function = OSD_PLAY,
2861 .begin_skip = MP_NOPTS_VALUE,
2862 .play_tree_step = 1,
2863 .global_sub_pos = -1,
2864 .set_of_sub_pos = -1,
2865 .file_format = DEMUXER_TYPE_UNKNOWN,
2866 .last_dvb_step = 1,
2869 #ifdef PTW32_STATIC_LIB
2870 pthread_win32_process_attach_np();
2871 pthread_win32_thread_attach_np();
2872 atexit(detach_ptw32);
2873 #endif
2875 InitTimer();
2876 srand(GetTimerMS());
2878 mp_msg_init();
2880 #ifdef CONFIG_X11
2881 mpctx->x11_state = vo_x11_init_state();
2882 #endif
2883 struct MPOpts *opts = &mpctx->opts;
2884 set_default_mplayer_options(opts);
2885 // Create the config context and register the options
2886 mpctx->mconfig = m_config_new(opts, cfg_include);
2887 m_config_register_options(mpctx->mconfig,mplayer_opts);
2888 mp_input_register_options(mpctx->mconfig);
2890 // Preparse the command line
2891 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
2893 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
2894 set_path_env();
2895 #endif
2897 #ifdef CONFIG_TV
2898 stream_tv_defaults.immediate = 1;
2899 #endif
2901 parse_cfgfiles(mpctx, mpctx->mconfig);
2903 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
2904 if(mpctx->playtree == NULL)
2905 opt_exit = 1;
2906 else {
2907 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
2908 if(mpctx->playtree) {
2909 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
2910 if(mpctx->playtree_iter) {
2911 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
2912 play_tree_iter_free(mpctx->playtree_iter);
2913 mpctx->playtree_iter = NULL;
2915 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
2919 mpctx->key_fifo = mp_fifo_create(opts);
2921 print_version("MPlayer");
2923 #if defined(__MINGW32__) || defined(__CYGWIN__)
2924 // stop Windows from showing all kinds of annoying error dialogs
2925 SetErrorMode(0x8003);
2926 // request 1ms timer resolution
2927 timeBeginPeriod(1);
2928 #endif
2930 #ifdef CONFIG_PRIORITY
2931 set_priority();
2932 #endif
2934 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
2935 list_video_out();
2936 opt_exit = 1;
2939 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
2940 list_audio_out();
2941 opt_exit = 1;
2944 /* Check codecs.conf. */
2945 if(!codecs_file || !parse_codec_cfg(codecs_file)){
2946 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
2947 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
2948 if(!parse_codec_cfg(NULL)){
2949 exit_player_with_rc(mpctx, EXIT_NONE, 0);
2951 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
2954 free( mem_ptr ); // release the buffer created by get_path()
2957 #if 0
2958 if(video_codec_list){
2959 int i;
2960 video_codec=video_codec_list[0];
2961 for(i=0;video_codec_list[i];i++)
2962 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
2964 #endif
2965 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
2966 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
2967 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
2968 list_codecs(1);
2969 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2970 opt_exit = 1;
2972 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
2973 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
2974 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
2975 list_codecs(0);
2976 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2977 opt_exit = 1;
2979 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
2980 vfm_help();
2981 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2982 opt_exit = 1;
2984 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
2985 afm_help();
2986 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2987 opt_exit = 1;
2989 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
2990 af_help();
2991 printf("\n");
2992 opt_exit = 1;
2994 #ifdef CONFIG_X11
2995 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
2996 fstype_help();
2997 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2998 opt_exit = 1;
3000 #endif
3001 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3002 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3003 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3004 demuxer_help();
3005 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3006 opt_exit = 1;
3008 if(list_properties) {
3009 property_print_help();
3010 opt_exit = 1;
3013 if(opt_exit)
3014 exit_player(mpctx, EXIT_NONE);
3016 if(!mpctx->filename && !player_idle_mode){
3017 // no file/vcd/dvd -> show HELP:
3018 mp_msg(MSGT_CPLAYER, MSGL_INFO, help_text);
3019 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3022 /* Display what configure line was used */
3023 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3025 // Many users forget to include command line in bugreports...
3026 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3027 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3028 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3029 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3032 //------ load global data first ------
3034 mpctx->osd = osd_create();
3036 // check font
3037 #ifdef CONFIG_FREETYPE
3038 init_freetype();
3039 #endif
3040 #ifdef CONFIG_FONTCONFIG
3041 if(font_fontconfig <= 0)
3043 #endif
3044 #ifdef CONFIG_BITMAP_FONT
3045 if(font_name){
3046 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3047 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3048 filename_recode(font_name));
3049 } else {
3050 // try default:
3051 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3052 free(mem_ptr); // release the buffer created by get_path()
3053 if(!vo_font)
3054 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3056 if (sub_font_name)
3057 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3058 else
3059 mpctx->osd->sub_font = vo_font;
3060 #endif
3061 #ifdef CONFIG_FONTCONFIG
3063 #endif
3065 #ifdef CONFIG_ASS
3066 ass_library = ass_init();
3067 #endif
3069 #ifdef HAVE_RTC
3070 if(!nortc)
3072 // seteuid(0); /* Can't hurt to try to get root here */
3073 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3074 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3075 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3076 else {
3077 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3079 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3080 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3081 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3082 close (rtc_fd);
3083 rtc_fd = -1;
3084 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3085 /* variable only by the root */
3086 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3087 close (rtc_fd);
3088 rtc_fd = -1;
3089 } else
3090 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3093 if(rtc_fd<0)
3094 #endif /* HAVE_RTC */
3095 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3096 softsleep?"software":timer_name);
3098 #ifdef HAVE_TERMCAP
3099 load_termcap(NULL); // load key-codes
3100 #endif
3102 // ========== Init keyboard FIFO (connection to libvo) ============
3104 // Init input system
3105 current_module = "init_input";
3106 mpctx->input = mp_input_init(&opts->input);
3107 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3108 if(slave_mode)
3109 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3110 else if(!noconsolecontrols)
3111 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3112 // Set the libstream interrupt callback
3113 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3115 #ifdef CONFIG_MENU
3116 if(use_menu) {
3117 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3118 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3119 else {
3120 menu_cfg = get_path("menu.conf");
3121 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3122 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3123 else {
3124 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3125 MPLAYER_CONFDIR "/menu.conf"))
3126 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3127 else {
3128 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3129 use_menu = 0;
3134 #endif
3136 current_module = NULL;
3138 /// Catch signals
3139 #ifndef __MINGW32__
3140 signal(SIGCHLD,child_sighandler);
3141 #endif
3143 #ifdef CONFIG_CRASH_DEBUG
3144 prog_path = argv[0];
3145 #endif
3146 //========= Catch terminate signals: ================
3147 // terminate requests:
3148 signal(SIGTERM,exit_sighandler); // kill
3149 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3151 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3153 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3154 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3155 #ifdef CONFIG_SIGHANDLER
3156 // fatal errors:
3157 signal(SIGBUS,exit_sighandler); // bus error
3158 signal(SIGSEGV,exit_sighandler); // segfault
3159 signal(SIGILL,exit_sighandler); // illegal instruction
3160 signal(SIGFPE,exit_sighandler); // floating point exc.
3161 signal(SIGABRT,exit_sighandler); // abort()
3162 #ifdef CONFIG_CRASH_DEBUG
3163 if (crash_debug)
3164 signal(SIGTRAP,exit_sighandler);
3165 #endif
3166 #endif
3168 // ******************* Now, let's see the per-file stuff ********************
3170 play_next_file:
3172 // init global sub numbers
3173 mpctx->global_sub_size = 0;
3174 { int i; for (i = 0; i < SUB_SOURCES; i++) mpctx->global_sub_indices[i] = -1; }
3176 if (mpctx->filename) {
3177 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3178 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3179 load_per_file_config (mpctx->mconfig, mpctx->filename);
3182 if (opts->video_driver_list)
3183 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3184 if (opts->audio_driver_list)
3185 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3187 // We must enable getch2 here to be able to interrupt network connection
3188 // or cache filling
3189 if(!noconsolecontrols && !slave_mode){
3190 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3191 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3192 else
3193 getch2_enable(); // prepare stdin for hotkeys...
3194 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3195 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3198 // =================== GUI idle loop (STOP state) ===========================
3199 while (player_idle_mode && !mpctx->filename) {
3200 play_tree_t * entry = NULL;
3201 mp_cmd_t * cmd;
3202 while (!(cmd = mp_input_get_cmd(mpctx->input, 0,1,0))) { // wait for command
3203 if (mpctx->video_out)
3204 vo_check_events(mpctx->video_out);
3205 usec_sleep(20000);
3207 switch (cmd->id) {
3208 case MP_CMD_LOADFILE:
3209 // prepare a tree entry with the new filename
3210 entry = play_tree_new();
3211 play_tree_add_file(entry, cmd->args[0].v.s);
3212 // The entry is added to the main playtree after the switch().
3213 break;
3214 case MP_CMD_LOADLIST:
3215 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3216 break;
3217 case MP_CMD_QUIT:
3218 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3219 break;
3220 case MP_CMD_GET_PROPERTY:
3221 case MP_CMD_SET_PROPERTY:
3222 case MP_CMD_STEP_PROPERTY:
3223 run_command(mpctx, cmd);
3224 break;
3227 mp_cmd_free(cmd);
3229 if (entry) { // user entered a command that gave a valid entry
3230 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3231 play_tree_free_list(mpctx->playtree->child, 1);
3232 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3234 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3236 play_tree_set_child(mpctx->playtree, entry);
3238 /* Make iterator start at the top the of tree. */
3239 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3240 if (!mpctx->playtree_iter) continue;
3242 // find the first real item in the tree
3243 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3244 // no items!
3245 play_tree_iter_free(mpctx->playtree_iter);
3246 mpctx->playtree_iter = NULL;
3247 continue; // wait for next command
3249 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3252 //---------------------------------------------------------------------------
3254 if(mpctx->filename)
3255 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3256 filename_recode(mpctx->filename));
3258 if (edl_filename) {
3259 if (edl_records) free_edl(edl_records);
3260 next_edl_record = edl_records = edl_parse_file();
3262 if (edl_output_filename) {
3263 if (edl_fd) fclose(edl_fd);
3264 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3266 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3267 filename_recode(edl_output_filename));
3271 //==================== Open VOB-Sub ============================
3273 current_module="vobsub";
3274 if (vobsub_name){
3275 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3276 if(vo_vobsub==NULL)
3277 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3278 filename_recode(vobsub_name));
3279 } else if (sub_auto && mpctx->filename){
3280 /* try to autodetect vobsub from movie filename ::atmos */
3281 char *buf = strdup(mpctx->filename), *psub;
3282 char *pdot = strrchr(buf, '.');
3283 char *pslash = strrchr(buf, '/');
3284 #if defined(__MINGW32__) || defined(__CYGWIN__)
3285 if (!pslash) pslash = strrchr(buf, '\\');
3286 #endif
3287 if (pdot && (!pslash || pdot > pslash))
3288 *pdot = '\0';
3289 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3290 /* try from ~/.mplayer/sub */
3291 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3292 char *bname;
3293 int l;
3294 bname = strrchr(buf,'/');
3295 #if defined(__MINGW32__) || defined(__CYGWIN__)
3296 if(!bname) bname = strrchr(buf,'\\');
3297 #endif
3298 if(bname) bname++;
3299 else bname = buf;
3300 l = strlen(psub) + strlen(bname) + 1;
3301 psub = realloc(psub,l);
3302 strcat(psub,bname);
3303 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3304 free(psub);
3306 free(buf);
3308 if(vo_vobsub){
3309 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3310 vobsub_set_from_lang(vo_vobsub, dvdsub_lang);
3311 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3313 // setup global sub numbering
3314 mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] = mpctx->global_sub_size; // the global # of the first vobsub.
3315 mpctx->global_sub_size += vobsub_get_indexes_count(vo_vobsub);
3318 //============ Open & Sync STREAM --- fork cache2 ====================
3320 mpctx->stream=NULL;
3321 mpctx->demuxer=NULL;
3322 if (mpctx->d_audio) {
3323 //free_demuxer_stream(mpctx->d_audio);
3324 mpctx->d_audio=NULL;
3326 if (mpctx->d_video) {
3327 //free_demuxer_stream(d_video);
3328 mpctx->d_video=NULL;
3330 mpctx->sh_audio=NULL;
3331 mpctx->sh_video=NULL;
3333 current_module="open_stream";
3334 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3335 if(!mpctx->stream) { // error...
3336 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3337 goto goto_next_file;
3339 mpctx->initialized_flags|=INITIALIZED_STREAM;
3341 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3342 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3343 "playlist support will not be used automatically.\n"
3344 "MPlayer's playlist code is unsafe and should only be used with "
3345 "trusted sources.\nPlayback will probably fail.\n\n");
3346 #if 0
3347 play_tree_t* entry;
3348 // Handle playlist
3349 current_module="handle_playlist";
3350 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3351 filename_recode(mpctx->filename));
3352 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3353 mpctx->eof=playtree_add_playlist(mpctx, entry);
3354 goto goto_next_file;
3355 #endif
3357 mpctx->stream->start_pos+=seek_to_byte;
3359 if(stream_dump_type==5){
3360 unsigned char buf[4096];
3361 int len;
3362 FILE *f;
3363 current_module="dumpstream";
3364 if(mpctx->stream->type==STREAMTYPE_STREAM && mpctx->stream->fd<0){
3365 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot dump this stream - no file descriptor available.\n");
3366 exit_player(mpctx, EXIT_ERROR);
3368 stream_reset(mpctx->stream);
3369 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3370 f=fopen(stream_dump_name,"wb");
3371 if(!f){
3372 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3373 exit_player(mpctx, EXIT_ERROR);
3375 if (dvd_chapter > 1) {
3376 int chapter = dvd_chapter - 1;
3377 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3379 while(!mpctx->stream->eof && !async_quit_request){
3380 len=stream_read(mpctx->stream,buf,4096);
3381 if(len>0) {
3382 if(fwrite(buf,len,1,f) != 1) {
3383 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3384 exit_player(mpctx, EXIT_ERROR);
3387 if(dvd_last_chapter > 0) {
3388 int chapter = -1;
3389 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3390 &chapter) == STREAM_OK && chapter + 1 > dvd_last_chapter)
3391 break;
3394 if(fclose(f)) {
3395 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3396 exit_player(mpctx, EXIT_ERROR);
3398 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3399 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3402 #ifdef CONFIG_DVDREAD
3403 if(mpctx->stream->type==STREAMTYPE_DVD){
3404 current_module="dvd lang->id";
3405 if(opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,audio_lang);
3406 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3407 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,dvdsub_lang);
3408 // setup global sub numbering
3409 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3410 mpctx->global_sub_size += dvd_number_of_subs(mpctx->stream);
3411 current_module=NULL;
3413 #endif
3415 #ifdef CONFIG_DVDNAV
3416 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3417 current_module="dvdnav lang->id";
3418 if(opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,audio_lang);
3419 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3420 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=mp_dvdnav_sid_from_lang(mpctx->stream,dvdsub_lang);
3421 // setup global sub numbering
3422 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3423 mpctx->global_sub_size += mp_dvdnav_number_of_subs(mpctx->stream);
3424 current_module=NULL;
3426 #endif
3428 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3429 goto_enable_cache:
3430 if(stream_cache_size>0){
3431 current_module="enable_cache";
3432 if(!stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3433 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3434 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0)))
3435 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3438 //============ Open DEMUXERS --- DETECT file type =======================
3439 current_module="demux_open";
3441 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3443 // HACK to get MOV Reference Files working
3445 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3447 unsigned char* playlist_entry;
3448 play_tree_t *list = NULL, *entry = NULL;
3450 current_module="handle_demux_playlist";
3451 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3453 char *temp, *bname;
3455 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3456 filename_recode(playlist_entry));
3458 bname=mp_basename(playlist_entry);
3459 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3460 continue;
3462 if (!strncmp(bname,mp_basename(mpctx->filename),strlen(bname))) // ignoring self-reference
3463 continue;
3465 entry = play_tree_new();
3467 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3469 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3470 if (temp)
3472 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3473 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3474 strcat(temp, playlist_entry);
3475 play_tree_add_file(entry,temp);
3476 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3477 free(temp);
3480 else
3481 play_tree_add_file(entry,playlist_entry);
3483 if(!list)
3484 list = entry;
3485 else
3486 play_tree_append_entry(list,entry);
3488 free_demuxer(mpctx->demuxer);
3489 mpctx->demuxer = NULL;
3491 if (list)
3493 entry = play_tree_new();
3494 play_tree_set_child(entry,list);
3495 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3496 goto goto_next_file;
3500 if(!mpctx->demuxer)
3501 goto goto_next_file;
3503 if (mpctx->demuxer->matroska_data.ordered_chapters)
3504 build_ordered_chapter_timeline(mpctx);
3506 if (!mpctx->sources) {
3507 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3508 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3509 .demuxer = mpctx->demuxer};
3510 mpctx->num_sources = 1;
3513 if(dvd_chapter>1) {
3514 double pts;
3515 if (seek_chapter(mpctx, dvd_chapter-1, &pts, NULL) >= 0 && pts > -1.0)
3516 seek(mpctx, pts, SEEK_ABSOLUTE);
3519 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3521 if (mpctx->stream->type != STREAMTYPE_DVD && mpctx->stream->type != STREAMTYPE_DVDNAV) {
3522 int i;
3523 int maxid = -1;
3524 // setup global sub numbering
3525 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3526 for (i = 0; i < MAX_S_STREAMS; i++)
3527 if (mpctx->demuxer->s_streams[i])
3528 maxid = FFMAX(maxid, mpctx->demuxer->s_streams[i]->sid);
3529 mpctx->global_sub_size += maxid + 1;
3531 // Make opts->sub_id always selectable if set.
3532 if (mpctx->global_sub_size <= mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id)
3533 mpctx->global_sub_size = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id + 1;
3535 #ifdef CONFIG_ASS
3536 if (ass_enabled && ass_library) {
3537 for (int j = 0; j < mpctx->num_sources; j++) {
3538 struct demuxer *d = mpctx->sources[j].demuxer;
3539 for (int i = 0; i < d->num_attachments; i++) {
3540 struct demux_attachment *att = d->attachments + i;
3541 if (extract_embedded_fonts
3542 && att->name && att->type && att->data && att->data_size
3543 && (strcmp(att->type, "application/x-truetype-font") == 0
3544 || strcmp(att->type, "application/x-font") == 0))
3545 ass_add_font(ass_library, att->name, att->data, att->data_size);
3549 #endif
3551 current_module="demux_open2";
3553 //file_format=demuxer->file_format;
3555 mpctx->d_audio=mpctx->demuxer->audio;
3556 mpctx->d_video=mpctx->demuxer->video;
3557 mpctx->d_sub=mpctx->demuxer->sub;
3559 // select audio stream
3560 select_audio(mpctx->demuxer, opts->audio_id, audio_lang);
3562 // DUMP STREAMS:
3563 if((stream_dump_type)&&(stream_dump_type<4)){
3564 FILE *f;
3565 demux_stream_t *ds=NULL;
3566 current_module="dump";
3567 // select stream to dump
3568 switch(stream_dump_type){
3569 case 1: ds=mpctx->d_audio;break;
3570 case 2: ds=mpctx->d_video;break;
3571 case 3: ds=mpctx->d_sub;break;
3573 if(!ds){
3574 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3575 exit_player(mpctx, EXIT_ERROR);
3577 // disable other streams:
3578 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3579 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3580 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3581 // let's dump it!
3582 f=fopen(stream_dump_name,"wb");
3583 if(!f){
3584 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3585 exit_player(mpctx, EXIT_ERROR);
3587 while(!ds->eof){
3588 unsigned char* start;
3589 int in_size=ds_get_packet(ds,&start);
3590 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3591 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3592 if(in_size>0) fwrite(start,in_size,1,f);
3593 if(dvd_last_chapter>0) {
3594 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3595 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3596 break;
3599 fclose(f);
3600 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3601 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3604 mpctx->sh_audio=mpctx->d_audio->sh;
3605 mpctx->sh_video=mpctx->d_video->sh;
3607 if(mpctx->sh_video){
3609 current_module="video_read_properties";
3610 if(!video_read_properties(mpctx->sh_video)) {
3611 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3612 mpctx->sh_video=mpctx->d_video->sh=NULL;
3613 } else {
3614 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3615 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3616 mpctx->sh_video->fps,mpctx->sh_video->frametime
3619 /* need to set fps here for output encoders to pick it up in their init */
3620 if(force_fps){
3621 mpctx->sh_video->fps=force_fps;
3622 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3624 vo_fps = mpctx->sh_video->fps;
3626 if(!mpctx->sh_video->fps && !force_fps){
3627 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3628 mpctx->sh_video=mpctx->d_video->sh=NULL;
3634 if(!mpctx->sh_video && !mpctx->sh_audio){
3635 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3636 #ifdef CONFIG_DVBIN
3637 if(mpctx->stream->type == STREAMTYPE_DVB)
3639 int dir;
3640 int v = mpctx->last_dvb_step;
3641 if(v > 0)
3642 dir = DVB_CHANNEL_HIGHER;
3643 else
3644 dir = DVB_CHANNEL_LOWER;
3646 if(dvb_step_channel(mpctx->stream, dir)) {
3647 mpctx->stop_play = PT_NEXT_ENTRY;
3648 mpctx->dvbin_reopen = 1;
3651 #endif
3652 goto goto_next_file; // exit_player(_("Fatal error"));
3655 /* display clip info */
3656 demux_info_print(mpctx->demuxer);
3658 //================== Read SUBTITLES (DVD & TEXT) ==========================
3659 if(vo_spudec==NULL && mpctx->sh_video &&
3660 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3661 init_vo_spudec(mpctx);
3664 if(mpctx->sh_video) {
3665 // after reading video params we should load subtitles because
3666 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3667 // check .sub
3668 current_module="read_subtitles_file";
3669 if(sub_name){
3670 for (i = 0; sub_name[i] != NULL; ++i)
3671 add_subtitles(mpctx, sub_name[i], mpctx->sh_video->fps, 0);
3673 if(sub_auto) { // auto load sub file ...
3674 char *psub = get_path( "sub/" );
3675 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3676 int i = 0;
3677 free(psub); // release the buffer created by get_path() above
3678 while (tmp[i]) {
3679 add_subtitles(mpctx, tmp[i], mpctx->sh_video->fps, 1);
3680 free(tmp[i++]);
3682 free(tmp);
3684 if (mpctx->set_of_sub_size > 0) {
3685 // setup global sub numbering
3686 mpctx->global_sub_indices[SUB_SOURCE_SUBS] = mpctx->global_sub_size; // the global # of the first sub.
3687 mpctx->global_sub_size += mpctx->set_of_sub_size;
3691 if (mpctx->global_sub_size) {
3692 // find the best sub to use
3693 int vobsub_index_id = vobsub_get_index_by_id(vo_vobsub, vobsub_id);
3694 mpctx->global_sub_pos = -1; // no subs by default
3695 if (vobsub_index_id >= 0) {
3696 // if user asks for a vobsub id, use that first.
3697 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] + vobsub_index_id;
3698 } else if (opts->sub_id >= 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3699 // if user asks for a dvd sub id, use that next.
3700 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3701 } else if (mpctx->global_sub_indices[SUB_SOURCE_SUBS] >= 0) {
3702 // if there are text subs to use, use those. (autosubs come last here)
3703 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_SUBS];
3704 } else if (opts->sub_id < 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3705 // finally select subs by language and container hints
3706 if (opts->sub_id < 0 && dvdsub_lang)
3707 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, dvdsub_lang);
3708 if (opts->sub_id < 0)
3709 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
3710 if (opts->sub_id >= 0)
3711 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3713 // rather than duplicate code, use the SUB_SELECT handler to init the right one.
3714 mpctx->global_sub_pos--;
3715 mp_property_do("sub",M_PROPERTY_STEP_UP,NULL, mpctx);
3716 if(subdata)
3717 switch (stream_dump_type) {
3718 case 3: list_sub_file(subdata); break;
3719 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3720 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3721 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3722 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3723 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3727 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
3728 filename_recode(mpctx->filename));
3729 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
3730 if (mpctx->sh_video) {
3731 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3732 if (mpctx->sh_video->format >= 0x20202020)
3733 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
3734 else
3735 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
3736 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
3737 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
3738 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
3739 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
3740 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
3742 if (mpctx->sh_audio) {
3743 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3744 if (mpctx->sh_audio->format >= 0x20202020)
3745 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
3746 else
3747 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
3748 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
3749 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
3750 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
3752 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", demuxer_get_time_length(mpctx->demuxer));
3753 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
3754 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
3755 if (mpctx->demuxer) {
3756 if (mpctx->demuxer->num_chapters == 0)
3757 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
3758 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
3761 if(!mpctx->sh_video) goto main; // audio-only
3763 if(!reinit_video_chain(mpctx)) {
3764 if(!mpctx->sh_video){
3765 if(!mpctx->sh_audio) goto goto_next_file;
3766 goto main; // exit_player(_("Fatal error"));
3770 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
3771 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3773 #ifdef CONFIG_FREETYPE
3774 force_load_font = 1;
3775 #endif
3777 //================== MAIN: ==========================
3778 main:
3779 current_module="main";
3781 if(playing_msg) {
3782 char* msg = property_expand_string(mpctx, playing_msg);
3783 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
3784 free(msg);
3788 // Disable the term OSD in verbose mode
3789 if(verbose) term_osd = 0;
3792 //int frame_corr_num=0; //
3793 //float v_frame=0; // Video
3794 //float num_frames=0; // number of frames played
3796 int frame_time_remaining=0; // flag
3797 int blit_frame=0;
3798 mpctx->num_buffered_frames=0;
3800 // Make sure old OSD does not stay around,
3801 // e.g. with -fixed-vo and same-resolution files
3802 clear_osd_msgs();
3803 update_osd_msg(mpctx);
3805 //================ SETUP AUDIO ==========================
3807 if(mpctx->sh_audio){
3808 reinit_audio_chain(mpctx);
3809 if (mpctx->sh_audio && mpctx->sh_audio->codec)
3810 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
3813 current_module="av_init";
3815 if(mpctx->sh_video){
3816 mpctx->sh_video->timer=0;
3817 if (! ignore_start)
3818 audio_delay += mpctx->sh_video->stream_delay;
3820 if(mpctx->sh_audio){
3821 if (start_volume >= 0)
3822 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
3823 if (! ignore_start)
3824 audio_delay -= mpctx->sh_audio->stream_delay;
3825 mpctx->delay=-audio_delay;
3828 if(!mpctx->sh_audio){
3829 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
3830 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
3831 ds_free_packs(mpctx->d_audio); // free buffered chunks
3832 //mpctx->d_audio->id=-2; // do not read audio chunks
3833 //uninit_player(mpctx, INITIALIZED_AO); // close device
3835 if(!mpctx->sh_video){
3836 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
3837 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
3838 ds_free_packs(mpctx->d_video);
3839 mpctx->d_video->id=-2;
3840 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
3843 if (!mpctx->sh_video && !mpctx->sh_audio)
3844 goto goto_next_file;
3846 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
3847 if(force_fps && mpctx->sh_video){
3848 vo_fps = mpctx->sh_video->fps=force_fps;
3849 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3850 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
3853 mp_input_set_section(mpctx->input, NULL);
3854 //TODO: add desired (stream-based) sections here
3855 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
3856 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
3858 //==================== START PLAYING =======================
3860 if(opts->loop_times>1) opts->loop_times--; else
3861 if(opts->loop_times==1) opts->loop_times = -1;
3863 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
3865 total_time_usage_start=GetTimer();
3866 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
3867 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
3868 play_n_frames=play_n_frames_mf;
3870 if(play_n_frames==0){
3871 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
3874 if (seek_to_sec) {
3875 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
3876 end_at.pos += seek_to_sec;
3879 if (end_at.type == END_AT_SIZE) {
3880 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
3881 end_at.type = END_AT_NONE;
3884 #ifdef CONFIG_DVDNAV
3885 mp_dvdnav_context_free(mpctx);
3886 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3887 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
3888 mp_dvdnav_cell_has_changed(mpctx->stream,1);
3890 #endif
3892 get_relative_time(mpctx); // reset current delta
3893 mpctx->time_frame = 0;
3894 mpctx->drop_message_shown = 0;
3895 mpctx->update_video_immediately = true;
3896 mpctx->total_avsync_change = 0;
3897 // Make sure VO knows current pause state
3898 if (mpctx->sh_video)
3899 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
3900 NULL);
3902 while(!mpctx->stop_play){
3903 float aq_sleep_time=0;
3905 if(dvd_last_chapter>0) {
3906 int cur_chapter = get_current_chapter(mpctx);
3907 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3908 goto goto_next_file;
3911 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
3912 mpctx->sh_audio = mpctx->d_audio->sh;
3913 mpctx->sh_audio->ds = mpctx->d_audio;
3914 reinit_audio_chain(mpctx);
3917 /*========================== PLAY AUDIO ============================*/
3919 if (mpctx->sh_audio && !mpctx->paused)
3920 if (!fill_audio_out_buffers(mpctx))
3921 // at eof, all audio at least written to ao
3922 if (!mpctx->sh_video)
3923 mpctx->stop_play = AT_END_OF_FILE;
3926 if(!mpctx->sh_video) {
3927 // handle audio-only case:
3928 double a_pos=0;
3929 // sh_audio can be NULL due to video stream switching
3930 // TODO: handle this better
3931 if (mpctx->sh_audio)
3932 a_pos = playing_audio_pts(mpctx);
3934 print_status(mpctx, a_pos, false);
3936 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
3937 mpctx->stop_play = PT_NEXT_ENTRY;
3938 update_osd_msg(mpctx);
3940 } else {
3942 /*========================== PLAY VIDEO ============================*/
3944 vo_pts=mpctx->sh_video->timer*90000.0;
3945 vo_fps=mpctx->sh_video->fps;
3947 if (!mpctx->num_buffered_frames) {
3948 double frame_time = update_video(mpctx, &blit_frame);
3949 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
3950 if (mpctx->sh_video->vf_initialized < 0) {
3951 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
3952 mpctx->stop_play = PT_NEXT_ENTRY;
3953 goto goto_next_file;
3955 if (blit_frame) {
3956 struct vf_instance *vf = mpctx->sh_video->vfilter;
3957 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3958 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3959 vo_osd_changed(0);
3961 if (frame_time < 0)
3962 mpctx->stop_play = AT_END_OF_FILE;
3963 else {
3964 // might return with !eof && !blit_frame if !correct_pts
3965 mpctx->num_buffered_frames += blit_frame;
3966 if (mpctx->update_video_immediately) {
3967 // Show this frame immediately, rest normally
3968 mpctx->update_video_immediately = false;
3969 } else {
3970 mpctx->time_frame += frame_time / opts->playback_speed;
3971 adjust_sync(mpctx, frame_time);
3975 if (mpctx->timeline) {
3976 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
3977 if (mpctx->sh_video->pts >= next->start
3978 || mpctx->stop_play == AT_END_OF_FILE
3979 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3980 seek(mpctx, next->start, SEEK_ABSOLUTE);
3981 continue;
3985 // ==========================================================================
3987 // current_module="draw_osd";
3988 // if(vo_config_count) mpctx->video_out->draw_osd();
3990 current_module="vo_check_events";
3991 vo_check_events(mpctx->video_out);
3993 #ifdef CONFIG_X11
3994 if (stop_xscreensaver) {
3995 current_module = "stop_xscreensaver";
3996 xscreensaver_heartbeat(mpctx->x11_state);
3998 #endif
3999 if (heartbeat_cmd) {
4000 static unsigned last_heartbeat;
4001 unsigned now = GetTimerMS();
4002 if (now - last_heartbeat > 30000) {
4003 last_heartbeat = now;
4004 system(heartbeat_cmd);
4008 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4010 //====================== FLIP PAGE (VIDEO BLT): =========================
4012 current_module="flip_page";
4013 if (!frame_time_remaining && blit_frame) {
4014 unsigned int t2=GetTimer();
4016 vo_flip_page(mpctx->video_out);
4017 mpctx->num_buffered_frames--;
4019 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4020 vout_time_usage += mpctx->last_vo_flip_duration;
4021 print_status(mpctx, MP_NOPTS_VALUE, true);
4023 else
4024 print_status(mpctx, MP_NOPTS_VALUE, false);
4026 //============================ Auto QUALITY ============================
4028 /*Output quality adjustments:*/
4029 if(auto_quality>0){
4030 current_module="autoq";
4031 // float total=0.000001f * (GetTimer()-aq_total_time);
4032 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4033 if(output_quality<auto_quality && aq_sleep_time>0)
4034 ++output_quality;
4035 else
4036 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4037 if(output_quality>1 && aq_sleep_time<0)
4038 --output_quality;
4039 else
4040 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4041 output_quality=0;
4042 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4043 set_video_quality(mpctx->sh_video,output_quality);
4046 if (!frame_time_remaining && blit_frame) {
4047 if (play_n_frames >= 0) {
4048 --play_n_frames;
4049 if (play_n_frames <= 0)
4050 mpctx->stop_play = PT_NEXT_ENTRY;
4052 if (mpctx->step_frames > 0) {
4053 mpctx->step_frames--;
4054 if (mpctx->step_frames == 0)
4055 pause_player(mpctx);
4060 // FIXME: add size based support for -endpos
4061 if (end_at.type == END_AT_TIME &&
4062 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4063 mpctx->stop_play = PT_NEXT_ENTRY;
4065 } // end if(mpctx->sh_video)
4067 #ifdef CONFIG_DVDNAV
4068 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4069 nav_highlight_t hl;
4070 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4071 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4072 vo_osd_changed (OSDTYPE_DVDNAV);
4074 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4075 double ar = -1.0;
4076 if (stream_control (mpctx->demuxer->stream,
4077 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4078 != STREAM_UNSUPPORTED)
4079 mpctx->sh_video->stream_aspect = ar;
4082 #endif
4084 //================= Keyboard events, SEEKing ====================
4086 current_module="key_events";
4089 while (1) {
4090 mp_cmd_t* cmd;
4091 while ((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
4092 run_command(mpctx, cmd);
4093 mp_cmd_free(cmd);
4094 if (mpctx->stop_play)
4095 break;
4097 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4098 || mpctx->abs_seek_pos)
4099 break;
4100 if (mpctx->sh_video) {
4101 update_osd_msg(mpctx);
4102 int hack = vo_osd_changed(0);
4103 vo_osd_changed(hack);
4104 if (hack)
4105 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4106 add_step_frame(mpctx);
4107 break;
4109 else
4110 vo_osd_changed(0);
4112 pause_loop(mpctx);
4116 // handle -sstep
4117 if (step_sec > 0 && !mpctx->paused) {
4118 mpctx->osd_function=OSD_FFW;
4119 mpctx->rel_seek_secs+=step_sec;
4122 edl_update(mpctx);
4124 /* Looping. */
4125 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4126 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4128 if(opts->loop_times>1) opts->loop_times--; else
4129 if(opts->loop_times==1) opts->loop_times=-1;
4130 play_n_frames=play_n_frames_mf;
4131 mpctx->stop_play=0;
4132 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4135 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4136 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4138 mpctx->rel_seek_secs=0;
4139 mpctx->abs_seek_pos=0;
4142 } // while(!mpctx->stop_play)
4144 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4146 #ifdef CONFIG_DVBIN
4147 if(mpctx->dvbin_reopen)
4149 mpctx->stop_play = 0;
4150 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4151 cache_uninit(mpctx->stream);
4152 mpctx->dvbin_reopen = 0;
4153 goto goto_enable_cache;
4155 #endif
4158 goto_next_file: // don't jump here after ao/vo/getch initialization!
4160 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4162 if(benchmark){
4163 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4164 double total_time_usage;
4165 total_time_usage_start=GetTimer()-total_time_usage_start;
4166 total_time_usage = (float)total_time_usage_start*0.000001;
4167 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4168 video_time_usage,vout_time_usage,audio_time_usage,
4169 total_time_usage-tot,total_time_usage);
4170 if(total_time_usage>0.0)
4171 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4172 100.0*video_time_usage/total_time_usage,
4173 100.0*vout_time_usage/total_time_usage,
4174 100.0*audio_time_usage/total_time_usage,
4175 100.0*(total_time_usage-tot)/total_time_usage,
4176 100.0);
4177 if(total_frame_cnt && frame_dropping)
4178 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4179 total_frame_cnt-drop_frame_cnt,
4180 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4181 drop_frame_cnt,
4182 100*drop_frame_cnt/total_frame_cnt,
4183 total_frame_cnt,
4184 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4187 // time to uninit all, except global stuff:
4188 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4190 if(mpctx->set_of_sub_size > 0) {
4191 current_module="sub_free";
4192 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4193 sub_free(mpctx->set_of_subtitles[i]);
4194 #ifdef CONFIG_ASS
4195 if(mpctx->set_of_ass_tracks[i])
4196 ass_free_track( mpctx->set_of_ass_tracks[i] );
4197 #endif
4199 mpctx->set_of_sub_size = 0;
4201 vo_sub_last = vo_sub=NULL;
4202 subdata=NULL;
4203 #ifdef CONFIG_ASS
4204 ass_track = NULL;
4205 if(ass_library)
4206 ass_clear_fonts(ass_library);
4207 #endif
4209 if (!mpctx->stop_play) // In case some goto jumped here...
4210 mpctx->stop_play = PT_NEXT_ENTRY;
4212 int playtree_direction = 1;
4214 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4215 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4216 play_tree_iter_free(mpctx->playtree_iter);
4217 mpctx->playtree_iter = NULL;
4219 mpctx->play_tree_step = 1;
4220 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4221 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4222 if(mpctx->playtree_iter) {
4223 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4224 play_tree_iter_free(mpctx->playtree_iter);
4225 mpctx->playtree_iter = NULL;
4228 } else if (mpctx->stop_play == PT_STOP) {
4229 play_tree_iter_free(mpctx->playtree_iter);
4230 mpctx->playtree_iter = NULL;
4231 } else { // NEXT PREV SRC
4232 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4235 while(mpctx->playtree_iter != NULL) {
4236 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4237 if(mpctx->filename == NULL) {
4238 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4239 play_tree_iter_free(mpctx->playtree_iter);
4240 mpctx->playtree_iter = NULL;
4242 } else
4243 break;
4246 if(mpctx->playtree_iter != NULL || player_idle_mode){
4247 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4248 mpctx->stop_play = 0;
4249 goto play_next_file;
4253 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4255 return 1;
4257 #endif /* DISABLE_MAIN */