Merge svn changes up to r29455
[mplayer.git] / mplayer.c
blob8697e47a85eda7424be903e47e797f4d3a3f913a
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 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
675 uninit_player(mpctx, INITIALIZED_ALL);
676 #if defined(__MINGW32__) || defined(__CYGWIN__)
677 timeEndPeriod(1);
678 #endif
679 #ifdef CONFIG_X11
680 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
681 #endif
683 current_module="uninit_input";
684 mp_input_uninit(mpctx->input);
685 #ifdef CONFIG_MENU
686 if (use_menu)
687 menu_uninit();
688 #endif
690 #ifdef CONFIG_FREETYPE
691 current_module="uninit_font";
692 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
693 free_font_desc(mpctx->osd->sub_font);
694 free_font_desc(vo_font);
695 vo_font = NULL;
696 done_freetype();
697 #endif
698 osd_free(mpctx->osd);
700 #ifdef CONFIG_ASS
701 ass_library_done(ass_library);
702 #endif
704 current_module="exit_player";
706 // free mplayer config
707 if(mpctx->mconfig)
708 m_config_free(mpctx->mconfig);
710 if(mpctx->playtree)
711 play_tree_free(mpctx->playtree, 1);
713 talloc_free(mpctx->key_fifo);
715 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
716 switch(how) {
717 case EXIT_QUIT:
718 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
719 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
720 break;
721 case EXIT_EOF:
722 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
723 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
724 break;
725 case EXIT_ERROR:
726 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
727 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
728 break;
729 default:
730 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
732 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
734 exit(rc);
737 static void exit_player(struct MPContext *mpctx, exit_reason_t how)
739 exit_player_with_rc(mpctx, how, 1);
742 #ifndef __MINGW32__
743 static void child_sighandler(int x){
744 pid_t pid;
745 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
747 #endif
749 #ifdef CONFIG_CRASH_DEBUG
750 static char *prog_path;
751 static int crash_debug = 0;
752 #endif
754 static void exit_sighandler(int x){
755 static int sig_count=0;
756 #ifdef CONFIG_CRASH_DEBUG
757 if (!crash_debug || x != SIGTRAP)
758 #endif
759 ++sig_count;
760 if(sig_count==5)
762 /* We're crashing bad and can't uninit cleanly :(
763 * by popular request, we make one last (dirty)
764 * effort to restore the user's
765 * terminal. */
766 getch2_disable();
767 exit(1);
769 if(sig_count==6) exit(1);
770 if(sig_count>6){
771 // can't stop :(
772 #ifndef __MINGW32__
773 kill(getpid(),SIGKILL);
774 #endif
776 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"\n" "\nMPlayer interrupted by signal %d in module: %s\n",x,
777 current_module?current_module:"unknown"
779 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
780 if(sig_count<=1)
781 switch(x){
782 case SIGINT:
783 case SIGQUIT:
784 case SIGTERM:
785 case SIGKILL:
786 async_quit_request = 1;
787 return; // killed from keyboard (^C) or killed [-9]
788 case SIGILL:
789 #if CONFIG_RUNTIME_CPUDETECT
790 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
791 #else
792 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
793 #endif
794 case SIGFPE:
795 case SIGSEGV:
796 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
797 default:
798 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
799 #ifdef CONFIG_CRASH_DEBUG
800 if (crash_debug) {
801 int gdb_pid;
802 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
803 gdb_pid = fork();
804 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
805 if (gdb_pid == 0) { // We are the child
806 char spid[20];
807 snprintf(spid, sizeof(spid), "%i", getppid());
808 getch2_disable(); // allow terminal to work properly with gdb
809 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
810 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
811 } else if (gdb_pid < 0)
812 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
813 else {
814 waitpid(gdb_pid, NULL, 0);
816 if (x == SIGTRAP) return;
818 #endif
820 getch2_disable();
821 exit(1);
824 #include "cfg-mplayer.h"
826 static int cfg_include(m_option_t *conf, char *filename)
828 return m_config_parse_config_file(conf->priv, filename);
831 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
833 char *conffile;
834 int conffile_fd;
835 if (!disable_system_conf &&
836 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
837 exit_player(mpctx, EXIT_NONE);
838 if ((conffile = get_path("")) == NULL) {
839 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
840 } else {
841 #ifdef __MINGW32__
842 mkdir(conffile);
843 #else
844 mkdir(conffile, 0777);
845 #endif
846 free(conffile);
847 if ((conffile = get_path("config")) == NULL) {
848 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
849 } else {
850 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
851 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
852 write(conffile_fd, default_config, strlen(default_config));
853 close(conffile_fd);
855 if (!disable_user_conf &&
856 m_config_parse_config_file(conf, conffile) < 0)
857 exit_player(mpctx, EXIT_NONE);
858 free(conffile);
863 #define PROFILE_CFG_PROTOCOL "protocol."
865 static void load_per_protocol_config (m_config_t* conf, const char *const file)
867 char *str;
868 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
869 m_profile_t *p;
871 /* does filename actually uses a protocol ? */
872 str = strstr (file, "://");
873 if (!str)
874 return;
876 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
877 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
878 p = m_config_get_profile (conf, protocol);
879 if (p)
881 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
882 m_config_set_profile(conf,p);
886 #define PROFILE_CFG_EXTENSION "extension."
888 static void load_per_extension_config (m_config_t* conf, const char *const file)
890 char *str;
891 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
892 m_profile_t *p;
894 /* does filename actually have an extension ? */
895 str = strrchr (file, '.');
896 if (!str)
897 return;
899 sprintf (extension, PROFILE_CFG_EXTENSION);
900 strncat (extension, ++str, 7);
901 p = m_config_get_profile (conf, extension);
902 if (p)
904 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
905 m_config_set_profile(conf,p);
909 #define PROFILE_CFG_VO "vo."
910 #define PROFILE_CFG_AO "ao."
912 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
914 char profile[strlen (cfg) + strlen (out) + 1];
915 m_profile_t *p;
917 sprintf (profile, "%s%s", cfg, out);
918 p = m_config_get_profile (conf, profile);
919 if (p)
921 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
922 m_config_set_profile(conf,p);
926 static void load_per_file_config (m_config_t* conf, const char *const file)
928 char *confpath;
929 char cfg[strlen(file)+10];
930 struct stat st;
931 char *name;
933 sprintf (cfg, "%s.conf", file);
935 if (use_filedir_conf && !stat (cfg, &st))
937 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading config '%s'\n", cfg);
938 m_config_parse_config_file (conf, cfg);
939 return;
942 if ((name = strrchr (cfg, '/')) == NULL)
943 name = cfg;
944 else
945 name++;
947 if ((confpath = get_path (name)) != NULL)
949 if (!stat (confpath, &st))
951 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading config '%s'\n", confpath);
952 m_config_parse_config_file (conf, confpath);
955 free (confpath);
959 /* When libmpdemux performs a blocking operation (network connection or
960 * cache filling) if the operation fails we use this function to check
961 * if it was interrupted by the user.
962 * The function returns a new value for eof. */
963 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
965 mp_cmd_t* cmd;
966 if((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
967 switch(cmd->id) {
968 case MP_CMD_QUIT:
969 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
970 case MP_CMD_PLAY_TREE_STEP: {
971 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
972 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
973 } break;
974 case MP_CMD_PLAY_TREE_UP_STEP: {
975 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
976 } break;
977 case MP_CMD_PLAY_ALT_SRC_STEP: {
978 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
979 } break;
981 mp_cmd_free(cmd);
983 return stop_play;
986 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
988 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
990 play_tree_add_bpf(entry,mpctx->filename);
993 if(!entry) {
994 entry = mpctx->playtree_iter->tree;
995 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
996 return PT_NEXT_ENTRY;
998 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
999 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1000 return PT_NEXT_ENTRY;
1003 play_tree_remove(entry,1,1);
1004 return PT_NEXT_SRC;
1006 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1007 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1008 entry = mpctx->playtree_iter->tree;
1009 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1010 return PT_NEXT_ENTRY;
1012 play_tree_remove(entry,1,1);
1014 return PT_NEXT_SRC;
1017 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1019 sub_data *subd;
1020 #ifdef CONFIG_ASS
1021 ass_track_t *asst = 0;
1022 #endif
1024 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1025 return;
1028 subd = sub_read_file(filename, fps);
1029 #ifdef CONFIG_ASS
1030 if (ass_enabled)
1031 #ifdef CONFIG_ICONV
1032 asst = ass_read_file(ass_library, filename, sub_cp);
1033 #else
1034 asst = ass_read_file(ass_library, filename, 0);
1035 #endif
1036 if (ass_enabled && subd && !asst)
1037 asst = ass_read_subdata(ass_library, subd, fps);
1039 if (!asst && !subd)
1040 #else
1041 if(!subd)
1042 #endif
1043 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR, "Cannot load subtitles: %s\n",
1044 filename_recode(filename));
1046 #ifdef CONFIG_ASS
1047 if (!asst && !subd) return;
1048 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1049 #else
1050 if (!subd) return;
1051 #endif
1052 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1053 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1054 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1055 filename_recode(filename));
1056 ++mpctx->set_of_sub_size;
1057 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1058 filename_recode(filename));
1061 void init_vo_spudec(struct MPContext *mpctx)
1063 if (vo_spudec)
1064 spudec_free(vo_spudec);
1065 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1066 vo_spudec = NULL;
1067 if (spudec_ifo) {
1068 unsigned int palette[16], width, height;
1069 current_module="spudec_init_vobsub";
1070 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1071 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1074 #ifdef CONFIG_DVDREAD
1075 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1076 current_module="spudec_init_dvdread";
1077 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1078 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1079 NULL, 0);
1081 #endif
1083 #ifdef CONFIG_DVDNAV
1084 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1085 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1086 current_module="spudec_init_dvdnav";
1087 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1089 #endif
1091 if (vo_spudec==NULL) {
1092 sh_sub_t *sh = (sh_sub_t *)mpctx->d_sub->sh;
1093 current_module="spudec_init_normal";
1094 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1095 spudec_set_font_factor(vo_spudec,font_factor);
1098 if (vo_spudec!=NULL) {
1099 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1100 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1105 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1106 * make it all work is to use the builtin SDL-bootstrap code, which
1107 * will be done automatically by replacing our main() if we include SDL.h.
1109 #if defined(__APPLE__) && defined(CONFIG_SDL)
1110 #include <SDL.h>
1111 #endif
1114 * \brief append a formatted string
1115 * \param buf buffer to print into
1116 * \param pos position of terminating 0 in buf
1117 * \param len maximum number of characters in buf, not including terminating 0
1118 * \param format printf format string
1120 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1122 va_list va;
1123 va_start(va, format);
1124 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1125 va_end(va);
1126 if (*pos >= len ) {
1127 buf[len] = 0;
1128 *pos = len;
1133 * \brief append time in the hh:mm:ss.f format
1134 * \param buf buffer to print into
1135 * \param pos position of terminating 0 in buf
1136 * \param len maximum number of characters in buf, not including terminating 0
1137 * \param time time value to convert/append
1139 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1140 long tenths = 10 * time;
1141 int f1 = tenths % 10;
1142 int ss = (tenths / 10) % 60;
1143 int mm = (tenths / 600) % 60;
1144 int hh = tenths / 36000;
1145 if (time <= 0) {
1146 saddf(buf, pos, len, "unknown");
1147 return;
1149 if (hh > 0)
1150 saddf(buf, pos, len, "%2d:", hh);
1151 if (hh > 0 || mm > 0)
1152 saddf(buf, pos, len, "%02d:", mm);
1153 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1156 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1158 struct MPOpts *opts = &mpctx->opts;
1159 sh_video_t * const sh_video = mpctx->sh_video;
1161 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1162 a_pos = playing_audio_pts(mpctx);
1163 if (mpctx->sh_audio && sh_video && at_frame) {
1164 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1165 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1166 && !mpctx->drop_message_shown) {
1167 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1168 mpctx->drop_message_shown = true;
1171 if (quiet)
1172 return;
1175 int width;
1176 char *line;
1177 unsigned pos = 0;
1178 get_screen_size();
1179 if (screen_width > 0)
1180 width = screen_width;
1181 else
1182 width = 80;
1183 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1184 /* Windows command line is broken (MinGW's rxvt works, but we
1185 * should not depend on that). */
1186 width--;
1187 #endif
1188 line = malloc(width + 1); // one additional char for the terminating null
1190 // Audio time
1191 if (mpctx->sh_audio) {
1192 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1193 if (!sh_video) {
1194 float len = demuxer_get_time_length(mpctx->demuxer);
1195 saddf(line, &pos, width, "(");
1196 sadd_hhmmssf(line, &pos, width, a_pos);
1197 saddf(line, &pos, width, ") of %.1f (", len);
1198 sadd_hhmmssf(line, &pos, width, len);
1199 saddf(line, &pos, width, ") ");
1203 // Video time
1204 if (sh_video)
1205 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1207 // A-V sync
1208 if (mpctx->sh_audio && sh_video)
1209 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1210 mpctx->last_av_difference, mpctx->total_avsync_change);
1212 // Video stats
1213 if (sh_video)
1214 saddf(line, &pos, width, "%3d/%3d ",
1215 (int)sh_video->num_frames,
1216 (int)sh_video->num_frames_decoded);
1218 // CPU usage
1219 if (sh_video) {
1220 if (sh_video->timer > 0.5)
1221 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1222 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1223 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1224 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1225 else
1226 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1227 } else if (mpctx->sh_audio) {
1228 if (mpctx->delay > 0.5)
1229 saddf(line, &pos, width, "%4.1f%% ",
1230 100.0*audio_time_usage/(double)mpctx->delay);
1231 else
1232 saddf(line, &pos, width, "??,?%% ");
1235 // VO stats
1236 if (sh_video)
1237 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1239 #ifdef CONFIG_STREAM_CACHE
1240 // cache stats
1241 if (stream_cache_size > 0)
1242 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1243 #endif
1245 // other
1246 if (opts->playback_speed != 1)
1247 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1249 // end
1250 if (erase_to_end_of_line) {
1251 line[pos] = 0;
1252 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1253 } else {
1254 memset(&line[pos], ' ', width - pos);
1255 line[width] = 0;
1256 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1258 free(line);
1262 * \brief build a chain of audio filters that converts the input format
1263 * to the ao's format, taking into account the current playback_speed.
1264 * \param sh_audio describes the requested input format of the chain.
1265 * \param ao_data describes the requested output format of the chain.
1267 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1269 struct MPOpts *opts = &mpctx->opts;
1270 int new_srate;
1271 int result;
1272 if (!sh_audio)
1274 mpctx->mixer.afilter = NULL;
1275 return 0;
1277 if(af_control_any_rev(sh_audio->afilter,
1278 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1279 &opts->playback_speed)) {
1280 new_srate = sh_audio->samplerate;
1281 } else {
1282 new_srate = sh_audio->samplerate * opts->playback_speed;
1283 if (new_srate != ao_data->samplerate) {
1284 // limits are taken from libaf/af_resample.c
1285 if (new_srate < 8000)
1286 new_srate = 8000;
1287 if (new_srate > 192000)
1288 new_srate = 192000;
1289 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1292 result = init_audio_filters(sh_audio, new_srate,
1293 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1294 mpctx->mixer.afilter = sh_audio->afilter;
1295 return result;
1299 typedef struct mp_osd_msg mp_osd_msg_t;
1300 struct mp_osd_msg {
1301 /// Previous message on the stack.
1302 mp_osd_msg_t* prev;
1303 /// Message text.
1304 char msg[128];
1305 int id,level,started;
1306 /// Display duration in ms.
1307 unsigned time;
1310 /// OSD message stack.
1311 static mp_osd_msg_t* osd_msg_stack = NULL;
1314 * \brief Add a message on the OSD message stack
1316 * If a message with the same id is already present in the stack
1317 * it is pulled on top of the stack, otherwise a new message is created.
1321 void set_osd_msg(int id, int level, int time, const char* fmt, ...) {
1322 mp_osd_msg_t *msg,*last=NULL;
1323 va_list va;
1324 int r;
1326 // look if the id is already in the stack
1327 for(msg = osd_msg_stack ; msg && msg->id != id ;
1328 last = msg, msg = msg->prev);
1329 // not found: alloc it
1330 if(!msg) {
1331 msg = calloc(1,sizeof(mp_osd_msg_t));
1332 msg->prev = osd_msg_stack;
1333 osd_msg_stack = msg;
1334 } else if(last) { // found, but it's not on top of the stack
1335 last->prev = msg->prev;
1336 msg->prev = osd_msg_stack;
1337 osd_msg_stack = msg;
1339 // write the msg
1340 va_start(va,fmt);
1341 r = vsnprintf(msg->msg, 128, fmt, va);
1342 va_end(va);
1343 if(r >= 128) msg->msg[127] = 0;
1344 // set id and time
1345 msg->id = id;
1346 msg->level = level;
1347 msg->time = time;
1352 * \brief Remove a message from the OSD stack
1354 * This function can be used to get rid of a message right away.
1358 void rm_osd_msg(int id) {
1359 mp_osd_msg_t *msg,*last=NULL;
1361 // Search for the msg
1362 for(msg = osd_msg_stack ; msg && msg->id != id ;
1363 last = msg, msg = msg->prev);
1364 if(!msg) return;
1366 // Detach it from the stack and free it
1367 if(last)
1368 last->prev = msg->prev;
1369 else
1370 osd_msg_stack = msg->prev;
1371 free(msg);
1375 * \brief Remove all messages from the OSD stack
1379 static void clear_osd_msgs(void) {
1380 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1381 while(msg) {
1382 prev = msg->prev;
1383 free(msg);
1384 msg = prev;
1386 osd_msg_stack = NULL;
1390 * \brief Get the current message from the OSD stack.
1392 * This function decrements the message timer and destroys the old ones.
1393 * The message that should be displayed is returned (if any).
1397 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1399 struct MPOpts *opts = &mpctx->opts;
1400 mp_osd_msg_t *msg,*prev,*last = NULL;
1401 static unsigned last_update = 0;
1402 unsigned now = GetTimerMS();
1403 unsigned diff;
1404 char hidden_dec_done = 0;
1406 if (mpctx->osd_visible) {
1407 // 36000000 means max timed visibility is 1 hour into the future, if
1408 // the difference is greater assume it's wrapped around from below 0
1409 if (mpctx->osd_visible - now > 36000000) {
1410 mpctx->osd_visible = 0;
1411 vo_osd_progbar_type = -1; // disable
1412 vo_osd_changed(OSDTYPE_PROGBAR);
1413 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1416 if (mpctx->osd_show_percentage_until - now > 36000000)
1417 mpctx->osd_show_percentage_until = 0;
1419 if(!last_update) last_update = now;
1420 diff = now >= last_update ? now - last_update : 0;
1422 last_update = now;
1424 // Look for the first message in the stack with high enough level.
1425 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1426 prev = msg->prev;
1427 if (msg->level > opts->osd_level && hidden_dec_done)
1428 continue;
1429 // The message has a high enough level or it is the first hidden one
1430 // in both cases we decrement the timer or kill it.
1431 if(!msg->started || msg->time > diff) {
1432 if(msg->started) msg->time -= diff;
1433 else msg->started = 1;
1434 // display it
1435 if (msg->level <= opts->osd_level)
1436 return msg;
1437 hidden_dec_done = 1;
1438 continue;
1440 // kill the message
1441 free(msg);
1442 if(last) {
1443 last->prev = prev;
1444 msg = last;
1445 } else {
1446 osd_msg_stack = prev;
1447 msg = NULL;
1450 // Nothing found
1451 return NULL;
1455 * \brief Display the OSD bar.
1457 * Display the OSD bar or fall back on a simple message.
1461 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1462 struct MPOpts *opts = &mpctx->opts;
1463 if (opts->osd_level < 1)
1464 return;
1466 if(mpctx->sh_video) {
1467 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1468 vo_osd_progbar_type = type;
1469 vo_osd_progbar_value = 256*(val-min)/(max-min);
1470 vo_osd_changed(OSDTYPE_PROGBAR);
1471 return;
1474 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1475 name, ROUND(100*(val-min)/(max-min)));
1480 * \brief Update the OSD message line.
1482 * This function displays the current message on the vo OSD or on the term.
1483 * If the stack is empty and the OSD level is high enough the timer
1484 * is displayed (only on the vo OSD).
1488 static void update_osd_msg(struct MPContext *mpctx)
1490 struct MPOpts *opts = &mpctx->opts;
1491 mp_osd_msg_t *msg;
1492 struct osd_state *osd = mpctx->osd;
1493 char osd_text_timer[128];
1495 if (mpctx->add_osd_seek_info) {
1496 double percentage;
1497 if (mpctx->timeline && mpctx->sh_video)
1498 percentage = mpctx->sh_video->pts * 100 /
1499 mpctx->timeline[mpctx->num_timeline_parts].start;
1500 else
1501 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1502 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1503 if (mpctx->sh_video)
1504 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1505 mpctx->add_osd_seek_info = false;
1508 // Look if we have a msg
1509 if((msg = get_osd_msg(mpctx))) {
1510 if (strcmp(osd->osd_text, msg->msg)) {
1511 strncpy(osd->osd_text, msg->msg, 127);
1512 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1513 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1515 return;
1518 if(mpctx->sh_video) {
1519 // fallback on the timer
1520 if (opts->osd_level >= 2) {
1521 int len;
1522 if (mpctx->timeline)
1523 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1524 else
1525 len = demuxer_get_time_length(mpctx->demuxer);
1526 int percentage = -1;
1527 char percentage_text[10];
1528 int pts = demuxer_get_current_time(mpctx->demuxer);
1530 if (mpctx->osd_show_percentage_until)
1531 if (mpctx->timeline)
1532 percentage = mpctx->sh_video->pts * 100 /
1533 mpctx->timeline[mpctx->num_timeline_parts].start;
1534 else
1535 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1537 if (percentage >= 0)
1538 snprintf(percentage_text, 9, " (%d%%)", percentage);
1539 else
1540 percentage_text[0] = 0;
1542 if (opts->osd_level == 3)
1543 snprintf(osd_text_timer, 63,
1544 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1545 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1546 len/3600,(len/60)%60,len%60,percentage_text);
1547 else
1548 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1549 mpctx->osd_function,pts/3600,(pts/60)%60,
1550 pts%60,percentage_text);
1551 } else
1552 osd_text_timer[0]=0;
1554 if (strcmp(osd->osd_text, osd_text_timer)) {
1555 strncpy(osd->osd_text, osd_text_timer, 63);
1556 vo_osd_changed(OSDTYPE_OSD);
1558 return;
1561 // Clear the term osd line
1562 if (term_osd && osd->osd_text[0]) {
1563 osd->osd_text[0] = 0;
1564 printf("%s\n",term_osd_esc);
1568 ///@}
1569 // OSDMsgStack
1572 void reinit_audio_chain(struct MPContext *mpctx)
1574 struct MPOpts *opts = &mpctx->opts;
1575 if(mpctx->sh_audio){
1576 current_module="init_audio_codec";
1577 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1578 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1579 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // failed to init :(
1580 mpctx->d_audio->id = -2;
1581 return;
1582 } else
1583 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1584 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1587 //const ao_info_t *info=audio_out->info;
1588 current_module="af_preinit";
1589 ao_data.samplerate=force_srate;
1590 ao_data.channels=0;
1591 ao_data.format=audio_output_format;
1592 #if 1
1593 // first init to detect best values
1594 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1595 // input:
1596 mpctx->sh_audio->samplerate,
1597 // output:
1598 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1599 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Error at audio filter chain pre-init!\n");
1600 exit_player(mpctx, EXIT_ERROR);
1602 #endif
1603 current_module="ao2_init";
1604 if(!(mpctx->audio_out=init_best_audio_out(opts->audio_driver_list,
1605 0, // plugin flag
1606 ao_data.samplerate,
1607 ao_data.channels,
1608 ao_data.format,0))){
1609 // FAILED:
1610 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1611 uninit_player(mpctx, INITIALIZED_ACODEC); // close codec
1612 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1613 mpctx->d_audio->id = -2;
1614 return;
1615 } else {
1616 // SUCCESS:
1617 mpctx->initialized_flags|=INITIALIZED_AO;
1618 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1619 mpctx->audio_out->info->short_name,
1620 ao_data.samplerate, ao_data.channels,
1621 af_fmt2str_short(ao_data.format),
1622 af_fmt2bits(ao_data.format)/8 );
1623 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1624 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1625 if(strlen(mpctx->audio_out->info->comment) > 0)
1626 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1627 // init audio filters:
1628 #if 1
1629 current_module="af_init";
1630 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1631 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1632 // mp_msg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter / ao format! -> NOSOUND\n");
1633 // uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec & ao
1634 // sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1636 #endif
1638 mpctx->mixer.audio_out = mpctx->audio_out;
1639 mpctx->mixer.volstep = volstep;
1644 ///@}
1645 // Command2Property
1648 // Return pts value corresponding to the end point of audio written to the
1649 // ao so far.
1650 static double written_audio_pts(struct MPContext *mpctx)
1652 sh_audio_t *sh_audio = mpctx->sh_audio;
1653 demux_stream_t *d_audio = mpctx->d_audio;
1654 double buffered_output;
1655 // first calculate the end pts of audio that has been output by decoder
1656 double a_pts = sh_audio->pts;
1657 if (a_pts != MP_NOPTS_VALUE)
1658 // Good, decoder supports new way of calculating audio pts.
1659 // sh_audio->pts is the timestamp of the latest input packet with
1660 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1661 // the amount of bytes the decoder has written after that timestamp.
1662 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1663 else {
1664 // Decoder doesn't support new way of calculating pts (or we're
1665 // being called before it has decoded anything with known timestamp).
1666 // Use the old method of audio pts calculation: take the timestamp
1667 // of last packet with known pts the decoder has read data from,
1668 // and add amount of bytes read after the beginning of that packet
1669 // divided by input bps. This will be inaccurate if the input/output
1670 // ratio is not constant for every audio packet or if it is constant
1671 // but not accurately known in sh_audio->i_bps.
1673 a_pts = d_audio->pts;
1674 // ds_tell_pts returns bytes read after last timestamp from
1675 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1676 // it has read but not decoded
1677 if (sh_audio->i_bps)
1678 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1679 (double)sh_audio->i_bps;
1681 // Now a_pts hopefully holds the pts for end of audio from decoder.
1682 // Substract data in buffers between decoder and audio out.
1684 // Decoded but not filtered
1685 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1687 // Data buffered in audio filters, measured in bytes of "missing" output
1688 buffered_output = af_calc_delay(sh_audio->afilter);
1690 // Data that was ready for ao but was buffered because ao didn't fully
1691 // accept everything to internal buffers yet
1692 buffered_output += sh_audio->a_out_buffer_len;
1694 // Filters divide audio length by playback_speed, so multiply by it
1695 // to get the length in original units without speedup or slowdown
1696 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1698 return a_pts + mpctx->video_offset;
1701 // Return pts value corresponding to currently playing audio.
1702 double playing_audio_pts(struct MPContext *mpctx)
1704 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1705 mpctx->audio_out->get_delay();
1708 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1709 struct MPOpts *opts = &mpctx->opts;
1710 // check for frame-drop:
1711 current_module = "check_framedrop";
1712 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1713 static int dropped_frames;
1714 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1715 float d = delay-mpctx->delay;
1716 ++total_frame_cnt;
1717 // we should avoid dropping too many frames in sequence unless we
1718 // are too late. and we allow 100ms A-V delay here:
1719 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1720 && !mpctx->update_video_immediately) {
1721 ++drop_frame_cnt;
1722 ++dropped_frames;
1723 return frame_dropping;
1724 } else
1725 dropped_frames = 0;
1727 return 0;
1731 #ifdef HAVE_RTC
1732 int rtc_fd = -1;
1733 #endif
1735 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1737 #ifdef HAVE_RTC
1738 if (rtc_fd >= 0){
1739 // -------- RTC -----------
1740 current_module="sleep_rtc";
1741 while (time_frame > 0.000) {
1742 unsigned long rtc_ts;
1743 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1744 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1745 time_frame -= get_relative_time(mpctx);
1747 } else
1748 #endif
1750 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1751 // unnecessarily high CPU usage
1752 float margin = softsleep ? 0.011 : 0;
1753 current_module = "sleep_timer";
1754 while (time_frame > margin) {
1755 usec_sleep(1000000 * (time_frame - margin));
1756 time_frame -= get_relative_time(mpctx);
1758 if (softsleep){
1759 current_module = "sleep_soft";
1760 if (time_frame < 0)
1761 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1762 while (time_frame > 0)
1763 time_frame -= get_relative_time(mpctx); // burn the CPU
1766 return time_frame;
1769 #ifdef CONFIG_DVDNAV
1770 #ifndef FF_B_TYPE
1771 #define FF_B_TYPE 3
1772 #endif
1773 /// store decoded video image
1774 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1775 mp_image_t *from_mpi) {
1776 mp_image_t *mpi;
1778 /// Do not store B-frames
1779 if (from_mpi->pict_type == FF_B_TYPE)
1780 return to_mpi;
1782 if (to_mpi &&
1783 to_mpi->w == from_mpi->w &&
1784 to_mpi->h == from_mpi->h &&
1785 to_mpi->imgfmt == from_mpi->imgfmt)
1786 mpi = to_mpi;
1787 else {
1788 if (to_mpi)
1789 free_mp_image(to_mpi);
1790 if (from_mpi->w == 0 || from_mpi->h == 0)
1791 return NULL;
1792 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1795 copy_mpi(mpi,from_mpi);
1796 return mpi;
1799 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1800 struct MPOpts *opts = &ctx->opts;
1801 if (ctx->sh_video) {
1802 /// clear video pts
1803 ctx->d_video->pts = 0.0f;
1804 ctx->sh_video->pts = 0.0f;
1805 ctx->sh_video->i_pts = 0.0f;
1806 ctx->sh_video->last_pts = 0.0f;
1807 ctx->sh_video->num_buffered_pts = 0;
1808 ctx->sh_video->num_frames = 0;
1809 ctx->sh_video->num_frames_decoded = 0;
1810 ctx->sh_video->timer = 0.0f;
1811 ctx->sh_video->stream_delay = 0.0f;
1812 ctx->sh_video->timer = 0;
1813 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1816 if (ctx->sh_audio) {
1817 /// free audio packets and reset
1818 ds_free_packs(ctx->d_audio);
1819 audio_delay -= ctx->sh_audio->stream_delay;
1820 ctx->delay =- audio_delay;
1821 ctx->audio_out->reset();
1822 resync_audio_stream(ctx->sh_audio);
1825 if (ctx->d_sub) opts->sub_id = -2;
1827 audio_delay = 0.0f;
1829 /// clear all EOF related flags
1830 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1833 /// Restore last decoded DVDNAV (still frame)
1834 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
1835 int *in_size,
1836 unsigned char **start,
1837 mp_image_t *decoded_frame)
1839 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1840 return decoded_frame;
1842 /// a change occured in dvdnav stream
1843 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
1844 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
1845 mp_dvdnav_context_free(mpctx);
1846 mp_dvdnav_reset_stream(mpctx);
1847 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
1848 mp_dvdnav_cell_has_changed(mpctx->stream,1);
1851 if (*in_size < 0) {
1852 float len;
1854 /// Display still frame, if any
1855 if (mpctx->nav_smpi && !mpctx->nav_buffer)
1856 decoded_frame = mpctx->nav_smpi;
1858 /// increment video frame : continue playing after still frame
1859 len = demuxer_get_time_length(mpctx->demuxer);
1860 if (mpctx->sh_video->pts >= len &&
1861 mpctx->sh_video->pts > 0.0 && len > 0.0) {
1862 mp_dvdnav_skip_still(mpctx->stream);
1863 mp_dvdnav_skip_wait(mpctx->stream);
1865 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
1867 if (mpctx->nav_buffer) {
1868 *start = mpctx->nav_start;
1869 *in_size = mpctx->nav_in_size;
1870 if (mpctx->nav_start)
1871 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
1875 return decoded_frame;
1878 /// Save last decoded DVDNAV (still frame)
1879 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
1880 unsigned char *start,
1881 mp_image_t *decoded_frame)
1883 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1884 return;
1886 if (mpctx->nav_buffer)
1887 free(mpctx->nav_buffer);
1889 mpctx->nav_buffer = malloc(in_size);
1890 mpctx->nav_start = start;
1891 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
1892 if (mpctx->nav_buffer)
1893 memcpy(mpctx->nav_buffer,start,in_size);
1895 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
1896 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
1898 #endif /* CONFIG_DVDNAV */
1900 /* Modify video timing to match the audio timeline. There are two main
1901 * reasons this is needed. First, video and audio can start from different
1902 * positions at beginning of file or after a seek (MPlayer starts both
1903 * immediately even if they have different pts). Second, the file can have
1904 * audio timestamps that are inconsistent with the duration of the audio
1905 * packets, for example two consecutive timestamp values differing by
1906 * one second but only a packet with enough samples for half a second
1907 * of playback between them.
1909 static void adjust_sync(struct MPContext *mpctx, double frame_time)
1911 struct MPOpts *opts = &mpctx->opts;
1912 current_module = "av_sync";
1914 if (!mpctx->sh_audio)
1915 return;
1917 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
1918 double v_pts = mpctx->sh_video->pts;
1919 double av_delay = a_pts - v_pts;
1920 // Try to sync vo_flip() so it will *finish* at given time
1921 av_delay += mpctx->last_vo_flip_duration;
1922 av_delay -= audio_delay; // This much pts difference is desired
1924 double change = av_delay * 0.1;
1925 double max_change = default_max_pts_correction >= 0 ?
1926 default_max_pts_correction : frame_time * 0.1;
1927 if (change < -max_change)
1928 change = -max_change;
1929 else if (change > max_change)
1930 change = max_change;
1931 mpctx->delay += change;
1932 mpctx->total_avsync_change += change;
1935 static int fill_audio_out_buffers(struct MPContext *mpctx)
1937 struct MPOpts *opts = &mpctx->opts;
1938 unsigned int t;
1939 double tt;
1940 int playsize;
1941 int playflags=0;
1942 int audio_eof=0;
1943 int bytes_to_write;
1944 sh_audio_t * const sh_audio = mpctx->sh_audio;
1946 current_module="play_audio";
1948 while (1) {
1949 int sleep_time;
1950 // all the current uses of ao_data.pts seem to be in aos that handle
1951 // sync completely wrong; there should be no need to use ao_data.pts
1952 // in get_space()
1953 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
1954 bytes_to_write = mpctx->audio_out->get_space();
1955 if (mpctx->sh_video || bytes_to_write >= ao_data.outburst)
1956 break;
1958 // handle audio-only case:
1959 // this is where mplayer sleeps during audio-only playback
1960 // to avoid 100% CPU use
1961 sleep_time = (ao_data.outburst - bytes_to_write) * 1000 / ao_data.bps;
1962 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
1963 usec_sleep(sleep_time * 1000);
1966 while (bytes_to_write) {
1967 playsize = bytes_to_write;
1968 if (playsize > MAX_OUTBURST)
1969 playsize = MAX_OUTBURST;
1970 bytes_to_write -= playsize;
1972 // Fill buffer if needed:
1973 current_module="decode_audio";
1974 t = GetTimer();
1975 if (decode_audio(sh_audio, playsize) < 0) // EOF or error
1976 if (mpctx->d_audio->eof) {
1977 audio_eof = 1;
1978 if (sh_audio->a_out_buffer_len == 0)
1979 return 0;
1981 t = GetTimer() - t;
1982 tt = t*0.000001f; audio_time_usage+=tt;
1983 if (playsize > sh_audio->a_out_buffer_len) {
1984 playsize = sh_audio->a_out_buffer_len;
1985 if (audio_eof)
1986 playflags |= AOPLAY_FINAL_CHUNK;
1988 if (!playsize)
1989 break;
1991 // play audio:
1992 current_module="play_audio";
1994 // Is this pts value actually useful for the aos that access it?
1995 // They're obviously badly broken in the way they handle av sync;
1996 // would not having access to this make them more broken?
1997 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
1998 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2000 if (playsize > 0) {
2001 sh_audio->a_out_buffer_len -= playsize;
2002 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2003 sh_audio->a_out_buffer_len);
2004 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2006 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2007 // Sanity check to avoid hanging in case current ao doesn't output
2008 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2009 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2010 sh_audio->a_out_buffer_len = 0;
2013 return 1;
2016 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2017 float *aq_sleep_time)
2019 struct MPOpts *opts = &mpctx->opts;
2020 int frame_time_remaining = 0;
2021 current_module="calc_sleep_time";
2023 *time_frame -= get_relative_time(mpctx); // reset timer
2025 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2026 float delay = mpctx->audio_out->get_delay();
2027 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2029 if (autosync) {
2031 * Adjust this raw delay value by calculating the expected
2032 * delay for this frame and generating a new value which is
2033 * weighted between the two. The higher autosync is, the
2034 * closer to the delay value gets to that which "-nosound"
2035 * would have used, and the longer it will take for A/V
2036 * sync to settle at the right value (but it eventually will.)
2037 * This settling time is very short for values below 100.
2039 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2040 float difference = delay - predicted;
2041 delay = predicted + difference / (float)autosync;
2044 *time_frame = delay - mpctx->delay / opts->playback_speed;
2046 // delay = amount of audio buffered in soundcard/driver
2047 if (delay > 0.25) delay=0.25; else
2048 if (delay < 0.10) delay=0.10;
2049 if (*time_frame > delay*0.6) {
2050 // sleep time too big - may cause audio drops (buffer underrun)
2051 frame_time_remaining = 1;
2052 *time_frame = delay*0.5;
2054 } else {
2055 // If we're lagging more than 200 ms behind the right playback rate,
2056 // don't try to "catch up".
2057 // If benchmark is set always output frames as fast as possible
2058 // without sleeping.
2059 if (*time_frame < -0.2 || benchmark)
2060 *time_frame = 0;
2063 *aq_sleep_time += *time_frame;
2066 //============================== SLEEP: ===================================
2068 // flag 256 means: libvo driver does its timing (dvb card)
2069 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2070 *time_frame = timing_sleep(mpctx, *time_frame);
2071 return frame_time_remaining;
2074 int reinit_video_chain(struct MPContext *mpctx)
2076 struct MPOpts *opts = &mpctx->opts;
2077 sh_video_t * const sh_video = mpctx->sh_video;
2078 double ar=-1.0;
2079 //================== Init VIDEO (codec & libvo) ==========================
2080 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2081 current_module="preinit_libvo";
2083 //shouldn't we set dvideo->id=-2 when we fail?
2084 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2085 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2086 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2087 goto err_out;
2089 mpctx->initialized_flags|=INITIALIZED_VO;
2092 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2093 mpctx->sh_video->stream_aspect = ar;
2094 current_module="init_video_filters";
2096 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2097 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2099 #ifdef CONFIG_MENU
2100 if(use_menu) {
2101 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2102 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2103 if(!vf_menu) {
2104 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2105 use_menu = 0;
2108 if(vf_menu)
2109 sh_video->vfilter = vf_menu;
2110 #endif
2112 #ifdef CONFIG_ASS
2113 if(ass_enabled) {
2114 int i;
2115 int insert = 1;
2116 if (opts->vf_settings)
2117 for (i = 0; opts->vf_settings[i].name; ++i)
2118 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2119 insert = 0;
2120 break;
2122 if (insert) {
2123 extern vf_info_t vf_info_ass;
2124 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2125 char* vf_arg[] = {"auto", "1", NULL};
2126 vf_instance_t* vf_ass = vf_open_plugin(opts, libass_vfs,sh_video->vfilter,"ass",vf_arg);
2127 if (vf_ass)
2128 sh_video->vfilter = vf_ass;
2129 else
2130 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2133 #endif
2135 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2137 #ifdef CONFIG_ASS
2138 if (ass_enabled)
2139 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2140 #endif
2142 current_module="init_video_codec";
2144 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2145 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2146 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2148 if(!sh_video->initialized){
2149 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2150 goto err_out;
2153 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2155 if (sh_video->codec)
2156 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2158 sh_video->last_pts = MP_NOPTS_VALUE;
2159 sh_video->num_buffered_pts = 0;
2160 sh_video->next_frame_time = 0;
2162 if(auto_quality>0){
2163 // Auto quality option enabled
2164 output_quality=get_video_quality_max(sh_video);
2165 if(auto_quality>output_quality) auto_quality=output_quality;
2166 else output_quality=auto_quality;
2167 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2168 set_video_quality(sh_video,output_quality);
2171 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2173 current_module="init_vo";
2175 return 1;
2177 err_out:
2178 mpctx->sh_video = mpctx->d_video->sh = NULL;
2179 return 0;
2182 static double update_video_nocorrect_pts(struct MPContext *mpctx,
2183 int *blit_frame)
2185 struct sh_video *sh_video = mpctx->sh_video;
2186 *blit_frame = 0;
2187 double frame_time = 0;
2188 while (1) {
2189 current_module = "filter_video";
2190 // In nocorrect-pts mode there is no way to properly time these frames
2191 if (vf_output_queued_frame(sh_video->vfilter))
2192 break;
2193 unsigned char *packet = NULL;
2194 frame_time = sh_video->next_frame_time;
2195 if (mpctx->update_video_immediately)
2196 frame_time = 0;
2197 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2198 &packet, force_fps);
2199 if (in_size < 0) {
2200 #ifdef CONFIG_DVDNAV
2201 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2202 if (mp_dvdnav_is_eof(mpctx->stream))
2203 return -1;
2204 if (mpctx->d_video)
2205 mpctx->d_video->eof = 0;
2206 if (mpctx->d_audio)
2207 mpctx->d_audio->eof = 0;
2208 mpctx->stream->eof = 0;
2209 } else
2210 #endif
2211 return -1;
2213 if (in_size > max_framesize)
2214 max_framesize = in_size;
2215 sh_video->timer += frame_time;
2216 if (mpctx->sh_audio)
2217 mpctx->delay -= frame_time;
2218 // video_read_frame can change fps (e.g. for ASF video)
2219 vo_fps = sh_video->fps;
2220 int framedrop_type = check_framedrop(mpctx, frame_time);
2221 current_module = "decode video";
2223 void *decoded_frame;
2224 #ifdef CONFIG_DVDNAV
2225 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2226 if (in_size >= 0 && !decoded_frame)
2227 #endif
2228 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2229 sh_video->pts);
2230 #ifdef CONFIG_DVDNAV
2231 // Save last still frame for future display
2232 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2233 #endif
2234 if (decoded_frame) {
2235 // These updates are done here for vf_expand OSD/subtitles
2236 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2237 update_teletext(sh_video, mpctx->demuxer, 0);
2238 update_osd_msg(mpctx);
2239 current_module = "filter video";
2240 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2241 break;
2244 *blit_frame = 1;
2245 return frame_time;
2248 static double update_video(struct MPContext *mpctx, int *blit_frame)
2250 struct sh_video *sh_video = mpctx->sh_video;
2251 *blit_frame = 0;
2252 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2253 mpctx->osd); // hack for vf_expand
2254 if (!mpctx->opts.correct_pts)
2255 return update_video_nocorrect_pts(mpctx, blit_frame);
2257 double pts;
2259 while (1) {
2260 current_module = "filter_video";
2261 // XXX Time used in this call is not counted in any performance
2262 // timer now, OSD time is not updated correctly for filter-added frames
2263 if (vf_output_queued_frame(sh_video->vfilter))
2264 break;
2265 unsigned char *packet = NULL;
2266 bool hit_eof = false;
2267 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2268 if (pts != MP_NOPTS_VALUE)
2269 pts += mpctx->video_offset;
2270 if (in_size < 0) {
2271 // try to extract last frames in case of decoder lag
2272 in_size = 0;
2273 pts = 1e300;
2274 hit_eof = true;
2276 if (in_size > max_framesize)
2277 max_framesize = in_size;
2278 current_module = "decode video";
2279 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2280 void *decoded_frame = decode_video(sh_video, packet, in_size,
2281 framedrop_type, pts);
2282 if (decoded_frame) {
2283 // These updates are done here for vf_expand OSD/subtitles
2284 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2285 update_teletext(sh_video, mpctx->demuxer, 0);
2286 update_osd_msg(mpctx);
2287 current_module = "filter video";
2288 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2289 break;
2290 } else if (hit_eof)
2291 return -1;
2294 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_GET_PTS, &pts);
2295 if (pts == MP_NOPTS_VALUE) {
2296 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2297 // Try to use decoder pts from before filters
2298 pts = sh_video->pts;
2299 if (pts == MP_NOPTS_VALUE)
2300 pts = sh_video->last_pts;
2302 sh_video->pts = pts;
2303 if (sh_video->last_pts == MP_NOPTS_VALUE)
2304 sh_video->last_pts = sh_video->pts;
2305 else if (sh_video->last_pts > sh_video->pts) {
2306 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2307 sh_video->pts, sh_video->last_pts);
2308 /* If the difference in pts is small treat it as jitter around the
2309 * right value (possibly caused by incorrect timestamp ordering) and
2310 * just show this frame immediately after the last one.
2311 * Treat bigger differences as timestamp resets and start counting
2312 * timing of later frames from the position of this one. */
2313 if (sh_video->last_pts - sh_video->pts > 0.5)
2314 sh_video->last_pts = sh_video->pts;
2315 else
2316 sh_video->pts = sh_video->last_pts;
2318 double frame_time = sh_video->pts - sh_video->last_pts;
2319 sh_video->last_pts = sh_video->pts;
2320 sh_video->timer += frame_time;
2321 if (mpctx->sh_audio)
2322 mpctx->delay -= frame_time;
2323 *blit_frame = 1;
2324 return frame_time;
2327 void pause_player(struct MPContext *mpctx)
2329 if (mpctx->paused)
2330 return;
2331 mpctx->paused = 1;
2332 mpctx->step_frames = 0;
2333 mpctx->time_frame -= get_relative_time(mpctx);
2335 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2336 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2338 if (mpctx->audio_out && mpctx->sh_audio)
2339 mpctx->audio_out->pause(); // pause audio, keep data if possible
2342 void unpause_player(struct MPContext *mpctx)
2344 if (!mpctx->paused)
2345 return;
2346 mpctx->paused = 0;
2348 if (mpctx->audio_out && mpctx->sh_audio)
2349 mpctx->audio_out->resume(); // resume audio
2350 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2351 && !mpctx->step_frames)
2352 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2353 (void)get_relative_time(mpctx); // ignore time that passed during pause
2356 void add_step_frame(struct MPContext *mpctx)
2358 mpctx->step_frames++;
2359 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2360 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2361 unpause_player(mpctx);
2364 static void pause_loop(struct MPContext *mpctx)
2366 mp_cmd_t* cmd;
2367 if (!quiet) {
2368 // Small hack to display the pause message on the OSD line.
2369 // The pause string is: "\n == PAUSE == \r" so we need to
2370 // take the first and the last char out
2371 if (term_osd && !mpctx->sh_video) {
2372 char msg[128] = _("\n ===== PAUSE =====\r");
2373 int mlen = strlen(msg);
2374 msg[mlen-1] = '\0';
2375 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2376 update_osd_msg(mpctx);
2377 } else
2378 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2379 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2382 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1, 1)) == NULL
2383 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2384 if (cmd) {
2385 cmd = mp_input_get_cmd(mpctx->input, 0,1,0);
2386 run_command(mpctx, cmd);
2387 mp_cmd_free(cmd);
2388 continue;
2390 if (mpctx->sh_video && mpctx->video_out)
2391 vo_check_events(mpctx->video_out);
2392 #ifdef CONFIG_MENU
2393 if (vf_menu)
2394 vf_menu_pause_update(vf_menu);
2395 #endif
2396 usec_sleep(20000);
2397 update_osd_msg(mpctx);
2398 int hack = vo_osd_changed(0);
2399 vo_osd_changed(hack);
2400 if (hack)
2401 break;
2406 // Find the right mute status and record position for new file position
2407 static void edl_seek_reset(MPContext *mpctx)
2409 mpctx->edl_muted = 0;
2410 next_edl_record = edl_records;
2412 while (next_edl_record) {
2413 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2414 break;
2416 if (next_edl_record->action == EDL_MUTE)
2417 mpctx->edl_muted = !mpctx->edl_muted;
2418 next_edl_record = next_edl_record->next;
2420 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2421 mixer_mute(&mpctx->mixer);
2425 // Execute EDL command for the current position if one exists
2426 static void edl_update(MPContext *mpctx)
2428 if (!next_edl_record)
2429 return;
2431 if (!mpctx->sh_video) {
2432 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2433 free_edl(edl_records);
2434 next_edl_record = NULL;
2435 edl_records = NULL;
2436 return;
2439 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2440 if (next_edl_record->action == EDL_SKIP) {
2441 mpctx->osd_function = OSD_FFW;
2442 mpctx->abs_seek_pos = 0;
2443 mpctx->rel_seek_secs = next_edl_record->length_sec;
2444 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2445 "[%f], length [%f]\n", next_edl_record->start_sec,
2446 next_edl_record->stop_sec, next_edl_record->length_sec);
2448 else if (next_edl_record->action == EDL_MUTE) {
2449 mpctx->edl_muted = !mpctx->edl_muted;
2450 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2451 mixer_mute(&mpctx->mixer);
2452 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2453 next_edl_record->start_sec );
2455 next_edl_record = next_edl_record->next;
2459 static void reinit_decoders(struct MPContext *mpctx)
2461 reinit_video_chain(mpctx);
2462 reinit_audio_chain(mpctx);
2463 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2466 static bool timeline_set_part(struct MPContext *mpctx, int i)
2468 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2469 struct timeline_part *n = mpctx->timeline + i;
2470 mpctx->timeline_part = i;
2471 mpctx->video_offset = n->start - n->source_start;
2472 if (n->source == p->source)
2473 return false;
2474 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2475 mpctx->demuxer = n->source->demuxer;
2476 mpctx->d_video = mpctx->demuxer->video;
2477 mpctx->d_audio = mpctx->demuxer->audio;
2478 mpctx->d_sub = mpctx->demuxer->sub;
2479 mpctx->sh_video = mpctx->d_video->sh;
2480 mpctx->sh_audio = mpctx->d_audio->sh;
2481 return true;
2484 // Given pts, switch playback to the corresponding part.
2485 // Return offset within that part.
2486 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2487 bool *need_reset)
2489 if (pts < 0)
2490 pts = 0;
2491 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2492 struct timeline_part *p = mpctx->timeline + i;
2493 if (pts < (p+1)->start) {
2494 *need_reset = timeline_set_part(mpctx, i);
2495 return pts - p->start + p->source_start;
2498 return -1;
2502 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2503 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2504 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2505 static int seek(MPContext *mpctx, double amount, int style)
2507 current_module = "seek";
2508 if (mpctx->stop_play == AT_END_OF_FILE)
2509 mpctx->stop_play = KEEP_PLAYING;
2510 if (mpctx->timeline && style & SEEK_FACTOR) {
2511 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2512 style &= ~SEEK_FACTOR;
2514 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2515 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2516 style |= SEEK_ABSOLUTE;
2517 if (amount > 0)
2518 style |= SEEK_FORWARD;
2519 else
2520 style |= SEEK_BACKWARD;
2521 amount += mpctx->sh_video->pts;
2524 /* At least the liba52 decoder wants to read from the input stream
2525 * during initialization, so reinit must be done after the demux_seek()
2526 * call that clears possible stream EOF. */
2527 bool need_reset = false;
2528 if (mpctx->timeline) {
2529 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2530 if (amount == -1) {
2531 mpctx->stop_play = AT_END_OF_FILE;
2532 // Clear audio from current position
2533 if (mpctx->sh_audio) {
2534 mpctx->audio_out->reset();
2535 mpctx->sh_audio->a_buffer_len = 0;
2536 mpctx->sh_audio->a_out_buffer_len = 0;
2538 return -1;
2541 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2542 if (need_reset)
2543 reinit_decoders(mpctx);
2544 if (seekresult == 0)
2545 return -1;
2547 if (mpctx->sh_video) {
2548 current_module = "seek_video_reset";
2549 resync_video_stream(mpctx->sh_video);
2550 if (mpctx->video_out->config_ok)
2551 vo_control(mpctx->video_out, VOCTRL_RESET, NULL);
2552 mpctx->sh_video->num_buffered_pts = 0;
2553 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2554 mpctx->num_buffered_frames = 0;
2555 mpctx->delay = 0;
2556 mpctx->time_frame = 0;
2557 mpctx->update_video_immediately = true;
2558 // Not all demuxers set d_video->pts during seek, so this value
2559 // (which is used by at least vobsub and edl code below) may
2560 // be completely wrong (probably 0).
2561 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2562 update_subtitles(mpctx->sh_video, mpctx->d_sub, mpctx->video_offset, 1);
2563 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2566 if (mpctx->sh_audio) {
2567 current_module = "seek_audio_reset";
2568 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2569 mpctx->sh_audio->a_buffer_len = 0;
2570 mpctx->sh_audio->a_out_buffer_len = 0;
2573 if (vo_vobsub && mpctx->sh_video) {
2574 current_module = "seek_vobsub_reset";
2575 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2578 edl_seek_reset(mpctx);
2580 mpctx->total_avsync_change = 0;
2581 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2582 drop_frame_cnt = 0;
2584 current_module = NULL;
2585 return 0;
2588 int get_current_chapter(struct MPContext *mpctx)
2590 if (!mpctx->chapters || !mpctx->sh_video)
2591 return demuxer_get_current_chapter(mpctx->demuxer);
2593 int i;
2594 double current_pts = mpctx->sh_video->pts;
2595 for (i = 1; i < mpctx->num_chapters; i++)
2596 if (current_pts < mpctx->chapters[i].start)
2597 break;
2598 return i - 1;
2601 // currently returns a string allocated with malloc, not talloc
2602 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2604 if (!mpctx->chapters || !mpctx->sh_video)
2605 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2606 return strdup(mpctx->chapters[chapter].name);
2609 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2610 char **chapter_name)
2612 if (!mpctx->chapters || !mpctx->sh_video)
2613 return demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2614 chapter_name);
2615 if (chapter >= mpctx->num_chapters)
2616 return -1;
2617 if (chapter < 0)
2618 chapter = 0;
2619 *seek_pts = mpctx->chapters[chapter].start;
2620 if (chapter_name)
2621 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2622 return chapter;
2625 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2626 struct content_source *sources,
2627 int num_sources,
2628 unsigned char uid_map[][16])
2630 int num_filenames = 0;
2631 char **filenames = NULL;
2632 if (num_sources > 1) {
2633 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2634 "other sources.\n");
2635 if (mpctx->stream->type != STREAMTYPE_FILE) {
2636 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2637 "normal disk file. Will not search for related files.\n");
2638 } else {
2639 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2640 "same directory to find referenced sources.\n");
2641 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2642 &num_filenames);
2646 int num_left = num_sources - 1;
2647 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2648 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2649 filename_recode(filenames[i]));
2650 int format;
2651 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2652 if (!s)
2653 continue;
2654 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2655 mpctx->opts.audio_id,
2656 mpctx->opts.video_id,
2657 mpctx->opts.sub_id, filenames[i]);
2658 if (!d) {
2659 free_stream(s);
2660 continue;
2662 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2663 for (int i = 1; i < num_sources; i++) {
2664 if (sources[i].demuxer)
2665 continue;
2666 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2667 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2668 i, filename_recode(d->filename));
2669 sources[i].stream = s;
2670 sources[i].demuxer = d;
2671 num_left--;
2672 goto match;
2676 free_demuxer(d);
2677 free_stream(s);
2678 continue;
2679 match:
2682 talloc_free(filenames);
2683 if (num_left) {
2684 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2685 "There will be parts MISSING from the video!\n");
2686 for (int i = 1, j = 1; i < num_sources; i++)
2687 if (sources[i].demuxer) {
2688 sources[j] = sources[i];
2689 memcpy(uid_map[j], uid_map[i], 16);
2690 j++;
2693 return num_sources - num_left;
2696 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2698 if (!mpctx->opts.ordered_chapters) {
2699 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
2700 "you have disabled support for them. Ignoring.\n");
2701 return;
2704 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
2705 "edit timeline.\n");
2707 struct demuxer *demuxer = mpctx->demuxer;
2708 struct matroska_data *m = &demuxer->matroska_data;
2710 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
2711 m->num_ordered_chapters);
2712 sources[0].stream = mpctx->stream;
2713 sources[0].demuxer = mpctx->demuxer;
2714 unsigned char uid_map[m->num_ordered_chapters][16];
2715 int num_sources = 1;
2716 memcpy(uid_map[0], m->segment_uid, 16);
2718 for (int i = 0; i < m->num_ordered_chapters; i++) {
2719 struct matroska_chapter *c = m->ordered_chapters + i;
2720 if (!c->has_segment_uid)
2721 memcpy(c->segment_uid, m->segment_uid, 16);
2723 for (int j = 0; j < num_sources; j++)
2724 if (!memcmp(c->segment_uid, uid_map[j], 16))
2725 goto found1;
2726 memcpy(uid_map[num_sources], c->segment_uid, 16);
2727 sources[num_sources] = (struct content_source){};
2728 num_sources++;
2729 found1:
2733 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
2734 uid_map);
2737 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
2738 m->num_ordered_chapters + 1);
2739 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
2740 m->num_ordered_chapters);
2741 uint64_t starttime = 0;
2742 uint64_t missing_time = 0;
2743 int part_count = 0;
2744 int num_chapters = 0;
2745 uint64_t prev_part_offset;
2746 for (int i = 0; i < m->num_ordered_chapters; i++) {
2747 struct matroska_chapter *c = m->ordered_chapters + i;
2749 int j;
2750 for (j = 0; j < num_sources; j++) {
2751 if (!memcmp(c->segment_uid, uid_map[j], 16))
2752 goto found2;
2754 missing_time += c->end - c->start;
2755 continue;
2756 found2:;
2757 chapters[num_chapters].start = starttime / 1000.;
2758 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
2759 /* Only add a separate part if the time or file actually changes.
2760 * Matroska files have chapter divisions that are redundant from
2761 * timeline point of view because the same chapter structure is used
2762 * both to specify the timeline and for normal chapter information.
2763 * Removing a missing inserted external chapter can also cause this. */
2764 if (part_count == 0 || c->start != starttime + prev_part_offset
2765 || sources + j != timeline[part_count - 1].source) {
2766 timeline[part_count].source = sources + j;
2767 timeline[part_count].start = chapters[num_chapters].start;
2768 timeline[part_count].source_start = c->start / 1000.;
2769 prev_part_offset = c->start - starttime;
2770 part_count++;
2772 starttime += c->end - c->start;
2773 num_chapters++;
2775 timeline[part_count].start = starttime / 1000.;
2777 if (!part_count) {
2778 // None of the parts come from the file itself???
2779 talloc_free(sources);
2780 talloc_free(timeline);
2781 talloc_free(chapters);
2782 return;
2785 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
2786 "sources. Total length %.3f seconds.\n", part_count, num_sources,
2787 timeline[part_count].start);
2788 if (missing_time)
2789 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
2790 "from the timeline!\n", missing_time / 1000.);
2791 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
2792 for (int i = 0; i < num_sources; i++)
2793 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
2794 filename_recode(sources[i].demuxer->filename));
2795 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
2796 "source_start, source):\n");
2797 for (int i = 0; i < part_count; i++) {
2798 struct timeline_part *p = timeline + i;
2799 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
2800 p->source_start, p->source - sources);
2802 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
2803 mpctx->sources = sources;
2804 mpctx->num_sources = num_sources;
2805 mpctx->timeline = timeline;
2806 mpctx->num_timeline_parts = part_count;
2807 mpctx->num_chapters = num_chapters;
2808 mpctx->chapters = chapters;
2810 mpctx->timeline_part = 0;
2811 mpctx->video_offset = timeline[0].source_start;
2812 mpctx->demuxer = timeline[0].source->demuxer;
2816 static int read_keys(void *ctx, int fd)
2818 getch2(ctx);
2819 return mplayer_get_key(ctx, 0);
2823 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
2824 * file for some tools to link against. */
2825 #ifndef DISABLE_MAIN
2826 int main(int argc,char* argv[]){
2829 char * mem_ptr;
2831 // movie info:
2833 /* Flag indicating whether MPlayer should exit without playing anything. */
2834 int opt_exit = 0;
2836 //float a_frame=0; // Audio
2838 int i;
2840 struct MPContext *mpctx = &(struct MPContext){
2841 .osd_function = OSD_PLAY,
2842 .begin_skip = MP_NOPTS_VALUE,
2843 .play_tree_step = 1,
2844 .global_sub_pos = -1,
2845 .set_of_sub_pos = -1,
2846 .file_format = DEMUXER_TYPE_UNKNOWN,
2847 .last_dvb_step = 1,
2850 InitTimer();
2851 srand(GetTimerMS());
2853 mp_msg_init();
2855 #ifdef CONFIG_X11
2856 mpctx->x11_state = vo_x11_init_state();
2857 #endif
2858 struct MPOpts *opts = &mpctx->opts;
2859 set_default_mplayer_options(opts);
2860 // Create the config context and register the options
2861 mpctx->mconfig = m_config_new(opts, cfg_include);
2862 m_config_register_options(mpctx->mconfig,mplayer_opts);
2863 mp_input_register_options(mpctx->mconfig);
2865 // Preparse the command line
2866 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
2868 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
2869 set_path_env();
2870 #endif
2872 #ifdef CONFIG_TV
2873 stream_tv_defaults.immediate = 1;
2874 #endif
2876 parse_cfgfiles(mpctx, mpctx->mconfig);
2878 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
2879 if(mpctx->playtree == NULL)
2880 opt_exit = 1;
2881 else {
2882 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
2883 if(mpctx->playtree) {
2884 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
2885 if(mpctx->playtree_iter) {
2886 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
2887 play_tree_iter_free(mpctx->playtree_iter);
2888 mpctx->playtree_iter = NULL;
2890 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
2894 mpctx->key_fifo = mp_fifo_create(opts);
2896 print_version("MPlayer");
2898 #if defined(__MINGW32__) || defined(__CYGWIN__)
2899 // stop Windows from showing all kinds of annoying error dialogs
2900 SetErrorMode(0x8003);
2901 // request 1ms timer resolution
2902 timeBeginPeriod(1);
2903 #endif
2905 #ifdef CONFIG_PRIORITY
2906 set_priority();
2907 #endif
2909 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
2910 list_video_out();
2911 opt_exit = 1;
2914 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
2915 list_audio_out();
2916 opt_exit = 1;
2919 /* Check codecs.conf. */
2920 if(!codecs_file || !parse_codec_cfg(codecs_file)){
2921 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
2922 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
2923 if(!parse_codec_cfg(NULL)){
2924 exit_player_with_rc(mpctx, EXIT_NONE, 0);
2926 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
2929 free( mem_ptr ); // release the buffer created by get_path()
2932 #if 0
2933 if(video_codec_list){
2934 int i;
2935 video_codec=video_codec_list[0];
2936 for(i=0;video_codec_list[i];i++)
2937 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
2939 #endif
2940 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
2941 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
2942 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
2943 list_codecs(1);
2944 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2945 opt_exit = 1;
2947 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
2948 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
2949 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
2950 list_codecs(0);
2951 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2952 opt_exit = 1;
2954 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
2955 vfm_help();
2956 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2957 opt_exit = 1;
2959 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
2960 afm_help();
2961 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2962 opt_exit = 1;
2964 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
2965 af_help();
2966 printf("\n");
2967 opt_exit = 1;
2969 #ifdef CONFIG_X11
2970 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
2971 fstype_help();
2972 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2973 opt_exit = 1;
2975 #endif
2976 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
2977 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
2978 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
2979 demuxer_help();
2980 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
2981 opt_exit = 1;
2983 if(list_properties) {
2984 property_print_help();
2985 opt_exit = 1;
2988 if(opt_exit)
2989 exit_player(mpctx, EXIT_NONE);
2991 if(!mpctx->filename && !player_idle_mode){
2992 // no file/vcd/dvd -> show HELP:
2993 mp_msg(MSGT_CPLAYER, MSGL_INFO, help_text);
2994 exit_player_with_rc(mpctx, EXIT_NONE, 0);
2997 /* Display what configure line was used */
2998 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3000 // Many users forget to include command line in bugreports...
3001 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3002 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3003 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3004 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3007 //------ load global data first ------
3009 mpctx->osd = osd_create();
3011 // check font
3012 #ifdef CONFIG_FREETYPE
3013 init_freetype();
3014 #endif
3015 #ifdef CONFIG_FONTCONFIG
3016 if(font_fontconfig <= 0)
3018 #endif
3019 #ifdef CONFIG_BITMAP_FONT
3020 if(font_name){
3021 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3022 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3023 filename_recode(font_name));
3024 } else {
3025 // try default:
3026 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3027 free(mem_ptr); // release the buffer created by get_path()
3028 if(!vo_font)
3029 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3031 if (sub_font_name)
3032 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3033 else
3034 mpctx->osd->sub_font = vo_font;
3035 #endif
3036 #ifdef CONFIG_FONTCONFIG
3038 #endif
3040 #ifdef CONFIG_ASS
3041 ass_library = ass_init();
3042 #endif
3044 #ifdef HAVE_RTC
3045 if(!nortc)
3047 // seteuid(0); /* Can't hurt to try to get root here */
3048 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3049 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3050 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3051 else {
3052 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3054 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3055 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3056 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3057 close (rtc_fd);
3058 rtc_fd = -1;
3059 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3060 /* variable only by the root */
3061 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3062 close (rtc_fd);
3063 rtc_fd = -1;
3064 } else
3065 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3068 if(rtc_fd<0)
3069 #endif /* HAVE_RTC */
3070 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3071 softsleep?"software":timer_name);
3073 #ifdef HAVE_TERMCAP
3074 load_termcap(NULL); // load key-codes
3075 #endif
3077 // ========== Init keyboard FIFO (connection to libvo) ============
3079 // Init input system
3080 current_module = "init_input";
3081 mpctx->input = mp_input_init(&opts->input);
3082 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3083 if(slave_mode)
3084 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3085 else if(!noconsolecontrols)
3086 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3087 // Set the libstream interrupt callback
3088 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3090 #ifdef CONFIG_MENU
3091 if(use_menu) {
3092 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3093 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3094 else {
3095 menu_cfg = get_path("menu.conf");
3096 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3097 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3098 else {
3099 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3100 MPLAYER_CONFDIR "/menu.conf"))
3101 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3102 else {
3103 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3104 use_menu = 0;
3109 #endif
3111 current_module = NULL;
3113 /// Catch signals
3114 #ifndef __MINGW32__
3115 signal(SIGCHLD,child_sighandler);
3116 #endif
3118 #ifdef CONFIG_CRASH_DEBUG
3119 prog_path = argv[0];
3120 #endif
3121 //========= Catch terminate signals: ================
3122 // terminate requests:
3123 signal(SIGTERM,exit_sighandler); // kill
3124 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3126 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3128 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3129 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3130 #ifdef CONFIG_SIGHANDLER
3131 // fatal errors:
3132 signal(SIGBUS,exit_sighandler); // bus error
3133 signal(SIGSEGV,exit_sighandler); // segfault
3134 signal(SIGILL,exit_sighandler); // illegal instruction
3135 signal(SIGFPE,exit_sighandler); // floating point exc.
3136 signal(SIGABRT,exit_sighandler); // abort()
3137 #ifdef CONFIG_CRASH_DEBUG
3138 if (crash_debug)
3139 signal(SIGTRAP,exit_sighandler);
3140 #endif
3141 #endif
3143 // ******************* Now, let's see the per-file stuff ********************
3145 play_next_file:
3147 // init global sub numbers
3148 mpctx->global_sub_size = 0;
3149 { int i; for (i = 0; i < SUB_SOURCES; i++) mpctx->global_sub_indices[i] = -1; }
3151 if (mpctx->filename) {
3152 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3153 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3154 load_per_file_config (mpctx->mconfig, mpctx->filename);
3157 if (opts->video_driver_list)
3158 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3159 if (opts->audio_driver_list)
3160 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3162 // We must enable getch2 here to be able to interrupt network connection
3163 // or cache filling
3164 if(!noconsolecontrols && !slave_mode){
3165 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3166 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3167 else
3168 getch2_enable(); // prepare stdin for hotkeys...
3169 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3170 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3173 // =================== GUI idle loop (STOP state) ===========================
3174 while (player_idle_mode && !mpctx->filename) {
3175 play_tree_t * entry = NULL;
3176 mp_cmd_t * cmd;
3177 while (!(cmd = mp_input_get_cmd(mpctx->input, 0,1,0))) { // wait for command
3178 if (mpctx->video_out)
3179 vo_check_events(mpctx->video_out);
3180 usec_sleep(20000);
3182 switch (cmd->id) {
3183 case MP_CMD_LOADFILE:
3184 // prepare a tree entry with the new filename
3185 entry = play_tree_new();
3186 play_tree_add_file(entry, cmd->args[0].v.s);
3187 // The entry is added to the main playtree after the switch().
3188 break;
3189 case MP_CMD_LOADLIST:
3190 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3191 break;
3192 case MP_CMD_QUIT:
3193 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3194 break;
3195 case MP_CMD_GET_PROPERTY:
3196 case MP_CMD_SET_PROPERTY:
3197 case MP_CMD_STEP_PROPERTY:
3198 run_command(mpctx, cmd);
3199 break;
3202 mp_cmd_free(cmd);
3204 if (entry) { // user entered a command that gave a valid entry
3205 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3206 play_tree_free_list(mpctx->playtree->child, 1);
3207 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3209 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3211 play_tree_set_child(mpctx->playtree, entry);
3213 /* Make iterator start at the top the of tree. */
3214 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3215 if (!mpctx->playtree_iter) continue;
3217 // find the first real item in the tree
3218 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3219 // no items!
3220 play_tree_iter_free(mpctx->playtree_iter);
3221 mpctx->playtree_iter = NULL;
3222 continue; // wait for next command
3224 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3227 //---------------------------------------------------------------------------
3229 if(mpctx->filename)
3230 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3231 filename_recode(mpctx->filename));
3233 if (edl_filename) {
3234 if (edl_records) free_edl(edl_records);
3235 next_edl_record = edl_records = edl_parse_file();
3237 if (edl_output_filename) {
3238 if (edl_fd) fclose(edl_fd);
3239 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3241 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3242 filename_recode(edl_output_filename));
3246 //==================== Open VOB-Sub ============================
3248 current_module="vobsub";
3249 if (vobsub_name){
3250 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3251 if(vo_vobsub==NULL)
3252 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3253 filename_recode(vobsub_name));
3254 } else if (sub_auto && mpctx->filename){
3255 /* try to autodetect vobsub from movie filename ::atmos */
3256 char *buf = strdup(mpctx->filename), *psub;
3257 char *pdot = strrchr(buf, '.');
3258 char *pslash = strrchr(buf, '/');
3259 #if defined(__MINGW32__) || defined(__CYGWIN__)
3260 if (!pslash) pslash = strrchr(buf, '\\');
3261 #endif
3262 if (pdot && (!pslash || pdot > pslash))
3263 *pdot = '\0';
3264 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3265 /* try from ~/.mplayer/sub */
3266 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3267 char *bname;
3268 int l;
3269 bname = strrchr(buf,'/');
3270 #if defined(__MINGW32__) || defined(__CYGWIN__)
3271 if(!bname) bname = strrchr(buf,'\\');
3272 #endif
3273 if(bname) bname++;
3274 else bname = buf;
3275 l = strlen(psub) + strlen(bname) + 1;
3276 psub = realloc(psub,l);
3277 strcat(psub,bname);
3278 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3279 free(psub);
3281 free(buf);
3283 if(vo_vobsub){
3284 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3285 vobsub_set_from_lang(vo_vobsub, dvdsub_lang);
3286 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3288 // setup global sub numbering
3289 mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] = mpctx->global_sub_size; // the global # of the first vobsub.
3290 mpctx->global_sub_size += vobsub_get_indexes_count(vo_vobsub);
3293 //============ Open & Sync STREAM --- fork cache2 ====================
3295 mpctx->stream=NULL;
3296 mpctx->demuxer=NULL;
3297 if (mpctx->d_audio) {
3298 //free_demuxer_stream(mpctx->d_audio);
3299 mpctx->d_audio=NULL;
3301 if (mpctx->d_video) {
3302 //free_demuxer_stream(d_video);
3303 mpctx->d_video=NULL;
3305 mpctx->sh_audio=NULL;
3306 mpctx->sh_video=NULL;
3308 current_module="open_stream";
3309 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3310 if(!mpctx->stream) { // error...
3311 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3312 goto goto_next_file;
3314 mpctx->initialized_flags|=INITIALIZED_STREAM;
3316 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3317 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3318 "playlist support will not be used automatically.\n"
3319 "MPlayer's playlist code is unsafe and should only be used with "
3320 "trusted sources.\nPlayback will probably fail.\n\n");
3321 #if 0
3322 play_tree_t* entry;
3323 // Handle playlist
3324 current_module="handle_playlist";
3325 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3326 filename_recode(mpctx->filename));
3327 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3328 mpctx->eof=playtree_add_playlist(mpctx, entry);
3329 goto goto_next_file;
3330 #endif
3332 mpctx->stream->start_pos+=seek_to_byte;
3334 if(stream_dump_type==5){
3335 unsigned char buf[4096];
3336 int len;
3337 FILE *f;
3338 current_module="dumpstream";
3339 if(mpctx->stream->type==STREAMTYPE_STREAM && mpctx->stream->fd<0){
3340 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot dump this stream - no file descriptor available.\n");
3341 exit_player(mpctx, EXIT_ERROR);
3343 stream_reset(mpctx->stream);
3344 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3345 f=fopen(stream_dump_name,"wb");
3346 if(!f){
3347 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3348 exit_player(mpctx, EXIT_ERROR);
3350 if (dvd_chapter > 1) {
3351 int chapter = dvd_chapter - 1;
3352 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3354 while(!mpctx->stream->eof && !async_quit_request){
3355 len=stream_read(mpctx->stream,buf,4096);
3356 if(len>0) {
3357 if(fwrite(buf,len,1,f) != 1) {
3358 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3359 exit_player(mpctx, EXIT_ERROR);
3362 if(dvd_last_chapter > 0) {
3363 int chapter = -1;
3364 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3365 &chapter) == STREAM_OK && chapter + 1 > dvd_last_chapter)
3366 break;
3369 if(fclose(f)) {
3370 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3371 exit_player(mpctx, EXIT_ERROR);
3373 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3374 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3377 #ifdef CONFIG_DVDREAD
3378 if(mpctx->stream->type==STREAMTYPE_DVD){
3379 current_module="dvd lang->id";
3380 if(opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,audio_lang);
3381 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3382 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,dvdsub_lang);
3383 // setup global sub numbering
3384 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3385 mpctx->global_sub_size += dvd_number_of_subs(mpctx->stream);
3386 current_module=NULL;
3388 #endif
3390 #ifdef CONFIG_DVDNAV
3391 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3392 current_module="dvdnav lang->id";
3393 if(opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,audio_lang);
3394 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3395 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=mp_dvdnav_sid_from_lang(mpctx->stream,dvdsub_lang);
3396 // setup global sub numbering
3397 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3398 mpctx->global_sub_size += mp_dvdnav_number_of_subs(mpctx->stream);
3399 current_module=NULL;
3401 #endif
3403 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3404 goto_enable_cache:
3405 if(stream_cache_size>0){
3406 current_module="enable_cache";
3407 if(!stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3408 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3409 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0)))
3410 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3413 //============ Open DEMUXERS --- DETECT file type =======================
3414 current_module="demux_open";
3416 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3418 // HACK to get MOV Reference Files working
3420 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3422 unsigned char* playlist_entry;
3423 play_tree_t *list = NULL, *entry = NULL;
3425 current_module="handle_demux_playlist";
3426 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3428 char *temp, *bname;
3430 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3431 filename_recode(playlist_entry));
3433 bname=mp_basename(playlist_entry);
3434 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3435 continue;
3437 if (!strncmp(bname,mp_basename(mpctx->filename),strlen(bname))) // ignoring self-reference
3438 continue;
3440 entry = play_tree_new();
3442 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3444 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3445 if (temp)
3447 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3448 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3449 strcat(temp, playlist_entry);
3450 play_tree_add_file(entry,temp);
3451 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3452 free(temp);
3455 else
3456 play_tree_add_file(entry,playlist_entry);
3458 if(!list)
3459 list = entry;
3460 else
3461 play_tree_append_entry(list,entry);
3463 free_demuxer(mpctx->demuxer);
3464 mpctx->demuxer = NULL;
3466 if (list)
3468 entry = play_tree_new();
3469 play_tree_set_child(entry,list);
3470 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3471 goto goto_next_file;
3475 if(!mpctx->demuxer)
3476 goto goto_next_file;
3478 if (mpctx->demuxer->matroska_data.ordered_chapters)
3479 build_ordered_chapter_timeline(mpctx);
3481 if (!mpctx->sources) {
3482 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3483 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3484 .demuxer = mpctx->demuxer};
3485 mpctx->num_sources = 1;
3488 if(dvd_chapter>1) {
3489 double pts;
3490 if (seek_chapter(mpctx, dvd_chapter-1, &pts, NULL) >= 0 && pts > -1.0)
3491 seek(mpctx, pts, SEEK_ABSOLUTE);
3494 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3496 if (mpctx->stream->type != STREAMTYPE_DVD && mpctx->stream->type != STREAMTYPE_DVDNAV) {
3497 int i;
3498 int maxid = -1;
3499 // setup global sub numbering
3500 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3501 for (i = 0; i < MAX_S_STREAMS; i++)
3502 if (mpctx->demuxer->s_streams[i])
3503 maxid = FFMAX(maxid, mpctx->demuxer->s_streams[i]->sid);
3504 mpctx->global_sub_size += maxid + 1;
3506 // Make opts->sub_id always selectable if set.
3507 if (mpctx->global_sub_size <= mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id)
3508 mpctx->global_sub_size = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id + 1;
3510 #ifdef CONFIG_ASS
3511 if (ass_enabled && ass_library) {
3512 for (int j = 0; j < mpctx->num_sources; j++) {
3513 struct demuxer *d = mpctx->sources[j].demuxer;
3514 for (int i = 0; i < d->num_attachments; i++) {
3515 struct demux_attachment *att = d->attachments + i;
3516 if (extract_embedded_fonts
3517 && att->name && att->type && att->data && att->data_size
3518 && (strcmp(att->type, "application/x-truetype-font") == 0
3519 || strcmp(att->type, "application/x-font") == 0))
3520 ass_add_font(ass_library, att->name, att->data, att->data_size);
3524 #endif
3526 current_module="demux_open2";
3528 //file_format=demuxer->file_format;
3530 mpctx->d_audio=mpctx->demuxer->audio;
3531 mpctx->d_video=mpctx->demuxer->video;
3532 mpctx->d_sub=mpctx->demuxer->sub;
3534 // select audio stream
3535 select_audio(mpctx->demuxer, opts->audio_id, audio_lang);
3537 // DUMP STREAMS:
3538 if((stream_dump_type)&&(stream_dump_type<4)){
3539 FILE *f;
3540 demux_stream_t *ds=NULL;
3541 current_module="dump";
3542 // select stream to dump
3543 switch(stream_dump_type){
3544 case 1: ds=mpctx->d_audio;break;
3545 case 2: ds=mpctx->d_video;break;
3546 case 3: ds=mpctx->d_sub;break;
3548 if(!ds){
3549 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3550 exit_player(mpctx, EXIT_ERROR);
3552 // disable other streams:
3553 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3554 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3555 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3556 // let's dump it!
3557 f=fopen(stream_dump_name,"wb");
3558 if(!f){
3559 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3560 exit_player(mpctx, EXIT_ERROR);
3562 while(!ds->eof){
3563 unsigned char* start;
3564 int in_size=ds_get_packet(ds,&start);
3565 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3566 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3567 if(in_size>0) fwrite(start,in_size,1,f);
3568 if(dvd_last_chapter>0) {
3569 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3570 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3571 break;
3574 fclose(f);
3575 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3576 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3579 mpctx->sh_audio=mpctx->d_audio->sh;
3580 mpctx->sh_video=mpctx->d_video->sh;
3582 if(mpctx->sh_video){
3584 current_module="video_read_properties";
3585 if(!video_read_properties(mpctx->sh_video)) {
3586 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3587 mpctx->sh_video=mpctx->d_video->sh=NULL;
3588 } else {
3589 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3590 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3591 mpctx->sh_video->fps,mpctx->sh_video->frametime
3594 /* need to set fps here for output encoders to pick it up in their init */
3595 if(force_fps){
3596 mpctx->sh_video->fps=force_fps;
3597 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3599 vo_fps = mpctx->sh_video->fps;
3601 if(!mpctx->sh_video->fps && !force_fps){
3602 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3603 mpctx->sh_video=mpctx->d_video->sh=NULL;
3609 if(!mpctx->sh_video && !mpctx->sh_audio){
3610 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3611 #ifdef CONFIG_DVBIN
3612 if(mpctx->stream->type == STREAMTYPE_DVB)
3614 int dir;
3615 int v = mpctx->last_dvb_step;
3616 if(v > 0)
3617 dir = DVB_CHANNEL_HIGHER;
3618 else
3619 dir = DVB_CHANNEL_LOWER;
3621 if(dvb_step_channel(mpctx->stream, dir)) {
3622 mpctx->stop_play = PT_NEXT_ENTRY;
3623 mpctx->dvbin_reopen = 1;
3626 #endif
3627 goto goto_next_file; // exit_player(_("Fatal error"));
3630 /* display clip info */
3631 demux_info_print(mpctx->demuxer);
3633 //================== Read SUBTITLES (DVD & TEXT) ==========================
3634 if(vo_spudec==NULL && mpctx->sh_video &&
3635 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3636 init_vo_spudec(mpctx);
3639 if(mpctx->sh_video) {
3640 // after reading video params we should load subtitles because
3641 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3642 // check .sub
3643 current_module="read_subtitles_file";
3644 if(sub_name){
3645 for (i = 0; sub_name[i] != NULL; ++i)
3646 add_subtitles(mpctx, sub_name[i], mpctx->sh_video->fps, 0);
3648 if(sub_auto) { // auto load sub file ...
3649 char *psub = get_path( "sub/" );
3650 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3651 int i = 0;
3652 free(psub); // release the buffer created by get_path() above
3653 while (tmp[i]) {
3654 add_subtitles(mpctx, tmp[i], mpctx->sh_video->fps, 1);
3655 free(tmp[i++]);
3657 free(tmp);
3659 if (mpctx->set_of_sub_size > 0) {
3660 // setup global sub numbering
3661 mpctx->global_sub_indices[SUB_SOURCE_SUBS] = mpctx->global_sub_size; // the global # of the first sub.
3662 mpctx->global_sub_size += mpctx->set_of_sub_size;
3666 if (mpctx->global_sub_size) {
3667 // find the best sub to use
3668 int vobsub_index_id = vobsub_get_index_by_id(vo_vobsub, vobsub_id);
3669 mpctx->global_sub_pos = -1; // no subs by default
3670 if (vobsub_index_id >= 0) {
3671 // if user asks for a vobsub id, use that first.
3672 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] + vobsub_index_id;
3673 } else if (opts->sub_id >= 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3674 // if user asks for a dvd sub id, use that next.
3675 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3676 } else if (mpctx->global_sub_indices[SUB_SOURCE_SUBS] >= 0) {
3677 // if there are text subs to use, use those. (autosubs come last here)
3678 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_SUBS];
3679 } else if (opts->sub_id < 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3680 // finally select subs by language and container hints
3681 if (opts->sub_id < 0 && dvdsub_lang)
3682 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, dvdsub_lang);
3683 if (opts->sub_id < 0)
3684 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
3685 if (opts->sub_id >= 0)
3686 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3688 // rather than duplicate code, use the SUB_SELECT handler to init the right one.
3689 mpctx->global_sub_pos--;
3690 mp_property_do("sub",M_PROPERTY_STEP_UP,NULL, mpctx);
3691 if(subdata)
3692 switch (stream_dump_type) {
3693 case 3: list_sub_file(subdata); break;
3694 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3695 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3696 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3697 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3698 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3702 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
3703 filename_recode(mpctx->filename));
3704 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
3705 if (mpctx->sh_video) {
3706 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3707 if (mpctx->sh_video->format >= 0x20202020)
3708 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
3709 else
3710 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
3711 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
3712 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
3713 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
3714 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
3715 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
3717 if (mpctx->sh_audio) {
3718 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3719 if (mpctx->sh_audio->format >= 0x20202020)
3720 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
3721 else
3722 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
3723 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
3724 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
3725 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
3727 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2lf\n", demuxer_get_time_length(mpctx->demuxer));
3728 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
3729 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
3730 if (mpctx->demuxer) {
3731 if (mpctx->demuxer->num_chapters == 0)
3732 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
3733 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
3736 if(!mpctx->sh_video) goto main; // audio-only
3738 if(!reinit_video_chain(mpctx)) {
3739 if(!mpctx->sh_video){
3740 if(!mpctx->sh_audio) goto goto_next_file;
3741 goto main; // exit_player(_("Fatal error"));
3745 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
3746 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3748 #ifdef CONFIG_FREETYPE
3749 force_load_font = 1;
3750 #endif
3752 //================== MAIN: ==========================
3753 main:
3754 current_module="main";
3756 if(playing_msg) {
3757 char* msg = property_expand_string(mpctx, playing_msg);
3758 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
3759 free(msg);
3763 // Disable the term OSD in verbose mode
3764 if(verbose) term_osd = 0;
3767 //int frame_corr_num=0; //
3768 //float v_frame=0; // Video
3769 //float num_frames=0; // number of frames played
3771 int frame_time_remaining=0; // flag
3772 int blit_frame=0;
3773 mpctx->num_buffered_frames=0;
3775 // Make sure old OSD does not stay around,
3776 // e.g. with -fixed-vo and same-resolution files
3777 clear_osd_msgs();
3778 update_osd_msg(mpctx);
3780 //================ SETUP AUDIO ==========================
3782 if(mpctx->sh_audio){
3783 reinit_audio_chain(mpctx);
3784 if (mpctx->sh_audio && mpctx->sh_audio->codec)
3785 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
3788 current_module="av_init";
3790 if(mpctx->sh_video){
3791 mpctx->sh_video->timer=0;
3792 if (! ignore_start)
3793 audio_delay += mpctx->sh_video->stream_delay;
3795 if(mpctx->sh_audio){
3796 if (start_volume >= 0)
3797 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
3798 if (! ignore_start)
3799 audio_delay -= mpctx->sh_audio->stream_delay;
3800 mpctx->delay=-audio_delay;
3803 if(!mpctx->sh_audio){
3804 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
3805 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
3806 ds_free_packs(mpctx->d_audio); // free buffered chunks
3807 //mpctx->d_audio->id=-2; // do not read audio chunks
3808 //uninit_player(mpctx, INITIALIZED_AO); // close device
3810 if(!mpctx->sh_video){
3811 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
3812 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
3813 ds_free_packs(mpctx->d_video);
3814 mpctx->d_video->id=-2;
3815 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
3818 if (!mpctx->sh_video && !mpctx->sh_audio)
3819 goto goto_next_file;
3821 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
3822 if(force_fps && mpctx->sh_video){
3823 vo_fps = mpctx->sh_video->fps=force_fps;
3824 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3825 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
3828 mp_input_set_section(mpctx->input, NULL);
3829 //TODO: add desired (stream-based) sections here
3830 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
3831 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
3833 //==================== START PLAYING =======================
3835 if(opts->loop_times>1) opts->loop_times--; else
3836 if(opts->loop_times==1) opts->loop_times = -1;
3838 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
3840 total_time_usage_start=GetTimer();
3841 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
3842 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
3843 play_n_frames=play_n_frames_mf;
3845 if(play_n_frames==0){
3846 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
3849 if (seek_to_sec) {
3850 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
3851 end_at.pos += seek_to_sec;
3854 if (end_at.type == END_AT_SIZE) {
3855 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
3856 end_at.type = END_AT_NONE;
3859 #ifdef CONFIG_DVDNAV
3860 mp_dvdnav_context_free(mpctx);
3861 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3862 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
3863 mp_dvdnav_cell_has_changed(mpctx->stream,1);
3865 #endif
3867 get_relative_time(mpctx); // reset current delta
3868 mpctx->time_frame = 0;
3869 mpctx->drop_message_shown = 0;
3870 mpctx->update_video_immediately = true;
3871 mpctx->total_avsync_change = 0;
3872 // Make sure VO knows current pause state
3873 if (mpctx->sh_video)
3874 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
3875 NULL);
3877 while(!mpctx->stop_play){
3878 float aq_sleep_time=0;
3880 if(dvd_last_chapter>0) {
3881 int cur_chapter = get_current_chapter(mpctx);
3882 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3883 goto goto_next_file;
3886 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
3887 mpctx->sh_audio = mpctx->d_audio->sh;
3888 mpctx->sh_audio->ds = mpctx->d_audio;
3889 reinit_audio_chain(mpctx);
3892 /*========================== PLAY AUDIO ============================*/
3894 if (mpctx->sh_audio && !mpctx->paused)
3895 if (!fill_audio_out_buffers(mpctx))
3896 // at eof, all audio at least written to ao
3897 if (!mpctx->sh_video)
3898 mpctx->stop_play = AT_END_OF_FILE;
3901 if(!mpctx->sh_video) {
3902 // handle audio-only case:
3903 double a_pos=0;
3904 // sh_audio can be NULL due to video stream switching
3905 // TODO: handle this better
3906 if (mpctx->sh_audio)
3907 a_pos = playing_audio_pts(mpctx);
3909 print_status(mpctx, a_pos, false);
3911 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
3912 mpctx->stop_play = PT_NEXT_ENTRY;
3913 update_osd_msg(mpctx);
3915 } else {
3917 /*========================== PLAY VIDEO ============================*/
3919 vo_pts=mpctx->sh_video->timer*90000.0;
3920 vo_fps=mpctx->sh_video->fps;
3922 if (!mpctx->num_buffered_frames) {
3923 double frame_time = update_video(mpctx, &blit_frame);
3924 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
3925 if (mpctx->sh_video->vf_initialized < 0) {
3926 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
3927 mpctx->stop_play = PT_NEXT_ENTRY;
3928 goto goto_next_file;
3930 if (blit_frame) {
3931 struct vf_instance *vf = mpctx->sh_video->vfilter;
3932 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3933 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3934 vo_osd_changed(0);
3936 if (frame_time < 0)
3937 mpctx->stop_play = AT_END_OF_FILE;
3938 else {
3939 // might return with !eof && !blit_frame if !correct_pts
3940 mpctx->num_buffered_frames += blit_frame;
3941 if (mpctx->update_video_immediately) {
3942 // Show this frame immediately, rest normally
3943 mpctx->update_video_immediately = false;
3944 } else {
3945 mpctx->time_frame += frame_time / opts->playback_speed;
3946 adjust_sync(mpctx, frame_time);
3950 if (mpctx->timeline) {
3951 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
3952 if (mpctx->sh_video->pts >= next->start
3953 || mpctx->stop_play == AT_END_OF_FILE
3954 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3955 seek(mpctx, next->start, SEEK_ABSOLUTE);
3956 continue;
3960 // ==========================================================================
3962 // current_module="draw_osd";
3963 // if(vo_config_count) mpctx->video_out->draw_osd();
3965 current_module="vo_check_events";
3966 vo_check_events(mpctx->video_out);
3968 #ifdef CONFIG_X11
3969 if (stop_xscreensaver) {
3970 current_module = "stop_xscreensaver";
3971 xscreensaver_heartbeat(mpctx->x11_state);
3973 #endif
3974 if (heartbeat_cmd) {
3975 static unsigned last_heartbeat;
3976 unsigned now = GetTimerMS();
3977 if (now - last_heartbeat > 30000) {
3978 last_heartbeat = now;
3979 system(heartbeat_cmd);
3983 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
3985 //====================== FLIP PAGE (VIDEO BLT): =========================
3987 current_module="flip_page";
3988 if (!frame_time_remaining && blit_frame) {
3989 unsigned int t2=GetTimer();
3991 vo_flip_page(mpctx->video_out);
3992 mpctx->num_buffered_frames--;
3994 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3995 vout_time_usage += mpctx->last_vo_flip_duration;
3996 print_status(mpctx, MP_NOPTS_VALUE, true);
3998 else
3999 print_status(mpctx, MP_NOPTS_VALUE, false);
4001 //============================ Auto QUALITY ============================
4003 /*Output quality adjustments:*/
4004 if(auto_quality>0){
4005 current_module="autoq";
4006 // float total=0.000001f * (GetTimer()-aq_total_time);
4007 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4008 if(output_quality<auto_quality && aq_sleep_time>0)
4009 ++output_quality;
4010 else
4011 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4012 if(output_quality>1 && aq_sleep_time<0)
4013 --output_quality;
4014 else
4015 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4016 output_quality=0;
4017 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4018 set_video_quality(mpctx->sh_video,output_quality);
4021 if (!frame_time_remaining && blit_frame) {
4022 if (play_n_frames >= 0) {
4023 --play_n_frames;
4024 if (play_n_frames <= 0)
4025 mpctx->stop_play = PT_NEXT_ENTRY;
4027 if (mpctx->step_frames > 0) {
4028 mpctx->step_frames--;
4029 if (mpctx->step_frames == 0)
4030 pause_player(mpctx);
4035 // FIXME: add size based support for -endpos
4036 if (end_at.type == END_AT_TIME &&
4037 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4038 mpctx->stop_play = PT_NEXT_ENTRY;
4040 } // end if(mpctx->sh_video)
4042 #ifdef CONFIG_DVDNAV
4043 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4044 nav_highlight_t hl;
4045 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4046 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4047 vo_osd_changed (OSDTYPE_DVDNAV);
4049 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4050 double ar = -1.0;
4051 if (stream_control (mpctx->demuxer->stream,
4052 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4053 != STREAM_UNSUPPORTED)
4054 mpctx->sh_video->stream_aspect = ar;
4057 #endif
4059 //================= Keyboard events, SEEKing ====================
4061 current_module="key_events";
4064 while (1) {
4065 mp_cmd_t* cmd;
4066 while ((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
4067 run_command(mpctx, cmd);
4068 mp_cmd_free(cmd);
4069 if (mpctx->stop_play)
4070 break;
4072 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4073 || mpctx->abs_seek_pos)
4074 break;
4075 if (mpctx->sh_video) {
4076 update_osd_msg(mpctx);
4077 int hack = vo_osd_changed(0);
4078 vo_osd_changed(hack);
4079 if (hack)
4080 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4081 add_step_frame(mpctx);
4082 break;
4084 else
4085 vo_osd_changed(0);
4087 pause_loop(mpctx);
4091 // handle -sstep
4092 if (step_sec > 0 && !mpctx->paused) {
4093 mpctx->osd_function=OSD_FFW;
4094 mpctx->rel_seek_secs+=step_sec;
4097 edl_update(mpctx);
4099 /* Looping. */
4100 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4101 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4103 if(opts->loop_times>1) opts->loop_times--; else
4104 if(opts->loop_times==1) opts->loop_times=-1;
4105 play_n_frames=play_n_frames_mf;
4106 mpctx->stop_play=0;
4107 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4110 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4111 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4113 mpctx->rel_seek_secs=0;
4114 mpctx->abs_seek_pos=0;
4117 } // while(!mpctx->stop_play)
4119 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4121 #ifdef CONFIG_DVBIN
4122 if(mpctx->dvbin_reopen)
4124 mpctx->stop_play = 0;
4125 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4126 cache_uninit(mpctx->stream);
4127 mpctx->dvbin_reopen = 0;
4128 goto goto_enable_cache;
4130 #endif
4133 goto_next_file: // don't jump here after ao/vo/getch initialization!
4135 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4137 if(benchmark){
4138 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4139 double total_time_usage;
4140 total_time_usage_start=GetTimer()-total_time_usage_start;
4141 total_time_usage = (float)total_time_usage_start*0.000001;
4142 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4143 video_time_usage,vout_time_usage,audio_time_usage,
4144 total_time_usage-tot,total_time_usage);
4145 if(total_time_usage>0.0)
4146 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4147 100.0*video_time_usage/total_time_usage,
4148 100.0*vout_time_usage/total_time_usage,
4149 100.0*audio_time_usage/total_time_usage,
4150 100.0*(total_time_usage-tot)/total_time_usage,
4151 100.0);
4152 if(total_frame_cnt && frame_dropping)
4153 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4154 total_frame_cnt-drop_frame_cnt,
4155 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4156 drop_frame_cnt,
4157 100*drop_frame_cnt/total_frame_cnt,
4158 total_frame_cnt,
4159 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4162 // time to uninit all, except global stuff:
4163 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4165 if(mpctx->set_of_sub_size > 0) {
4166 current_module="sub_free";
4167 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4168 sub_free(mpctx->set_of_subtitles[i]);
4169 #ifdef CONFIG_ASS
4170 if(mpctx->set_of_ass_tracks[i])
4171 ass_free_track( mpctx->set_of_ass_tracks[i] );
4172 #endif
4174 mpctx->set_of_sub_size = 0;
4176 vo_sub_last = vo_sub=NULL;
4177 subdata=NULL;
4178 #ifdef CONFIG_ASS
4179 ass_track = NULL;
4180 if(ass_library)
4181 ass_clear_fonts(ass_library);
4182 #endif
4184 if (!mpctx->stop_play) // In case some goto jumped here...
4185 mpctx->stop_play = PT_NEXT_ENTRY;
4187 int playtree_direction = 1;
4189 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4190 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4191 play_tree_iter_free(mpctx->playtree_iter);
4192 mpctx->playtree_iter = NULL;
4194 mpctx->play_tree_step = 1;
4195 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4196 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4197 if(mpctx->playtree_iter) {
4198 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4199 play_tree_iter_free(mpctx->playtree_iter);
4200 mpctx->playtree_iter = NULL;
4203 } else if (mpctx->stop_play == PT_STOP) {
4204 play_tree_iter_free(mpctx->playtree_iter);
4205 mpctx->playtree_iter = NULL;
4206 } else { // NEXT PREV SRC
4207 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4210 while(mpctx->playtree_iter != NULL) {
4211 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4212 if(mpctx->filename == NULL) {
4213 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4214 play_tree_iter_free(mpctx->playtree_iter);
4215 mpctx->playtree_iter = NULL;
4217 } else
4218 break;
4221 if(mpctx->playtree_iter != NULL || player_idle_mode){
4222 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4223 mpctx->stop_play = 0;
4224 goto play_next_file;
4228 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4230 return 1;
4232 #endif /* DISABLE_MAIN */