debian/: DEB_BUILD_OPTIONS -> DEB_BUILD_CONFIGURE
[mplayer.git] / mplayer.c
blob7553621f9ad194ab69c3fb443b097929f5fa6c4a
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 #include "stream/tv.h"
107 #include "stream/stream_radio.h"
108 #ifdef CONFIG_DVBIN
109 #include "stream/dvbin.h"
110 #endif
111 #include "stream/cache2.h"
113 //**************************************************************************//
114 // Playtree
115 //**************************************************************************//
116 #include "playtree.h"
117 #include "playtreeparser.h"
119 //**************************************************************************//
120 // Config
121 //**************************************************************************//
122 #include "parser-cfg.h"
123 #include "parser-mpcmd.h"
125 //**************************************************************************//
126 // Config file
127 //**************************************************************************//
129 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
131 #include "get_path.h"
133 //**************************************************************************//
134 //**************************************************************************//
135 // Input media streaming & demultiplexer:
136 //**************************************************************************//
138 static int max_framesize=0;
140 #include "stream/stream.h"
141 #include "libmpdemux/demuxer.h"
142 #include "libmpdemux/stheader.h"
144 #ifdef CONFIG_DVDREAD
145 #include "stream/stream_dvd.h"
146 #endif
147 #include "stream/stream_dvdnav.h"
149 #include "libmpcodecs/dec_audio.h"
150 #include "libmpcodecs/dec_video.h"
151 #include "libmpcodecs/mp_image.h"
152 #include "libmpcodecs/vf.h"
153 #include "libmpcodecs/vd.h"
155 #include "mixer.h"
157 #include "mp_core.h"
158 #include "options.h"
159 #include "defaultopts.h"
161 #define Exit_SIGILL_RTCpuSel _(\
162 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
163 " It may be a bug in our new runtime CPU-detection code...\n"\
164 " Please read DOCS/HTML/en/bugreports.html.\n")
166 #define Exit_SIGILL _(\
167 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
168 " It usually happens when you run it on a CPU different than the one it was\n"\
169 " compiled/optimized for.\n"\
170 " Verify this!\n")
172 #define Exit_SIGSEGV_SIGFPE _(\
173 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
174 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
175 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
177 #define Exit_SIGCRASH _(\
178 "- MPlayer crashed. This shouldn't happen.\n"\
179 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
180 " gcc version. If you think it's MPlayer's fault, please read\n"\
181 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
182 " won't help unless you provide this information when reporting a possible bug.\n")
184 #define SystemTooSlow _("\n\n"\
185 " ************************************************\n"\
186 " **** Your system is too SLOW to play this! ****\n"\
187 " ************************************************\n\n"\
188 "Possible reasons, problems, workarounds:\n"\
189 "- Most common: broken/buggy _audio_ driver\n"\
190 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
191 " - Experiment with different values for -autosync, 30 is a good start.\n"\
192 "- Slow video output\n"\
193 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
194 "- Slow CPU\n"\
195 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
196 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
197 "- Broken file\n"\
198 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
199 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
200 " - Try -cache 8192.\n"\
201 "- Are you using -cache to play a non-interleaved AVI file?\n"\
202 " - Try -nocache.\n"\
203 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
204 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
207 //**************************************************************************//
208 //**************************************************************************//
210 // Common FIFO functions, and keyboard/event FIFO code
211 #include "mp_fifo.h"
212 int noconsolecontrols=0;
213 //**************************************************************************//
215 // benchmark:
216 double video_time_usage=0;
217 double vout_time_usage=0;
218 static double audio_time_usage=0;
219 static int total_time_usage_start=0;
220 static int total_frame_cnt=0;
221 static int drop_frame_cnt=0; // total number of dropped frames
222 int benchmark=0;
224 // options:
225 int auto_quality=0;
226 static int output_quality=0;
228 static int list_properties = 0;
230 int term_osd = 1;
231 static char* term_osd_esc = "\x1b[A\r\x1b[K";
232 static char* playing_msg = NULL;
233 // seek:
234 static double seek_to_sec;
235 static off_t seek_to_byte=0;
236 static off_t step_sec=0;
238 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
240 // A/V sync:
241 int autosync=0; // 30 might be a good default value.
243 // codecs:
244 char **audio_codec_list=NULL; // override audio codec
245 char **video_codec_list=NULL; // override video codec
246 char **audio_fm_list=NULL; // override audio codec family
247 char **video_fm_list=NULL; // override video codec family
249 // demuxer:
250 extern char *demuxer_name; // override demuxer
251 extern char *audio_demuxer_name; // override audio demuxer
252 extern char *sub_demuxer_name; // override sub demuxer
254 int vobsub_id=-1;
255 char* audio_lang=NULL;
256 char* dvdsub_lang=NULL;
257 static char* spudec_ifo=NULL;
258 int forced_subs_only=0;
259 int file_filter=1;
261 // cache2:
262 int stream_cache_size=-1;
263 #ifdef CONFIG_STREAM_CACHE
264 extern int cache_fill_status;
266 float stream_cache_min_percent=20.0;
267 float stream_cache_seek_min_percent=50.0;
268 #else
269 #define cache_fill_status 0
270 #endif
272 // dump:
273 static char *stream_dump_name="stream.dump";
274 int stream_dump_type=0;
276 // A-V sync:
277 static float default_max_pts_correction=-1;//0.01f;
278 float audio_delay=0;
279 static int ignore_start=0;
281 static int softsleep=0;
283 double force_fps=0;
284 static int force_srate=0;
285 static int audio_output_format=-1; // AF_FORMAT_UNKNOWN
286 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
287 static int play_n_frames=-1;
288 static int play_n_frames_mf=-1;
290 // sub:
291 char *font_name=NULL;
292 char *sub_font_name=NULL;
293 extern int font_fontconfig;
294 float font_factor=0.75;
295 char **sub_name=NULL;
296 float sub_delay=0;
297 float sub_fps=0;
298 int sub_auto = 1;
299 char *vobsub_name=NULL;
300 /*DSP!!char *dsp=NULL;*/
301 int subcc_enabled=0;
302 int suboverlap_enabled = 1;
304 #include "ass_mp.h"
306 char* current_module=NULL; // for debugging
309 // ---
311 #ifdef CONFIG_MENU
312 #include "m_struct.h"
313 #include "libmenu/menu.h"
314 void vf_menu_pause_update(struct vf_instance* vf);
315 extern vf_info_t vf_info_menu;
316 static const vf_info_t* const libmenu_vfs[] = {
317 &vf_info_menu,
318 NULL
320 static vf_instance_t* vf_menu = NULL;
321 int use_menu = 0;
322 static char* menu_cfg = NULL;
323 static char* menu_root = "main";
324 #endif
327 #ifdef HAVE_RTC
328 static int nortc = 1;
329 static char* rtc_device;
330 #endif
332 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
333 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
334 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
335 int use_filedir_conf;
337 #include "mpcommon.h"
338 #include "command.h"
340 #include "metadata.h"
342 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
344 const void *mpctx_get_video_out(MPContext *mpctx)
346 return mpctx->video_out;
349 const void *mpctx_get_audio_out(MPContext *mpctx)
351 return mpctx->audio_out;
354 void *mpctx_get_demuxer(MPContext *mpctx)
356 return mpctx->demuxer;
359 void *mpctx_get_playtree_iter(MPContext *mpctx)
361 return mpctx->playtree_iter;
364 void *mpctx_get_mixer(MPContext *mpctx)
366 return &mpctx->mixer;
369 int mpctx_get_global_sub_size(MPContext *mpctx)
371 return mpctx->global_sub_size;
374 int mpctx_get_osd_function(MPContext *mpctx)
376 return mpctx->osd_function;
379 static float get_relative_time(struct MPContext *mpctx)
381 unsigned int new_time = GetTimer();
382 unsigned int delta = new_time - mpctx->last_time;
383 mpctx->last_time = new_time;
384 return delta * 0.000001;
387 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
388 switch (type)
390 /* check for valid video stream */
391 case META_VIDEO_CODEC:
392 case META_VIDEO_BITRATE:
393 case META_VIDEO_RESOLUTION:
395 if (!mpctx->sh_video)
396 return 0;
397 break;
400 /* check for valid audio stream */
401 case META_AUDIO_CODEC:
402 case META_AUDIO_BITRATE:
403 case META_AUDIO_SAMPLES:
405 if (!mpctx->sh_audio)
406 return 0;
407 break;
410 /* check for valid demuxer */
411 case META_INFO_TITLE:
412 case META_INFO_ARTIST:
413 case META_INFO_ALBUM:
414 case META_INFO_YEAR:
415 case META_INFO_COMMENT:
416 case META_INFO_TRACK:
417 case META_INFO_GENRE:
419 if (!mpctx->demuxer)
420 return 0;
421 break;
424 default:
425 break;
428 return 1;
431 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
432 char **info = mpctx->demuxer->info;
433 int n;
435 if (!info || !tag)
436 return NULL;
438 for (n = 0; info[2*n] != NULL ; n++)
439 if (!strcasecmp (info[2*n], tag))
440 break;
442 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
445 char *get_metadata(struct MPContext *mpctx, metadata_t type)
447 char *meta = NULL;
448 sh_audio_t * const sh_audio = mpctx->sh_audio;
449 sh_video_t * const sh_video = mpctx->sh_video;
451 if (!is_valid_metadata_type(mpctx, type))
452 return NULL;
454 switch (type)
456 case META_NAME:
458 return strdup (mp_basename2 (mpctx->filename));
461 case META_VIDEO_CODEC:
463 if (sh_video->format == 0x10000001)
464 meta = strdup ("mpeg1");
465 else if (sh_video->format == 0x10000002)
466 meta = strdup ("mpeg2");
467 else if (sh_video->format == 0x10000004)
468 meta = strdup ("mpeg4");
469 else if (sh_video->format == 0x10000005)
470 meta = strdup ("h264");
471 else if (sh_video->format >= 0x20202020)
473 meta = malloc (8);
474 sprintf (meta, "%.4s", (char *) &sh_video->format);
476 else
478 meta = malloc (8);
479 sprintf (meta, "0x%08X", sh_video->format);
481 return meta;
484 case META_VIDEO_BITRATE:
486 meta = malloc (16);
487 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
488 return meta;
491 case META_VIDEO_RESOLUTION:
493 meta = malloc (16);
494 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
495 return meta;
498 case META_AUDIO_CODEC:
500 if (sh_audio->codec && sh_audio->codec->name)
501 meta = strdup (sh_audio->codec->name);
502 return meta;
505 case META_AUDIO_BITRATE:
507 meta = malloc (16);
508 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
509 return meta;
512 case META_AUDIO_SAMPLES:
514 meta = malloc (16);
515 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
516 return meta;
519 /* check for valid demuxer */
520 case META_INFO_TITLE:
521 return get_demuxer_info(mpctx, "Title");
523 case META_INFO_ARTIST:
524 return get_demuxer_info(mpctx, "Artist");
526 case META_INFO_ALBUM:
527 return get_demuxer_info(mpctx, "Album");
529 case META_INFO_YEAR:
530 return get_demuxer_info(mpctx, "Year");
532 case META_INFO_COMMENT:
533 return get_demuxer_info(mpctx, "Comment");
535 case META_INFO_TRACK:
536 return get_demuxer_info(mpctx, "Track");
538 case META_INFO_GENRE:
539 return get_demuxer_info(mpctx, "Genre");
541 default:
542 break;
545 return meta;
548 /// step size of mixer changes
549 int volstep = 3;
551 #ifdef CONFIG_DVDNAV
552 static void mp_dvdnav_context_free(MPContext *ctx){
553 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
554 ctx->nav_smpi = NULL;
555 if (ctx->nav_buffer) free(ctx->nav_buffer);
556 ctx->nav_buffer = NULL;
557 ctx->nav_start = NULL;
558 ctx->nav_in_size = 0;
560 #endif
562 void uninit_player(struct MPContext *mpctx, unsigned int mask){
563 mask=mpctx->initialized_flags&mask;
565 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
567 if(mask&INITIALIZED_ACODEC){
568 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
569 current_module="uninit_acodec";
570 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
571 mpctx->sh_audio=NULL;
572 mpctx->mixer.afilter = NULL;
575 if(mask&INITIALIZED_VCODEC){
576 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
577 current_module="uninit_vcodec";
578 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
579 mpctx->sh_video=NULL;
580 #ifdef CONFIG_MENU
581 vf_menu=NULL;
582 #endif
585 if(mask&INITIALIZED_DEMUXER){
586 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
587 current_module="free_demuxer";
588 if (mpctx->num_sources) {
589 mpctx->demuxer = mpctx->sources[0].demuxer;
590 for (int i = 1; i < mpctx->num_sources; i++) {
591 free_stream(mpctx->sources[i].stream);
592 free_demuxer(mpctx->sources[i].demuxer);
595 talloc_free(mpctx->sources);
596 mpctx->sources = NULL;
597 mpctx->num_sources = 0;
598 talloc_free(mpctx->timeline);
599 mpctx->timeline = NULL;
600 mpctx->num_timeline_parts = 0;
601 talloc_free(mpctx->chapters);
602 mpctx->chapters = NULL;
603 mpctx->num_chapters = 0;
604 mpctx->video_offset = 0;
605 if(mpctx->demuxer){
606 mpctx->stream=mpctx->demuxer->stream;
607 free_demuxer(mpctx->demuxer);
609 mpctx->demuxer=NULL;
612 // kill the cache process:
613 if(mask&INITIALIZED_STREAM){
614 mpctx->initialized_flags&=~INITIALIZED_STREAM;
615 current_module="uninit_stream";
616 if(mpctx->stream) free_stream(mpctx->stream);
617 mpctx->stream=NULL;
620 if(mask&INITIALIZED_VO){
621 mpctx->initialized_flags&=~INITIALIZED_VO;
622 current_module="uninit_vo";
623 vo_destroy(mpctx->video_out);
624 mpctx->video_out=NULL;
625 #ifdef CONFIG_DVDNAV
626 mp_dvdnav_context_free(mpctx);
627 #endif
630 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
631 if(mask&INITIALIZED_GETCH2){
632 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
633 current_module="uninit_getch2";
634 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
635 // restore terminal:
636 getch2_disable();
639 if(mask&INITIALIZED_VOBSUB){
640 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
641 current_module="uninit_vobsub";
642 if(vo_vobsub) vobsub_close(vo_vobsub);
643 vo_vobsub=NULL;
646 if (mask&INITIALIZED_SPUDEC){
647 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
648 current_module="uninit_spudec";
649 spudec_free(vo_spudec);
650 vo_spudec=NULL;
653 if(mask&INITIALIZED_AO){
654 mpctx->initialized_flags&=~INITIALIZED_AO;
655 current_module="uninit_ao";
656 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
657 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
658 mpctx->audio_out=NULL;
661 current_module=NULL;
664 void exit_player_with_rc(struct MPContext *mpctx, exit_reason_t how, int rc)
666 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
667 uninit_player(mpctx, INITIALIZED_ALL);
668 #if defined(__MINGW32__) || defined(__CYGWIN__)
669 timeEndPeriod(1);
670 #endif
671 #ifdef CONFIG_X11
672 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
673 #endif
675 current_module="uninit_input";
676 mp_input_uninit(mpctx->input);
677 #ifdef CONFIG_MENU
678 if (use_menu)
679 menu_uninit();
680 #endif
682 #ifdef CONFIG_FREETYPE
683 current_module="uninit_font";
684 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
685 free_font_desc(mpctx->osd->sub_font);
686 free_font_desc(vo_font);
687 vo_font = NULL;
688 done_freetype();
689 #endif
690 osd_free(mpctx->osd);
692 #ifdef CONFIG_ASS
693 ass_library_done(ass_library);
694 #endif
696 current_module="exit_player";
698 // free mplayer config
699 if(mpctx->mconfig)
700 m_config_free(mpctx->mconfig);
702 if(mpctx->playtree)
703 play_tree_free(mpctx->playtree, 1);
705 talloc_free(mpctx->key_fifo);
707 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
708 switch(how) {
709 case EXIT_QUIT:
710 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
711 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
712 break;
713 case EXIT_EOF:
714 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
715 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
716 break;
717 case EXIT_ERROR:
718 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
719 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
720 break;
721 default:
722 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
724 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
726 exit(rc);
729 static void exit_player(struct MPContext *mpctx, exit_reason_t how)
731 exit_player_with_rc(mpctx, how, 1);
734 #ifndef __MINGW32__
735 static void child_sighandler(int x){
736 pid_t pid;
737 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
739 #endif
741 #ifdef CONFIG_CRASH_DEBUG
742 static char *prog_path;
743 static int crash_debug = 0;
744 #endif
746 static void exit_sighandler(int x){
747 static int sig_count=0;
748 #ifdef CONFIG_CRASH_DEBUG
749 if (!crash_debug || x != SIGTRAP)
750 #endif
751 ++sig_count;
752 if(sig_count==5)
754 /* We're crashing bad and can't uninit cleanly :(
755 * by popular request, we make one last (dirty)
756 * effort to restore the user's
757 * terminal. */
758 getch2_disable();
759 exit(1);
761 if(sig_count==6) exit(1);
762 if(sig_count>6){
763 // can't stop :(
764 #ifndef __MINGW32__
765 kill(getpid(),SIGKILL);
766 #endif
768 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"\n" "\nMPlayer interrupted by signal %d in module: %s\n",x,
769 current_module?current_module:"unknown"
771 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
772 if(sig_count<=1)
773 switch(x){
774 case SIGINT:
775 case SIGQUIT:
776 case SIGTERM:
777 case SIGKILL:
778 async_quit_request = 1;
779 return; // killed from keyboard (^C) or killed [-9]
780 case SIGILL:
781 #if CONFIG_RUNTIME_CPUDETECT
782 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
783 #else
784 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
785 #endif
786 case SIGFPE:
787 case SIGSEGV:
788 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
789 default:
790 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
791 #ifdef CONFIG_CRASH_DEBUG
792 if (crash_debug) {
793 int gdb_pid;
794 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
795 gdb_pid = fork();
796 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
797 if (gdb_pid == 0) { // We are the child
798 char spid[20];
799 snprintf(spid, sizeof(spid), "%i", getppid());
800 getch2_disable(); // allow terminal to work properly with gdb
801 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
802 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
803 } else if (gdb_pid < 0)
804 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
805 else {
806 waitpid(gdb_pid, NULL, 0);
808 if (x == SIGTRAP) return;
810 #endif
812 getch2_disable();
813 exit(1);
816 #include "cfg-mplayer.h"
818 static int cfg_include(m_option_t *conf, char *filename)
820 return m_config_parse_config_file(conf->priv, filename);
823 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
825 char *conffile;
826 int conffile_fd;
827 if (!disable_system_conf &&
828 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
829 exit_player(mpctx, EXIT_NONE);
830 if ((conffile = get_path("")) == NULL) {
831 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
832 } else {
833 #ifdef __MINGW32__
834 mkdir(conffile);
835 #else
836 mkdir(conffile, 0777);
837 #endif
838 free(conffile);
839 if ((conffile = get_path("config")) == NULL) {
840 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
841 } else {
842 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
843 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
844 write(conffile_fd, default_config, strlen(default_config));
845 close(conffile_fd);
847 if (!disable_user_conf &&
848 m_config_parse_config_file(conf, conffile) < 0)
849 exit_player(mpctx, EXIT_NONE);
850 free(conffile);
855 #define PROFILE_CFG_PROTOCOL "protocol."
857 static void load_per_protocol_config (m_config_t* conf, const char *const file)
859 char *str;
860 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
861 m_profile_t *p;
863 /* does filename actually uses a protocol ? */
864 str = strstr (file, "://");
865 if (!str)
866 return;
868 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
869 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
870 p = m_config_get_profile (conf, protocol);
871 if (p)
873 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
874 m_config_set_profile(conf,p);
878 #define PROFILE_CFG_EXTENSION "extension."
880 static void load_per_extension_config (m_config_t* conf, const char *const file)
882 char *str;
883 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
884 m_profile_t *p;
886 /* does filename actually have an extension ? */
887 str = strrchr (file, '.');
888 if (!str)
889 return;
891 sprintf (extension, PROFILE_CFG_EXTENSION);
892 strncat (extension, ++str, 7);
893 p = m_config_get_profile (conf, extension);
894 if (p)
896 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
897 m_config_set_profile(conf,p);
901 #define PROFILE_CFG_VO "vo."
902 #define PROFILE_CFG_AO "ao."
904 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
906 char profile[strlen (cfg) + strlen (out) + 1];
907 m_profile_t *p;
909 sprintf (profile, "%s%s", cfg, out);
910 p = m_config_get_profile (conf, profile);
911 if (p)
913 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
914 m_config_set_profile(conf,p);
918 static void load_per_file_config (m_config_t* conf, const char *const file)
920 char *confpath;
921 char cfg[strlen(file)+10];
922 struct stat st;
923 char *name;
925 sprintf (cfg, "%s.conf", file);
927 if (use_filedir_conf && !stat (cfg, &st))
929 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading config '%s'\n", cfg);
930 m_config_parse_config_file (conf, cfg);
931 return;
934 if ((name = strrchr (cfg, '/')) == NULL)
935 name = cfg;
936 else
937 name++;
939 if ((confpath = get_path (name)) != NULL)
941 if (!stat (confpath, &st))
943 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading config '%s'\n", confpath);
944 m_config_parse_config_file (conf, confpath);
947 free (confpath);
951 /* When libmpdemux performs a blocking operation (network connection or
952 * cache filling) if the operation fails we use this function to check
953 * if it was interrupted by the user.
954 * The function returns a new value for eof. */
955 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
957 mp_cmd_t* cmd;
958 if((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
959 switch(cmd->id) {
960 case MP_CMD_QUIT:
961 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
962 case MP_CMD_PLAY_TREE_STEP: {
963 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
964 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
965 } break;
966 case MP_CMD_PLAY_TREE_UP_STEP: {
967 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
968 } break;
969 case MP_CMD_PLAY_ALT_SRC_STEP: {
970 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
971 } break;
973 mp_cmd_free(cmd);
975 return stop_play;
978 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
980 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
982 play_tree_add_bpf(entry,mpctx->filename);
985 if(!entry) {
986 entry = mpctx->playtree_iter->tree;
987 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
988 return PT_NEXT_ENTRY;
990 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
991 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
992 return PT_NEXT_ENTRY;
995 play_tree_remove(entry,1,1);
996 return PT_NEXT_SRC;
998 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
999 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1000 entry = mpctx->playtree_iter->tree;
1001 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1002 return PT_NEXT_ENTRY;
1004 play_tree_remove(entry,1,1);
1006 return PT_NEXT_SRC;
1009 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1011 sub_data *subd;
1012 #ifdef CONFIG_ASS
1013 ASS_Track *asst = 0;
1014 #endif
1016 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1017 return;
1020 subd = sub_read_file(filename, fps);
1021 #ifdef CONFIG_ASS
1022 if (ass_enabled)
1023 #ifdef CONFIG_ICONV
1024 asst = ass_read_file(ass_library, filename, sub_cp);
1025 #else
1026 asst = ass_read_file(ass_library, filename, 0);
1027 #endif
1028 if (ass_enabled && subd && !asst)
1029 asst = ass_read_subdata(ass_library, subd, fps);
1031 if (!asst && !subd)
1032 #else
1033 if(!subd)
1034 #endif
1035 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR, "Cannot load subtitles: %s\n",
1036 filename_recode(filename));
1038 #ifdef CONFIG_ASS
1039 if (!asst && !subd) return;
1040 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1041 #else
1042 if (!subd) return;
1043 #endif
1044 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1045 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1046 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1047 filename_recode(filename));
1048 ++mpctx->set_of_sub_size;
1049 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1050 filename_recode(filename));
1053 void init_vo_spudec(struct MPContext *mpctx)
1055 if (vo_spudec)
1056 spudec_free(vo_spudec);
1057 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1058 vo_spudec = NULL;
1059 if (spudec_ifo) {
1060 unsigned int palette[16], width, height;
1061 current_module="spudec_init_vobsub";
1062 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1063 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1066 #ifdef CONFIG_DVDREAD
1067 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1068 current_module="spudec_init_dvdread";
1069 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1070 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1071 NULL, 0);
1073 #endif
1075 #ifdef CONFIG_DVDNAV
1076 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1077 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1078 current_module="spudec_init_dvdnav";
1079 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1081 #endif
1083 if (vo_spudec==NULL) {
1084 sh_sub_t *sh = (sh_sub_t *)mpctx->d_sub->sh;
1085 current_module="spudec_init_normal";
1086 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1087 spudec_set_font_factor(vo_spudec,font_factor);
1090 if (vo_spudec!=NULL) {
1091 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1092 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1097 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1098 * make it all work is to use the builtin SDL-bootstrap code, which
1099 * will be done automatically by replacing our main() if we include SDL.h.
1101 #if defined(__APPLE__) && defined(CONFIG_SDL)
1102 #include <SDL.h>
1103 #endif
1106 * \brief append a formatted string
1107 * \param buf buffer to print into
1108 * \param pos position of terminating 0 in buf
1109 * \param len maximum number of characters in buf, not including terminating 0
1110 * \param format printf format string
1112 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1114 va_list va;
1115 va_start(va, format);
1116 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1117 va_end(va);
1118 if (*pos >= len ) {
1119 buf[len] = 0;
1120 *pos = len;
1125 * \brief append time in the hh:mm:ss.f format
1126 * \param buf buffer to print into
1127 * \param pos position of terminating 0 in buf
1128 * \param len maximum number of characters in buf, not including terminating 0
1129 * \param time time value to convert/append
1131 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1132 long tenths = 10 * time;
1133 int f1 = tenths % 10;
1134 int ss = (tenths / 10) % 60;
1135 int mm = (tenths / 600) % 60;
1136 int hh = tenths / 36000;
1137 if (time <= 0) {
1138 saddf(buf, pos, len, "unknown");
1139 return;
1141 if (hh > 0)
1142 saddf(buf, pos, len, "%2d:", hh);
1143 if (hh > 0 || mm > 0)
1144 saddf(buf, pos, len, "%02d:", mm);
1145 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1148 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1150 struct MPOpts *opts = &mpctx->opts;
1151 sh_video_t * const sh_video = mpctx->sh_video;
1153 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1154 a_pos = playing_audio_pts(mpctx);
1155 if (mpctx->sh_audio && sh_video && at_frame) {
1156 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1157 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1158 && !mpctx->drop_message_shown) {
1159 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1160 mpctx->drop_message_shown = true;
1163 if (quiet)
1164 return;
1167 int width;
1168 char *line;
1169 unsigned pos = 0;
1170 get_screen_size();
1171 if (screen_width > 0)
1172 width = screen_width;
1173 else
1174 width = 80;
1175 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1176 /* Windows command line is broken (MinGW's rxvt works, but we
1177 * should not depend on that). */
1178 width--;
1179 #endif
1180 line = malloc(width + 1); // one additional char for the terminating null
1182 // Audio time
1183 if (mpctx->sh_audio) {
1184 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1185 if (!sh_video) {
1186 float len = demuxer_get_time_length(mpctx->demuxer);
1187 saddf(line, &pos, width, "(");
1188 sadd_hhmmssf(line, &pos, width, a_pos);
1189 saddf(line, &pos, width, ") of %.1f (", len);
1190 sadd_hhmmssf(line, &pos, width, len);
1191 saddf(line, &pos, width, ") ");
1195 // Video time
1196 if (sh_video)
1197 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1199 // A-V sync
1200 if (mpctx->sh_audio && sh_video)
1201 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1202 mpctx->last_av_difference, mpctx->total_avsync_change);
1204 // Video stats
1205 if (sh_video)
1206 saddf(line, &pos, width, "%3d/%3d ",
1207 (int)sh_video->num_frames,
1208 (int)sh_video->num_frames_decoded);
1210 // CPU usage
1211 if (sh_video) {
1212 if (sh_video->timer > 0.5)
1213 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1214 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1215 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1216 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1217 else
1218 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1219 } else if (mpctx->sh_audio) {
1220 if (mpctx->delay > 0.5)
1221 saddf(line, &pos, width, "%4.1f%% ",
1222 100.0*audio_time_usage/(double)mpctx->delay);
1223 else
1224 saddf(line, &pos, width, "??,?%% ");
1227 // VO stats
1228 if (sh_video)
1229 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1231 #ifdef CONFIG_STREAM_CACHE
1232 // cache stats
1233 if (stream_cache_size > 0)
1234 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1235 #endif
1237 // other
1238 if (opts->playback_speed != 1)
1239 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1241 // end
1242 if (erase_to_end_of_line) {
1243 line[pos] = 0;
1244 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1245 } else {
1246 memset(&line[pos], ' ', width - pos);
1247 line[width] = 0;
1248 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1250 free(line);
1254 * \brief build a chain of audio filters that converts the input format
1255 * to the ao's format, taking into account the current playback_speed.
1256 * \param sh_audio describes the requested input format of the chain.
1257 * \param ao_data describes the requested output format of the chain.
1259 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1261 struct MPOpts *opts = &mpctx->opts;
1262 int new_srate;
1263 int result;
1264 if (!sh_audio)
1266 mpctx->mixer.afilter = NULL;
1267 return 0;
1269 if(af_control_any_rev(sh_audio->afilter,
1270 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1271 &opts->playback_speed)) {
1272 new_srate = sh_audio->samplerate;
1273 } else {
1274 new_srate = sh_audio->samplerate * opts->playback_speed;
1275 if (new_srate != ao_data->samplerate) {
1276 // limits are taken from libaf/af_resample.c
1277 if (new_srate < 8000)
1278 new_srate = 8000;
1279 if (new_srate > 192000)
1280 new_srate = 192000;
1281 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1284 result = init_audio_filters(sh_audio, new_srate,
1285 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1286 mpctx->mixer.afilter = sh_audio->afilter;
1287 return result;
1291 typedef struct mp_osd_msg mp_osd_msg_t;
1292 struct mp_osd_msg {
1293 /// Previous message on the stack.
1294 mp_osd_msg_t* prev;
1295 /// Message text.
1296 char msg[128];
1297 int id,level,started;
1298 /// Display duration in ms.
1299 unsigned time;
1302 /// OSD message stack.
1303 static mp_osd_msg_t* osd_msg_stack = NULL;
1306 * \brief Add a message on the OSD message stack
1308 * If a message with the same id is already present in the stack
1309 * it is pulled on top of the stack, otherwise a new message is created.
1313 void set_osd_msg(int id, int level, int time, const char* fmt, ...) {
1314 mp_osd_msg_t *msg,*last=NULL;
1315 va_list va;
1316 int r;
1318 // look if the id is already in the stack
1319 for(msg = osd_msg_stack ; msg && msg->id != id ;
1320 last = msg, msg = msg->prev);
1321 // not found: alloc it
1322 if(!msg) {
1323 msg = calloc(1,sizeof(mp_osd_msg_t));
1324 msg->prev = osd_msg_stack;
1325 osd_msg_stack = msg;
1326 } else if(last) { // found, but it's not on top of the stack
1327 last->prev = msg->prev;
1328 msg->prev = osd_msg_stack;
1329 osd_msg_stack = msg;
1331 // write the msg
1332 va_start(va,fmt);
1333 r = vsnprintf(msg->msg, 128, fmt, va);
1334 va_end(va);
1335 if(r >= 128) msg->msg[127] = 0;
1336 // set id and time
1337 msg->id = id;
1338 msg->level = level;
1339 msg->time = time;
1344 * \brief Remove a message from the OSD stack
1346 * This function can be used to get rid of a message right away.
1350 void rm_osd_msg(int id) {
1351 mp_osd_msg_t *msg,*last=NULL;
1353 // Search for the msg
1354 for(msg = osd_msg_stack ; msg && msg->id != id ;
1355 last = msg, msg = msg->prev);
1356 if(!msg) return;
1358 // Detach it from the stack and free it
1359 if(last)
1360 last->prev = msg->prev;
1361 else
1362 osd_msg_stack = msg->prev;
1363 free(msg);
1367 * \brief Remove all messages from the OSD stack
1371 static void clear_osd_msgs(void) {
1372 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1373 while(msg) {
1374 prev = msg->prev;
1375 free(msg);
1376 msg = prev;
1378 osd_msg_stack = NULL;
1382 * \brief Get the current message from the OSD stack.
1384 * This function decrements the message timer and destroys the old ones.
1385 * The message that should be displayed is returned (if any).
1389 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1391 struct MPOpts *opts = &mpctx->opts;
1392 mp_osd_msg_t *msg,*prev,*last = NULL;
1393 static unsigned last_update = 0;
1394 unsigned now = GetTimerMS();
1395 unsigned diff;
1396 char hidden_dec_done = 0;
1398 if (mpctx->osd_visible) {
1399 // 36000000 means max timed visibility is 1 hour into the future, if
1400 // the difference is greater assume it's wrapped around from below 0
1401 if (mpctx->osd_visible - now > 36000000) {
1402 mpctx->osd_visible = 0;
1403 vo_osd_progbar_type = -1; // disable
1404 vo_osd_changed(OSDTYPE_PROGBAR);
1405 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1408 if (mpctx->osd_show_percentage_until - now > 36000000)
1409 mpctx->osd_show_percentage_until = 0;
1411 if(!last_update) last_update = now;
1412 diff = now >= last_update ? now - last_update : 0;
1414 last_update = now;
1416 // Look for the first message in the stack with high enough level.
1417 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1418 prev = msg->prev;
1419 if (msg->level > opts->osd_level && hidden_dec_done)
1420 continue;
1421 // The message has a high enough level or it is the first hidden one
1422 // in both cases we decrement the timer or kill it.
1423 if(!msg->started || msg->time > diff) {
1424 if(msg->started) msg->time -= diff;
1425 else msg->started = 1;
1426 // display it
1427 if (msg->level <= opts->osd_level)
1428 return msg;
1429 hidden_dec_done = 1;
1430 continue;
1432 // kill the message
1433 free(msg);
1434 if(last) {
1435 last->prev = prev;
1436 msg = last;
1437 } else {
1438 osd_msg_stack = prev;
1439 msg = NULL;
1442 // Nothing found
1443 return NULL;
1447 * \brief Display the OSD bar.
1449 * Display the OSD bar or fall back on a simple message.
1453 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1454 struct MPOpts *opts = &mpctx->opts;
1455 if (opts->osd_level < 1)
1456 return;
1458 if(mpctx->sh_video) {
1459 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1460 vo_osd_progbar_type = type;
1461 vo_osd_progbar_value = 256*(val-min)/(max-min);
1462 vo_osd_changed(OSDTYPE_PROGBAR);
1463 return;
1466 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1467 name, ROUND(100*(val-min)/(max-min)));
1472 * \brief Update the OSD message line.
1474 * This function displays the current message on the vo OSD or on the term.
1475 * If the stack is empty and the OSD level is high enough the timer
1476 * is displayed (only on the vo OSD).
1480 static void update_osd_msg(struct MPContext *mpctx)
1482 struct MPOpts *opts = &mpctx->opts;
1483 mp_osd_msg_t *msg;
1484 struct osd_state *osd = mpctx->osd;
1485 char osd_text_timer[128];
1487 if (mpctx->add_osd_seek_info) {
1488 double percentage;
1489 if (mpctx->timeline && mpctx->sh_video)
1490 percentage = mpctx->sh_video->pts * 100 /
1491 mpctx->timeline[mpctx->num_timeline_parts].start;
1492 else
1493 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1494 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1495 if (mpctx->sh_video)
1496 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1497 mpctx->add_osd_seek_info = false;
1500 // Look if we have a msg
1501 if((msg = get_osd_msg(mpctx))) {
1502 if (strcmp(osd->osd_text, msg->msg)) {
1503 strncpy(osd->osd_text, msg->msg, 127);
1504 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1505 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1507 return;
1510 if(mpctx->sh_video) {
1511 // fallback on the timer
1512 if (opts->osd_level >= 2) {
1513 int len;
1514 if (mpctx->timeline)
1515 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1516 else
1517 len = demuxer_get_time_length(mpctx->demuxer);
1518 int percentage = -1;
1519 char percentage_text[10];
1520 int pts = demuxer_get_current_time(mpctx->demuxer);
1522 if (mpctx->osd_show_percentage_until)
1523 if (mpctx->timeline)
1524 percentage = mpctx->sh_video->pts * 100 /
1525 mpctx->timeline[mpctx->num_timeline_parts].start;
1526 else
1527 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1529 if (percentage >= 0)
1530 snprintf(percentage_text, 9, " (%d%%)", percentage);
1531 else
1532 percentage_text[0] = 0;
1534 if (opts->osd_level == 3)
1535 snprintf(osd_text_timer, 63,
1536 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1537 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1538 len/3600,(len/60)%60,len%60,percentage_text);
1539 else
1540 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1541 mpctx->osd_function,pts/3600,(pts/60)%60,
1542 pts%60,percentage_text);
1543 } else
1544 osd_text_timer[0]=0;
1546 if (strcmp(osd->osd_text, osd_text_timer)) {
1547 strncpy(osd->osd_text, osd_text_timer, 63);
1548 vo_osd_changed(OSDTYPE_OSD);
1550 return;
1553 // Clear the term osd line
1554 if (term_osd && osd->osd_text[0]) {
1555 osd->osd_text[0] = 0;
1556 printf("%s\n",term_osd_esc);
1560 ///@}
1561 // OSDMsgStack
1564 void reinit_audio_chain(struct MPContext *mpctx)
1566 struct MPOpts *opts = &mpctx->opts;
1567 if(mpctx->sh_audio){
1568 current_module="init_audio_codec";
1569 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1570 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1571 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // failed to init :(
1572 mpctx->d_audio->id = -2;
1573 return;
1574 } else
1575 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1576 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1579 //const ao_info_t *info=audio_out->info;
1580 current_module="af_preinit";
1581 ao_data.samplerate=force_srate;
1582 ao_data.channels=0;
1583 ao_data.format=audio_output_format;
1584 #if 1
1585 // first init to detect best values
1586 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1587 // input:
1588 mpctx->sh_audio->samplerate,
1589 // output:
1590 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1591 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Error at audio filter chain pre-init!\n");
1592 exit_player(mpctx, EXIT_ERROR);
1594 #endif
1595 current_module="ao2_init";
1596 if(!(mpctx->audio_out=init_best_audio_out(opts->audio_driver_list,
1597 0, // plugin flag
1598 ao_data.samplerate,
1599 ao_data.channels,
1600 ao_data.format,0))){
1601 // FAILED:
1602 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1603 uninit_player(mpctx, INITIALIZED_ACODEC); // close codec
1604 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1605 mpctx->d_audio->id = -2;
1606 return;
1607 } else {
1608 // SUCCESS:
1609 mpctx->initialized_flags|=INITIALIZED_AO;
1610 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1611 mpctx->audio_out->info->short_name,
1612 ao_data.samplerate, ao_data.channels,
1613 af_fmt2str_short(ao_data.format),
1614 af_fmt2bits(ao_data.format)/8 );
1615 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1616 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1617 if(strlen(mpctx->audio_out->info->comment) > 0)
1618 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1619 // init audio filters:
1620 #if 1
1621 current_module="af_init";
1622 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1623 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1624 // mp_msg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter / ao format! -> NOSOUND\n");
1625 // uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec & ao
1626 // sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1628 #endif
1630 mpctx->mixer.audio_out = mpctx->audio_out;
1631 mpctx->mixer.volstep = volstep;
1636 ///@}
1637 // Command2Property
1640 // Return pts value corresponding to the end point of audio written to the
1641 // ao so far.
1642 static double written_audio_pts(struct MPContext *mpctx)
1644 sh_audio_t *sh_audio = mpctx->sh_audio;
1645 demux_stream_t *d_audio = mpctx->d_audio;
1646 double buffered_output;
1647 // first calculate the end pts of audio that has been output by decoder
1648 double a_pts = sh_audio->pts;
1649 if (a_pts != MP_NOPTS_VALUE)
1650 // Good, decoder supports new way of calculating audio pts.
1651 // sh_audio->pts is the timestamp of the latest input packet with
1652 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1653 // the amount of bytes the decoder has written after that timestamp.
1654 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1655 else {
1656 // Decoder doesn't support new way of calculating pts (or we're
1657 // being called before it has decoded anything with known timestamp).
1658 // Use the old method of audio pts calculation: take the timestamp
1659 // of last packet with known pts the decoder has read data from,
1660 // and add amount of bytes read after the beginning of that packet
1661 // divided by input bps. This will be inaccurate if the input/output
1662 // ratio is not constant for every audio packet or if it is constant
1663 // but not accurately known in sh_audio->i_bps.
1665 a_pts = d_audio->pts;
1666 // ds_tell_pts returns bytes read after last timestamp from
1667 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1668 // it has read but not decoded
1669 if (sh_audio->i_bps)
1670 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1671 (double)sh_audio->i_bps;
1673 // Now a_pts hopefully holds the pts for end of audio from decoder.
1674 // Substract data in buffers between decoder and audio out.
1676 // Decoded but not filtered
1677 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1679 // Data buffered in audio filters, measured in bytes of "missing" output
1680 buffered_output = af_calc_delay(sh_audio->afilter);
1682 // Data that was ready for ao but was buffered because ao didn't fully
1683 // accept everything to internal buffers yet
1684 buffered_output += sh_audio->a_out_buffer_len;
1686 // Filters divide audio length by playback_speed, so multiply by it
1687 // to get the length in original units without speedup or slowdown
1688 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1690 return a_pts + mpctx->video_offset;
1693 // Return pts value corresponding to currently playing audio.
1694 double playing_audio_pts(struct MPContext *mpctx)
1696 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1697 mpctx->audio_out->get_delay();
1700 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1701 struct MPOpts *opts = &mpctx->opts;
1702 // check for frame-drop:
1703 current_module = "check_framedrop";
1704 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1705 static int dropped_frames;
1706 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1707 float d = delay-mpctx->delay;
1708 ++total_frame_cnt;
1709 // we should avoid dropping too many frames in sequence unless we
1710 // are too late. and we allow 100ms A-V delay here:
1711 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1712 && !mpctx->update_video_immediately) {
1713 ++drop_frame_cnt;
1714 ++dropped_frames;
1715 return frame_dropping;
1716 } else
1717 dropped_frames = 0;
1719 return 0;
1723 #ifdef HAVE_RTC
1724 int rtc_fd = -1;
1725 #endif
1727 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1729 #ifdef HAVE_RTC
1730 if (rtc_fd >= 0){
1731 // -------- RTC -----------
1732 current_module="sleep_rtc";
1733 while (time_frame > 0.000) {
1734 unsigned long rtc_ts;
1735 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1736 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1737 time_frame -= get_relative_time(mpctx);
1739 } else
1740 #endif
1742 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1743 // unnecessarily high CPU usage
1744 float margin = softsleep ? 0.011 : 0;
1745 current_module = "sleep_timer";
1746 while (time_frame > margin) {
1747 usec_sleep(1000000 * (time_frame - margin));
1748 time_frame -= get_relative_time(mpctx);
1750 if (softsleep){
1751 current_module = "sleep_soft";
1752 if (time_frame < 0)
1753 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1754 while (time_frame > 0)
1755 time_frame -= get_relative_time(mpctx); // burn the CPU
1758 return time_frame;
1761 #ifdef CONFIG_DVDNAV
1762 #ifndef FF_B_TYPE
1763 #define FF_B_TYPE 3
1764 #endif
1765 /// store decoded video image
1766 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1767 mp_image_t *from_mpi) {
1768 mp_image_t *mpi;
1770 /// Do not store B-frames
1771 if (from_mpi->pict_type == FF_B_TYPE)
1772 return to_mpi;
1774 if (to_mpi &&
1775 to_mpi->w == from_mpi->w &&
1776 to_mpi->h == from_mpi->h &&
1777 to_mpi->imgfmt == from_mpi->imgfmt)
1778 mpi = to_mpi;
1779 else {
1780 if (to_mpi)
1781 free_mp_image(to_mpi);
1782 if (from_mpi->w == 0 || from_mpi->h == 0)
1783 return NULL;
1784 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1787 copy_mpi(mpi,from_mpi);
1788 return mpi;
1791 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1792 struct MPOpts *opts = &ctx->opts;
1793 if (ctx->sh_video) {
1794 /// clear video pts
1795 ctx->d_video->pts = 0.0f;
1796 ctx->sh_video->pts = 0.0f;
1797 ctx->sh_video->i_pts = 0.0f;
1798 ctx->sh_video->last_pts = 0.0f;
1799 ctx->sh_video->num_buffered_pts = 0;
1800 ctx->sh_video->num_frames = 0;
1801 ctx->sh_video->num_frames_decoded = 0;
1802 ctx->sh_video->timer = 0.0f;
1803 ctx->sh_video->stream_delay = 0.0f;
1804 ctx->sh_video->timer = 0;
1805 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1808 if (ctx->sh_audio) {
1809 /// free audio packets and reset
1810 ds_free_packs(ctx->d_audio);
1811 audio_delay -= ctx->sh_audio->stream_delay;
1812 ctx->delay =- audio_delay;
1813 ctx->audio_out->reset();
1814 resync_audio_stream(ctx->sh_audio);
1817 if (ctx->d_sub) opts->sub_id = -2;
1819 audio_delay = 0.0f;
1821 /// clear all EOF related flags
1822 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1825 /// Restore last decoded DVDNAV (still frame)
1826 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
1827 int *in_size,
1828 unsigned char **start,
1829 mp_image_t *decoded_frame)
1831 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1832 return decoded_frame;
1834 /// a change occured in dvdnav stream
1835 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
1836 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
1837 mp_dvdnav_context_free(mpctx);
1838 mp_dvdnav_reset_stream(mpctx);
1839 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
1840 mp_dvdnav_cell_has_changed(mpctx->stream,1);
1843 if (*in_size < 0) {
1844 float len;
1846 /// Display still frame, if any
1847 if (mpctx->nav_smpi && !mpctx->nav_buffer)
1848 decoded_frame = mpctx->nav_smpi;
1850 /// increment video frame : continue playing after still frame
1851 len = demuxer_get_time_length(mpctx->demuxer);
1852 if (mpctx->sh_video->pts >= len &&
1853 mpctx->sh_video->pts > 0.0 && len > 0.0) {
1854 mp_dvdnav_skip_still(mpctx->stream);
1855 mp_dvdnav_skip_wait(mpctx->stream);
1857 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
1859 if (mpctx->nav_buffer) {
1860 *start = mpctx->nav_start;
1861 *in_size = mpctx->nav_in_size;
1862 if (mpctx->nav_start)
1863 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
1867 return decoded_frame;
1870 /// Save last decoded DVDNAV (still frame)
1871 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
1872 unsigned char *start,
1873 mp_image_t *decoded_frame)
1875 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1876 return;
1878 if (mpctx->nav_buffer)
1879 free(mpctx->nav_buffer);
1881 mpctx->nav_buffer = malloc(in_size);
1882 mpctx->nav_start = start;
1883 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
1884 if (mpctx->nav_buffer)
1885 memcpy(mpctx->nav_buffer,start,in_size);
1887 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
1888 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
1890 #endif /* CONFIG_DVDNAV */
1892 /* Modify video timing to match the audio timeline. There are two main
1893 * reasons this is needed. First, video and audio can start from different
1894 * positions at beginning of file or after a seek (MPlayer starts both
1895 * immediately even if they have different pts). Second, the file can have
1896 * audio timestamps that are inconsistent with the duration of the audio
1897 * packets, for example two consecutive timestamp values differing by
1898 * one second but only a packet with enough samples for half a second
1899 * of playback between them.
1901 static void adjust_sync(struct MPContext *mpctx, double frame_time)
1903 struct MPOpts *opts = &mpctx->opts;
1904 current_module = "av_sync";
1906 if (!mpctx->sh_audio)
1907 return;
1909 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
1910 double v_pts = mpctx->sh_video->pts;
1911 double av_delay = a_pts - v_pts;
1912 // Try to sync vo_flip() so it will *finish* at given time
1913 av_delay += mpctx->last_vo_flip_duration;
1914 av_delay -= audio_delay; // This much pts difference is desired
1916 double change = av_delay * 0.1;
1917 double max_change = default_max_pts_correction >= 0 ?
1918 default_max_pts_correction : frame_time * 0.1;
1919 if (change < -max_change)
1920 change = -max_change;
1921 else if (change > max_change)
1922 change = max_change;
1923 mpctx->delay += change;
1924 mpctx->total_avsync_change += change;
1927 static int fill_audio_out_buffers(struct MPContext *mpctx)
1929 struct MPOpts *opts = &mpctx->opts;
1930 unsigned int t;
1931 double tt;
1932 int playsize;
1933 int playflags=0;
1934 int audio_eof=0;
1935 int bytes_to_write;
1936 sh_audio_t * const sh_audio = mpctx->sh_audio;
1938 current_module="play_audio";
1940 while (1) {
1941 int sleep_time;
1942 // all the current uses of ao_data.pts seem to be in aos that handle
1943 // sync completely wrong; there should be no need to use ao_data.pts
1944 // in get_space()
1945 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
1946 bytes_to_write = mpctx->audio_out->get_space();
1947 if (mpctx->sh_video || bytes_to_write >= ao_data.outburst)
1948 break;
1950 // handle audio-only case:
1951 // this is where mplayer sleeps during audio-only playback
1952 // to avoid 100% CPU use
1953 sleep_time = (ao_data.outburst - bytes_to_write) * 1000 / ao_data.bps;
1954 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
1955 usec_sleep(sleep_time * 1000);
1958 while (bytes_to_write) {
1959 playsize = bytes_to_write;
1960 if (playsize > MAX_OUTBURST)
1961 playsize = MAX_OUTBURST;
1962 bytes_to_write -= playsize;
1964 // Fill buffer if needed:
1965 current_module="decode_audio";
1966 t = GetTimer();
1967 if (decode_audio(sh_audio, playsize) < 0) // EOF or error
1968 if (mpctx->d_audio->eof) {
1969 audio_eof = 1;
1970 if (sh_audio->a_out_buffer_len == 0)
1971 return 0;
1973 t = GetTimer() - t;
1974 tt = t*0.000001f; audio_time_usage+=tt;
1975 if (playsize > sh_audio->a_out_buffer_len) {
1976 playsize = sh_audio->a_out_buffer_len;
1977 if (audio_eof)
1978 playflags |= AOPLAY_FINAL_CHUNK;
1980 if (!playsize)
1981 break;
1983 // play audio:
1984 current_module="play_audio";
1986 // Is this pts value actually useful for the aos that access it?
1987 // They're obviously badly broken in the way they handle av sync;
1988 // would not having access to this make them more broken?
1989 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
1990 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
1992 if (playsize > 0) {
1993 sh_audio->a_out_buffer_len -= playsize;
1994 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
1995 sh_audio->a_out_buffer_len);
1996 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
1998 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
1999 // Sanity check to avoid hanging in case current ao doesn't output
2000 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2001 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2002 sh_audio->a_out_buffer_len = 0;
2005 return 1;
2008 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2009 float *aq_sleep_time)
2011 struct MPOpts *opts = &mpctx->opts;
2012 int frame_time_remaining = 0;
2013 current_module="calc_sleep_time";
2015 *time_frame -= get_relative_time(mpctx); // reset timer
2017 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2018 float delay = mpctx->audio_out->get_delay();
2019 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2021 if (autosync) {
2023 * Adjust this raw delay value by calculating the expected
2024 * delay for this frame and generating a new value which is
2025 * weighted between the two. The higher autosync is, the
2026 * closer to the delay value gets to that which "-nosound"
2027 * would have used, and the longer it will take for A/V
2028 * sync to settle at the right value (but it eventually will.)
2029 * This settling time is very short for values below 100.
2031 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2032 float difference = delay - predicted;
2033 delay = predicted + difference / (float)autosync;
2036 *time_frame = delay - mpctx->delay / opts->playback_speed;
2038 // delay = amount of audio buffered in soundcard/driver
2039 if (delay > 0.25) delay=0.25; else
2040 if (delay < 0.10) delay=0.10;
2041 if (*time_frame > delay*0.6) {
2042 // sleep time too big - may cause audio drops (buffer underrun)
2043 frame_time_remaining = 1;
2044 *time_frame = delay*0.5;
2046 } else {
2047 // If we're lagging more than 200 ms behind the right playback rate,
2048 // don't try to "catch up".
2049 // If benchmark is set always output frames as fast as possible
2050 // without sleeping.
2051 if (*time_frame < -0.2 || benchmark)
2052 *time_frame = 0;
2055 *aq_sleep_time += *time_frame;
2058 //============================== SLEEP: ===================================
2060 // flag 256 means: libvo driver does its timing (dvb card)
2061 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2062 *time_frame = timing_sleep(mpctx, *time_frame);
2063 return frame_time_remaining;
2066 int reinit_video_chain(struct MPContext *mpctx)
2068 struct MPOpts *opts = &mpctx->opts;
2069 sh_video_t * const sh_video = mpctx->sh_video;
2070 double ar=-1.0;
2071 //================== Init VIDEO (codec & libvo) ==========================
2072 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2073 current_module="preinit_libvo";
2075 //shouldn't we set dvideo->id=-2 when we fail?
2076 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2077 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2078 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2079 goto err_out;
2081 mpctx->initialized_flags|=INITIALIZED_VO;
2084 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2085 mpctx->sh_video->stream_aspect = ar;
2086 current_module="init_video_filters";
2088 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2089 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2091 #ifdef CONFIG_MENU
2092 if(use_menu) {
2093 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2094 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2095 if(!vf_menu) {
2096 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2097 use_menu = 0;
2100 if(vf_menu)
2101 sh_video->vfilter = vf_menu;
2102 #endif
2104 #ifdef CONFIG_ASS
2105 if(ass_enabled) {
2106 int i;
2107 int insert = 1;
2108 if (opts->vf_settings)
2109 for (i = 0; opts->vf_settings[i].name; ++i)
2110 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2111 insert = 0;
2112 break;
2114 if (insert) {
2115 extern vf_info_t vf_info_ass;
2116 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2117 char* vf_arg[] = {"auto", "1", NULL};
2118 vf_instance_t* vf_ass = vf_open_plugin(opts, libass_vfs,sh_video->vfilter,"ass",vf_arg);
2119 if (vf_ass)
2120 sh_video->vfilter = vf_ass;
2121 else
2122 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2125 #endif
2127 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2129 #ifdef CONFIG_ASS
2130 if (ass_enabled)
2131 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2132 #endif
2134 current_module="init_video_codec";
2136 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2137 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2138 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2140 if(!sh_video->initialized){
2141 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2142 goto err_out;
2145 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2147 if (sh_video->codec)
2148 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2150 sh_video->last_pts = MP_NOPTS_VALUE;
2151 sh_video->num_buffered_pts = 0;
2152 sh_video->next_frame_time = 0;
2154 if(auto_quality>0){
2155 // Auto quality option enabled
2156 output_quality=get_video_quality_max(sh_video);
2157 if(auto_quality>output_quality) auto_quality=output_quality;
2158 else output_quality=auto_quality;
2159 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2160 set_video_quality(sh_video,output_quality);
2163 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2165 current_module="init_vo";
2167 return 1;
2169 err_out:
2170 mpctx->sh_video = mpctx->d_video->sh = NULL;
2171 return 0;
2174 static double update_video_nocorrect_pts(struct MPContext *mpctx,
2175 int *blit_frame)
2177 struct sh_video *sh_video = mpctx->sh_video;
2178 *blit_frame = 0;
2179 double frame_time = 0;
2180 while (1) {
2181 current_module = "filter_video";
2182 // In nocorrect-pts mode there is no way to properly time these frames
2183 if (vf_output_queued_frame(sh_video->vfilter))
2184 break;
2185 unsigned char *packet = NULL;
2186 frame_time = sh_video->next_frame_time;
2187 if (mpctx->update_video_immediately)
2188 frame_time = 0;
2189 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2190 &packet, force_fps);
2191 if (in_size < 0) {
2192 #ifdef CONFIG_DVDNAV
2193 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2194 if (mp_dvdnav_is_eof(mpctx->stream))
2195 return -1;
2196 if (mpctx->d_video)
2197 mpctx->d_video->eof = 0;
2198 if (mpctx->d_audio)
2199 mpctx->d_audio->eof = 0;
2200 mpctx->stream->eof = 0;
2201 } else
2202 #endif
2203 return -1;
2205 if (in_size > max_framesize)
2206 max_framesize = in_size;
2207 sh_video->timer += frame_time;
2208 if (mpctx->sh_audio)
2209 mpctx->delay -= frame_time;
2210 // video_read_frame can change fps (e.g. for ASF video)
2211 vo_fps = sh_video->fps;
2212 int framedrop_type = check_framedrop(mpctx, frame_time);
2213 current_module = "decode video";
2215 void *decoded_frame;
2216 #ifdef CONFIG_DVDNAV
2217 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2218 if (in_size >= 0 && !decoded_frame)
2219 #endif
2220 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2221 sh_video->pts);
2222 #ifdef CONFIG_DVDNAV
2223 // Save last still frame for future display
2224 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2225 #endif
2226 if (decoded_frame) {
2227 // These updates are done here for vf_expand OSD/subtitles
2228 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2229 update_teletext(sh_video, mpctx->demuxer, 0);
2230 update_osd_msg(mpctx);
2231 current_module = "filter video";
2232 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2233 break;
2236 *blit_frame = 1;
2237 return frame_time;
2240 static double update_video(struct MPContext *mpctx, int *blit_frame)
2242 struct sh_video *sh_video = mpctx->sh_video;
2243 *blit_frame = 0;
2244 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2245 mpctx->osd); // hack for vf_expand
2246 if (!mpctx->opts.correct_pts)
2247 return update_video_nocorrect_pts(mpctx, blit_frame);
2249 double pts;
2251 while (1) {
2252 current_module = "filter_video";
2253 // XXX Time used in this call is not counted in any performance
2254 // timer now, OSD time is not updated correctly for filter-added frames
2255 if (vf_output_queued_frame(sh_video->vfilter))
2256 break;
2257 unsigned char *packet = NULL;
2258 bool hit_eof = false;
2259 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2260 if (pts != MP_NOPTS_VALUE)
2261 pts += mpctx->video_offset;
2262 if (in_size < 0) {
2263 // try to extract last frames in case of decoder lag
2264 in_size = 0;
2265 pts = 1e300;
2266 hit_eof = true;
2268 if (in_size > max_framesize)
2269 max_framesize = in_size;
2270 current_module = "decode video";
2271 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2272 void *decoded_frame = decode_video(sh_video, packet, in_size,
2273 framedrop_type, pts);
2274 if (decoded_frame) {
2275 // These updates are done here for vf_expand OSD/subtitles
2276 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2277 update_teletext(sh_video, mpctx->demuxer, 0);
2278 update_osd_msg(mpctx);
2279 current_module = "filter video";
2280 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2281 break;
2282 } else if (hit_eof)
2283 return -1;
2286 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_GET_PTS, &pts);
2287 if (pts == MP_NOPTS_VALUE) {
2288 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2289 // Try to use decoder pts from before filters
2290 pts = sh_video->pts;
2291 if (pts == MP_NOPTS_VALUE)
2292 pts = sh_video->last_pts;
2294 sh_video->pts = pts;
2295 if (sh_video->last_pts == MP_NOPTS_VALUE)
2296 sh_video->last_pts = sh_video->pts;
2297 else if (sh_video->last_pts > sh_video->pts) {
2298 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2299 sh_video->pts, sh_video->last_pts);
2300 /* If the difference in pts is small treat it as jitter around the
2301 * right value (possibly caused by incorrect timestamp ordering) and
2302 * just show this frame immediately after the last one.
2303 * Treat bigger differences as timestamp resets and start counting
2304 * timing of later frames from the position of this one. */
2305 if (sh_video->last_pts - sh_video->pts > 0.5)
2306 sh_video->last_pts = sh_video->pts;
2307 else
2308 sh_video->pts = sh_video->last_pts;
2310 double frame_time = sh_video->pts - sh_video->last_pts;
2311 sh_video->last_pts = sh_video->pts;
2312 sh_video->timer += frame_time;
2313 if (mpctx->sh_audio)
2314 mpctx->delay -= frame_time;
2315 *blit_frame = 1;
2316 return frame_time;
2319 void pause_player(struct MPContext *mpctx)
2321 if (mpctx->paused)
2322 return;
2323 mpctx->paused = 1;
2324 mpctx->step_frames = 0;
2325 mpctx->time_frame -= get_relative_time(mpctx);
2327 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2328 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2330 if (mpctx->audio_out && mpctx->sh_audio)
2331 mpctx->audio_out->pause(); // pause audio, keep data if possible
2334 void unpause_player(struct MPContext *mpctx)
2336 if (!mpctx->paused)
2337 return;
2338 mpctx->paused = 0;
2340 if (mpctx->audio_out && mpctx->sh_audio)
2341 mpctx->audio_out->resume(); // resume audio
2342 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2343 && !mpctx->step_frames)
2344 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2345 (void)get_relative_time(mpctx); // ignore time that passed during pause
2348 void add_step_frame(struct MPContext *mpctx)
2350 mpctx->step_frames++;
2351 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2352 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2353 unpause_player(mpctx);
2356 static void pause_loop(struct MPContext *mpctx)
2358 mp_cmd_t* cmd;
2359 if (!quiet) {
2360 // Small hack to display the pause message on the OSD line.
2361 // The pause string is: "\n == PAUSE == \r" so we need to
2362 // take the first and the last char out
2363 if (term_osd && !mpctx->sh_video) {
2364 char msg[128] = _("\n ===== PAUSE =====\r");
2365 int mlen = strlen(msg);
2366 msg[mlen-1] = '\0';
2367 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2368 update_osd_msg(mpctx);
2369 } else
2370 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2371 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2374 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1, 1)) == NULL
2375 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2376 if (cmd) {
2377 cmd = mp_input_get_cmd(mpctx->input, 0,1,0);
2378 run_command(mpctx, cmd);
2379 mp_cmd_free(cmd);
2380 continue;
2382 if (mpctx->sh_video && mpctx->video_out)
2383 vo_check_events(mpctx->video_out);
2384 #ifdef CONFIG_MENU
2385 if (vf_menu)
2386 vf_menu_pause_update(vf_menu);
2387 #endif
2388 usec_sleep(20000);
2389 update_osd_msg(mpctx);
2390 int hack = vo_osd_changed(0);
2391 vo_osd_changed(hack);
2392 if (hack)
2393 break;
2398 // Find the right mute status and record position for new file position
2399 static void edl_seek_reset(MPContext *mpctx)
2401 mpctx->edl_muted = 0;
2402 next_edl_record = edl_records;
2404 while (next_edl_record) {
2405 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2406 break;
2408 if (next_edl_record->action == EDL_MUTE)
2409 mpctx->edl_muted = !mpctx->edl_muted;
2410 next_edl_record = next_edl_record->next;
2412 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2413 mixer_mute(&mpctx->mixer);
2417 // Execute EDL command for the current position if one exists
2418 static void edl_update(MPContext *mpctx)
2420 if (!next_edl_record)
2421 return;
2423 if (!mpctx->sh_video) {
2424 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2425 free_edl(edl_records);
2426 next_edl_record = NULL;
2427 edl_records = NULL;
2428 return;
2431 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2432 if (next_edl_record->action == EDL_SKIP) {
2433 mpctx->osd_function = OSD_FFW;
2434 mpctx->abs_seek_pos = 0;
2435 mpctx->rel_seek_secs = next_edl_record->length_sec;
2436 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2437 "[%f], length [%f]\n", next_edl_record->start_sec,
2438 next_edl_record->stop_sec, next_edl_record->length_sec);
2440 else if (next_edl_record->action == EDL_MUTE) {
2441 mpctx->edl_muted = !mpctx->edl_muted;
2442 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2443 mixer_mute(&mpctx->mixer);
2444 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2445 next_edl_record->start_sec );
2447 next_edl_record = next_edl_record->next;
2451 static void reinit_decoders(struct MPContext *mpctx)
2453 reinit_video_chain(mpctx);
2454 reinit_audio_chain(mpctx);
2455 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2458 static bool timeline_set_part(struct MPContext *mpctx, int i)
2460 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2461 struct timeline_part *n = mpctx->timeline + i;
2462 mpctx->timeline_part = i;
2463 mpctx->video_offset = n->start - n->source_start;
2464 if (n->source == p->source)
2465 return false;
2466 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2467 mpctx->demuxer = n->source->demuxer;
2468 mpctx->d_video = mpctx->demuxer->video;
2469 mpctx->d_audio = mpctx->demuxer->audio;
2470 mpctx->d_sub = mpctx->demuxer->sub;
2471 mpctx->sh_video = mpctx->d_video->sh;
2472 mpctx->sh_audio = mpctx->d_audio->sh;
2473 return true;
2476 // Given pts, switch playback to the corresponding part.
2477 // Return offset within that part.
2478 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2479 bool *need_reset)
2481 if (pts < 0)
2482 pts = 0;
2483 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2484 struct timeline_part *p = mpctx->timeline + i;
2485 if (pts < (p+1)->start) {
2486 *need_reset = timeline_set_part(mpctx, i);
2487 return pts - p->start + p->source_start;
2490 return -1;
2494 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2495 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2496 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2497 static int seek(MPContext *mpctx, double amount, int style)
2499 current_module = "seek";
2500 if (mpctx->stop_play == AT_END_OF_FILE)
2501 mpctx->stop_play = KEEP_PLAYING;
2502 if (mpctx->timeline && style & SEEK_FACTOR) {
2503 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2504 style &= ~SEEK_FACTOR;
2506 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2507 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2508 style |= SEEK_ABSOLUTE;
2509 if (amount > 0)
2510 style |= SEEK_FORWARD;
2511 else
2512 style |= SEEK_BACKWARD;
2513 amount += mpctx->sh_video->pts;
2516 /* At least the liba52 decoder wants to read from the input stream
2517 * during initialization, so reinit must be done after the demux_seek()
2518 * call that clears possible stream EOF. */
2519 bool need_reset = false;
2520 if (mpctx->timeline) {
2521 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2522 if (amount == -1) {
2523 mpctx->stop_play = AT_END_OF_FILE;
2524 // Clear audio from current position
2525 if (mpctx->sh_audio) {
2526 mpctx->audio_out->reset();
2527 mpctx->sh_audio->a_buffer_len = 0;
2528 mpctx->sh_audio->a_out_buffer_len = 0;
2530 return -1;
2533 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2534 if (need_reset)
2535 reinit_decoders(mpctx);
2536 if (seekresult == 0)
2537 return -1;
2539 if (mpctx->sh_video) {
2540 current_module = "seek_video_reset";
2541 resync_video_stream(mpctx->sh_video);
2542 if (mpctx->video_out->config_ok)
2543 vo_control(mpctx->video_out, VOCTRL_RESET, NULL);
2544 mpctx->sh_video->num_buffered_pts = 0;
2545 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2546 mpctx->num_buffered_frames = 0;
2547 mpctx->delay = 0;
2548 mpctx->time_frame = 0;
2549 mpctx->update_video_immediately = true;
2550 // Not all demuxers set d_video->pts during seek, so this value
2551 // (which is used by at least vobsub and edl code below) may
2552 // be completely wrong (probably 0).
2553 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2554 update_subtitles(mpctx->sh_video, mpctx->d_sub, mpctx->video_offset, 1);
2555 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2558 if (mpctx->sh_audio) {
2559 current_module = "seek_audio_reset";
2560 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2561 mpctx->sh_audio->a_buffer_len = 0;
2562 mpctx->sh_audio->a_out_buffer_len = 0;
2565 if (vo_vobsub && mpctx->sh_video) {
2566 current_module = "seek_vobsub_reset";
2567 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2570 edl_seek_reset(mpctx);
2572 mpctx->total_avsync_change = 0;
2573 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2574 drop_frame_cnt = 0;
2576 current_module = NULL;
2577 return 0;
2580 int get_current_chapter(struct MPContext *mpctx)
2582 if (!mpctx->chapters || !mpctx->sh_video)
2583 return demuxer_get_current_chapter(mpctx->demuxer);
2585 int i;
2586 double current_pts = mpctx->sh_video->pts;
2587 for (i = 1; i < mpctx->num_chapters; i++)
2588 if (current_pts < mpctx->chapters[i].start)
2589 break;
2590 return i - 1;
2593 // currently returns a string allocated with malloc, not talloc
2594 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2596 if (!mpctx->chapters || !mpctx->sh_video)
2597 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2598 return strdup(mpctx->chapters[chapter].name);
2601 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2602 char **chapter_name)
2604 if (!mpctx->chapters || !mpctx->sh_video)
2605 return demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2606 chapter_name);
2607 if (chapter >= mpctx->num_chapters)
2608 return -1;
2609 if (chapter < 0)
2610 chapter = 0;
2611 *seek_pts = mpctx->chapters[chapter].start;
2612 if (chapter_name)
2613 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2614 return chapter;
2617 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2618 struct content_source *sources,
2619 int num_sources,
2620 unsigned char uid_map[][16])
2622 int num_filenames = 0;
2623 char **filenames = NULL;
2624 if (num_sources > 1) {
2625 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2626 "other sources.\n");
2627 if (mpctx->stream->type != STREAMTYPE_FILE) {
2628 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2629 "normal disk file. Will not search for related files.\n");
2630 } else {
2631 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2632 "same directory to find referenced sources.\n");
2633 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2634 &num_filenames);
2638 int num_left = num_sources - 1;
2639 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2640 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2641 filename_recode(filenames[i]));
2642 int format;
2643 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2644 if (!s)
2645 continue;
2646 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2647 mpctx->opts.audio_id,
2648 mpctx->opts.video_id,
2649 mpctx->opts.sub_id, filenames[i]);
2650 if (!d) {
2651 free_stream(s);
2652 continue;
2654 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2655 for (int i = 1; i < num_sources; i++) {
2656 if (sources[i].demuxer)
2657 continue;
2658 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2659 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2660 i, filename_recode(d->filename));
2661 sources[i].stream = s;
2662 sources[i].demuxer = d;
2663 num_left--;
2664 goto match;
2668 free_demuxer(d);
2669 free_stream(s);
2670 continue;
2671 match:
2674 talloc_free(filenames);
2675 if (num_left) {
2676 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2677 "There will be parts MISSING from the video!\n");
2678 for (int i = 1, j = 1; i < num_sources; i++)
2679 if (sources[i].demuxer) {
2680 sources[j] = sources[i];
2681 memcpy(uid_map[j], uid_map[i], 16);
2682 j++;
2685 return num_sources - num_left;
2688 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2690 if (!mpctx->opts.ordered_chapters) {
2691 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
2692 "you have disabled support for them. Ignoring.\n");
2693 return;
2696 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
2697 "edit timeline.\n");
2699 struct demuxer *demuxer = mpctx->demuxer;
2700 struct matroska_data *m = &demuxer->matroska_data;
2702 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
2703 m->num_ordered_chapters);
2704 sources[0].stream = mpctx->stream;
2705 sources[0].demuxer = mpctx->demuxer;
2706 unsigned char uid_map[m->num_ordered_chapters][16];
2707 int num_sources = 1;
2708 memcpy(uid_map[0], m->segment_uid, 16);
2710 for (int i = 0; i < m->num_ordered_chapters; i++) {
2711 struct matroska_chapter *c = m->ordered_chapters + i;
2712 if (!c->has_segment_uid)
2713 memcpy(c->segment_uid, m->segment_uid, 16);
2715 for (int j = 0; j < num_sources; j++)
2716 if (!memcmp(c->segment_uid, uid_map[j], 16))
2717 goto found1;
2718 memcpy(uid_map[num_sources], c->segment_uid, 16);
2719 sources[num_sources] = (struct content_source){};
2720 num_sources++;
2721 found1:
2725 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
2726 uid_map);
2729 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
2730 m->num_ordered_chapters + 1);
2731 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
2732 m->num_ordered_chapters);
2733 uint64_t starttime = 0;
2734 uint64_t missing_time = 0;
2735 int part_count = 0;
2736 int num_chapters = 0;
2737 uint64_t prev_part_offset;
2738 for (int i = 0; i < m->num_ordered_chapters; i++) {
2739 struct matroska_chapter *c = m->ordered_chapters + i;
2741 int j;
2742 for (j = 0; j < num_sources; j++) {
2743 if (!memcmp(c->segment_uid, uid_map[j], 16))
2744 goto found2;
2746 missing_time += c->end - c->start;
2747 continue;
2748 found2:;
2749 chapters[num_chapters].start = starttime / 1000.;
2750 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
2751 /* Only add a separate part if the time or file actually changes.
2752 * Matroska files have chapter divisions that are redundant from
2753 * timeline point of view because the same chapter structure is used
2754 * both to specify the timeline and for normal chapter information.
2755 * Removing a missing inserted external chapter can also cause this. */
2756 if (part_count == 0 || c->start != starttime + prev_part_offset
2757 || sources + j != timeline[part_count - 1].source) {
2758 timeline[part_count].source = sources + j;
2759 timeline[part_count].start = chapters[num_chapters].start;
2760 timeline[part_count].source_start = c->start / 1000.;
2761 prev_part_offset = c->start - starttime;
2762 part_count++;
2764 starttime += c->end - c->start;
2765 num_chapters++;
2767 timeline[part_count].start = starttime / 1000.;
2769 if (!part_count) {
2770 // None of the parts come from the file itself???
2771 talloc_free(sources);
2772 talloc_free(timeline);
2773 talloc_free(chapters);
2774 return;
2777 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
2778 "sources. Total length %.3f seconds.\n", part_count, num_sources,
2779 timeline[part_count].start);
2780 if (missing_time)
2781 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
2782 "from the timeline!\n", missing_time / 1000.);
2783 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
2784 for (int i = 0; i < num_sources; i++)
2785 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
2786 filename_recode(sources[i].demuxer->filename));
2787 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
2788 "source_start, source):\n");
2789 for (int i = 0; i < part_count; i++) {
2790 struct timeline_part *p = timeline + i;
2791 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
2792 p->source_start, p->source - sources);
2794 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
2795 mpctx->sources = sources;
2796 mpctx->num_sources = num_sources;
2797 mpctx->timeline = timeline;
2798 mpctx->num_timeline_parts = part_count;
2799 mpctx->num_chapters = num_chapters;
2800 mpctx->chapters = chapters;
2802 mpctx->timeline_part = 0;
2803 mpctx->video_offset = timeline[0].source_start;
2804 mpctx->demuxer = timeline[0].source->demuxer;
2808 static int read_keys(void *ctx, int fd)
2810 getch2(ctx);
2811 return mplayer_get_key(ctx, 0);
2815 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
2816 * file for some tools to link against. */
2817 #ifndef DISABLE_MAIN
2818 int main(int argc,char* argv[]){
2821 char * mem_ptr;
2823 // movie info:
2825 /* Flag indicating whether MPlayer should exit without playing anything. */
2826 int opt_exit = 0;
2828 //float a_frame=0; // Audio
2830 int i;
2832 struct MPContext *mpctx = &(struct MPContext){
2833 .osd_function = OSD_PLAY,
2834 .begin_skip = MP_NOPTS_VALUE,
2835 .play_tree_step = 1,
2836 .global_sub_pos = -1,
2837 .set_of_sub_pos = -1,
2838 .file_format = DEMUXER_TYPE_UNKNOWN,
2839 .last_dvb_step = 1,
2842 InitTimer();
2843 srand(GetTimerMS());
2845 mp_msg_init();
2847 #ifdef CONFIG_X11
2848 mpctx->x11_state = vo_x11_init_state();
2849 #endif
2850 struct MPOpts *opts = &mpctx->opts;
2851 set_default_mplayer_options(opts);
2852 // Create the config context and register the options
2853 mpctx->mconfig = m_config_new(opts, cfg_include);
2854 m_config_register_options(mpctx->mconfig,mplayer_opts);
2855 mp_input_register_options(mpctx->mconfig);
2857 // Preparse the command line
2858 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
2860 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
2861 set_path_env();
2862 #endif
2864 #ifdef CONFIG_TV
2865 stream_tv_defaults.immediate = 1;
2866 #endif
2868 parse_cfgfiles(mpctx, mpctx->mconfig);
2870 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
2871 if(mpctx->playtree == NULL)
2872 opt_exit = 1;
2873 else {
2874 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
2875 if(mpctx->playtree) {
2876 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
2877 if(mpctx->playtree_iter) {
2878 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
2879 play_tree_iter_free(mpctx->playtree_iter);
2880 mpctx->playtree_iter = NULL;
2882 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
2886 mpctx->key_fifo = mp_fifo_create(opts);
2888 print_version("MPlayer");
2890 #if defined(__MINGW32__) || defined(__CYGWIN__)
2891 // stop Windows from showing all kinds of annoying error dialogs
2892 SetErrorMode(0x8003);
2893 // request 1ms timer resolution
2894 timeBeginPeriod(1);
2895 #endif
2897 #ifdef CONFIG_PRIORITY
2898 set_priority();
2899 #endif
2901 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
2902 list_video_out();
2903 opt_exit = 1;
2906 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
2907 list_audio_out();
2908 opt_exit = 1;
2911 /* Check codecs.conf. */
2912 if(!codecs_file || !parse_codec_cfg(codecs_file)){
2913 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
2914 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
2915 if(!parse_codec_cfg(NULL)){
2916 exit_player_with_rc(mpctx, EXIT_NONE, 0);
2918 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
2921 free( mem_ptr ); // release the buffer created by get_path()
2924 #if 0
2925 if(video_codec_list){
2926 int i;
2927 video_codec=video_codec_list[0];
2928 for(i=0;video_codec_list[i];i++)
2929 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
2931 #endif
2932 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
2933 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
2934 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
2935 list_codecs(1);
2936 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2937 opt_exit = 1;
2939 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
2940 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
2941 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
2942 list_codecs(0);
2943 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2944 opt_exit = 1;
2946 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
2947 vfm_help();
2948 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2949 opt_exit = 1;
2951 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
2952 afm_help();
2953 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2954 opt_exit = 1;
2956 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
2957 af_help();
2958 printf("\n");
2959 opt_exit = 1;
2961 #ifdef CONFIG_X11
2962 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
2963 fstype_help();
2964 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2965 opt_exit = 1;
2967 #endif
2968 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
2969 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
2970 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
2971 demuxer_help();
2972 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
2973 opt_exit = 1;
2975 if(list_properties) {
2976 property_print_help();
2977 opt_exit = 1;
2980 if(opt_exit)
2981 exit_player(mpctx, EXIT_NONE);
2983 if(!mpctx->filename && !player_idle_mode){
2984 // no file/vcd/dvd -> show HELP:
2985 mp_msg(MSGT_CPLAYER, MSGL_INFO, help_text);
2986 exit_player_with_rc(mpctx, EXIT_NONE, 0);
2989 /* Display what configure line was used */
2990 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
2992 // Many users forget to include command line in bugreports...
2993 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
2994 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
2995 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
2996 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
2999 //------ load global data first ------
3001 mpctx->osd = osd_create();
3003 // check font
3004 #ifdef CONFIG_FREETYPE
3005 init_freetype();
3006 #endif
3007 #ifdef CONFIG_FONTCONFIG
3008 if(font_fontconfig <= 0)
3010 #endif
3011 #ifdef CONFIG_BITMAP_FONT
3012 if(font_name){
3013 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3014 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3015 filename_recode(font_name));
3016 } else {
3017 // try default:
3018 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3019 free(mem_ptr); // release the buffer created by get_path()
3020 if(!vo_font)
3021 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3023 if (sub_font_name)
3024 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3025 else
3026 mpctx->osd->sub_font = vo_font;
3027 #endif
3028 #ifdef CONFIG_FONTCONFIG
3030 #endif
3032 #ifdef CONFIG_ASS
3033 ass_library = ass_init();
3034 #endif
3036 #ifdef HAVE_RTC
3037 if(!nortc)
3039 // seteuid(0); /* Can't hurt to try to get root here */
3040 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3041 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3042 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3043 else {
3044 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3046 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3047 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3048 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3049 close (rtc_fd);
3050 rtc_fd = -1;
3051 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3052 /* variable only by the root */
3053 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3054 close (rtc_fd);
3055 rtc_fd = -1;
3056 } else
3057 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3060 if(rtc_fd<0)
3061 #endif /* HAVE_RTC */
3062 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3063 softsleep?"software":timer_name);
3065 #ifdef HAVE_TERMCAP
3066 load_termcap(NULL); // load key-codes
3067 #endif
3069 // ========== Init keyboard FIFO (connection to libvo) ============
3071 // Init input system
3072 current_module = "init_input";
3073 mpctx->input = mp_input_init(&opts->input);
3074 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3075 if(slave_mode)
3076 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3077 else if(!noconsolecontrols)
3078 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3079 // Set the libstream interrupt callback
3080 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3082 #ifdef CONFIG_MENU
3083 if(use_menu) {
3084 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3085 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3086 else {
3087 menu_cfg = get_path("menu.conf");
3088 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3089 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3090 else {
3091 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3092 MPLAYER_CONFDIR "/menu.conf"))
3093 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3094 else {
3095 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3096 use_menu = 0;
3101 #endif
3103 current_module = NULL;
3105 /// Catch signals
3106 #ifndef __MINGW32__
3107 signal(SIGCHLD,child_sighandler);
3108 #endif
3110 #ifdef CONFIG_CRASH_DEBUG
3111 prog_path = argv[0];
3112 #endif
3113 //========= Catch terminate signals: ================
3114 // terminate requests:
3115 signal(SIGTERM,exit_sighandler); // kill
3116 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3118 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3120 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3121 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3122 #ifdef CONFIG_SIGHANDLER
3123 // fatal errors:
3124 signal(SIGBUS,exit_sighandler); // bus error
3125 signal(SIGSEGV,exit_sighandler); // segfault
3126 signal(SIGILL,exit_sighandler); // illegal instruction
3127 signal(SIGFPE,exit_sighandler); // floating point exc.
3128 signal(SIGABRT,exit_sighandler); // abort()
3129 #ifdef CONFIG_CRASH_DEBUG
3130 if (crash_debug)
3131 signal(SIGTRAP,exit_sighandler);
3132 #endif
3133 #endif
3135 // ******************* Now, let's see the per-file stuff ********************
3137 play_next_file:
3139 // init global sub numbers
3140 mpctx->global_sub_size = 0;
3141 { int i; for (i = 0; i < SUB_SOURCES; i++) mpctx->global_sub_indices[i] = -1; }
3143 if (mpctx->filename) {
3144 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3145 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3146 load_per_file_config (mpctx->mconfig, mpctx->filename);
3149 if (opts->video_driver_list)
3150 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3151 if (opts->audio_driver_list)
3152 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3154 // We must enable getch2 here to be able to interrupt network connection
3155 // or cache filling
3156 if(!noconsolecontrols && !slave_mode){
3157 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3158 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3159 else
3160 getch2_enable(); // prepare stdin for hotkeys...
3161 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3162 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3165 // =================== GUI idle loop (STOP state) ===========================
3166 while (player_idle_mode && !mpctx->filename) {
3167 play_tree_t * entry = NULL;
3168 mp_cmd_t * cmd;
3169 while (!(cmd = mp_input_get_cmd(mpctx->input, 0,1,0))) { // wait for command
3170 if (mpctx->video_out)
3171 vo_check_events(mpctx->video_out);
3172 usec_sleep(20000);
3174 switch (cmd->id) {
3175 case MP_CMD_LOADFILE:
3176 // prepare a tree entry with the new filename
3177 entry = play_tree_new();
3178 play_tree_add_file(entry, cmd->args[0].v.s);
3179 // The entry is added to the main playtree after the switch().
3180 break;
3181 case MP_CMD_LOADLIST:
3182 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3183 break;
3184 case MP_CMD_QUIT:
3185 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3186 break;
3187 case MP_CMD_GET_PROPERTY:
3188 case MP_CMD_SET_PROPERTY:
3189 case MP_CMD_STEP_PROPERTY:
3190 run_command(mpctx, cmd);
3191 break;
3194 mp_cmd_free(cmd);
3196 if (entry) { // user entered a command that gave a valid entry
3197 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3198 play_tree_free_list(mpctx->playtree->child, 1);
3199 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3201 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3203 play_tree_set_child(mpctx->playtree, entry);
3205 /* Make iterator start at the top the of tree. */
3206 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3207 if (!mpctx->playtree_iter) continue;
3209 // find the first real item in the tree
3210 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3211 // no items!
3212 play_tree_iter_free(mpctx->playtree_iter);
3213 mpctx->playtree_iter = NULL;
3214 continue; // wait for next command
3216 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3219 //---------------------------------------------------------------------------
3221 if(mpctx->filename)
3222 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3223 filename_recode(mpctx->filename));
3225 if (edl_filename) {
3226 if (edl_records) free_edl(edl_records);
3227 next_edl_record = edl_records = edl_parse_file();
3229 if (edl_output_filename) {
3230 if (edl_fd) fclose(edl_fd);
3231 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3233 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3234 filename_recode(edl_output_filename));
3238 //==================== Open VOB-Sub ============================
3240 current_module="vobsub";
3241 if (vobsub_name){
3242 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3243 if(vo_vobsub==NULL)
3244 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3245 filename_recode(vobsub_name));
3246 } else if (sub_auto && mpctx->filename){
3247 /* try to autodetect vobsub from movie filename ::atmos */
3248 char *buf = strdup(mpctx->filename), *psub;
3249 char *pdot = strrchr(buf, '.');
3250 char *pslash = strrchr(buf, '/');
3251 #if defined(__MINGW32__) || defined(__CYGWIN__)
3252 if (!pslash) pslash = strrchr(buf, '\\');
3253 #endif
3254 if (pdot && (!pslash || pdot > pslash))
3255 *pdot = '\0';
3256 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3257 /* try from ~/.mplayer/sub */
3258 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3259 char *bname;
3260 int l;
3261 bname = strrchr(buf,'/');
3262 #if defined(__MINGW32__) || defined(__CYGWIN__)
3263 if(!bname) bname = strrchr(buf,'\\');
3264 #endif
3265 if(bname) bname++;
3266 else bname = buf;
3267 l = strlen(psub) + strlen(bname) + 1;
3268 psub = realloc(psub,l);
3269 strcat(psub,bname);
3270 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3271 free(psub);
3273 free(buf);
3275 if(vo_vobsub){
3276 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3277 vobsub_set_from_lang(vo_vobsub, dvdsub_lang);
3278 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3280 // setup global sub numbering
3281 mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] = mpctx->global_sub_size; // the global # of the first vobsub.
3282 mpctx->global_sub_size += vobsub_get_indexes_count(vo_vobsub);
3285 //============ Open & Sync STREAM --- fork cache2 ====================
3287 mpctx->stream=NULL;
3288 mpctx->demuxer=NULL;
3289 if (mpctx->d_audio) {
3290 //free_demuxer_stream(mpctx->d_audio);
3291 mpctx->d_audio=NULL;
3293 if (mpctx->d_video) {
3294 //free_demuxer_stream(d_video);
3295 mpctx->d_video=NULL;
3297 mpctx->sh_audio=NULL;
3298 mpctx->sh_video=NULL;
3300 current_module="open_stream";
3301 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3302 if(!mpctx->stream) { // error...
3303 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3304 goto goto_next_file;
3306 mpctx->initialized_flags|=INITIALIZED_STREAM;
3308 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3309 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3310 "playlist support will not be used automatically.\n"
3311 "MPlayer's playlist code is unsafe and should only be used with "
3312 "trusted sources.\nPlayback will probably fail.\n\n");
3313 #if 0
3314 play_tree_t* entry;
3315 // Handle playlist
3316 current_module="handle_playlist";
3317 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3318 filename_recode(mpctx->filename));
3319 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3320 mpctx->eof=playtree_add_playlist(mpctx, entry);
3321 goto goto_next_file;
3322 #endif
3324 mpctx->stream->start_pos+=seek_to_byte;
3326 if(stream_dump_type==5){
3327 unsigned char buf[4096];
3328 int len;
3329 FILE *f;
3330 current_module="dumpstream";
3331 if(mpctx->stream->type==STREAMTYPE_STREAM && mpctx->stream->fd<0){
3332 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot dump this stream - no file descriptor available.\n");
3333 exit_player(mpctx, EXIT_ERROR);
3335 stream_reset(mpctx->stream);
3336 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3337 f=fopen(stream_dump_name,"wb");
3338 if(!f){
3339 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3340 exit_player(mpctx, EXIT_ERROR);
3342 if (dvd_chapter > 1) {
3343 int chapter = dvd_chapter - 1;
3344 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3346 while(!mpctx->stream->eof && !async_quit_request){
3347 len=stream_read(mpctx->stream,buf,4096);
3348 if(len>0) {
3349 if(fwrite(buf,len,1,f) != 1) {
3350 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3351 exit_player(mpctx, EXIT_ERROR);
3354 if(dvd_last_chapter > 0) {
3355 int chapter = -1;
3356 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3357 &chapter) == STREAM_OK && chapter + 1 > dvd_last_chapter)
3358 break;
3361 if(fclose(f)) {
3362 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3363 exit_player(mpctx, EXIT_ERROR);
3365 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3366 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3369 #ifdef CONFIG_DVDREAD
3370 if(mpctx->stream->type==STREAMTYPE_DVD){
3371 current_module="dvd lang->id";
3372 if(opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,audio_lang);
3373 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3374 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,dvdsub_lang);
3375 // setup global sub numbering
3376 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3377 mpctx->global_sub_size += dvd_number_of_subs(mpctx->stream);
3378 current_module=NULL;
3380 #endif
3382 #ifdef CONFIG_DVDNAV
3383 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3384 current_module="dvdnav lang->id";
3385 if(opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,audio_lang);
3386 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3387 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=mp_dvdnav_sid_from_lang(mpctx->stream,dvdsub_lang);
3388 // setup global sub numbering
3389 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3390 mpctx->global_sub_size += mp_dvdnav_number_of_subs(mpctx->stream);
3391 current_module=NULL;
3393 #endif
3395 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3396 goto_enable_cache:
3397 if(stream_cache_size>0){
3398 current_module="enable_cache";
3399 if(!stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3400 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3401 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0)))
3402 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3405 //============ Open DEMUXERS --- DETECT file type =======================
3406 current_module="demux_open";
3408 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3410 // HACK to get MOV Reference Files working
3412 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3414 unsigned char* playlist_entry;
3415 play_tree_t *list = NULL, *entry = NULL;
3417 current_module="handle_demux_playlist";
3418 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3420 char *temp, *bname;
3422 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3423 filename_recode(playlist_entry));
3425 bname=mp_basename(playlist_entry);
3426 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3427 continue;
3429 if (!strncmp(bname,mp_basename(mpctx->filename),strlen(bname))) // ignoring self-reference
3430 continue;
3432 entry = play_tree_new();
3434 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3436 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3437 if (temp)
3439 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3440 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3441 strcat(temp, playlist_entry);
3442 play_tree_add_file(entry,temp);
3443 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3444 free(temp);
3447 else
3448 play_tree_add_file(entry,playlist_entry);
3450 if(!list)
3451 list = entry;
3452 else
3453 play_tree_append_entry(list,entry);
3455 free_demuxer(mpctx->demuxer);
3456 mpctx->demuxer = NULL;
3458 if (list)
3460 entry = play_tree_new();
3461 play_tree_set_child(entry,list);
3462 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3463 goto goto_next_file;
3467 if(!mpctx->demuxer)
3468 goto goto_next_file;
3470 if (mpctx->demuxer->matroska_data.ordered_chapters)
3471 build_ordered_chapter_timeline(mpctx);
3473 if (!mpctx->sources) {
3474 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3475 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3476 .demuxer = mpctx->demuxer};
3477 mpctx->num_sources = 1;
3480 if(dvd_chapter>1) {
3481 double pts;
3482 if (seek_chapter(mpctx, dvd_chapter-1, &pts, NULL) >= 0 && pts > -1.0)
3483 seek(mpctx, pts, SEEK_ABSOLUTE);
3486 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3488 if (mpctx->stream->type != STREAMTYPE_DVD && mpctx->stream->type != STREAMTYPE_DVDNAV) {
3489 int i;
3490 int maxid = -1;
3491 // setup global sub numbering
3492 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3493 for (i = 0; i < MAX_S_STREAMS; i++)
3494 if (mpctx->demuxer->s_streams[i])
3495 maxid = FFMAX(maxid, mpctx->demuxer->s_streams[i]->sid);
3496 mpctx->global_sub_size += maxid + 1;
3498 // Make opts->sub_id always selectable if set.
3499 if (mpctx->global_sub_size <= mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id)
3500 mpctx->global_sub_size = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id + 1;
3502 #ifdef CONFIG_ASS
3503 if (ass_enabled && ass_library) {
3504 for (int j = 0; j < mpctx->num_sources; j++) {
3505 struct demuxer *d = mpctx->sources[j].demuxer;
3506 for (int i = 0; i < d->num_attachments; i++) {
3507 struct demux_attachment *att = d->attachments + i;
3508 if (extract_embedded_fonts
3509 && att->name && att->type && att->data && att->data_size
3510 && (strcmp(att->type, "application/x-truetype-font") == 0
3511 || strcmp(att->type, "application/x-font") == 0))
3512 ass_add_font(ass_library, att->name, att->data, att->data_size);
3516 #endif
3518 current_module="demux_open2";
3520 //file_format=demuxer->file_format;
3522 mpctx->d_audio=mpctx->demuxer->audio;
3523 mpctx->d_video=mpctx->demuxer->video;
3524 mpctx->d_sub=mpctx->demuxer->sub;
3526 // select audio stream
3527 select_audio(mpctx->demuxer, opts->audio_id, audio_lang);
3529 // DUMP STREAMS:
3530 if((stream_dump_type)&&(stream_dump_type<4)){
3531 FILE *f;
3532 demux_stream_t *ds=NULL;
3533 current_module="dump";
3534 // select stream to dump
3535 switch(stream_dump_type){
3536 case 1: ds=mpctx->d_audio;break;
3537 case 2: ds=mpctx->d_video;break;
3538 case 3: ds=mpctx->d_sub;break;
3540 if(!ds){
3541 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3542 exit_player(mpctx, EXIT_ERROR);
3544 // disable other streams:
3545 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3546 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3547 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3548 // let's dump it!
3549 f=fopen(stream_dump_name,"wb");
3550 if(!f){
3551 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3552 exit_player(mpctx, EXIT_ERROR);
3554 while(!ds->eof){
3555 unsigned char* start;
3556 int in_size=ds_get_packet(ds,&start);
3557 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3558 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3559 if(in_size>0) fwrite(start,in_size,1,f);
3560 if(dvd_last_chapter>0) {
3561 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3562 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3563 break;
3566 fclose(f);
3567 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3568 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3571 mpctx->sh_audio=mpctx->d_audio->sh;
3572 mpctx->sh_video=mpctx->d_video->sh;
3574 if(mpctx->sh_video){
3576 current_module="video_read_properties";
3577 if(!video_read_properties(mpctx->sh_video)) {
3578 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3579 mpctx->sh_video=mpctx->d_video->sh=NULL;
3580 } else {
3581 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3582 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3583 mpctx->sh_video->fps,mpctx->sh_video->frametime
3586 /* need to set fps here for output encoders to pick it up in their init */
3587 if(force_fps){
3588 mpctx->sh_video->fps=force_fps;
3589 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3591 vo_fps = mpctx->sh_video->fps;
3593 if(!mpctx->sh_video->fps && !force_fps){
3594 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3595 mpctx->sh_video=mpctx->d_video->sh=NULL;
3601 if(!mpctx->sh_video && !mpctx->sh_audio){
3602 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3603 #ifdef CONFIG_DVBIN
3604 if(mpctx->stream->type == STREAMTYPE_DVB)
3606 int dir;
3607 int v = mpctx->last_dvb_step;
3608 if(v > 0)
3609 dir = DVB_CHANNEL_HIGHER;
3610 else
3611 dir = DVB_CHANNEL_LOWER;
3613 if(dvb_step_channel(mpctx->stream, dir)) {
3614 mpctx->stop_play = PT_NEXT_ENTRY;
3615 mpctx->dvbin_reopen = 1;
3618 #endif
3619 goto goto_next_file; // exit_player(_("Fatal error"));
3622 /* display clip info */
3623 demux_info_print(mpctx->demuxer);
3625 //================== Read SUBTITLES (DVD & TEXT) ==========================
3626 if(vo_spudec==NULL && mpctx->sh_video &&
3627 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3628 init_vo_spudec(mpctx);
3631 if(mpctx->sh_video) {
3632 // after reading video params we should load subtitles because
3633 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3634 // check .sub
3635 current_module="read_subtitles_file";
3636 if(sub_name){
3637 for (i = 0; sub_name[i] != NULL; ++i)
3638 add_subtitles(mpctx, sub_name[i], mpctx->sh_video->fps, 0);
3640 if(sub_auto) { // auto load sub file ...
3641 char *psub = get_path( "sub/" );
3642 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3643 int i = 0;
3644 free(psub); // release the buffer created by get_path() above
3645 while (tmp[i]) {
3646 add_subtitles(mpctx, tmp[i], mpctx->sh_video->fps, 1);
3647 free(tmp[i++]);
3649 free(tmp);
3651 if (mpctx->set_of_sub_size > 0) {
3652 // setup global sub numbering
3653 mpctx->global_sub_indices[SUB_SOURCE_SUBS] = mpctx->global_sub_size; // the global # of the first sub.
3654 mpctx->global_sub_size += mpctx->set_of_sub_size;
3658 if (mpctx->global_sub_size) {
3659 // find the best sub to use
3660 int vobsub_index_id = vobsub_get_index_by_id(vo_vobsub, vobsub_id);
3661 mpctx->global_sub_pos = -1; // no subs by default
3662 if (vobsub_index_id >= 0) {
3663 // if user asks for a vobsub id, use that first.
3664 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] + vobsub_index_id;
3665 } else if (opts->sub_id >= 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3666 // if user asks for a dvd sub id, use that next.
3667 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3668 } else if (mpctx->global_sub_indices[SUB_SOURCE_SUBS] >= 0) {
3669 // if there are text subs to use, use those. (autosubs come last here)
3670 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_SUBS];
3671 } else if (opts->sub_id < 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3672 // finally select subs by language and container hints
3673 if (opts->sub_id < 0 && dvdsub_lang)
3674 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, dvdsub_lang);
3675 if (opts->sub_id < 0)
3676 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
3677 if (opts->sub_id >= 0)
3678 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3680 // rather than duplicate code, use the SUB_SELECT handler to init the right one.
3681 mpctx->global_sub_pos--;
3682 mp_property_do("sub",M_PROPERTY_STEP_UP,NULL, mpctx);
3683 if(subdata)
3684 switch (stream_dump_type) {
3685 case 3: list_sub_file(subdata); break;
3686 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3687 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3688 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3689 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3690 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3694 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
3695 filename_recode(mpctx->filename));
3696 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
3697 if (mpctx->sh_video) {
3698 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3699 if (mpctx->sh_video->format >= 0x20202020)
3700 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
3701 else
3702 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
3703 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
3704 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
3705 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
3706 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
3707 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
3709 if (mpctx->sh_audio) {
3710 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3711 if (mpctx->sh_audio->format >= 0x20202020)
3712 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
3713 else
3714 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
3715 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
3716 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
3717 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
3719 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2lf\n", demuxer_get_time_length(mpctx->demuxer));
3720 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
3721 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
3722 if (mpctx->demuxer) {
3723 if (mpctx->demuxer->num_chapters == 0)
3724 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
3725 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
3728 if(!mpctx->sh_video) goto main; // audio-only
3730 if(!reinit_video_chain(mpctx)) {
3731 if(!mpctx->sh_video){
3732 if(!mpctx->sh_audio) goto goto_next_file;
3733 goto main; // exit_player(_("Fatal error"));
3737 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
3738 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3740 #ifdef CONFIG_FREETYPE
3741 force_load_font = 1;
3742 #endif
3744 //================== MAIN: ==========================
3745 main:
3746 current_module="main";
3748 if(playing_msg) {
3749 char* msg = property_expand_string(mpctx, playing_msg);
3750 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
3751 free(msg);
3755 // Disable the term OSD in verbose mode
3756 if(verbose) term_osd = 0;
3759 //int frame_corr_num=0; //
3760 //float v_frame=0; // Video
3761 //float num_frames=0; // number of frames played
3763 int frame_time_remaining=0; // flag
3764 int blit_frame=0;
3765 mpctx->num_buffered_frames=0;
3767 // Make sure old OSD does not stay around,
3768 // e.g. with -fixed-vo and same-resolution files
3769 clear_osd_msgs();
3770 update_osd_msg(mpctx);
3772 //================ SETUP AUDIO ==========================
3774 if(mpctx->sh_audio){
3775 reinit_audio_chain(mpctx);
3776 if (mpctx->sh_audio && mpctx->sh_audio->codec)
3777 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
3780 current_module="av_init";
3782 if(mpctx->sh_video){
3783 mpctx->sh_video->timer=0;
3784 if (! ignore_start)
3785 audio_delay += mpctx->sh_video->stream_delay;
3787 if(mpctx->sh_audio){
3788 if (start_volume >= 0)
3789 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
3790 if (! ignore_start)
3791 audio_delay -= mpctx->sh_audio->stream_delay;
3792 mpctx->delay=-audio_delay;
3795 if(!mpctx->sh_audio){
3796 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
3797 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
3798 ds_free_packs(mpctx->d_audio); // free buffered chunks
3799 //mpctx->d_audio->id=-2; // do not read audio chunks
3800 //uninit_player(mpctx, INITIALIZED_AO); // close device
3802 if(!mpctx->sh_video){
3803 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
3804 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
3805 ds_free_packs(mpctx->d_video);
3806 mpctx->d_video->id=-2;
3807 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
3810 if (!mpctx->sh_video && !mpctx->sh_audio)
3811 goto goto_next_file;
3813 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
3814 if(force_fps && mpctx->sh_video){
3815 vo_fps = mpctx->sh_video->fps=force_fps;
3816 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3817 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
3820 mp_input_set_section(mpctx->input, NULL);
3821 //TODO: add desired (stream-based) sections here
3822 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
3823 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
3825 //==================== START PLAYING =======================
3827 if(opts->loop_times>1) opts->loop_times--; else
3828 if(opts->loop_times==1) opts->loop_times = -1;
3830 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
3832 total_time_usage_start=GetTimer();
3833 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
3834 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
3835 play_n_frames=play_n_frames_mf;
3837 if(play_n_frames==0){
3838 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
3841 if (seek_to_sec) {
3842 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
3843 end_at.pos += seek_to_sec;
3846 if (end_at.type == END_AT_SIZE) {
3847 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
3848 end_at.type = END_AT_NONE;
3851 #ifdef CONFIG_DVDNAV
3852 mp_dvdnav_context_free(mpctx);
3853 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3854 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
3855 mp_dvdnav_cell_has_changed(mpctx->stream,1);
3857 #endif
3859 get_relative_time(mpctx); // reset current delta
3860 mpctx->time_frame = 0;
3861 mpctx->drop_message_shown = 0;
3862 mpctx->update_video_immediately = true;
3863 mpctx->total_avsync_change = 0;
3864 // Make sure VO knows current pause state
3865 if (mpctx->sh_video)
3866 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
3867 NULL);
3869 while(!mpctx->stop_play){
3870 float aq_sleep_time=0;
3872 if(dvd_last_chapter>0) {
3873 int cur_chapter = get_current_chapter(mpctx);
3874 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3875 goto goto_next_file;
3878 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
3879 mpctx->sh_audio = mpctx->d_audio->sh;
3880 mpctx->sh_audio->ds = mpctx->d_audio;
3881 reinit_audio_chain(mpctx);
3884 /*========================== PLAY AUDIO ============================*/
3886 if (mpctx->sh_audio && !mpctx->paused)
3887 if (!fill_audio_out_buffers(mpctx))
3888 // at eof, all audio at least written to ao
3889 if (!mpctx->sh_video)
3890 mpctx->stop_play = AT_END_OF_FILE;
3893 if(!mpctx->sh_video) {
3894 // handle audio-only case:
3895 double a_pos=0;
3896 // sh_audio can be NULL due to video stream switching
3897 // TODO: handle this better
3898 if (mpctx->sh_audio)
3899 a_pos = playing_audio_pts(mpctx);
3901 print_status(mpctx, a_pos, false);
3903 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
3904 mpctx->stop_play = PT_NEXT_ENTRY;
3905 update_osd_msg(mpctx);
3907 } else {
3909 /*========================== PLAY VIDEO ============================*/
3911 vo_pts=mpctx->sh_video->timer*90000.0;
3912 vo_fps=mpctx->sh_video->fps;
3914 if (!mpctx->num_buffered_frames) {
3915 double frame_time = update_video(mpctx, &blit_frame);
3916 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
3917 if (mpctx->sh_video->vf_initialized < 0) {
3918 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
3919 mpctx->stop_play = PT_NEXT_ENTRY;
3920 goto goto_next_file;
3922 if (blit_frame) {
3923 struct vf_instance *vf = mpctx->sh_video->vfilter;
3924 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3925 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3926 vo_osd_changed(0);
3928 if (frame_time < 0)
3929 mpctx->stop_play = AT_END_OF_FILE;
3930 else {
3931 // might return with !eof && !blit_frame if !correct_pts
3932 mpctx->num_buffered_frames += blit_frame;
3933 if (mpctx->update_video_immediately) {
3934 // Show this frame immediately, rest normally
3935 mpctx->update_video_immediately = false;
3936 } else {
3937 mpctx->time_frame += frame_time / opts->playback_speed;
3938 adjust_sync(mpctx, frame_time);
3942 if (mpctx->timeline) {
3943 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
3944 if (mpctx->sh_video->pts >= next->start
3945 || mpctx->stop_play == AT_END_OF_FILE
3946 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3947 seek(mpctx, next->start, SEEK_ABSOLUTE);
3948 continue;
3952 // ==========================================================================
3954 // current_module="draw_osd";
3955 // if(vo_config_count) mpctx->video_out->draw_osd();
3957 current_module="vo_check_events";
3958 vo_check_events(mpctx->video_out);
3960 #ifdef CONFIG_X11
3961 if (stop_xscreensaver) {
3962 current_module = "stop_xscreensaver";
3963 xscreensaver_heartbeat(mpctx->x11_state);
3965 #endif
3966 if (heartbeat_cmd) {
3967 static unsigned last_heartbeat;
3968 unsigned now = GetTimerMS();
3969 if (now - last_heartbeat > 30000) {
3970 last_heartbeat = now;
3971 system(heartbeat_cmd);
3975 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
3977 //====================== FLIP PAGE (VIDEO BLT): =========================
3979 current_module="flip_page";
3980 if (!frame_time_remaining && blit_frame) {
3981 unsigned int t2=GetTimer();
3983 vo_flip_page(mpctx->video_out);
3984 mpctx->num_buffered_frames--;
3986 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3987 vout_time_usage += mpctx->last_vo_flip_duration;
3988 print_status(mpctx, MP_NOPTS_VALUE, true);
3990 else
3991 print_status(mpctx, MP_NOPTS_VALUE, false);
3993 //============================ Auto QUALITY ============================
3995 /*Output quality adjustments:*/
3996 if(auto_quality>0){
3997 current_module="autoq";
3998 // float total=0.000001f * (GetTimer()-aq_total_time);
3999 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4000 if(output_quality<auto_quality && aq_sleep_time>0)
4001 ++output_quality;
4002 else
4003 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4004 if(output_quality>1 && aq_sleep_time<0)
4005 --output_quality;
4006 else
4007 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4008 output_quality=0;
4009 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4010 set_video_quality(mpctx->sh_video,output_quality);
4013 if (!frame_time_remaining && blit_frame) {
4014 if (play_n_frames >= 0) {
4015 --play_n_frames;
4016 if (play_n_frames <= 0)
4017 mpctx->stop_play = PT_NEXT_ENTRY;
4019 if (mpctx->step_frames > 0) {
4020 mpctx->step_frames--;
4021 if (mpctx->step_frames == 0)
4022 pause_player(mpctx);
4027 // FIXME: add size based support for -endpos
4028 if (end_at.type == END_AT_TIME &&
4029 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4030 mpctx->stop_play = PT_NEXT_ENTRY;
4032 } // end if(mpctx->sh_video)
4034 #ifdef CONFIG_DVDNAV
4035 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4036 nav_highlight_t hl;
4037 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4038 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4039 vo_osd_changed (OSDTYPE_DVDNAV);
4041 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4042 double ar = -1.0;
4043 if (stream_control (mpctx->demuxer->stream,
4044 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4045 != STREAM_UNSUPPORTED)
4046 mpctx->sh_video->stream_aspect = ar;
4049 #endif
4051 //================= Keyboard events, SEEKing ====================
4053 current_module="key_events";
4056 while (1) {
4057 mp_cmd_t* cmd;
4058 while ((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
4059 run_command(mpctx, cmd);
4060 mp_cmd_free(cmd);
4061 if (mpctx->stop_play)
4062 break;
4064 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4065 || mpctx->abs_seek_pos)
4066 break;
4067 if (mpctx->sh_video) {
4068 update_osd_msg(mpctx);
4069 int hack = vo_osd_changed(0);
4070 vo_osd_changed(hack);
4071 if (hack)
4072 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4073 add_step_frame(mpctx);
4074 break;
4076 else
4077 vo_osd_changed(0);
4079 pause_loop(mpctx);
4083 // handle -sstep
4084 if (step_sec > 0 && !mpctx->paused) {
4085 mpctx->osd_function=OSD_FFW;
4086 mpctx->rel_seek_secs+=step_sec;
4089 edl_update(mpctx);
4091 /* Looping. */
4092 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4093 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4095 if(opts->loop_times>1) opts->loop_times--; else
4096 if(opts->loop_times==1) opts->loop_times=-1;
4097 play_n_frames=play_n_frames_mf;
4098 mpctx->stop_play=0;
4099 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4102 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4103 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4105 mpctx->rel_seek_secs=0;
4106 mpctx->abs_seek_pos=0;
4109 } // while(!mpctx->stop_play)
4111 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4113 #ifdef CONFIG_DVBIN
4114 if(mpctx->dvbin_reopen)
4116 mpctx->stop_play = 0;
4117 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4118 cache_uninit(mpctx->stream);
4119 mpctx->dvbin_reopen = 0;
4120 goto goto_enable_cache;
4122 #endif
4125 goto_next_file: // don't jump here after ao/vo/getch initialization!
4127 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4129 if(benchmark){
4130 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4131 double total_time_usage;
4132 total_time_usage_start=GetTimer()-total_time_usage_start;
4133 total_time_usage = (float)total_time_usage_start*0.000001;
4134 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4135 video_time_usage,vout_time_usage,audio_time_usage,
4136 total_time_usage-tot,total_time_usage);
4137 if(total_time_usage>0.0)
4138 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4139 100.0*video_time_usage/total_time_usage,
4140 100.0*vout_time_usage/total_time_usage,
4141 100.0*audio_time_usage/total_time_usage,
4142 100.0*(total_time_usage-tot)/total_time_usage,
4143 100.0);
4144 if(total_frame_cnt && frame_dropping)
4145 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4146 total_frame_cnt-drop_frame_cnt,
4147 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4148 drop_frame_cnt,
4149 100*drop_frame_cnt/total_frame_cnt,
4150 total_frame_cnt,
4151 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4154 // time to uninit all, except global stuff:
4155 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4157 if(mpctx->set_of_sub_size > 0) {
4158 current_module="sub_free";
4159 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4160 sub_free(mpctx->set_of_subtitles[i]);
4161 #ifdef CONFIG_ASS
4162 if(mpctx->set_of_ass_tracks[i])
4163 ass_free_track( mpctx->set_of_ass_tracks[i] );
4164 #endif
4166 mpctx->set_of_sub_size = 0;
4168 vo_sub_last = vo_sub=NULL;
4169 subdata=NULL;
4170 #ifdef CONFIG_ASS
4171 ass_track = NULL;
4172 if(ass_library)
4173 ass_clear_fonts(ass_library);
4174 #endif
4176 if (!mpctx->stop_play) // In case some goto jumped here...
4177 mpctx->stop_play = PT_NEXT_ENTRY;
4179 int playtree_direction = 1;
4181 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4182 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4183 play_tree_iter_free(mpctx->playtree_iter);
4184 mpctx->playtree_iter = NULL;
4186 mpctx->play_tree_step = 1;
4187 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4188 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4189 if(mpctx->playtree_iter) {
4190 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4191 play_tree_iter_free(mpctx->playtree_iter);
4192 mpctx->playtree_iter = NULL;
4195 } else if (mpctx->stop_play == PT_STOP) {
4196 play_tree_iter_free(mpctx->playtree_iter);
4197 mpctx->playtree_iter = NULL;
4198 } else { // NEXT PREV SRC
4199 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4202 while(mpctx->playtree_iter != NULL) {
4203 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4204 if(mpctx->filename == NULL) {
4205 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4206 play_tree_iter_free(mpctx->playtree_iter);
4207 mpctx->playtree_iter = NULL;
4209 } else
4210 break;
4213 if(mpctx->playtree_iter != NULL || player_idle_mode){
4214 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4215 mpctx->stop_play = 0;
4216 goto play_next_file;
4220 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4222 return 1;
4224 #endif /* DISABLE_MAIN */