Replace libavutil internal header #includes with MPlayer copies
[mplayer.git] / mplayer.c
blobac02447eb537343eddc19b29b325a39805491677
2 /// \file
3 /// \ingroup Properties Command2Property OSDMsgStack
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdbool.h>
8 #include "config.h"
9 #include "talloc.h"
11 #if defined(__MINGW32__) || defined(__CYGWIN__)
12 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
13 #include <windows.h>
14 #endif
15 #include <string.h>
16 #include <unistd.h>
18 // #include <sys/mman.h>
19 #include <sys/types.h>
20 #ifndef __MINGW32__
21 #include <sys/ioctl.h>
22 #include <sys/wait.h>
23 #else
24 #define SIGHUP 1 /* hangup */
25 #define SIGQUIT 3 /* quit */
26 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
27 #define SIGBUS 10 /* bus error */
28 #define SIGPIPE 13 /* broken pipe */
29 #endif
31 #include <sys/time.h>
32 #include <sys/stat.h>
34 #include <signal.h>
35 #include <time.h>
36 #include <fcntl.h>
37 #include <limits.h>
39 #include <errno.h>
41 #include "mp_msg.h"
43 #define HELP_MP_DEFINE_STATIC
44 #include "help_mp.h"
46 #include "m_option.h"
47 #include "m_config.h"
48 #include "mplayer.h"
49 #include "access_mpcontext.h"
50 #include "m_property.h"
52 #include "cfg-mplayer-def.h"
54 #include "ffmpeg_files/intreadwrite.h"
56 #include "subreader.h"
58 #include "mp_osd.h"
59 #include "libvo/video_out.h"
61 #include "libvo/font_load.h"
62 #include "libvo/sub.h"
64 #ifdef CONFIG_X11
65 #include "libvo/x11_common.h"
66 #endif
68 #include "libao2/audio_out.h"
70 #include "codec-cfg.h"
72 #include "edl.h"
74 #include "spudec.h"
75 #include "vobsub.h"
77 #include "osdep/getch2.h"
78 #include "osdep/timer.h"
79 #include "osdep/findfiles.h"
81 #include "input/input.h"
83 const int under_mencoder = 0;
84 int slave_mode=0;
85 int player_idle_mode=0;
86 int quiet=0;
87 int enable_mouse_movements=0;
88 float start_volume = -1;
90 #include "osdep/priority.h"
92 char *heartbeat_cmd;
94 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
96 #ifdef HAVE_RTC
97 #ifdef __linux__
98 #include <linux/rtc.h>
99 #else
100 #include <rtc.h>
101 #define RTC_IRQP_SET RTCIO_IRQP_SET
102 #define RTC_PIE_ON RTCIO_PIE_ON
103 #endif /* __linux__ */
104 #endif /* HAVE_RTC */
106 #ifdef CONFIG_TV
107 #include "stream/tv.h"
108 #endif
109 #ifdef CONFIG_RADIO
110 #include "stream/stream_radio.h"
111 #endif
113 #ifdef CONFIG_DVBIN
114 #include "stream/dvbin.h"
115 #include "stream/cache2.h"
116 #endif
118 //**************************************************************************//
119 // Playtree
120 //**************************************************************************//
121 #include "playtree.h"
122 #include "playtreeparser.h"
124 //**************************************************************************//
125 // Config
126 //**************************************************************************//
127 #include "parser-cfg.h"
128 #include "parser-mpcmd.h"
130 //**************************************************************************//
131 // Config file
132 //**************************************************************************//
134 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
136 #include "get_path.h"
138 //**************************************************************************//
139 //**************************************************************************//
140 // Input media streaming & demultiplexer:
141 //**************************************************************************//
143 static int max_framesize=0;
145 #include "stream/stream.h"
146 #include "libmpdemux/demuxer.h"
147 #include "libmpdemux/stheader.h"
149 #ifdef CONFIG_DVDREAD
150 #include "stream/stream_dvd.h"
151 #endif
153 #ifdef CONFIG_DVDNAV
154 #include "stream/stream_dvdnav.h"
155 #endif
157 #include "libmpcodecs/dec_audio.h"
158 #include "libmpcodecs/dec_video.h"
159 #include "libmpcodecs/mp_image.h"
160 #include "libmpcodecs/vf.h"
161 #include "libmpcodecs/vd.h"
163 #include "mixer.h"
165 #include "mp_core.h"
166 #include "options.h"
167 #include "defaultopts.h"
169 #define Exit_SIGILL_RTCpuSel _(\
170 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
171 " It may be a bug in our new runtime CPU-detection code...\n"\
172 " Please read DOCS/HTML/en/bugreports.html.\n")
174 #define Exit_SIGILL _(\
175 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
176 " It usually happens when you run it on a CPU different than the one it was\n"\
177 " compiled/optimized for.\n"\
178 " Verify this!\n")
180 #define Exit_SIGSEGV_SIGFPE _(\
181 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
182 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
183 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
185 #define Exit_SIGCRASH _(\
186 "- MPlayer crashed. This shouldn't happen.\n"\
187 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
188 " gcc version. If you think it's MPlayer's fault, please read\n"\
189 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
190 " won't help unless you provide this information when reporting a possible bug.\n")
192 #define SystemTooSlow _("\n\n"\
193 " ************************************************\n"\
194 " **** Your system is too SLOW to play this! ****\n"\
195 " ************************************************\n\n"\
196 "Possible reasons, problems, workarounds:\n"\
197 "- Most common: broken/buggy _audio_ driver\n"\
198 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
199 " - Experiment with different values for -autosync, 30 is a good start.\n"\
200 "- Slow video output\n"\
201 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
202 "- Slow CPU\n"\
203 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
204 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
205 "- Broken file\n"\
206 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
207 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
208 " - Try -cache 8192.\n"\
209 "- Are you using -cache to play a non-interleaved AVI file?\n"\
210 " - Try -nocache.\n"\
211 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
212 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
215 //**************************************************************************//
216 //**************************************************************************//
218 // Common FIFO functions, and keyboard/event FIFO code
219 #include "mp_fifo.h"
220 int noconsolecontrols=0;
221 //**************************************************************************//
223 // benchmark:
224 double video_time_usage=0;
225 double vout_time_usage=0;
226 static double audio_time_usage=0;
227 static int total_time_usage_start=0;
228 static int total_frame_cnt=0;
229 static int drop_frame_cnt=0; // total number of dropped frames
230 int benchmark=0;
232 // options:
233 int auto_quality=0;
234 static int output_quality=0;
236 static int list_properties = 0;
238 int term_osd = 1;
239 static char* term_osd_esc = "\x1b[A\r\x1b[K";
240 static char* playing_msg = NULL;
241 // seek:
242 static double seek_to_sec;
243 static off_t seek_to_byte=0;
244 static off_t step_sec=0;
246 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
248 // A/V sync:
249 int autosync=0; // 30 might be a good default value.
251 // codecs:
252 char **audio_codec_list=NULL; // override audio codec
253 char **video_codec_list=NULL; // override video codec
254 char **audio_fm_list=NULL; // override audio codec family
255 char **video_fm_list=NULL; // override video codec family
257 // demuxer:
258 extern char *demuxer_name; // override demuxer
259 extern char *audio_demuxer_name; // override audio demuxer
260 extern char *sub_demuxer_name; // override sub demuxer
262 int vobsub_id=-1;
263 char* audio_lang=NULL;
264 char* dvdsub_lang=NULL;
265 static char* spudec_ifo=NULL;
266 int forced_subs_only=0;
267 int file_filter=1;
269 // cache2:
270 int stream_cache_size=-1;
271 #ifdef CONFIG_STREAM_CACHE
272 extern int cache_fill_status;
274 float stream_cache_min_percent=20.0;
275 float stream_cache_seek_min_percent=50.0;
276 #else
277 #define cache_fill_status 0
278 #endif
280 // dump:
281 static char *stream_dump_name="stream.dump";
282 int stream_dump_type=0;
284 // A-V sync:
285 static float default_max_pts_correction=-1;//0.01f;
286 float audio_delay=0;
287 static int ignore_start=0;
289 static int softsleep=0;
291 double force_fps=0;
292 static int force_srate=0;
293 static int audio_output_format=-1; // AF_FORMAT_UNKNOWN
294 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
295 static int play_n_frames=-1;
296 static int play_n_frames_mf=-1;
298 // sub:
299 char *font_name=NULL;
300 char *sub_font_name=NULL;
301 extern int font_fontconfig;
302 float font_factor=0.75;
303 char **sub_name=NULL;
304 float sub_delay=0;
305 float sub_fps=0;
306 int sub_auto = 1;
307 char *vobsub_name=NULL;
308 /*DSP!!char *dsp=NULL;*/
309 int subcc_enabled=0;
310 int suboverlap_enabled = 1;
312 #ifdef CONFIG_ASS
313 #include "libass/ass.h"
314 #include "libass/ass_mp.h"
315 #endif
317 char* current_module=NULL; // for debugging
320 // ---
322 #ifdef CONFIG_MENU
323 #include "m_struct.h"
324 #include "libmenu/menu.h"
325 void vf_menu_pause_update(struct vf_instance* vf);
326 extern vf_info_t vf_info_menu;
327 static const vf_info_t* const libmenu_vfs[] = {
328 &vf_info_menu,
329 NULL
331 static vf_instance_t* vf_menu = NULL;
332 int use_menu = 0;
333 static char* menu_cfg = NULL;
334 static char* menu_root = "main";
335 #endif
338 #ifdef HAVE_RTC
339 static int nortc = 1;
340 static char* rtc_device;
341 #endif
343 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
344 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
345 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
346 int use_filedir_conf;
348 #include "mpcommon.h"
349 #include "command.h"
351 #include "metadata.h"
353 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
355 const void *mpctx_get_video_out(MPContext *mpctx)
357 return mpctx->video_out;
360 const void *mpctx_get_audio_out(MPContext *mpctx)
362 return mpctx->audio_out;
365 void *mpctx_get_demuxer(MPContext *mpctx)
367 return mpctx->demuxer;
370 void *mpctx_get_playtree_iter(MPContext *mpctx)
372 return mpctx->playtree_iter;
375 void *mpctx_get_mixer(MPContext *mpctx)
377 return &mpctx->mixer;
380 int mpctx_get_global_sub_size(MPContext *mpctx)
382 return mpctx->global_sub_size;
385 int mpctx_get_osd_function(MPContext *mpctx)
387 return mpctx->osd_function;
390 static float get_relative_time(struct MPContext *mpctx)
392 unsigned int new_time = GetTimer();
393 unsigned int delta = new_time - mpctx->last_time;
394 mpctx->last_time = new_time;
395 return delta * 0.000001;
398 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
399 switch (type)
401 /* check for valid video stream */
402 case META_VIDEO_CODEC:
403 case META_VIDEO_BITRATE:
404 case META_VIDEO_RESOLUTION:
406 if (!mpctx->sh_video)
407 return 0;
408 break;
411 /* check for valid audio stream */
412 case META_AUDIO_CODEC:
413 case META_AUDIO_BITRATE:
414 case META_AUDIO_SAMPLES:
416 if (!mpctx->sh_audio)
417 return 0;
418 break;
421 /* check for valid demuxer */
422 case META_INFO_TITLE:
423 case META_INFO_ARTIST:
424 case META_INFO_ALBUM:
425 case META_INFO_YEAR:
426 case META_INFO_COMMENT:
427 case META_INFO_TRACK:
428 case META_INFO_GENRE:
430 if (!mpctx->demuxer)
431 return 0;
432 break;
435 default:
436 break;
439 return 1;
442 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
443 char **info = mpctx->demuxer->info;
444 int n;
446 if (!info || !tag)
447 return NULL;
449 for (n = 0; info[2*n] != NULL ; n++)
450 if (!strcasecmp (info[2*n], tag))
451 break;
453 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
456 char *get_metadata(struct MPContext *mpctx, metadata_t type)
458 char *meta = NULL;
459 sh_audio_t * const sh_audio = mpctx->sh_audio;
460 sh_video_t * const sh_video = mpctx->sh_video;
462 if (!is_valid_metadata_type(mpctx, type))
463 return NULL;
465 switch (type)
467 case META_NAME:
469 return strdup (mp_basename2 (mpctx->filename));
472 case META_VIDEO_CODEC:
474 if (sh_video->format == 0x10000001)
475 meta = strdup ("mpeg1");
476 else if (sh_video->format == 0x10000002)
477 meta = strdup ("mpeg2");
478 else if (sh_video->format == 0x10000004)
479 meta = strdup ("mpeg4");
480 else if (sh_video->format == 0x10000005)
481 meta = strdup ("h264");
482 else if (sh_video->format >= 0x20202020)
484 meta = malloc (8);
485 sprintf (meta, "%.4s", (char *) &sh_video->format);
487 else
489 meta = malloc (8);
490 sprintf (meta, "0x%08X", sh_video->format);
492 return meta;
495 case META_VIDEO_BITRATE:
497 meta = malloc (16);
498 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
499 return meta;
502 case META_VIDEO_RESOLUTION:
504 meta = malloc (16);
505 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
506 return meta;
509 case META_AUDIO_CODEC:
511 if (sh_audio->codec && sh_audio->codec->name)
512 meta = strdup (sh_audio->codec->name);
513 return meta;
516 case META_AUDIO_BITRATE:
518 meta = malloc (16);
519 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
520 return meta;
523 case META_AUDIO_SAMPLES:
525 meta = malloc (16);
526 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
527 return meta;
530 /* check for valid demuxer */
531 case META_INFO_TITLE:
532 return get_demuxer_info(mpctx, "Title");
534 case META_INFO_ARTIST:
535 return get_demuxer_info(mpctx, "Artist");
537 case META_INFO_ALBUM:
538 return get_demuxer_info(mpctx, "Album");
540 case META_INFO_YEAR:
541 return get_demuxer_info(mpctx, "Year");
543 case META_INFO_COMMENT:
544 return get_demuxer_info(mpctx, "Comment");
546 case META_INFO_TRACK:
547 return get_demuxer_info(mpctx, "Track");
549 case META_INFO_GENRE:
550 return get_demuxer_info(mpctx, "Genre");
552 default:
553 break;
556 return meta;
559 /// step size of mixer changes
560 int volstep = 3;
562 #ifdef CONFIG_DVDNAV
563 static void mp_dvdnav_context_free(MPContext *ctx){
564 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
565 ctx->nav_smpi = NULL;
566 if (ctx->nav_buffer) free(ctx->nav_buffer);
567 ctx->nav_buffer = NULL;
568 ctx->nav_start = NULL;
569 ctx->nav_in_size = 0;
571 #endif
573 void uninit_player(struct MPContext *mpctx, unsigned int mask){
574 mask=mpctx->initialized_flags&mask;
576 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
578 if(mask&INITIALIZED_ACODEC){
579 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
580 current_module="uninit_acodec";
581 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
582 mpctx->sh_audio=NULL;
583 mpctx->mixer.afilter = NULL;
586 if(mask&INITIALIZED_VCODEC){
587 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
588 current_module="uninit_vcodec";
589 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
590 mpctx->sh_video=NULL;
591 #ifdef CONFIG_MENU
592 vf_menu=NULL;
593 #endif
596 if(mask&INITIALIZED_DEMUXER){
597 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
598 current_module="free_demuxer";
599 if (mpctx->num_sources) {
600 mpctx->demuxer = mpctx->sources[0].demuxer;
601 for (int i = 1; i < mpctx->num_sources; i++) {
602 free_stream(mpctx->sources[i].stream);
603 free_demuxer(mpctx->sources[i].demuxer);
606 talloc_free(mpctx->sources);
607 mpctx->sources = NULL;
608 mpctx->num_sources = 0;
609 talloc_free(mpctx->timeline);
610 mpctx->timeline = NULL;
611 mpctx->num_timeline_parts = 0;
612 talloc_free(mpctx->chapters);
613 mpctx->chapters = NULL;
614 mpctx->num_chapters = 0;
615 mpctx->video_offset = 0;
616 if(mpctx->demuxer){
617 mpctx->stream=mpctx->demuxer->stream;
618 free_demuxer(mpctx->demuxer);
620 mpctx->demuxer=NULL;
623 // kill the cache process:
624 if(mask&INITIALIZED_STREAM){
625 mpctx->initialized_flags&=~INITIALIZED_STREAM;
626 current_module="uninit_stream";
627 if(mpctx->stream) free_stream(mpctx->stream);
628 mpctx->stream=NULL;
631 if(mask&INITIALIZED_VO){
632 mpctx->initialized_flags&=~INITIALIZED_VO;
633 current_module="uninit_vo";
634 vo_destroy(mpctx->video_out);
635 mpctx->video_out=NULL;
636 #ifdef CONFIG_DVDNAV
637 mp_dvdnav_context_free(mpctx);
638 #endif
641 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
642 if(mask&INITIALIZED_GETCH2){
643 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
644 current_module="uninit_getch2";
645 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
646 // restore terminal:
647 getch2_disable();
650 if(mask&INITIALIZED_VOBSUB){
651 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
652 current_module="uninit_vobsub";
653 if(vo_vobsub) vobsub_close(vo_vobsub);
654 vo_vobsub=NULL;
657 if (mask&INITIALIZED_SPUDEC){
658 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
659 current_module="uninit_spudec";
660 spudec_free(vo_spudec);
661 vo_spudec=NULL;
664 if(mask&INITIALIZED_AO){
665 mpctx->initialized_flags&=~INITIALIZED_AO;
666 current_module="uninit_ao";
667 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
668 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
669 mpctx->audio_out=NULL;
672 current_module=NULL;
675 void exit_player_with_rc(struct MPContext *mpctx, exit_reason_t how, int rc)
677 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
678 uninit_player(mpctx, INITIALIZED_ALL);
679 #if defined(__MINGW32__) || defined(__CYGWIN__)
680 timeEndPeriod(1);
681 #endif
682 #ifdef CONFIG_X11
683 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
684 #endif
686 current_module="uninit_input";
687 mp_input_uninit(mpctx->input);
688 #ifdef CONFIG_MENU
689 if (use_menu)
690 menu_uninit();
691 #endif
693 #ifdef CONFIG_FREETYPE
694 current_module="uninit_font";
695 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
696 free_font_desc(mpctx->osd->sub_font);
697 free_font_desc(vo_font);
698 vo_font = NULL;
699 done_freetype();
700 #endif
701 osd_free(mpctx->osd);
703 #ifdef CONFIG_ASS
704 ass_library_done(ass_library);
705 #endif
707 current_module="exit_player";
709 // free mplayer config
710 if(mpctx->mconfig)
711 m_config_free(mpctx->mconfig);
713 if(mpctx->playtree)
714 play_tree_free(mpctx->playtree, 1);
716 talloc_free(mpctx->key_fifo);
718 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
719 switch(how) {
720 case EXIT_QUIT:
721 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
722 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
723 break;
724 case EXIT_EOF:
725 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
726 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
727 break;
728 case EXIT_ERROR:
729 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
730 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
731 break;
732 default:
733 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
735 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
737 exit(rc);
740 static void exit_player(struct MPContext *mpctx, exit_reason_t how)
742 exit_player_with_rc(mpctx, how, 1);
745 #ifndef __MINGW32__
746 static void child_sighandler(int x){
747 pid_t pid;
748 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
750 #endif
752 #ifdef CONFIG_CRASH_DEBUG
753 static char *prog_path;
754 static int crash_debug = 0;
755 #endif
757 static void exit_sighandler(int x){
758 static int sig_count=0;
759 #ifdef CONFIG_CRASH_DEBUG
760 if (!crash_debug || x != SIGTRAP)
761 #endif
762 ++sig_count;
763 if(sig_count==5)
765 /* We're crashing bad and can't uninit cleanly :(
766 * by popular request, we make one last (dirty)
767 * effort to restore the user's
768 * terminal. */
769 getch2_disable();
770 exit(1);
772 if(sig_count==6) exit(1);
773 if(sig_count>6){
774 // can't stop :(
775 #ifndef __MINGW32__
776 kill(getpid(),SIGKILL);
777 #endif
779 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"\n" "\nMPlayer interrupted by signal %d in module: %s\n",x,
780 current_module?current_module:"unknown"
782 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
783 if(sig_count<=1)
784 switch(x){
785 case SIGINT:
786 case SIGQUIT:
787 case SIGTERM:
788 case SIGKILL:
789 async_quit_request = 1;
790 return; // killed from keyboard (^C) or killed [-9]
791 case SIGILL:
792 #if CONFIG_RUNTIME_CPUDETECT
793 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
794 #else
795 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
796 #endif
797 case SIGFPE:
798 case SIGSEGV:
799 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
800 default:
801 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
802 #ifdef CONFIG_CRASH_DEBUG
803 if (crash_debug) {
804 int gdb_pid;
805 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
806 gdb_pid = fork();
807 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
808 if (gdb_pid == 0) { // We are the child
809 char spid[20];
810 snprintf(spid, sizeof(spid), "%i", getppid());
811 getch2_disable(); // allow terminal to work properly with gdb
812 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
813 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
814 } else if (gdb_pid < 0)
815 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
816 else {
817 waitpid(gdb_pid, NULL, 0);
819 if (x == SIGTRAP) return;
821 #endif
823 getch2_disable();
824 exit(1);
827 #include "cfg-mplayer.h"
829 static int cfg_include(m_option_t *conf, char *filename)
831 return m_config_parse_config_file(conf->priv, filename);
834 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
836 char *conffile;
837 int conffile_fd;
838 if (!disable_system_conf &&
839 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
840 exit_player(mpctx, EXIT_NONE);
841 if ((conffile = get_path("")) == NULL) {
842 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
843 } else {
844 #ifdef __MINGW32__
845 mkdir(conffile);
846 #else
847 mkdir(conffile, 0777);
848 #endif
849 free(conffile);
850 if ((conffile = get_path("config")) == NULL) {
851 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
852 } else {
853 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
854 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
855 write(conffile_fd, default_config, strlen(default_config));
856 close(conffile_fd);
858 if (!disable_user_conf &&
859 m_config_parse_config_file(conf, conffile) < 0)
860 exit_player(mpctx, EXIT_NONE);
861 free(conffile);
866 #define PROFILE_CFG_PROTOCOL "protocol."
868 static void load_per_protocol_config (m_config_t* conf, const char *const file)
870 char *str;
871 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
872 m_profile_t *p;
874 /* does filename actually uses a protocol ? */
875 str = strstr (file, "://");
876 if (!str)
877 return;
879 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
880 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
881 p = m_config_get_profile (conf, protocol);
882 if (p)
884 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
885 m_config_set_profile(conf,p);
889 #define PROFILE_CFG_EXTENSION "extension."
891 static void load_per_extension_config (m_config_t* conf, const char *const file)
893 char *str;
894 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
895 m_profile_t *p;
897 /* does filename actually have an extension ? */
898 str = strrchr (file, '.');
899 if (!str)
900 return;
902 sprintf (extension, PROFILE_CFG_EXTENSION);
903 strncat (extension, ++str, 7);
904 p = m_config_get_profile (conf, extension);
905 if (p)
907 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
908 m_config_set_profile(conf,p);
912 #define PROFILE_CFG_VO "vo."
913 #define PROFILE_CFG_AO "ao."
915 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
917 char profile[strlen (cfg) + strlen (out) + 1];
918 m_profile_t *p;
920 sprintf (profile, "%s%s", cfg, out);
921 p = m_config_get_profile (conf, profile);
922 if (p)
924 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
925 m_config_set_profile(conf,p);
929 static void load_per_file_config (m_config_t* conf, const char *const file)
931 char *confpath;
932 char cfg[strlen(file)+10];
933 struct stat st;
934 char *name;
936 sprintf (cfg, "%s.conf", file);
938 if (use_filedir_conf && !stat (cfg, &st))
940 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading config '%s'\n", cfg);
941 m_config_parse_config_file (conf, cfg);
942 return;
945 if ((name = strrchr (cfg, '/')) == NULL)
946 name = cfg;
947 else
948 name++;
950 if ((confpath = get_path (name)) != NULL)
952 if (!stat (confpath, &st))
954 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading config '%s'\n", confpath);
955 m_config_parse_config_file (conf, confpath);
958 free (confpath);
962 /* When libmpdemux performs a blocking operation (network connection or
963 * cache filling) if the operation fails we use this function to check
964 * if it was interrupted by the user.
965 * The function returns a new value for eof. */
966 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
968 mp_cmd_t* cmd;
969 if((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
970 switch(cmd->id) {
971 case MP_CMD_QUIT:
972 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
973 case MP_CMD_PLAY_TREE_STEP: {
974 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
975 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
976 } break;
977 case MP_CMD_PLAY_TREE_UP_STEP: {
978 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
979 } break;
980 case MP_CMD_PLAY_ALT_SRC_STEP: {
981 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
982 } break;
984 mp_cmd_free(cmd);
986 return stop_play;
989 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
991 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
993 play_tree_add_bpf(entry,mpctx->filename);
996 if(!entry) {
997 entry = mpctx->playtree_iter->tree;
998 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
999 return PT_NEXT_ENTRY;
1001 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1002 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1003 return PT_NEXT_ENTRY;
1006 play_tree_remove(entry,1,1);
1007 return PT_NEXT_SRC;
1009 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1010 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1011 entry = mpctx->playtree_iter->tree;
1012 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1013 return PT_NEXT_ENTRY;
1015 play_tree_remove(entry,1,1);
1017 return PT_NEXT_SRC;
1020 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1022 sub_data *subd;
1023 #ifdef CONFIG_ASS
1024 ass_track_t *asst = 0;
1025 #endif
1027 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1028 return;
1031 subd = sub_read_file(filename, fps);
1032 #ifdef CONFIG_ASS
1033 if (ass_enabled)
1034 #ifdef CONFIG_ICONV
1035 asst = ass_read_file(ass_library, filename, sub_cp);
1036 #else
1037 asst = ass_read_file(ass_library, filename, 0);
1038 #endif
1039 if (ass_enabled && subd && !asst)
1040 asst = ass_read_subdata(ass_library, subd, fps);
1042 if (!asst && !subd)
1043 #else
1044 if(!subd)
1045 #endif
1046 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR, "Cannot load subtitles: %s\n",
1047 filename_recode(filename));
1049 #ifdef CONFIG_ASS
1050 if (!asst && !subd) return;
1051 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1052 #else
1053 if (!subd) return;
1054 #endif
1055 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1056 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1057 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1058 filename_recode(filename));
1059 ++mpctx->set_of_sub_size;
1060 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1061 filename_recode(filename));
1064 void init_vo_spudec(struct MPContext *mpctx)
1066 if (vo_spudec)
1067 spudec_free(vo_spudec);
1068 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1069 vo_spudec = NULL;
1070 if (spudec_ifo) {
1071 unsigned int palette[16], width, height;
1072 current_module="spudec_init_vobsub";
1073 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1074 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1077 #ifdef CONFIG_DVDREAD
1078 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1079 current_module="spudec_init_dvdread";
1080 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1081 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1082 NULL, 0);
1084 #endif
1086 #ifdef CONFIG_DVDNAV
1087 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1088 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1089 current_module="spudec_init_dvdnav";
1090 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1092 #endif
1094 if (vo_spudec==NULL) {
1095 sh_sub_t *sh = (sh_sub_t *)mpctx->d_sub->sh;
1096 current_module="spudec_init_normal";
1097 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1098 spudec_set_font_factor(vo_spudec,font_factor);
1101 if (vo_spudec!=NULL) {
1102 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1103 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1108 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1109 * make it all work is to use the builtin SDL-bootstrap code, which
1110 * will be done automatically by replacing our main() if we include SDL.h.
1112 #if defined(__APPLE__) && defined(CONFIG_SDL)
1113 #include <SDL.h>
1114 #endif
1117 * \brief append a formatted string
1118 * \param buf buffer to print into
1119 * \param pos position of terminating 0 in buf
1120 * \param len maximum number of characters in buf, not including terminating 0
1121 * \param format printf format string
1123 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1125 va_list va;
1126 va_start(va, format);
1127 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1128 va_end(va);
1129 if (*pos >= len ) {
1130 buf[len] = 0;
1131 *pos = len;
1136 * \brief append time in the hh:mm:ss.f format
1137 * \param buf buffer to print into
1138 * \param pos position of terminating 0 in buf
1139 * \param len maximum number of characters in buf, not including terminating 0
1140 * \param time time value to convert/append
1142 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1143 long tenths = 10 * time;
1144 int f1 = tenths % 10;
1145 int ss = (tenths / 10) % 60;
1146 int mm = (tenths / 600) % 60;
1147 int hh = tenths / 36000;
1148 if (time <= 0) {
1149 saddf(buf, pos, len, "unknown");
1150 return;
1152 if (hh > 0)
1153 saddf(buf, pos, len, "%2d:", hh);
1154 if (hh > 0 || mm > 0)
1155 saddf(buf, pos, len, "%02d:", mm);
1156 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1159 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1161 struct MPOpts *opts = &mpctx->opts;
1162 sh_video_t * const sh_video = mpctx->sh_video;
1164 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1165 a_pos = playing_audio_pts(mpctx);
1166 if (mpctx->sh_audio && sh_video && at_frame) {
1167 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1168 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1169 && !mpctx->drop_message_shown) {
1170 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1171 mpctx->drop_message_shown = true;
1174 if (quiet)
1175 return;
1178 int width;
1179 char *line;
1180 unsigned pos = 0;
1181 get_screen_size();
1182 if (screen_width > 0)
1183 width = screen_width;
1184 else
1185 width = 80;
1186 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1187 /* Windows command line is broken (MinGW's rxvt works, but we
1188 * should not depend on that). */
1189 width--;
1190 #endif
1191 line = malloc(width + 1); // one additional char for the terminating null
1193 // Audio time
1194 if (mpctx->sh_audio) {
1195 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1196 if (!sh_video) {
1197 float len = demuxer_get_time_length(mpctx->demuxer);
1198 saddf(line, &pos, width, "(");
1199 sadd_hhmmssf(line, &pos, width, a_pos);
1200 saddf(line, &pos, width, ") of %.1f (", len);
1201 sadd_hhmmssf(line, &pos, width, len);
1202 saddf(line, &pos, width, ") ");
1206 // Video time
1207 if (sh_video)
1208 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1210 // A-V sync
1211 if (mpctx->sh_audio && sh_video)
1212 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1213 mpctx->last_av_difference, mpctx->total_avsync_change);
1215 // Video stats
1216 if (sh_video)
1217 saddf(line, &pos, width, "%3d/%3d ",
1218 (int)sh_video->num_frames,
1219 (int)sh_video->num_frames_decoded);
1221 // CPU usage
1222 if (sh_video) {
1223 if (sh_video->timer > 0.5)
1224 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1225 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1226 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1227 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1228 else
1229 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1230 } else if (mpctx->sh_audio) {
1231 if (mpctx->delay > 0.5)
1232 saddf(line, &pos, width, "%4.1f%% ",
1233 100.0*audio_time_usage/(double)mpctx->delay);
1234 else
1235 saddf(line, &pos, width, "??,?%% ");
1238 // VO stats
1239 if (sh_video)
1240 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1242 #ifdef CONFIG_STREAM_CACHE
1243 // cache stats
1244 if (stream_cache_size > 0)
1245 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1246 #endif
1248 // other
1249 if (opts->playback_speed != 1)
1250 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1252 // end
1253 if (erase_to_end_of_line) {
1254 line[pos] = 0;
1255 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1256 } else {
1257 memset(&line[pos], ' ', width - pos);
1258 line[width] = 0;
1259 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1261 free(line);
1265 * \brief build a chain of audio filters that converts the input format
1266 * to the ao's format, taking into account the current playback_speed.
1267 * \param sh_audio describes the requested input format of the chain.
1268 * \param ao_data describes the requested output format of the chain.
1270 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1272 struct MPOpts *opts = &mpctx->opts;
1273 int new_srate;
1274 int result;
1275 if (!sh_audio)
1277 mpctx->mixer.afilter = NULL;
1278 return 0;
1280 if(af_control_any_rev(sh_audio->afilter,
1281 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1282 &opts->playback_speed)) {
1283 new_srate = sh_audio->samplerate;
1284 } else {
1285 new_srate = sh_audio->samplerate * opts->playback_speed;
1286 if (new_srate != ao_data->samplerate) {
1287 // limits are taken from libaf/af_resample.c
1288 if (new_srate < 8000)
1289 new_srate = 8000;
1290 if (new_srate > 192000)
1291 new_srate = 192000;
1292 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1295 result = init_audio_filters(sh_audio, new_srate,
1296 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1297 mpctx->mixer.afilter = sh_audio->afilter;
1298 return result;
1302 typedef struct mp_osd_msg mp_osd_msg_t;
1303 struct mp_osd_msg {
1304 /// Previous message on the stack.
1305 mp_osd_msg_t* prev;
1306 /// Message text.
1307 char msg[128];
1308 int id,level,started;
1309 /// Display duration in ms.
1310 unsigned time;
1313 /// OSD message stack.
1314 static mp_osd_msg_t* osd_msg_stack = NULL;
1317 * \brief Add a message on the OSD message stack
1319 * If a message with the same id is already present in the stack
1320 * it is pulled on top of the stack, otherwise a new message is created.
1324 void set_osd_msg(int id, int level, int time, const char* fmt, ...) {
1325 mp_osd_msg_t *msg,*last=NULL;
1326 va_list va;
1327 int r;
1329 // look if the id is already in the stack
1330 for(msg = osd_msg_stack ; msg && msg->id != id ;
1331 last = msg, msg = msg->prev);
1332 // not found: alloc it
1333 if(!msg) {
1334 msg = calloc(1,sizeof(mp_osd_msg_t));
1335 msg->prev = osd_msg_stack;
1336 osd_msg_stack = msg;
1337 } else if(last) { // found, but it's not on top of the stack
1338 last->prev = msg->prev;
1339 msg->prev = osd_msg_stack;
1340 osd_msg_stack = msg;
1342 // write the msg
1343 va_start(va,fmt);
1344 r = vsnprintf(msg->msg, 128, fmt, va);
1345 va_end(va);
1346 if(r >= 128) msg->msg[127] = 0;
1347 // set id and time
1348 msg->id = id;
1349 msg->level = level;
1350 msg->time = time;
1355 * \brief Remove a message from the OSD stack
1357 * This function can be used to get rid of a message right away.
1361 void rm_osd_msg(int id) {
1362 mp_osd_msg_t *msg,*last=NULL;
1364 // Search for the msg
1365 for(msg = osd_msg_stack ; msg && msg->id != id ;
1366 last = msg, msg = msg->prev);
1367 if(!msg) return;
1369 // Detach it from the stack and free it
1370 if(last)
1371 last->prev = msg->prev;
1372 else
1373 osd_msg_stack = msg->prev;
1374 free(msg);
1378 * \brief Remove all messages from the OSD stack
1382 static void clear_osd_msgs(void) {
1383 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1384 while(msg) {
1385 prev = msg->prev;
1386 free(msg);
1387 msg = prev;
1389 osd_msg_stack = NULL;
1393 * \brief Get the current message from the OSD stack.
1395 * This function decrements the message timer and destroys the old ones.
1396 * The message that should be displayed is returned (if any).
1400 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1402 struct MPOpts *opts = &mpctx->opts;
1403 mp_osd_msg_t *msg,*prev,*last = NULL;
1404 static unsigned last_update = 0;
1405 unsigned now = GetTimerMS();
1406 unsigned diff;
1407 char hidden_dec_done = 0;
1409 if (mpctx->osd_visible) {
1410 // 36000000 means max timed visibility is 1 hour into the future, if
1411 // the difference is greater assume it's wrapped around from below 0
1412 if (mpctx->osd_visible - now > 36000000) {
1413 mpctx->osd_visible = 0;
1414 vo_osd_progbar_type = -1; // disable
1415 vo_osd_changed(OSDTYPE_PROGBAR);
1416 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1419 if (mpctx->osd_show_percentage_until - now > 36000000)
1420 mpctx->osd_show_percentage_until = 0;
1422 if(!last_update) last_update = now;
1423 diff = now >= last_update ? now - last_update : 0;
1425 last_update = now;
1427 // Look for the first message in the stack with high enough level.
1428 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1429 prev = msg->prev;
1430 if (msg->level > opts->osd_level && hidden_dec_done)
1431 continue;
1432 // The message has a high enough level or it is the first hidden one
1433 // in both cases we decrement the timer or kill it.
1434 if(!msg->started || msg->time > diff) {
1435 if(msg->started) msg->time -= diff;
1436 else msg->started = 1;
1437 // display it
1438 if (msg->level <= opts->osd_level)
1439 return msg;
1440 hidden_dec_done = 1;
1441 continue;
1443 // kill the message
1444 free(msg);
1445 if(last) {
1446 last->prev = prev;
1447 msg = last;
1448 } else {
1449 osd_msg_stack = prev;
1450 msg = NULL;
1453 // Nothing found
1454 return NULL;
1458 * \brief Display the OSD bar.
1460 * Display the OSD bar or fall back on a simple message.
1464 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1465 struct MPOpts *opts = &mpctx->opts;
1466 if (opts->osd_level < 1)
1467 return;
1469 if(mpctx->sh_video) {
1470 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1471 vo_osd_progbar_type = type;
1472 vo_osd_progbar_value = 256*(val-min)/(max-min);
1473 vo_osd_changed(OSDTYPE_PROGBAR);
1474 return;
1477 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1478 name, ROUND(100*(val-min)/(max-min)));
1483 * \brief Update the OSD message line.
1485 * This function displays the current message on the vo OSD or on the term.
1486 * If the stack is empty and the OSD level is high enough the timer
1487 * is displayed (only on the vo OSD).
1491 static void update_osd_msg(struct MPContext *mpctx)
1493 struct MPOpts *opts = &mpctx->opts;
1494 mp_osd_msg_t *msg;
1495 struct osd_state *osd = mpctx->osd;
1496 char osd_text_timer[128];
1498 if (mpctx->add_osd_seek_info) {
1499 double percentage;
1500 if (mpctx->timeline && mpctx->sh_video)
1501 percentage = mpctx->sh_video->pts * 100 /
1502 mpctx->timeline[mpctx->num_timeline_parts].start;
1503 else
1504 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1505 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1506 if (mpctx->sh_video)
1507 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1508 mpctx->add_osd_seek_info = false;
1511 // Look if we have a msg
1512 if((msg = get_osd_msg(mpctx))) {
1513 if (strcmp(osd->osd_text, msg->msg)) {
1514 strncpy(osd->osd_text, msg->msg, 127);
1515 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1516 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1518 return;
1521 if(mpctx->sh_video) {
1522 // fallback on the timer
1523 if (opts->osd_level >= 2) {
1524 int len;
1525 if (mpctx->timeline)
1526 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1527 else
1528 len = demuxer_get_time_length(mpctx->demuxer);
1529 int percentage = -1;
1530 char percentage_text[10];
1531 int pts = demuxer_get_current_time(mpctx->demuxer);
1533 if (mpctx->osd_show_percentage_until)
1534 if (mpctx->timeline)
1535 percentage = mpctx->sh_video->pts * 100 /
1536 mpctx->timeline[mpctx->num_timeline_parts].start;
1537 else
1538 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1540 if (percentage >= 0)
1541 snprintf(percentage_text, 9, " (%d%%)", percentage);
1542 else
1543 percentage_text[0] = 0;
1545 if (opts->osd_level == 3)
1546 snprintf(osd_text_timer, 63,
1547 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1548 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1549 len/3600,(len/60)%60,len%60,percentage_text);
1550 else
1551 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1552 mpctx->osd_function,pts/3600,(pts/60)%60,
1553 pts%60,percentage_text);
1554 } else
1555 osd_text_timer[0]=0;
1557 if (strcmp(osd->osd_text, osd_text_timer)) {
1558 strncpy(osd->osd_text, osd_text_timer, 63);
1559 vo_osd_changed(OSDTYPE_OSD);
1561 return;
1564 // Clear the term osd line
1565 if (term_osd && osd->osd_text[0]) {
1566 osd->osd_text[0] = 0;
1567 printf("%s\n",term_osd_esc);
1571 ///@}
1572 // OSDMsgStack
1575 void reinit_audio_chain(struct MPContext *mpctx)
1577 struct MPOpts *opts = &mpctx->opts;
1578 if(mpctx->sh_audio){
1579 current_module="init_audio_codec";
1580 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1581 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1582 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // failed to init :(
1583 mpctx->d_audio->id = -2;
1584 return;
1585 } else
1586 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1587 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1590 //const ao_info_t *info=audio_out->info;
1591 current_module="af_preinit";
1592 ao_data.samplerate=force_srate;
1593 ao_data.channels=0;
1594 ao_data.format=audio_output_format;
1595 #if 1
1596 // first init to detect best values
1597 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1598 // input:
1599 mpctx->sh_audio->samplerate,
1600 // output:
1601 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1602 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Error at audio filter chain pre-init!\n");
1603 exit_player(mpctx, EXIT_ERROR);
1605 #endif
1606 current_module="ao2_init";
1607 if(!(mpctx->audio_out=init_best_audio_out(opts->audio_driver_list,
1608 0, // plugin flag
1609 ao_data.samplerate,
1610 ao_data.channels,
1611 ao_data.format,0))){
1612 // FAILED:
1613 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1614 uninit_player(mpctx, INITIALIZED_ACODEC); // close codec
1615 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1616 mpctx->d_audio->id = -2;
1617 return;
1618 } else {
1619 // SUCCESS:
1620 mpctx->initialized_flags|=INITIALIZED_AO;
1621 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1622 mpctx->audio_out->info->short_name,
1623 ao_data.samplerate, ao_data.channels,
1624 af_fmt2str_short(ao_data.format),
1625 af_fmt2bits(ao_data.format)/8 );
1626 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1627 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1628 if(strlen(mpctx->audio_out->info->comment) > 0)
1629 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1630 // init audio filters:
1631 #if 1
1632 current_module="af_init";
1633 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1634 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1635 // mp_msg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter / ao format! -> NOSOUND\n");
1636 // uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec & ao
1637 // sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1639 #endif
1641 mpctx->mixer.audio_out = mpctx->audio_out;
1642 mpctx->mixer.volstep = volstep;
1647 ///@}
1648 // Command2Property
1651 // Return pts value corresponding to the end point of audio written to the
1652 // ao so far.
1653 static double written_audio_pts(struct MPContext *mpctx)
1655 sh_audio_t *sh_audio = mpctx->sh_audio;
1656 demux_stream_t *d_audio = mpctx->d_audio;
1657 double buffered_output;
1658 // first calculate the end pts of audio that has been output by decoder
1659 double a_pts = sh_audio->pts;
1660 if (a_pts != MP_NOPTS_VALUE)
1661 // Good, decoder supports new way of calculating audio pts.
1662 // sh_audio->pts is the timestamp of the latest input packet with
1663 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1664 // the amount of bytes the decoder has written after that timestamp.
1665 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1666 else {
1667 // Decoder doesn't support new way of calculating pts (or we're
1668 // being called before it has decoded anything with known timestamp).
1669 // Use the old method of audio pts calculation: take the timestamp
1670 // of last packet with known pts the decoder has read data from,
1671 // and add amount of bytes read after the beginning of that packet
1672 // divided by input bps. This will be inaccurate if the input/output
1673 // ratio is not constant for every audio packet or if it is constant
1674 // but not accurately known in sh_audio->i_bps.
1676 a_pts = d_audio->pts;
1677 // ds_tell_pts returns bytes read after last timestamp from
1678 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1679 // it has read but not decoded
1680 if (sh_audio->i_bps)
1681 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1682 (double)sh_audio->i_bps;
1684 // Now a_pts hopefully holds the pts for end of audio from decoder.
1685 // Substract data in buffers between decoder and audio out.
1687 // Decoded but not filtered
1688 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1690 // Data buffered in audio filters, measured in bytes of "missing" output
1691 buffered_output = af_calc_delay(sh_audio->afilter);
1693 // Data that was ready for ao but was buffered because ao didn't fully
1694 // accept everything to internal buffers yet
1695 buffered_output += sh_audio->a_out_buffer_len;
1697 // Filters divide audio length by playback_speed, so multiply by it
1698 // to get the length in original units without speedup or slowdown
1699 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1701 return a_pts + mpctx->video_offset;
1704 // Return pts value corresponding to currently playing audio.
1705 double playing_audio_pts(struct MPContext *mpctx)
1707 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1708 mpctx->audio_out->get_delay();
1711 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1712 struct MPOpts *opts = &mpctx->opts;
1713 // check for frame-drop:
1714 current_module = "check_framedrop";
1715 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1716 static int dropped_frames;
1717 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1718 float d = delay-mpctx->delay;
1719 ++total_frame_cnt;
1720 // we should avoid dropping too many frames in sequence unless we
1721 // are too late. and we allow 100ms A-V delay here:
1722 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1723 && !mpctx->update_video_immediately) {
1724 ++drop_frame_cnt;
1725 ++dropped_frames;
1726 return frame_dropping;
1727 } else
1728 dropped_frames = 0;
1730 return 0;
1734 #ifdef HAVE_RTC
1735 int rtc_fd = -1;
1736 #endif
1738 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1740 #ifdef HAVE_RTC
1741 if (rtc_fd >= 0){
1742 // -------- RTC -----------
1743 current_module="sleep_rtc";
1744 while (time_frame > 0.000) {
1745 unsigned long rtc_ts;
1746 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1747 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1748 time_frame -= get_relative_time(mpctx);
1750 } else
1751 #endif
1753 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1754 // unnecessarily high CPU usage
1755 float margin = softsleep ? 0.011 : 0;
1756 current_module = "sleep_timer";
1757 while (time_frame > margin) {
1758 usec_sleep(1000000 * (time_frame - margin));
1759 time_frame -= get_relative_time(mpctx);
1761 if (softsleep){
1762 current_module = "sleep_soft";
1763 if (time_frame < 0)
1764 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1765 while (time_frame > 0)
1766 time_frame -= get_relative_time(mpctx); // burn the CPU
1769 return time_frame;
1772 #ifdef CONFIG_DVDNAV
1773 #ifndef FF_B_TYPE
1774 #define FF_B_TYPE 3
1775 #endif
1776 /// store decoded video image
1777 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1778 mp_image_t *from_mpi) {
1779 mp_image_t *mpi;
1781 /// Do not store B-frames
1782 if (from_mpi->pict_type == FF_B_TYPE)
1783 return to_mpi;
1785 if (to_mpi &&
1786 to_mpi->w == from_mpi->w &&
1787 to_mpi->h == from_mpi->h &&
1788 to_mpi->imgfmt == from_mpi->imgfmt)
1789 mpi = to_mpi;
1790 else {
1791 if (to_mpi)
1792 free_mp_image(to_mpi);
1793 if (from_mpi->w == 0 || from_mpi->h == 0)
1794 return NULL;
1795 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1798 copy_mpi(mpi,from_mpi);
1799 return mpi;
1802 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1803 struct MPOpts *opts = &ctx->opts;
1804 if (ctx->sh_video) {
1805 /// clear video pts
1806 ctx->d_video->pts = 0.0f;
1807 ctx->sh_video->pts = 0.0f;
1808 ctx->sh_video->i_pts = 0.0f;
1809 ctx->sh_video->last_pts = 0.0f;
1810 ctx->sh_video->num_buffered_pts = 0;
1811 ctx->sh_video->num_frames = 0;
1812 ctx->sh_video->num_frames_decoded = 0;
1813 ctx->sh_video->timer = 0.0f;
1814 ctx->sh_video->stream_delay = 0.0f;
1815 ctx->sh_video->timer = 0;
1816 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1819 if (ctx->sh_audio) {
1820 /// free audio packets and reset
1821 ds_free_packs(ctx->d_audio);
1822 audio_delay -= ctx->sh_audio->stream_delay;
1823 ctx->delay =- audio_delay;
1824 ctx->audio_out->reset();
1825 resync_audio_stream(ctx->sh_audio);
1828 if (ctx->d_sub) opts->sub_id = -2;
1830 audio_delay = 0.0f;
1832 /// clear all EOF related flags
1833 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1836 /// Restore last decoded DVDNAV (still frame)
1837 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
1838 int *in_size,
1839 unsigned char **start,
1840 mp_image_t *decoded_frame)
1842 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1843 return decoded_frame;
1845 /// a change occured in dvdnav stream
1846 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
1847 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
1848 mp_dvdnav_context_free(mpctx);
1849 mp_dvdnav_reset_stream(mpctx);
1850 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
1851 mp_dvdnav_cell_has_changed(mpctx->stream,1);
1854 if (*in_size < 0) {
1855 float len;
1857 /// Display still frame, if any
1858 if (mpctx->nav_smpi && !mpctx->nav_buffer)
1859 decoded_frame = mpctx->nav_smpi;
1861 /// increment video frame : continue playing after still frame
1862 len = demuxer_get_time_length(mpctx->demuxer);
1863 if (mpctx->sh_video->pts >= len &&
1864 mpctx->sh_video->pts > 0.0 && len > 0.0) {
1865 mp_dvdnav_skip_still(mpctx->stream);
1866 mp_dvdnav_skip_wait(mpctx->stream);
1868 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
1870 if (mpctx->nav_buffer) {
1871 *start = mpctx->nav_start;
1872 *in_size = mpctx->nav_in_size;
1873 if (mpctx->nav_start)
1874 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
1878 return decoded_frame;
1881 /// Save last decoded DVDNAV (still frame)
1882 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
1883 unsigned char *start,
1884 mp_image_t *decoded_frame)
1886 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1887 return;
1889 if (mpctx->nav_buffer)
1890 free(mpctx->nav_buffer);
1892 mpctx->nav_buffer = malloc(in_size);
1893 mpctx->nav_start = start;
1894 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
1895 if (mpctx->nav_buffer)
1896 memcpy(mpctx->nav_buffer,start,in_size);
1898 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
1899 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
1901 #endif /* CONFIG_DVDNAV */
1903 /* Modify video timing to match the audio timeline. There are two main
1904 * reasons this is needed. First, video and audio can start from different
1905 * positions at beginning of file or after a seek (MPlayer starts both
1906 * immediately even if they have different pts). Second, the file can have
1907 * audio timestamps that are inconsistent with the duration of the audio
1908 * packets, for example two consecutive timestamp values differing by
1909 * one second but only a packet with enough samples for half a second
1910 * of playback between them.
1912 static void adjust_sync(struct MPContext *mpctx, double frame_time)
1914 struct MPOpts *opts = &mpctx->opts;
1915 current_module = "av_sync";
1917 if (!mpctx->sh_audio)
1918 return;
1920 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
1921 double v_pts = mpctx->sh_video->pts;
1922 double av_delay = a_pts - v_pts;
1923 // Try to sync vo_flip() so it will *finish* at given time
1924 av_delay += mpctx->last_vo_flip_duration;
1925 av_delay -= audio_delay; // This much pts difference is desired
1927 double change = av_delay * 0.1;
1928 double max_change = default_max_pts_correction >= 0 ?
1929 default_max_pts_correction : frame_time * 0.1;
1930 if (change < -max_change)
1931 change = -max_change;
1932 else if (change > max_change)
1933 change = max_change;
1934 mpctx->delay += change;
1935 mpctx->total_avsync_change += change;
1938 static int fill_audio_out_buffers(struct MPContext *mpctx)
1940 struct MPOpts *opts = &mpctx->opts;
1941 unsigned int t;
1942 double tt;
1943 int playsize;
1944 int playflags=0;
1945 int audio_eof=0;
1946 int bytes_to_write;
1947 sh_audio_t * const sh_audio = mpctx->sh_audio;
1949 current_module="play_audio";
1951 while (1) {
1952 int sleep_time;
1953 // all the current uses of ao_data.pts seem to be in aos that handle
1954 // sync completely wrong; there should be no need to use ao_data.pts
1955 // in get_space()
1956 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
1957 bytes_to_write = mpctx->audio_out->get_space();
1958 if (mpctx->sh_video || bytes_to_write >= ao_data.outburst)
1959 break;
1961 // handle audio-only case:
1962 // this is where mplayer sleeps during audio-only playback
1963 // to avoid 100% CPU use
1964 sleep_time = (ao_data.outburst - bytes_to_write) * 1000 / ao_data.bps;
1965 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
1966 usec_sleep(sleep_time * 1000);
1969 while (bytes_to_write) {
1970 playsize = bytes_to_write;
1971 if (playsize > MAX_OUTBURST)
1972 playsize = MAX_OUTBURST;
1973 bytes_to_write -= playsize;
1975 // Fill buffer if needed:
1976 current_module="decode_audio";
1977 t = GetTimer();
1978 if (decode_audio(sh_audio, playsize) < 0) // EOF or error
1979 if (mpctx->d_audio->eof) {
1980 audio_eof = 1;
1981 if (sh_audio->a_out_buffer_len == 0)
1982 return 0;
1984 t = GetTimer() - t;
1985 tt = t*0.000001f; audio_time_usage+=tt;
1986 if (playsize > sh_audio->a_out_buffer_len) {
1987 playsize = sh_audio->a_out_buffer_len;
1988 if (audio_eof)
1989 playflags |= AOPLAY_FINAL_CHUNK;
1991 if (!playsize)
1992 break;
1994 // play audio:
1995 current_module="play_audio";
1997 // Is this pts value actually useful for the aos that access it?
1998 // They're obviously badly broken in the way they handle av sync;
1999 // would not having access to this make them more broken?
2000 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2001 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2003 if (playsize > 0) {
2004 sh_audio->a_out_buffer_len -= playsize;
2005 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2006 sh_audio->a_out_buffer_len);
2007 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2009 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2010 // Sanity check to avoid hanging in case current ao doesn't output
2011 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2012 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2013 sh_audio->a_out_buffer_len = 0;
2016 return 1;
2019 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2020 float *aq_sleep_time)
2022 struct MPOpts *opts = &mpctx->opts;
2023 int frame_time_remaining = 0;
2024 current_module="calc_sleep_time";
2026 *time_frame -= get_relative_time(mpctx); // reset timer
2028 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2029 float delay = mpctx->audio_out->get_delay();
2030 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2032 if (autosync) {
2034 * Adjust this raw delay value by calculating the expected
2035 * delay for this frame and generating a new value which is
2036 * weighted between the two. The higher autosync is, the
2037 * closer to the delay value gets to that which "-nosound"
2038 * would have used, and the longer it will take for A/V
2039 * sync to settle at the right value (but it eventually will.)
2040 * This settling time is very short for values below 100.
2042 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2043 float difference = delay - predicted;
2044 delay = predicted + difference / (float)autosync;
2047 *time_frame = delay - mpctx->delay / opts->playback_speed;
2049 // delay = amount of audio buffered in soundcard/driver
2050 if (delay > 0.25) delay=0.25; else
2051 if (delay < 0.10) delay=0.10;
2052 if (*time_frame > delay*0.6) {
2053 // sleep time too big - may cause audio drops (buffer underrun)
2054 frame_time_remaining = 1;
2055 *time_frame = delay*0.5;
2057 } else {
2058 // If we're lagging more than 200 ms behind the right playback rate,
2059 // don't try to "catch up".
2060 // If benchmark is set always output frames as fast as possible
2061 // without sleeping.
2062 if (*time_frame < -0.2 || benchmark)
2063 *time_frame = 0;
2066 *aq_sleep_time += *time_frame;
2069 //============================== SLEEP: ===================================
2071 // flag 256 means: libvo driver does its timing (dvb card)
2072 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2073 *time_frame = timing_sleep(mpctx, *time_frame);
2074 return frame_time_remaining;
2077 int reinit_video_chain(struct MPContext *mpctx)
2079 struct MPOpts *opts = &mpctx->opts;
2080 sh_video_t * const sh_video = mpctx->sh_video;
2081 double ar=-1.0;
2082 //================== Init VIDEO (codec & libvo) ==========================
2083 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2084 current_module="preinit_libvo";
2086 //shouldn't we set dvideo->id=-2 when we fail?
2087 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2088 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2089 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2090 goto err_out;
2092 mpctx->initialized_flags|=INITIALIZED_VO;
2095 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2096 mpctx->sh_video->stream_aspect = ar;
2097 current_module="init_video_filters";
2099 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2100 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2102 #ifdef CONFIG_MENU
2103 if(use_menu) {
2104 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2105 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2106 if(!vf_menu) {
2107 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2108 use_menu = 0;
2111 if(vf_menu)
2112 sh_video->vfilter = vf_menu;
2113 #endif
2115 #ifdef CONFIG_ASS
2116 if(ass_enabled) {
2117 int i;
2118 int insert = 1;
2119 if (opts->vf_settings)
2120 for (i = 0; opts->vf_settings[i].name; ++i)
2121 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2122 insert = 0;
2123 break;
2125 if (insert) {
2126 extern vf_info_t vf_info_ass;
2127 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2128 char* vf_arg[] = {"auto", "1", NULL};
2129 vf_instance_t* vf_ass = vf_open_plugin(opts, libass_vfs,sh_video->vfilter,"ass",vf_arg);
2130 if (vf_ass)
2131 sh_video->vfilter = vf_ass;
2132 else
2133 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2136 #endif
2138 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2140 #ifdef CONFIG_ASS
2141 if (ass_enabled)
2142 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2143 #endif
2145 current_module="init_video_codec";
2147 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2148 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2149 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2151 if(!sh_video->initialized){
2152 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2153 goto err_out;
2156 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2158 if (sh_video->codec)
2159 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2161 sh_video->last_pts = MP_NOPTS_VALUE;
2162 sh_video->num_buffered_pts = 0;
2163 sh_video->next_frame_time = 0;
2165 if(auto_quality>0){
2166 // Auto quality option enabled
2167 output_quality=get_video_quality_max(sh_video);
2168 if(auto_quality>output_quality) auto_quality=output_quality;
2169 else output_quality=auto_quality;
2170 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2171 set_video_quality(sh_video,output_quality);
2174 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2176 current_module="init_vo";
2178 return 1;
2180 err_out:
2181 mpctx->sh_video = mpctx->d_video->sh = NULL;
2182 return 0;
2185 static double update_video_nocorrect_pts(struct MPContext *mpctx,
2186 int *blit_frame)
2188 struct sh_video *sh_video = mpctx->sh_video;
2189 *blit_frame = 0;
2190 double frame_time = 0;
2191 while (1) {
2192 current_module = "filter_video";
2193 // In nocorrect-pts mode there is no way to properly time these frames
2194 if (vf_output_queued_frame(sh_video->vfilter))
2195 break;
2196 unsigned char *packet = NULL;
2197 frame_time = sh_video->next_frame_time;
2198 if (mpctx->update_video_immediately)
2199 frame_time = 0;
2200 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2201 &packet, force_fps);
2202 if (in_size < 0) {
2203 #ifdef CONFIG_DVDNAV
2204 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2205 if (mp_dvdnav_is_eof(mpctx->stream))
2206 return -1;
2207 if (mpctx->d_video)
2208 mpctx->d_video->eof = 0;
2209 if (mpctx->d_audio)
2210 mpctx->d_audio->eof = 0;
2211 mpctx->stream->eof = 0;
2212 } else
2213 #endif
2214 return -1;
2216 if (in_size > max_framesize)
2217 max_framesize = in_size;
2218 sh_video->timer += frame_time;
2219 if (mpctx->sh_audio)
2220 mpctx->delay -= frame_time;
2221 // video_read_frame can change fps (e.g. for ASF video)
2222 vo_fps = sh_video->fps;
2223 int framedrop_type = check_framedrop(mpctx, frame_time);
2224 current_module = "decode video";
2226 void *decoded_frame;
2227 #ifdef CONFIG_DVDNAV
2228 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2229 if (in_size >= 0 && !decoded_frame)
2230 #endif
2231 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2232 sh_video->pts);
2233 #ifdef CONFIG_DVDNAV
2234 // Save last still frame for future display
2235 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2236 #endif
2237 if (decoded_frame) {
2238 // These updates are done here for vf_expand OSD/subtitles
2239 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2240 update_teletext(sh_video, mpctx->demuxer, 0);
2241 update_osd_msg(mpctx);
2242 current_module = "filter video";
2243 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2244 break;
2247 *blit_frame = 1;
2248 return frame_time;
2251 static double update_video(struct MPContext *mpctx, int *blit_frame)
2253 struct sh_video *sh_video = mpctx->sh_video;
2254 *blit_frame = 0;
2255 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2256 mpctx->osd); // hack for vf_expand
2257 if (!mpctx->opts.correct_pts)
2258 return update_video_nocorrect_pts(mpctx, blit_frame);
2260 double pts;
2262 while (1) {
2263 current_module = "filter_video";
2264 // XXX Time used in this call is not counted in any performance
2265 // timer now, OSD time is not updated correctly for filter-added frames
2266 if (vf_output_queued_frame(sh_video->vfilter))
2267 break;
2268 unsigned char *packet = NULL;
2269 bool hit_eof = false;
2270 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2271 if (pts != MP_NOPTS_VALUE)
2272 pts += mpctx->video_offset;
2273 if (in_size < 0) {
2274 // try to extract last frames in case of decoder lag
2275 in_size = 0;
2276 pts = 1e300;
2277 hit_eof = true;
2279 if (in_size > max_framesize)
2280 max_framesize = in_size;
2281 current_module = "decode video";
2282 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2283 void *decoded_frame = decode_video(sh_video, packet, in_size,
2284 framedrop_type, pts);
2285 if (decoded_frame) {
2286 // These updates are done here for vf_expand OSD/subtitles
2287 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2288 update_teletext(sh_video, mpctx->demuxer, 0);
2289 update_osd_msg(mpctx);
2290 current_module = "filter video";
2291 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2292 break;
2293 } else if (hit_eof)
2294 return -1;
2297 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_GET_PTS, &pts);
2298 if (pts == MP_NOPTS_VALUE) {
2299 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2300 // Try to use decoder pts from before filters
2301 pts = sh_video->pts;
2302 if (pts == MP_NOPTS_VALUE)
2303 pts = sh_video->last_pts;
2305 sh_video->pts = pts;
2306 if (sh_video->last_pts == MP_NOPTS_VALUE)
2307 sh_video->last_pts = sh_video->pts;
2308 else if (sh_video->last_pts > sh_video->pts) {
2309 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2310 sh_video->pts, sh_video->last_pts);
2311 /* If the difference in pts is small treat it as jitter around the
2312 * right value (possibly caused by incorrect timestamp ordering) and
2313 * just show this frame immediately after the last one.
2314 * Treat bigger differences as timestamp resets and start counting
2315 * timing of later frames from the position of this one. */
2316 if (sh_video->last_pts - sh_video->pts > 0.5)
2317 sh_video->last_pts = sh_video->pts;
2318 else
2319 sh_video->pts = sh_video->last_pts;
2321 double frame_time = sh_video->pts - sh_video->last_pts;
2322 sh_video->last_pts = sh_video->pts;
2323 sh_video->timer += frame_time;
2324 if (mpctx->sh_audio)
2325 mpctx->delay -= frame_time;
2326 *blit_frame = 1;
2327 return frame_time;
2330 void pause_player(struct MPContext *mpctx)
2332 if (mpctx->paused)
2333 return;
2334 mpctx->paused = 1;
2335 mpctx->step_frames = 0;
2336 mpctx->time_frame -= get_relative_time(mpctx);
2338 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2339 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2341 if (mpctx->audio_out && mpctx->sh_audio)
2342 mpctx->audio_out->pause(); // pause audio, keep data if possible
2345 void unpause_player(struct MPContext *mpctx)
2347 if (!mpctx->paused)
2348 return;
2349 mpctx->paused = 0;
2351 if (mpctx->audio_out && mpctx->sh_audio)
2352 mpctx->audio_out->resume(); // resume audio
2353 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2354 && !mpctx->step_frames)
2355 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2356 (void)get_relative_time(mpctx); // ignore time that passed during pause
2359 void add_step_frame(struct MPContext *mpctx)
2361 mpctx->step_frames++;
2362 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2363 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2364 unpause_player(mpctx);
2367 static void pause_loop(struct MPContext *mpctx)
2369 mp_cmd_t* cmd;
2370 if (!quiet) {
2371 // Small hack to display the pause message on the OSD line.
2372 // The pause string is: "\n == PAUSE == \r" so we need to
2373 // take the first and the last char out
2374 if (term_osd && !mpctx->sh_video) {
2375 char msg[128] = _("\n ===== PAUSE =====\r");
2376 int mlen = strlen(msg);
2377 msg[mlen-1] = '\0';
2378 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2379 update_osd_msg(mpctx);
2380 } else
2381 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2382 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2385 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1, 1)) == NULL
2386 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2387 if (cmd) {
2388 cmd = mp_input_get_cmd(mpctx->input, 0,1,0);
2389 run_command(mpctx, cmd);
2390 mp_cmd_free(cmd);
2391 continue;
2393 if (mpctx->sh_video && mpctx->video_out)
2394 vo_check_events(mpctx->video_out);
2395 #ifdef CONFIG_MENU
2396 if (vf_menu)
2397 vf_menu_pause_update(vf_menu);
2398 #endif
2399 usec_sleep(20000);
2400 update_osd_msg(mpctx);
2401 int hack = vo_osd_changed(0);
2402 vo_osd_changed(hack);
2403 if (hack)
2404 break;
2409 // Find the right mute status and record position for new file position
2410 static void edl_seek_reset(MPContext *mpctx)
2412 mpctx->edl_muted = 0;
2413 next_edl_record = edl_records;
2415 while (next_edl_record) {
2416 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2417 break;
2419 if (next_edl_record->action == EDL_MUTE)
2420 mpctx->edl_muted = !mpctx->edl_muted;
2421 next_edl_record = next_edl_record->next;
2423 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2424 mixer_mute(&mpctx->mixer);
2428 // Execute EDL command for the current position if one exists
2429 static void edl_update(MPContext *mpctx)
2431 if (!next_edl_record)
2432 return;
2434 if (!mpctx->sh_video) {
2435 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2436 free_edl(edl_records);
2437 next_edl_record = NULL;
2438 edl_records = NULL;
2439 return;
2442 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2443 if (next_edl_record->action == EDL_SKIP) {
2444 mpctx->osd_function = OSD_FFW;
2445 mpctx->abs_seek_pos = 0;
2446 mpctx->rel_seek_secs = next_edl_record->length_sec;
2447 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2448 "[%f], length [%f]\n", next_edl_record->start_sec,
2449 next_edl_record->stop_sec, next_edl_record->length_sec);
2451 else if (next_edl_record->action == EDL_MUTE) {
2452 mpctx->edl_muted = !mpctx->edl_muted;
2453 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2454 mixer_mute(&mpctx->mixer);
2455 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2456 next_edl_record->start_sec );
2458 next_edl_record = next_edl_record->next;
2462 static void reinit_decoders(struct MPContext *mpctx)
2464 reinit_video_chain(mpctx);
2465 reinit_audio_chain(mpctx);
2466 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2469 static bool timeline_set_part(struct MPContext *mpctx, int i)
2471 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2472 struct timeline_part *n = mpctx->timeline + i;
2473 mpctx->timeline_part = i;
2474 mpctx->video_offset = n->start - n->source_start;
2475 if (n->source == p->source)
2476 return false;
2477 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2478 mpctx->demuxer = n->source->demuxer;
2479 mpctx->d_video = mpctx->demuxer->video;
2480 mpctx->d_audio = mpctx->demuxer->audio;
2481 mpctx->d_sub = mpctx->demuxer->sub;
2482 mpctx->sh_video = mpctx->d_video->sh;
2483 mpctx->sh_audio = mpctx->d_audio->sh;
2484 return true;
2487 // Given pts, switch playback to the corresponding part.
2488 // Return offset within that part.
2489 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2490 bool *need_reset)
2492 if (pts < 0)
2493 pts = 0;
2494 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2495 struct timeline_part *p = mpctx->timeline + i;
2496 if (pts < (p+1)->start) {
2497 *need_reset = timeline_set_part(mpctx, i);
2498 return pts - p->start + p->source_start;
2501 return -1;
2505 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2506 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2507 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2508 static int seek(MPContext *mpctx, double amount, int style)
2510 current_module = "seek";
2511 if (mpctx->stop_play == AT_END_OF_FILE)
2512 mpctx->stop_play = KEEP_PLAYING;
2513 if (mpctx->timeline && style & SEEK_FACTOR) {
2514 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2515 style &= ~SEEK_FACTOR;
2517 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2518 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2519 style |= SEEK_ABSOLUTE;
2520 if (amount > 0)
2521 style |= SEEK_FORWARD;
2522 else
2523 style |= SEEK_BACKWARD;
2524 amount += mpctx->sh_video->pts;
2527 /* At least the liba52 decoder wants to read from the input stream
2528 * during initialization, so reinit must be done after the demux_seek()
2529 * call that clears possible stream EOF. */
2530 bool need_reset = false;
2531 if (mpctx->timeline) {
2532 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2533 if (amount == -1) {
2534 mpctx->stop_play = AT_END_OF_FILE;
2535 // Clear audio from current position
2536 if (mpctx->sh_audio) {
2537 mpctx->audio_out->reset();
2538 mpctx->sh_audio->a_buffer_len = 0;
2539 mpctx->sh_audio->a_out_buffer_len = 0;
2541 return -1;
2544 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2545 if (need_reset)
2546 reinit_decoders(mpctx);
2547 if (seekresult == 0)
2548 return -1;
2550 if (mpctx->sh_video) {
2551 current_module = "seek_video_reset";
2552 resync_video_stream(mpctx->sh_video);
2553 if (mpctx->video_out->config_ok)
2554 vo_control(mpctx->video_out, VOCTRL_RESET, NULL);
2555 mpctx->sh_video->num_buffered_pts = 0;
2556 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2557 mpctx->num_buffered_frames = 0;
2558 mpctx->delay = 0;
2559 mpctx->time_frame = 0;
2560 mpctx->update_video_immediately = true;
2561 // Not all demuxers set d_video->pts during seek, so this value
2562 // (which is used by at least vobsub and edl code below) may
2563 // be completely wrong (probably 0).
2564 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2565 update_subtitles(mpctx->sh_video, mpctx->d_sub, mpctx->video_offset, 1);
2566 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2569 if (mpctx->sh_audio) {
2570 current_module = "seek_audio_reset";
2571 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2572 mpctx->sh_audio->a_buffer_len = 0;
2573 mpctx->sh_audio->a_out_buffer_len = 0;
2576 if (vo_vobsub && mpctx->sh_video) {
2577 current_module = "seek_vobsub_reset";
2578 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2581 edl_seek_reset(mpctx);
2583 mpctx->total_avsync_change = 0;
2584 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2585 drop_frame_cnt = 0;
2587 current_module = NULL;
2588 return 0;
2591 int get_current_chapter(struct MPContext *mpctx)
2593 if (!mpctx->chapters || !mpctx->sh_video)
2594 return demuxer_get_current_chapter(mpctx->demuxer);
2596 int i;
2597 double current_pts = mpctx->sh_video->pts;
2598 for (i = 1; i < mpctx->num_chapters; i++)
2599 if (current_pts < mpctx->chapters[i].start)
2600 break;
2601 return i - 1;
2604 // currently returns a string allocated with malloc, not talloc
2605 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2607 if (!mpctx->chapters || !mpctx->sh_video)
2608 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2609 return strdup(mpctx->chapters[chapter].name);
2612 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2613 char **chapter_name)
2615 if (!mpctx->chapters || !mpctx->sh_video)
2616 return demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2617 chapter_name);
2618 if (chapter >= mpctx->num_chapters)
2619 return -1;
2620 if (chapter < 0)
2621 chapter = 0;
2622 *seek_pts = mpctx->chapters[chapter].start;
2623 if (chapter_name)
2624 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2625 return chapter;
2628 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2629 struct content_source *sources,
2630 int num_sources,
2631 unsigned char uid_map[][16])
2633 int num_filenames = 0;
2634 char **filenames = NULL;
2635 if (num_sources > 1) {
2636 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2637 "other sources.\n");
2638 if (mpctx->stream->type != STREAMTYPE_FILE) {
2639 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2640 "normal disk file. Will not search for related files.\n");
2641 } else {
2642 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2643 "same directory to find referenced sources.\n");
2644 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2645 &num_filenames);
2649 int num_left = num_sources - 1;
2650 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2651 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2652 filename_recode(filenames[i]));
2653 int format;
2654 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2655 if (!s)
2656 continue;
2657 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2658 mpctx->opts.audio_id,
2659 mpctx->opts.video_id,
2660 mpctx->opts.sub_id, filenames[i]);
2661 if (!d) {
2662 free_stream(s);
2663 continue;
2665 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2666 for (int i = 1; i < num_sources; i++) {
2667 if (sources[i].demuxer)
2668 continue;
2669 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2670 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2671 i, filename_recode(d->filename));
2672 sources[i].stream = s;
2673 sources[i].demuxer = d;
2674 num_left--;
2675 goto match;
2679 free_demuxer(d);
2680 free_stream(s);
2681 continue;
2682 match:
2685 talloc_free(filenames);
2686 if (num_left) {
2687 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2688 "There will be parts MISSING from the video!\n");
2689 for (int i = 1, j = 1; i < num_sources; i++)
2690 if (sources[i].demuxer) {
2691 sources[j] = sources[i];
2692 memcpy(uid_map[j], uid_map[i], 16);
2693 j++;
2696 return num_sources - num_left;
2699 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2701 if (!mpctx->opts.ordered_chapters) {
2702 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
2703 "you have disabled support for them. Ignoring.\n");
2704 return;
2707 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
2708 "edit timeline.\n");
2710 struct demuxer *demuxer = mpctx->demuxer;
2711 struct matroska_data *m = &demuxer->matroska_data;
2713 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
2714 m->num_ordered_chapters);
2715 sources[0].stream = mpctx->stream;
2716 sources[0].demuxer = mpctx->demuxer;
2717 unsigned char uid_map[m->num_ordered_chapters][16];
2718 int num_sources = 1;
2719 memcpy(uid_map[0], m->segment_uid, 16);
2721 for (int i = 0; i < m->num_ordered_chapters; i++) {
2722 struct matroska_chapter *c = m->ordered_chapters + i;
2723 if (!c->has_segment_uid)
2724 memcpy(c->segment_uid, m->segment_uid, 16);
2726 for (int j = 0; j < num_sources; j++)
2727 if (!memcmp(c->segment_uid, uid_map[j], 16))
2728 goto found1;
2729 memcpy(uid_map[num_sources], c->segment_uid, 16);
2730 sources[num_sources] = (struct content_source){};
2731 num_sources++;
2732 found1:
2736 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
2737 uid_map);
2740 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
2741 m->num_ordered_chapters + 1);
2742 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
2743 m->num_ordered_chapters);
2744 uint64_t starttime = 0;
2745 uint64_t missing_time = 0;
2746 int part_count = 0;
2747 int num_chapters = 0;
2748 uint64_t prev_part_offset;
2749 for (int i = 0; i < m->num_ordered_chapters; i++) {
2750 struct matroska_chapter *c = m->ordered_chapters + i;
2752 int j;
2753 for (j = 0; j < num_sources; j++) {
2754 if (!memcmp(c->segment_uid, uid_map[j], 16))
2755 goto found2;
2757 missing_time += c->end - c->start;
2758 continue;
2759 found2:;
2760 chapters[num_chapters].start = starttime / 1000.;
2761 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
2762 /* Only add a separate part if the time or file actually changes.
2763 * Matroska files have chapter divisions that are redundant from
2764 * timeline point of view because the same chapter structure is used
2765 * both to specify the timeline and for normal chapter information.
2766 * Removing a missing inserted external chapter can also cause this. */
2767 if (part_count == 0 || c->start != starttime + prev_part_offset
2768 || sources + j != timeline[part_count - 1].source) {
2769 timeline[part_count].source = sources + j;
2770 timeline[part_count].start = chapters[num_chapters].start;
2771 timeline[part_count].source_start = c->start / 1000.;
2772 prev_part_offset = c->start - starttime;
2773 part_count++;
2775 starttime += c->end - c->start;
2776 num_chapters++;
2778 timeline[part_count].start = starttime / 1000.;
2780 if (!part_count) {
2781 // None of the parts come from the file itself???
2782 talloc_free(sources);
2783 talloc_free(timeline);
2784 talloc_free(chapters);
2785 return;
2788 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
2789 "sources. Total length %.3f seconds.\n", part_count, num_sources,
2790 timeline[part_count].start);
2791 if (missing_time)
2792 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
2793 "from the timeline!\n", missing_time / 1000.);
2794 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
2795 for (int i = 0; i < num_sources; i++)
2796 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
2797 filename_recode(sources[i].demuxer->filename));
2798 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
2799 "source_start, source):\n");
2800 for (int i = 0; i < part_count; i++) {
2801 struct timeline_part *p = timeline + i;
2802 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
2803 p->source_start, p->source - sources);
2805 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
2806 mpctx->sources = sources;
2807 mpctx->num_sources = num_sources;
2808 mpctx->timeline = timeline;
2809 mpctx->num_timeline_parts = part_count;
2810 mpctx->num_chapters = num_chapters;
2811 mpctx->chapters = chapters;
2813 mpctx->timeline_part = 0;
2814 mpctx->video_offset = timeline[0].source_start;
2815 mpctx->demuxer = timeline[0].source->demuxer;
2819 static int read_keys(void *ctx, int fd)
2821 getch2(ctx);
2822 return mplayer_get_key(ctx, 0);
2826 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
2827 * file for some tools to link against. */
2828 #ifndef DISABLE_MAIN
2829 int main(int argc,char* argv[]){
2832 char * mem_ptr;
2834 // movie info:
2836 /* Flag indicating whether MPlayer should exit without playing anything. */
2837 int opt_exit = 0;
2839 //float a_frame=0; // Audio
2841 int i;
2843 struct MPContext *mpctx = &(struct MPContext){
2844 .osd_function = OSD_PLAY,
2845 .begin_skip = MP_NOPTS_VALUE,
2846 .play_tree_step = 1,
2847 .global_sub_pos = -1,
2848 .set_of_sub_pos = -1,
2849 .file_format = DEMUXER_TYPE_UNKNOWN,
2850 .last_dvb_step = 1,
2853 InitTimer();
2854 srand(GetTimerMS());
2856 mp_msg_init();
2858 #ifdef CONFIG_X11
2859 mpctx->x11_state = vo_x11_init_state();
2860 #endif
2861 struct MPOpts *opts = &mpctx->opts;
2862 set_default_mplayer_options(opts);
2863 // Create the config context and register the options
2864 mpctx->mconfig = m_config_new(opts, cfg_include);
2865 m_config_register_options(mpctx->mconfig,mplayer_opts);
2866 mp_input_register_options(mpctx->mconfig);
2868 // Preparse the command line
2869 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
2871 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
2872 set_path_env();
2873 #endif
2875 #ifdef CONFIG_TV
2876 stream_tv_defaults.immediate = 1;
2877 #endif
2879 parse_cfgfiles(mpctx, mpctx->mconfig);
2881 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
2882 if(mpctx->playtree == NULL)
2883 opt_exit = 1;
2884 else {
2885 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
2886 if(mpctx->playtree) {
2887 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
2888 if(mpctx->playtree_iter) {
2889 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
2890 play_tree_iter_free(mpctx->playtree_iter);
2891 mpctx->playtree_iter = NULL;
2893 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
2897 mpctx->key_fifo = mp_fifo_create(opts);
2899 print_version("MPlayer");
2901 #if defined(__MINGW32__) || defined(__CYGWIN__)
2902 // stop Windows from showing all kinds of annoying error dialogs
2903 SetErrorMode(0x8003);
2904 // request 1ms timer resolution
2905 timeBeginPeriod(1);
2906 #endif
2908 #ifdef CONFIG_PRIORITY
2909 set_priority();
2910 #endif
2912 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
2913 list_video_out();
2914 opt_exit = 1;
2917 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
2918 list_audio_out();
2919 opt_exit = 1;
2922 /* Check codecs.conf. */
2923 if(!codecs_file || !parse_codec_cfg(codecs_file)){
2924 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
2925 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
2926 if(!parse_codec_cfg(NULL)){
2927 exit_player_with_rc(mpctx, EXIT_NONE, 0);
2929 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
2932 free( mem_ptr ); // release the buffer created by get_path()
2935 #if 0
2936 if(video_codec_list){
2937 int i;
2938 video_codec=video_codec_list[0];
2939 for(i=0;video_codec_list[i];i++)
2940 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
2942 #endif
2943 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
2944 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
2945 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
2946 list_codecs(1);
2947 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2948 opt_exit = 1;
2950 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
2951 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
2952 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
2953 list_codecs(0);
2954 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2955 opt_exit = 1;
2957 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
2958 vfm_help();
2959 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2960 opt_exit = 1;
2962 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
2963 afm_help();
2964 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2965 opt_exit = 1;
2967 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
2968 af_help();
2969 printf("\n");
2970 opt_exit = 1;
2972 #ifdef CONFIG_X11
2973 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
2974 fstype_help();
2975 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2976 opt_exit = 1;
2978 #endif
2979 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
2980 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
2981 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
2982 demuxer_help();
2983 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
2984 opt_exit = 1;
2986 if(list_properties) {
2987 property_print_help();
2988 opt_exit = 1;
2991 if(opt_exit)
2992 exit_player(mpctx, EXIT_NONE);
2994 if(!mpctx->filename && !player_idle_mode){
2995 // no file/vcd/dvd -> show HELP:
2996 mp_msg(MSGT_CPLAYER, MSGL_INFO, help_text);
2997 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3000 /* Display what configure line was used */
3001 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3003 // Many users forget to include command line in bugreports...
3004 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3005 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3006 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3007 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3010 //------ load global data first ------
3012 mpctx->osd = osd_create();
3014 // check font
3015 #ifdef CONFIG_FREETYPE
3016 init_freetype();
3017 #endif
3018 #ifdef CONFIG_FONTCONFIG
3019 if(font_fontconfig <= 0)
3021 #endif
3022 #ifdef CONFIG_BITMAP_FONT
3023 if(font_name){
3024 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3025 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3026 filename_recode(font_name));
3027 } else {
3028 // try default:
3029 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3030 free(mem_ptr); // release the buffer created by get_path()
3031 if(!vo_font)
3032 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3034 if (sub_font_name)
3035 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3036 else
3037 mpctx->osd->sub_font = vo_font;
3038 #endif
3039 #ifdef CONFIG_FONTCONFIG
3041 #endif
3043 #ifdef CONFIG_ASS
3044 ass_library = ass_init();
3045 #endif
3047 #ifdef HAVE_RTC
3048 if(!nortc)
3050 // seteuid(0); /* Can't hurt to try to get root here */
3051 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3052 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3053 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3054 else {
3055 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3057 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3058 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3059 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3060 close (rtc_fd);
3061 rtc_fd = -1;
3062 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3063 /* variable only by the root */
3064 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3065 close (rtc_fd);
3066 rtc_fd = -1;
3067 } else
3068 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3071 if(rtc_fd<0)
3072 #endif /* HAVE_RTC */
3073 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3074 softsleep?"software":timer_name);
3076 #ifdef HAVE_TERMCAP
3077 load_termcap(NULL); // load key-codes
3078 #endif
3080 // ========== Init keyboard FIFO (connection to libvo) ============
3082 // Init input system
3083 current_module = "init_input";
3084 mpctx->input = mp_input_init(&opts->input);
3085 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3086 if(slave_mode)
3087 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3088 else if(!noconsolecontrols)
3089 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3090 // Set the libstream interrupt callback
3091 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3093 #ifdef CONFIG_MENU
3094 if(use_menu) {
3095 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3096 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3097 else {
3098 menu_cfg = get_path("menu.conf");
3099 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3100 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3101 else {
3102 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3103 MPLAYER_CONFDIR "/menu.conf"))
3104 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3105 else {
3106 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3107 use_menu = 0;
3112 #endif
3114 current_module = NULL;
3116 /// Catch signals
3117 #ifndef __MINGW32__
3118 signal(SIGCHLD,child_sighandler);
3119 #endif
3121 #ifdef CONFIG_CRASH_DEBUG
3122 prog_path = argv[0];
3123 #endif
3124 //========= Catch terminate signals: ================
3125 // terminate requests:
3126 signal(SIGTERM,exit_sighandler); // kill
3127 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3129 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3131 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3132 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3133 #ifdef CONFIG_SIGHANDLER
3134 // fatal errors:
3135 signal(SIGBUS,exit_sighandler); // bus error
3136 signal(SIGSEGV,exit_sighandler); // segfault
3137 signal(SIGILL,exit_sighandler); // illegal instruction
3138 signal(SIGFPE,exit_sighandler); // floating point exc.
3139 signal(SIGABRT,exit_sighandler); // abort()
3140 #ifdef CONFIG_CRASH_DEBUG
3141 if (crash_debug)
3142 signal(SIGTRAP,exit_sighandler);
3143 #endif
3144 #endif
3146 // ******************* Now, let's see the per-file stuff ********************
3148 play_next_file:
3150 // init global sub numbers
3151 mpctx->global_sub_size = 0;
3152 { int i; for (i = 0; i < SUB_SOURCES; i++) mpctx->global_sub_indices[i] = -1; }
3154 if (mpctx->filename) {
3155 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3156 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3157 load_per_file_config (mpctx->mconfig, mpctx->filename);
3160 if (opts->video_driver_list)
3161 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3162 if (opts->audio_driver_list)
3163 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3165 // We must enable getch2 here to be able to interrupt network connection
3166 // or cache filling
3167 if(!noconsolecontrols && !slave_mode){
3168 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3169 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3170 else
3171 getch2_enable(); // prepare stdin for hotkeys...
3172 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3173 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3176 // =================== GUI idle loop (STOP state) ===========================
3177 while (player_idle_mode && !mpctx->filename) {
3178 play_tree_t * entry = NULL;
3179 mp_cmd_t * cmd;
3180 while (!(cmd = mp_input_get_cmd(mpctx->input, 0,1,0))) { // wait for command
3181 if (mpctx->video_out)
3182 vo_check_events(mpctx->video_out);
3183 usec_sleep(20000);
3185 switch (cmd->id) {
3186 case MP_CMD_LOADFILE:
3187 // prepare a tree entry with the new filename
3188 entry = play_tree_new();
3189 play_tree_add_file(entry, cmd->args[0].v.s);
3190 // The entry is added to the main playtree after the switch().
3191 break;
3192 case MP_CMD_LOADLIST:
3193 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3194 break;
3195 case MP_CMD_QUIT:
3196 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3197 break;
3198 case MP_CMD_GET_PROPERTY:
3199 case MP_CMD_SET_PROPERTY:
3200 case MP_CMD_STEP_PROPERTY:
3201 run_command(mpctx, cmd);
3202 break;
3205 mp_cmd_free(cmd);
3207 if (entry) { // user entered a command that gave a valid entry
3208 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3209 play_tree_free_list(mpctx->playtree->child, 1);
3210 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3212 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3214 play_tree_set_child(mpctx->playtree, entry);
3216 /* Make iterator start at the top the of tree. */
3217 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3218 if (!mpctx->playtree_iter) continue;
3220 // find the first real item in the tree
3221 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3222 // no items!
3223 play_tree_iter_free(mpctx->playtree_iter);
3224 mpctx->playtree_iter = NULL;
3225 continue; // wait for next command
3227 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3230 //---------------------------------------------------------------------------
3232 if(mpctx->filename)
3233 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3234 filename_recode(mpctx->filename));
3236 if (edl_filename) {
3237 if (edl_records) free_edl(edl_records);
3238 next_edl_record = edl_records = edl_parse_file();
3240 if (edl_output_filename) {
3241 if (edl_fd) fclose(edl_fd);
3242 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3244 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3245 filename_recode(edl_output_filename));
3249 //==================== Open VOB-Sub ============================
3251 current_module="vobsub";
3252 if (vobsub_name){
3253 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3254 if(vo_vobsub==NULL)
3255 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3256 filename_recode(vobsub_name));
3257 } else if (sub_auto && mpctx->filename){
3258 /* try to autodetect vobsub from movie filename ::atmos */
3259 char *buf = strdup(mpctx->filename), *psub;
3260 char *pdot = strrchr(buf, '.');
3261 char *pslash = strrchr(buf, '/');
3262 #if defined(__MINGW32__) || defined(__CYGWIN__)
3263 if (!pslash) pslash = strrchr(buf, '\\');
3264 #endif
3265 if (pdot && (!pslash || pdot > pslash))
3266 *pdot = '\0';
3267 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3268 /* try from ~/.mplayer/sub */
3269 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3270 char *bname;
3271 int l;
3272 bname = strrchr(buf,'/');
3273 #if defined(__MINGW32__) || defined(__CYGWIN__)
3274 if(!bname) bname = strrchr(buf,'\\');
3275 #endif
3276 if(bname) bname++;
3277 else bname = buf;
3278 l = strlen(psub) + strlen(bname) + 1;
3279 psub = realloc(psub,l);
3280 strcat(psub,bname);
3281 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3282 free(psub);
3284 free(buf);
3286 if(vo_vobsub){
3287 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3288 vobsub_set_from_lang(vo_vobsub, dvdsub_lang);
3289 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3291 // setup global sub numbering
3292 mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] = mpctx->global_sub_size; // the global # of the first vobsub.
3293 mpctx->global_sub_size += vobsub_get_indexes_count(vo_vobsub);
3296 //============ Open & Sync STREAM --- fork cache2 ====================
3298 mpctx->stream=NULL;
3299 mpctx->demuxer=NULL;
3300 if (mpctx->d_audio) {
3301 //free_demuxer_stream(mpctx->d_audio);
3302 mpctx->d_audio=NULL;
3304 if (mpctx->d_video) {
3305 //free_demuxer_stream(d_video);
3306 mpctx->d_video=NULL;
3308 mpctx->sh_audio=NULL;
3309 mpctx->sh_video=NULL;
3311 current_module="open_stream";
3312 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3313 if(!mpctx->stream) { // error...
3314 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3315 goto goto_next_file;
3317 mpctx->initialized_flags|=INITIALIZED_STREAM;
3319 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3320 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3321 "playlist support will not be used automatically.\n"
3322 "MPlayer's playlist code is unsafe and should only be used with "
3323 "trusted sources.\nPlayback will probably fail.\n\n");
3324 #if 0
3325 play_tree_t* entry;
3326 // Handle playlist
3327 current_module="handle_playlist";
3328 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3329 filename_recode(mpctx->filename));
3330 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3331 mpctx->eof=playtree_add_playlist(mpctx, entry);
3332 goto goto_next_file;
3333 #endif
3335 mpctx->stream->start_pos+=seek_to_byte;
3337 if(stream_dump_type==5){
3338 unsigned char buf[4096];
3339 int len;
3340 FILE *f;
3341 current_module="dumpstream";
3342 if(mpctx->stream->type==STREAMTYPE_STREAM && mpctx->stream->fd<0){
3343 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot dump this stream - no file descriptor available.\n");
3344 exit_player(mpctx, EXIT_ERROR);
3346 stream_reset(mpctx->stream);
3347 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3348 f=fopen(stream_dump_name,"wb");
3349 if(!f){
3350 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3351 exit_player(mpctx, EXIT_ERROR);
3353 if (dvd_chapter > 1) {
3354 int chapter = dvd_chapter - 1;
3355 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3357 while(!mpctx->stream->eof && !async_quit_request){
3358 len=stream_read(mpctx->stream,buf,4096);
3359 if(len>0) {
3360 if(fwrite(buf,len,1,f) != 1) {
3361 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3362 exit_player(mpctx, EXIT_ERROR);
3365 if(dvd_last_chapter > 0) {
3366 int chapter = -1;
3367 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3368 &chapter) == STREAM_OK && chapter + 1 > dvd_last_chapter)
3369 break;
3372 if(fclose(f)) {
3373 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3374 exit_player(mpctx, EXIT_ERROR);
3376 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3377 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3380 #ifdef CONFIG_DVDREAD
3381 if(mpctx->stream->type==STREAMTYPE_DVD){
3382 current_module="dvd lang->id";
3383 if(opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,audio_lang);
3384 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3385 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,dvdsub_lang);
3386 // setup global sub numbering
3387 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3388 mpctx->global_sub_size += dvd_number_of_subs(mpctx->stream);
3389 current_module=NULL;
3391 #endif
3393 #ifdef CONFIG_DVDNAV
3394 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3395 current_module="dvdnav lang->id";
3396 if(opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,audio_lang);
3397 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3398 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=mp_dvdnav_sid_from_lang(mpctx->stream,dvdsub_lang);
3399 // setup global sub numbering
3400 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3401 mpctx->global_sub_size += mp_dvdnav_number_of_subs(mpctx->stream);
3402 current_module=NULL;
3404 #endif
3406 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3407 goto_enable_cache:
3408 if(stream_cache_size>0){
3409 current_module="enable_cache";
3410 if(!stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3411 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3412 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0)))
3413 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3416 //============ Open DEMUXERS --- DETECT file type =======================
3417 current_module="demux_open";
3419 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3421 // HACK to get MOV Reference Files working
3423 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3425 unsigned char* playlist_entry;
3426 play_tree_t *list = NULL, *entry = NULL;
3428 current_module="handle_demux_playlist";
3429 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3431 char *temp, *bname;
3433 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3434 filename_recode(playlist_entry));
3436 bname=mp_basename(playlist_entry);
3437 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3438 continue;
3440 if (!strncmp(bname,mp_basename(mpctx->filename),strlen(bname))) // ignoring self-reference
3441 continue;
3443 entry = play_tree_new();
3445 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3447 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3448 if (temp)
3450 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3451 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3452 strcat(temp, playlist_entry);
3453 play_tree_add_file(entry,temp);
3454 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3455 free(temp);
3458 else
3459 play_tree_add_file(entry,playlist_entry);
3461 if(!list)
3462 list = entry;
3463 else
3464 play_tree_append_entry(list,entry);
3466 free_demuxer(mpctx->demuxer);
3467 mpctx->demuxer = NULL;
3469 if (list)
3471 entry = play_tree_new();
3472 play_tree_set_child(entry,list);
3473 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3474 goto goto_next_file;
3478 if(!mpctx->demuxer)
3479 goto goto_next_file;
3481 if (mpctx->demuxer->matroska_data.ordered_chapters)
3482 build_ordered_chapter_timeline(mpctx);
3484 if (!mpctx->sources) {
3485 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3486 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3487 .demuxer = mpctx->demuxer};
3488 mpctx->num_sources = 1;
3491 if(dvd_chapter>1) {
3492 double pts;
3493 if (seek_chapter(mpctx, dvd_chapter-1, &pts, NULL) >= 0 && pts > -1.0)
3494 seek(mpctx, pts, SEEK_ABSOLUTE);
3497 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3499 if (mpctx->stream->type != STREAMTYPE_DVD && mpctx->stream->type != STREAMTYPE_DVDNAV) {
3500 int i;
3501 int maxid = -1;
3502 // setup global sub numbering
3503 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3504 for (i = 0; i < MAX_S_STREAMS; i++)
3505 if (mpctx->demuxer->s_streams[i])
3506 maxid = FFMAX(maxid, mpctx->demuxer->s_streams[i]->sid);
3507 mpctx->global_sub_size += maxid + 1;
3509 // Make opts->sub_id always selectable if set.
3510 if (mpctx->global_sub_size <= mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id)
3511 mpctx->global_sub_size = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id + 1;
3513 #ifdef CONFIG_ASS
3514 if (ass_enabled && ass_library) {
3515 for (int j = 0; j < mpctx->num_sources; j++) {
3516 struct demuxer *d = mpctx->sources[j].demuxer;
3517 for (int i = 0; i < d->num_attachments; i++) {
3518 struct demux_attachment *att = d->attachments + i;
3519 if (extract_embedded_fonts
3520 && att->name && att->type && att->data && att->data_size
3521 && (strcmp(att->type, "application/x-truetype-font") == 0
3522 || strcmp(att->type, "application/x-font") == 0))
3523 ass_add_font(ass_library, att->name, att->data, att->data_size);
3527 #endif
3529 current_module="demux_open2";
3531 //file_format=demuxer->file_format;
3533 mpctx->d_audio=mpctx->demuxer->audio;
3534 mpctx->d_video=mpctx->demuxer->video;
3535 mpctx->d_sub=mpctx->demuxer->sub;
3537 // select audio stream
3538 select_audio(mpctx->demuxer, opts->audio_id, audio_lang);
3540 // DUMP STREAMS:
3541 if((stream_dump_type)&&(stream_dump_type<4)){
3542 FILE *f;
3543 demux_stream_t *ds=NULL;
3544 current_module="dump";
3545 // select stream to dump
3546 switch(stream_dump_type){
3547 case 1: ds=mpctx->d_audio;break;
3548 case 2: ds=mpctx->d_video;break;
3549 case 3: ds=mpctx->d_sub;break;
3551 if(!ds){
3552 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3553 exit_player(mpctx, EXIT_ERROR);
3555 // disable other streams:
3556 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3557 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3558 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3559 // let's dump it!
3560 f=fopen(stream_dump_name,"wb");
3561 if(!f){
3562 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3563 exit_player(mpctx, EXIT_ERROR);
3565 while(!ds->eof){
3566 unsigned char* start;
3567 int in_size=ds_get_packet(ds,&start);
3568 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3569 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3570 if(in_size>0) fwrite(start,in_size,1,f);
3571 if(dvd_last_chapter>0) {
3572 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3573 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3574 break;
3577 fclose(f);
3578 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3579 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3582 mpctx->sh_audio=mpctx->d_audio->sh;
3583 mpctx->sh_video=mpctx->d_video->sh;
3585 if(mpctx->sh_video){
3587 current_module="video_read_properties";
3588 if(!video_read_properties(mpctx->sh_video)) {
3589 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3590 mpctx->sh_video=mpctx->d_video->sh=NULL;
3591 } else {
3592 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3593 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3594 mpctx->sh_video->fps,mpctx->sh_video->frametime
3597 /* need to set fps here for output encoders to pick it up in their init */
3598 if(force_fps){
3599 mpctx->sh_video->fps=force_fps;
3600 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3602 vo_fps = mpctx->sh_video->fps;
3604 if(!mpctx->sh_video->fps && !force_fps){
3605 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3606 mpctx->sh_video=mpctx->d_video->sh=NULL;
3612 if(!mpctx->sh_video && !mpctx->sh_audio){
3613 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3614 #ifdef CONFIG_DVBIN
3615 if(mpctx->stream->type == STREAMTYPE_DVB)
3617 int dir;
3618 int v = mpctx->last_dvb_step;
3619 if(v > 0)
3620 dir = DVB_CHANNEL_HIGHER;
3621 else
3622 dir = DVB_CHANNEL_LOWER;
3624 if(dvb_step_channel(mpctx->stream, dir)) {
3625 mpctx->stop_play = PT_NEXT_ENTRY;
3626 mpctx->dvbin_reopen = 1;
3629 #endif
3630 goto goto_next_file; // exit_player(_("Fatal error"));
3633 /* display clip info */
3634 demux_info_print(mpctx->demuxer);
3636 //================== Read SUBTITLES (DVD & TEXT) ==========================
3637 if(vo_spudec==NULL && mpctx->sh_video &&
3638 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3639 init_vo_spudec(mpctx);
3642 if(mpctx->sh_video) {
3643 // after reading video params we should load subtitles because
3644 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3645 // check .sub
3646 current_module="read_subtitles_file";
3647 if(sub_name){
3648 for (i = 0; sub_name[i] != NULL; ++i)
3649 add_subtitles(mpctx, sub_name[i], mpctx->sh_video->fps, 0);
3651 if(sub_auto) { // auto load sub file ...
3652 char *psub = get_path( "sub/" );
3653 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3654 int i = 0;
3655 free(psub); // release the buffer created by get_path() above
3656 while (tmp[i]) {
3657 add_subtitles(mpctx, tmp[i], mpctx->sh_video->fps, 1);
3658 free(tmp[i++]);
3660 free(tmp);
3662 if (mpctx->set_of_sub_size > 0) {
3663 // setup global sub numbering
3664 mpctx->global_sub_indices[SUB_SOURCE_SUBS] = mpctx->global_sub_size; // the global # of the first sub.
3665 mpctx->global_sub_size += mpctx->set_of_sub_size;
3669 if (mpctx->global_sub_size) {
3670 // find the best sub to use
3671 int vobsub_index_id = vobsub_get_index_by_id(vo_vobsub, vobsub_id);
3672 mpctx->global_sub_pos = -1; // no subs by default
3673 if (vobsub_index_id >= 0) {
3674 // if user asks for a vobsub id, use that first.
3675 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] + vobsub_index_id;
3676 } else if (opts->sub_id >= 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3677 // if user asks for a dvd sub id, use that next.
3678 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3679 } else if (mpctx->global_sub_indices[SUB_SOURCE_SUBS] >= 0) {
3680 // if there are text subs to use, use those. (autosubs come last here)
3681 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_SUBS];
3682 } else if (opts->sub_id < 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3683 // finally select subs by language and container hints
3684 if (opts->sub_id < 0 && dvdsub_lang)
3685 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, dvdsub_lang);
3686 if (opts->sub_id < 0)
3687 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
3688 if (opts->sub_id >= 0)
3689 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3691 // rather than duplicate code, use the SUB_SELECT handler to init the right one.
3692 mpctx->global_sub_pos--;
3693 mp_property_do("sub",M_PROPERTY_STEP_UP,NULL, mpctx);
3694 if(subdata)
3695 switch (stream_dump_type) {
3696 case 3: list_sub_file(subdata); break;
3697 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3698 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3699 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3700 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3701 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3705 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
3706 filename_recode(mpctx->filename));
3707 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
3708 if (mpctx->sh_video) {
3709 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3710 if (mpctx->sh_video->format >= 0x20202020)
3711 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
3712 else
3713 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
3714 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
3715 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
3716 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
3717 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
3718 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
3720 if (mpctx->sh_audio) {
3721 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3722 if (mpctx->sh_audio->format >= 0x20202020)
3723 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
3724 else
3725 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
3726 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
3727 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
3728 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
3730 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2lf\n", demuxer_get_time_length(mpctx->demuxer));
3731 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
3732 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
3733 if (mpctx->demuxer) {
3734 if (mpctx->demuxer->num_chapters == 0)
3735 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
3736 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
3739 if(!mpctx->sh_video) goto main; // audio-only
3741 if(!reinit_video_chain(mpctx)) {
3742 if(!mpctx->sh_video){
3743 if(!mpctx->sh_audio) goto goto_next_file;
3744 goto main; // exit_player(_("Fatal error"));
3748 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
3749 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3751 #ifdef CONFIG_FREETYPE
3752 force_load_font = 1;
3753 #endif
3755 //================== MAIN: ==========================
3756 main:
3757 current_module="main";
3759 if(playing_msg) {
3760 char* msg = property_expand_string(mpctx, playing_msg);
3761 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
3762 free(msg);
3766 // Disable the term OSD in verbose mode
3767 if(verbose) term_osd = 0;
3770 //int frame_corr_num=0; //
3771 //float v_frame=0; // Video
3772 //float num_frames=0; // number of frames played
3774 int frame_time_remaining=0; // flag
3775 int blit_frame=0;
3776 mpctx->num_buffered_frames=0;
3778 // Make sure old OSD does not stay around,
3779 // e.g. with -fixed-vo and same-resolution files
3780 clear_osd_msgs();
3781 update_osd_msg(mpctx);
3783 //================ SETUP AUDIO ==========================
3785 if(mpctx->sh_audio){
3786 reinit_audio_chain(mpctx);
3787 if (mpctx->sh_audio && mpctx->sh_audio->codec)
3788 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
3791 current_module="av_init";
3793 if(mpctx->sh_video){
3794 mpctx->sh_video->timer=0;
3795 if (! ignore_start)
3796 audio_delay += mpctx->sh_video->stream_delay;
3798 if(mpctx->sh_audio){
3799 if (start_volume >= 0)
3800 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
3801 if (! ignore_start)
3802 audio_delay -= mpctx->sh_audio->stream_delay;
3803 mpctx->delay=-audio_delay;
3806 if(!mpctx->sh_audio){
3807 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
3808 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
3809 ds_free_packs(mpctx->d_audio); // free buffered chunks
3810 //mpctx->d_audio->id=-2; // do not read audio chunks
3811 //uninit_player(mpctx, INITIALIZED_AO); // close device
3813 if(!mpctx->sh_video){
3814 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
3815 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
3816 ds_free_packs(mpctx->d_video);
3817 mpctx->d_video->id=-2;
3818 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
3821 if (!mpctx->sh_video && !mpctx->sh_audio)
3822 goto goto_next_file;
3824 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
3825 if(force_fps && mpctx->sh_video){
3826 vo_fps = mpctx->sh_video->fps=force_fps;
3827 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3828 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
3831 mp_input_set_section(mpctx->input, NULL);
3832 //TODO: add desired (stream-based) sections here
3833 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
3834 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
3836 //==================== START PLAYING =======================
3838 if(opts->loop_times>1) opts->loop_times--; else
3839 if(opts->loop_times==1) opts->loop_times = -1;
3841 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
3843 total_time_usage_start=GetTimer();
3844 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
3845 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
3846 play_n_frames=play_n_frames_mf;
3848 if(play_n_frames==0){
3849 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
3852 if (seek_to_sec) {
3853 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
3854 end_at.pos += seek_to_sec;
3857 if (end_at.type == END_AT_SIZE) {
3858 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
3859 end_at.type = END_AT_NONE;
3862 #ifdef CONFIG_DVDNAV
3863 mp_dvdnav_context_free(mpctx);
3864 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3865 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
3866 mp_dvdnav_cell_has_changed(mpctx->stream,1);
3868 #endif
3870 get_relative_time(mpctx); // reset current delta
3871 mpctx->time_frame = 0;
3872 mpctx->drop_message_shown = 0;
3873 mpctx->update_video_immediately = true;
3874 mpctx->total_avsync_change = 0;
3875 // Make sure VO knows current pause state
3876 if (mpctx->sh_video)
3877 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
3878 NULL);
3880 while(!mpctx->stop_play){
3881 float aq_sleep_time=0;
3883 if(dvd_last_chapter>0) {
3884 int cur_chapter = get_current_chapter(mpctx);
3885 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3886 goto goto_next_file;
3889 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
3890 mpctx->sh_audio = mpctx->d_audio->sh;
3891 mpctx->sh_audio->ds = mpctx->d_audio;
3892 reinit_audio_chain(mpctx);
3895 /*========================== PLAY AUDIO ============================*/
3897 if (mpctx->sh_audio && !mpctx->paused)
3898 if (!fill_audio_out_buffers(mpctx))
3899 // at eof, all audio at least written to ao
3900 if (!mpctx->sh_video)
3901 mpctx->stop_play = AT_END_OF_FILE;
3904 if(!mpctx->sh_video) {
3905 // handle audio-only case:
3906 double a_pos=0;
3907 // sh_audio can be NULL due to video stream switching
3908 // TODO: handle this better
3909 if (mpctx->sh_audio)
3910 a_pos = playing_audio_pts(mpctx);
3912 print_status(mpctx, a_pos, false);
3914 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
3915 mpctx->stop_play = PT_NEXT_ENTRY;
3916 update_osd_msg(mpctx);
3918 } else {
3920 /*========================== PLAY VIDEO ============================*/
3922 vo_pts=mpctx->sh_video->timer*90000.0;
3923 vo_fps=mpctx->sh_video->fps;
3925 if (!mpctx->num_buffered_frames) {
3926 double frame_time = update_video(mpctx, &blit_frame);
3927 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
3928 if (mpctx->sh_video->vf_initialized < 0) {
3929 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
3930 mpctx->stop_play = PT_NEXT_ENTRY;
3931 goto goto_next_file;
3933 if (blit_frame) {
3934 struct vf_instance *vf = mpctx->sh_video->vfilter;
3935 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3936 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3937 vo_osd_changed(0);
3939 if (frame_time < 0)
3940 mpctx->stop_play = AT_END_OF_FILE;
3941 else {
3942 // might return with !eof && !blit_frame if !correct_pts
3943 mpctx->num_buffered_frames += blit_frame;
3944 if (mpctx->update_video_immediately) {
3945 // Show this frame immediately, rest normally
3946 mpctx->update_video_immediately = false;
3947 } else {
3948 mpctx->time_frame += frame_time / opts->playback_speed;
3949 adjust_sync(mpctx, frame_time);
3953 if (mpctx->timeline) {
3954 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
3955 if (mpctx->sh_video->pts >= next->start
3956 || mpctx->stop_play == AT_END_OF_FILE
3957 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3958 seek(mpctx, next->start, SEEK_ABSOLUTE);
3959 continue;
3963 // ==========================================================================
3965 // current_module="draw_osd";
3966 // if(vo_config_count) mpctx->video_out->draw_osd();
3968 current_module="vo_check_events";
3969 vo_check_events(mpctx->video_out);
3971 #ifdef CONFIG_X11
3972 if (stop_xscreensaver) {
3973 current_module = "stop_xscreensaver";
3974 xscreensaver_heartbeat(mpctx->x11_state);
3976 #endif
3977 if (heartbeat_cmd) {
3978 static unsigned last_heartbeat;
3979 unsigned now = GetTimerMS();
3980 if (now - last_heartbeat > 30000) {
3981 last_heartbeat = now;
3982 system(heartbeat_cmd);
3986 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
3988 //====================== FLIP PAGE (VIDEO BLT): =========================
3990 current_module="flip_page";
3991 if (!frame_time_remaining && blit_frame) {
3992 unsigned int t2=GetTimer();
3994 vo_flip_page(mpctx->video_out);
3995 mpctx->num_buffered_frames--;
3997 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3998 vout_time_usage += mpctx->last_vo_flip_duration;
3999 print_status(mpctx, MP_NOPTS_VALUE, true);
4001 else
4002 print_status(mpctx, MP_NOPTS_VALUE, false);
4004 //============================ Auto QUALITY ============================
4006 /*Output quality adjustments:*/
4007 if(auto_quality>0){
4008 current_module="autoq";
4009 // float total=0.000001f * (GetTimer()-aq_total_time);
4010 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4011 if(output_quality<auto_quality && aq_sleep_time>0)
4012 ++output_quality;
4013 else
4014 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4015 if(output_quality>1 && aq_sleep_time<0)
4016 --output_quality;
4017 else
4018 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4019 output_quality=0;
4020 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4021 set_video_quality(mpctx->sh_video,output_quality);
4024 if (!frame_time_remaining && blit_frame) {
4025 if (play_n_frames >= 0) {
4026 --play_n_frames;
4027 if (play_n_frames <= 0)
4028 mpctx->stop_play = PT_NEXT_ENTRY;
4030 if (mpctx->step_frames > 0) {
4031 mpctx->step_frames--;
4032 if (mpctx->step_frames == 0)
4033 pause_player(mpctx);
4038 // FIXME: add size based support for -endpos
4039 if (end_at.type == END_AT_TIME &&
4040 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4041 mpctx->stop_play = PT_NEXT_ENTRY;
4043 } // end if(mpctx->sh_video)
4045 #ifdef CONFIG_DVDNAV
4046 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4047 nav_highlight_t hl;
4048 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4049 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4050 vo_osd_changed (OSDTYPE_DVDNAV);
4052 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4053 double ar = -1.0;
4054 if (stream_control (mpctx->demuxer->stream,
4055 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4056 != STREAM_UNSUPPORTED)
4057 mpctx->sh_video->stream_aspect = ar;
4060 #endif
4062 //================= Keyboard events, SEEKing ====================
4064 current_module="key_events";
4067 while (1) {
4068 mp_cmd_t* cmd;
4069 while ((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
4070 run_command(mpctx, cmd);
4071 mp_cmd_free(cmd);
4072 if (mpctx->stop_play)
4073 break;
4075 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4076 || mpctx->abs_seek_pos)
4077 break;
4078 if (mpctx->sh_video) {
4079 update_osd_msg(mpctx);
4080 int hack = vo_osd_changed(0);
4081 vo_osd_changed(hack);
4082 if (hack)
4083 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4084 add_step_frame(mpctx);
4085 break;
4087 else
4088 vo_osd_changed(0);
4090 pause_loop(mpctx);
4094 // handle -sstep
4095 if (step_sec > 0 && !mpctx->paused) {
4096 mpctx->osd_function=OSD_FFW;
4097 mpctx->rel_seek_secs+=step_sec;
4100 edl_update(mpctx);
4102 /* Looping. */
4103 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4104 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4106 if(opts->loop_times>1) opts->loop_times--; else
4107 if(opts->loop_times==1) opts->loop_times=-1;
4108 play_n_frames=play_n_frames_mf;
4109 mpctx->stop_play=0;
4110 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4113 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4114 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4116 mpctx->rel_seek_secs=0;
4117 mpctx->abs_seek_pos=0;
4120 } // while(!mpctx->stop_play)
4122 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4124 #ifdef CONFIG_DVBIN
4125 if(mpctx->dvbin_reopen)
4127 mpctx->stop_play = 0;
4128 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4129 cache_uninit(mpctx->stream);
4130 mpctx->dvbin_reopen = 0;
4131 goto goto_enable_cache;
4133 #endif
4136 goto_next_file: // don't jump here after ao/vo/getch initialization!
4138 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4140 if(benchmark){
4141 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4142 double total_time_usage;
4143 total_time_usage_start=GetTimer()-total_time_usage_start;
4144 total_time_usage = (float)total_time_usage_start*0.000001;
4145 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4146 video_time_usage,vout_time_usage,audio_time_usage,
4147 total_time_usage-tot,total_time_usage);
4148 if(total_time_usage>0.0)
4149 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4150 100.0*video_time_usage/total_time_usage,
4151 100.0*vout_time_usage/total_time_usage,
4152 100.0*audio_time_usage/total_time_usage,
4153 100.0*(total_time_usage-tot)/total_time_usage,
4154 100.0);
4155 if(total_frame_cnt && frame_dropping)
4156 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4157 total_frame_cnt-drop_frame_cnt,
4158 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4159 drop_frame_cnt,
4160 100*drop_frame_cnt/total_frame_cnt,
4161 total_frame_cnt,
4162 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4165 // time to uninit all, except global stuff:
4166 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4168 if(mpctx->set_of_sub_size > 0) {
4169 current_module="sub_free";
4170 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4171 sub_free(mpctx->set_of_subtitles[i]);
4172 #ifdef CONFIG_ASS
4173 if(mpctx->set_of_ass_tracks[i])
4174 ass_free_track( mpctx->set_of_ass_tracks[i] );
4175 #endif
4177 mpctx->set_of_sub_size = 0;
4179 vo_sub_last = vo_sub=NULL;
4180 subdata=NULL;
4181 #ifdef CONFIG_ASS
4182 ass_track = NULL;
4183 if(ass_library)
4184 ass_clear_fonts(ass_library);
4185 #endif
4187 if (!mpctx->stop_play) // In case some goto jumped here...
4188 mpctx->stop_play = PT_NEXT_ENTRY;
4190 int playtree_direction = 1;
4192 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4193 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4194 play_tree_iter_free(mpctx->playtree_iter);
4195 mpctx->playtree_iter = NULL;
4197 mpctx->play_tree_step = 1;
4198 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4199 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4200 if(mpctx->playtree_iter) {
4201 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4202 play_tree_iter_free(mpctx->playtree_iter);
4203 mpctx->playtree_iter = NULL;
4206 } else if (mpctx->stop_play == PT_STOP) {
4207 play_tree_iter_free(mpctx->playtree_iter);
4208 mpctx->playtree_iter = NULL;
4209 } else { // NEXT PREV SRC
4210 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4213 while(mpctx->playtree_iter != NULL) {
4214 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4215 if(mpctx->filename == NULL) {
4216 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4217 play_tree_iter_free(mpctx->playtree_iter);
4218 mpctx->playtree_iter = NULL;
4220 } else
4221 break;
4224 if(mpctx->playtree_iter != NULL || player_idle_mode){
4225 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4226 mpctx->stop_play = 0;
4227 goto play_next_file;
4231 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4233 return 1;
4235 #endif /* DISABLE_MAIN */