Merge branch 'vdpau' into build
[mplayer/kovensky.git] / mplayer.c
blob1677b601efd8d9aa37ce4b537bc182057174bf71
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"
55 #include "libavutil/avstring.h"
57 #include "subreader.h"
59 #include "mp_osd.h"
60 #include "libvo/video_out.h"
62 #include "libvo/font_load.h"
63 #include "libvo/sub.h"
65 #ifdef CONFIG_X11
66 #include "libvo/x11_common.h"
67 #endif
69 #include "libao2/audio_out.h"
71 #include "codec-cfg.h"
73 #include "edl.h"
75 #include "spudec.h"
76 #include "vobsub.h"
78 #include "osdep/getch2.h"
79 #include "osdep/timer.h"
80 #include "osdep/findfiles.h"
82 #include "input/input.h"
84 const int under_mencoder = 0;
85 int slave_mode=0;
86 int player_idle_mode=0;
87 int quiet=0;
88 int enable_mouse_movements=0;
89 float start_volume = -1;
91 #include "osdep/priority.h"
93 char *heartbeat_cmd;
95 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
97 #ifdef HAVE_RTC
98 #ifdef __linux__
99 #include <linux/rtc.h>
100 #else
101 #include <rtc.h>
102 #define RTC_IRQP_SET RTCIO_IRQP_SET
103 #define RTC_PIE_ON RTCIO_PIE_ON
104 #endif /* __linux__ */
105 #endif /* HAVE_RTC */
107 #include "stream/tv.h"
108 #include "stream/stream_radio.h"
109 #ifdef CONFIG_DVBIN
110 #include "stream/dvbin.h"
111 #endif
112 #include "stream/cache2.h"
114 //**************************************************************************//
115 // Playtree
116 //**************************************************************************//
117 #include "playtree.h"
118 #include "playtreeparser.h"
120 //**************************************************************************//
121 // Config
122 //**************************************************************************//
123 #include "parser-cfg.h"
124 #include "parser-mpcmd.h"
126 //**************************************************************************//
127 // Config file
128 //**************************************************************************//
130 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
132 #include "get_path.h"
134 //**************************************************************************//
135 //**************************************************************************//
136 // Input media streaming & demultiplexer:
137 //**************************************************************************//
139 static int max_framesize=0;
141 #include "stream/stream.h"
142 #include "libmpdemux/demuxer.h"
143 #include "libmpdemux/stheader.h"
145 #ifdef CONFIG_DVDREAD
146 #include "stream/stream_dvd.h"
147 #endif
148 #include "stream/stream_dvdnav.h"
150 #include "libmpcodecs/dec_audio.h"
151 #include "libmpcodecs/dec_video.h"
152 #include "libmpcodecs/mp_image.h"
153 #include "libmpcodecs/vf.h"
154 #include "libmpcodecs/vd.h"
156 #include "mixer.h"
158 #include "mp_core.h"
159 #include "options.h"
160 #include "defaultopts.h"
162 #define Exit_SIGILL_RTCpuSel _(\
163 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
164 " It may be a bug in our new runtime CPU-detection code...\n"\
165 " Please read DOCS/HTML/en/bugreports.html.\n")
167 #define Exit_SIGILL _(\
168 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
169 " It usually happens when you run it on a CPU different than the one it was\n"\
170 " compiled/optimized for.\n"\
171 " Verify this!\n")
173 #define Exit_SIGSEGV_SIGFPE _(\
174 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
175 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
176 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
178 #define Exit_SIGCRASH _(\
179 "- MPlayer crashed. This shouldn't happen.\n"\
180 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
181 " gcc version. If you think it's MPlayer's fault, please read\n"\
182 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
183 " won't help unless you provide this information when reporting a possible bug.\n")
185 #define SystemTooSlow _("\n\n"\
186 " ************************************************\n"\
187 " **** Your system is too SLOW to play this! ****\n"\
188 " ************************************************\n\n"\
189 "Possible reasons, problems, workarounds:\n"\
190 "- Most common: broken/buggy _audio_ driver\n"\
191 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
192 " - Experiment with different values for -autosync, 30 is a good start.\n"\
193 "- Slow video output\n"\
194 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
195 "- Slow CPU\n"\
196 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
197 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
198 "- Broken file\n"\
199 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
200 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
201 " - Try -cache 8192.\n"\
202 "- Are you using -cache to play a non-interleaved AVI file?\n"\
203 " - Try -nocache.\n"\
204 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
205 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
208 //**************************************************************************//
209 //**************************************************************************//
211 // Common FIFO functions, and keyboard/event FIFO code
212 #include "mp_fifo.h"
213 int noconsolecontrols=0;
214 //**************************************************************************//
216 // benchmark:
217 double video_time_usage=0;
218 double vout_time_usage=0;
219 static double audio_time_usage=0;
220 static int total_time_usage_start=0;
221 static int total_frame_cnt=0;
222 static int drop_frame_cnt=0; // total number of dropped frames
223 int benchmark=0;
225 // options:
226 int auto_quality=0;
227 static int output_quality=0;
229 static int list_properties = 0;
231 int term_osd = 1;
232 static char* term_osd_esc = "\x1b[A\r\x1b[K";
233 static char* playing_msg = NULL;
234 // seek:
235 static double seek_to_sec;
236 static off_t seek_to_byte=0;
237 static off_t step_sec=0;
239 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
241 // A/V sync:
242 int autosync=0; // 30 might be a good default value.
244 // codecs:
245 char **audio_codec_list=NULL; // override audio codec
246 char **video_codec_list=NULL; // override video codec
247 char **audio_fm_list=NULL; // override audio codec family
248 char **video_fm_list=NULL; // override video codec family
250 // demuxer:
251 extern char *demuxer_name; // override demuxer
252 extern char *audio_demuxer_name; // override audio demuxer
253 extern char *sub_demuxer_name; // override sub demuxer
255 int vobsub_id=-1;
256 char* audio_lang=NULL;
257 char* dvdsub_lang=NULL;
258 static char* spudec_ifo=NULL;
259 int forced_subs_only=0;
260 int file_filter=1;
262 // cache2:
263 int stream_cache_size=-1;
264 #ifdef CONFIG_STREAM_CACHE
265 extern int cache_fill_status;
267 float stream_cache_min_percent=20.0;
268 float stream_cache_seek_min_percent=50.0;
269 #else
270 #define cache_fill_status 0
271 #endif
273 // dump:
274 static char *stream_dump_name="stream.dump";
275 int stream_dump_type=0;
277 // A-V sync:
278 static float default_max_pts_correction=-1;//0.01f;
279 float audio_delay=0;
280 static int ignore_start=0;
282 static int softsleep=0;
284 double force_fps=0;
285 static int force_srate=0;
286 static int audio_output_format=-1; // AF_FORMAT_UNKNOWN
287 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
288 static int play_n_frames=-1;
289 static int play_n_frames_mf=-1;
291 // sub:
292 char *font_name=NULL;
293 char *sub_font_name=NULL;
294 extern int font_fontconfig;
295 float font_factor=0.75;
296 char **sub_name=NULL;
297 float sub_delay=0;
298 float sub_fps=0;
299 int sub_auto = 1;
300 char *vobsub_name=NULL;
301 /*DSP!!char *dsp=NULL;*/
302 int subcc_enabled=0;
303 int suboverlap_enabled = 1;
305 #include "ass_mp.h"
307 char* current_module=NULL; // for debugging
310 // ---
312 #ifdef CONFIG_MENU
313 #include "m_struct.h"
314 #include "libmenu/menu.h"
315 void vf_menu_pause_update(struct vf_instance* vf);
316 extern vf_info_t vf_info_menu;
317 static const vf_info_t* const libmenu_vfs[] = {
318 &vf_info_menu,
319 NULL
321 static vf_instance_t* vf_menu = NULL;
322 int use_menu = 0;
323 static char* menu_cfg = NULL;
324 static char* menu_root = "main";
325 #endif
328 #ifdef HAVE_RTC
329 static int nortc = 1;
330 static char* rtc_device;
331 #endif
333 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
334 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
335 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
336 int use_filedir_conf;
338 #include "mpcommon.h"
339 #include "command.h"
341 #include "metadata.h"
343 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
345 const void *mpctx_get_video_out(MPContext *mpctx)
347 return mpctx->video_out;
350 const void *mpctx_get_audio_out(MPContext *mpctx)
352 return mpctx->audio_out;
355 void *mpctx_get_demuxer(MPContext *mpctx)
357 return mpctx->demuxer;
360 void *mpctx_get_playtree_iter(MPContext *mpctx)
362 return mpctx->playtree_iter;
365 void *mpctx_get_mixer(MPContext *mpctx)
367 return &mpctx->mixer;
370 int mpctx_get_global_sub_size(MPContext *mpctx)
372 return mpctx->global_sub_size;
375 int mpctx_get_osd_function(MPContext *mpctx)
377 return mpctx->osd_function;
380 static float get_relative_time(struct MPContext *mpctx)
382 unsigned int new_time = GetTimer();
383 unsigned int delta = new_time - mpctx->last_time;
384 mpctx->last_time = new_time;
385 return delta * 0.000001;
388 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
389 switch (type)
391 /* check for valid video stream */
392 case META_VIDEO_CODEC:
393 case META_VIDEO_BITRATE:
394 case META_VIDEO_RESOLUTION:
396 if (!mpctx->sh_video)
397 return 0;
398 break;
401 /* check for valid audio stream */
402 case META_AUDIO_CODEC:
403 case META_AUDIO_BITRATE:
404 case META_AUDIO_SAMPLES:
406 if (!mpctx->sh_audio)
407 return 0;
408 break;
411 /* check for valid demuxer */
412 case META_INFO_TITLE:
413 case META_INFO_ARTIST:
414 case META_INFO_ALBUM:
415 case META_INFO_YEAR:
416 case META_INFO_COMMENT:
417 case META_INFO_TRACK:
418 case META_INFO_GENRE:
420 if (!mpctx->demuxer)
421 return 0;
422 break;
425 default:
426 break;
429 return 1;
432 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
433 char **info = mpctx->demuxer->info;
434 int n;
436 if (!info || !tag)
437 return NULL;
439 for (n = 0; info[2*n] != NULL ; n++)
440 if (!strcasecmp (info[2*n], tag))
441 break;
443 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
446 char *get_metadata(struct MPContext *mpctx, metadata_t type)
448 char *meta = NULL;
449 sh_audio_t * const sh_audio = mpctx->sh_audio;
450 sh_video_t * const sh_video = mpctx->sh_video;
452 if (!is_valid_metadata_type(mpctx, type))
453 return NULL;
455 switch (type)
457 case META_NAME:
459 return strdup (mp_basename2 (mpctx->filename));
462 case META_VIDEO_CODEC:
464 if (sh_video->format == 0x10000001)
465 meta = strdup ("mpeg1");
466 else if (sh_video->format == 0x10000002)
467 meta = strdup ("mpeg2");
468 else if (sh_video->format == 0x10000004)
469 meta = strdup ("mpeg4");
470 else if (sh_video->format == 0x10000005)
471 meta = strdup ("h264");
472 else if (sh_video->format >= 0x20202020)
474 meta = malloc (8);
475 sprintf (meta, "%.4s", (char *) &sh_video->format);
477 else
479 meta = malloc (8);
480 sprintf (meta, "0x%08X", sh_video->format);
482 return meta;
485 case META_VIDEO_BITRATE:
487 meta = malloc (16);
488 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
489 return meta;
492 case META_VIDEO_RESOLUTION:
494 meta = malloc (16);
495 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
496 return meta;
499 case META_AUDIO_CODEC:
501 if (sh_audio->codec && sh_audio->codec->name)
502 meta = strdup (sh_audio->codec->name);
503 return meta;
506 case META_AUDIO_BITRATE:
508 meta = malloc (16);
509 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
510 return meta;
513 case META_AUDIO_SAMPLES:
515 meta = malloc (16);
516 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
517 return meta;
520 /* check for valid demuxer */
521 case META_INFO_TITLE:
522 return get_demuxer_info(mpctx, "Title");
524 case META_INFO_ARTIST:
525 return get_demuxer_info(mpctx, "Artist");
527 case META_INFO_ALBUM:
528 return get_demuxer_info(mpctx, "Album");
530 case META_INFO_YEAR:
531 return get_demuxer_info(mpctx, "Year");
533 case META_INFO_COMMENT:
534 return get_demuxer_info(mpctx, "Comment");
536 case META_INFO_TRACK:
537 return get_demuxer_info(mpctx, "Track");
539 case META_INFO_GENRE:
540 return get_demuxer_info(mpctx, "Genre");
542 default:
543 break;
546 return meta;
549 /// step size of mixer changes
550 int volstep = 3;
552 #ifdef CONFIG_DVDNAV
553 static void mp_dvdnav_context_free(MPContext *ctx){
554 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
555 ctx->nav_smpi = NULL;
556 if (ctx->nav_buffer) free(ctx->nav_buffer);
557 ctx->nav_buffer = NULL;
558 ctx->nav_start = NULL;
559 ctx->nav_in_size = 0;
561 #endif
563 void uninit_player(struct MPContext *mpctx, unsigned int mask){
564 mask=mpctx->initialized_flags&mask;
566 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
568 if(mask&INITIALIZED_ACODEC){
569 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
570 current_module="uninit_acodec";
571 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
572 mpctx->sh_audio=NULL;
573 mpctx->mixer.afilter = NULL;
576 if(mask&INITIALIZED_VCODEC){
577 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
578 current_module="uninit_vcodec";
579 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
580 mpctx->sh_video=NULL;
581 #ifdef CONFIG_MENU
582 vf_menu=NULL;
583 #endif
586 if(mask&INITIALIZED_DEMUXER){
587 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
588 current_module="free_demuxer";
589 if (mpctx->num_sources) {
590 mpctx->demuxer = mpctx->sources[0].demuxer;
591 for (int i = 1; i < mpctx->num_sources; i++) {
592 free_stream(mpctx->sources[i].stream);
593 free_demuxer(mpctx->sources[i].demuxer);
596 talloc_free(mpctx->sources);
597 mpctx->sources = NULL;
598 mpctx->num_sources = 0;
599 talloc_free(mpctx->timeline);
600 mpctx->timeline = NULL;
601 mpctx->num_timeline_parts = 0;
602 talloc_free(mpctx->chapters);
603 mpctx->chapters = NULL;
604 mpctx->num_chapters = 0;
605 mpctx->video_offset = 0;
606 if(mpctx->demuxer){
607 mpctx->stream=mpctx->demuxer->stream;
608 free_demuxer(mpctx->demuxer);
610 mpctx->demuxer=NULL;
613 // kill the cache process:
614 if(mask&INITIALIZED_STREAM){
615 mpctx->initialized_flags&=~INITIALIZED_STREAM;
616 current_module="uninit_stream";
617 if(mpctx->stream) free_stream(mpctx->stream);
618 mpctx->stream=NULL;
621 if(mask&INITIALIZED_VO){
622 mpctx->initialized_flags&=~INITIALIZED_VO;
623 current_module="uninit_vo";
624 vo_destroy(mpctx->video_out);
625 mpctx->video_out=NULL;
626 #ifdef CONFIG_DVDNAV
627 mp_dvdnav_context_free(mpctx);
628 #endif
631 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
632 if(mask&INITIALIZED_GETCH2){
633 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
634 current_module="uninit_getch2";
635 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
636 // restore terminal:
637 getch2_disable();
640 if(mask&INITIALIZED_VOBSUB){
641 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
642 current_module="uninit_vobsub";
643 if(vo_vobsub) vobsub_close(vo_vobsub);
644 vo_vobsub=NULL;
647 if (mask&INITIALIZED_SPUDEC){
648 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
649 current_module="uninit_spudec";
650 spudec_free(vo_spudec);
651 vo_spudec=NULL;
654 if(mask&INITIALIZED_AO){
655 mpctx->initialized_flags&=~INITIALIZED_AO;
656 current_module="uninit_ao";
657 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
658 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
659 mpctx->audio_out=NULL;
662 current_module=NULL;
665 void exit_player_with_rc(struct MPContext *mpctx, exit_reason_t how, int rc)
667 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
668 uninit_player(mpctx, INITIALIZED_ALL);
669 #if defined(__MINGW32__) || defined(__CYGWIN__)
670 timeEndPeriod(1);
671 #endif
672 #ifdef CONFIG_X11
673 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
674 #endif
676 current_module="uninit_input";
677 mp_input_uninit(mpctx->input);
678 #ifdef CONFIG_MENU
679 if (use_menu)
680 menu_uninit();
681 #endif
683 #ifdef CONFIG_FREETYPE
684 current_module="uninit_font";
685 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
686 free_font_desc(mpctx->osd->sub_font);
687 free_font_desc(vo_font);
688 vo_font = NULL;
689 done_freetype();
690 #endif
691 osd_free(mpctx->osd);
693 #ifdef CONFIG_ASS
694 ass_library_done(ass_library);
695 #endif
697 current_module="exit_player";
699 // free mplayer config
700 if(mpctx->mconfig)
701 m_config_free(mpctx->mconfig);
703 if(mpctx->playtree)
704 play_tree_free(mpctx->playtree, 1);
706 talloc_free(mpctx->key_fifo);
708 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
709 switch(how) {
710 case EXIT_QUIT:
711 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
712 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
713 break;
714 case EXIT_EOF:
715 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
716 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
717 break;
718 case EXIT_ERROR:
719 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
720 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
721 break;
722 default:
723 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
725 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
727 exit(rc);
730 static void exit_player(struct MPContext *mpctx, exit_reason_t how)
732 exit_player_with_rc(mpctx, how, 1);
735 #ifndef __MINGW32__
736 static void child_sighandler(int x){
737 pid_t pid;
738 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
740 #endif
742 #ifdef CONFIG_CRASH_DEBUG
743 static char *prog_path;
744 static int crash_debug = 0;
745 #endif
747 static void exit_sighandler(int x){
748 static int sig_count=0;
749 #ifdef CONFIG_CRASH_DEBUG
750 if (!crash_debug || x != SIGTRAP)
751 #endif
752 ++sig_count;
753 if(sig_count==5)
755 /* We're crashing bad and can't uninit cleanly :(
756 * by popular request, we make one last (dirty)
757 * effort to restore the user's
758 * terminal. */
759 getch2_disable();
760 exit(1);
762 if(sig_count==6) exit(1);
763 if(sig_count>6){
764 // can't stop :(
765 #ifndef __MINGW32__
766 kill(getpid(),SIGKILL);
767 #endif
769 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"\n" "\nMPlayer interrupted by signal %d in module: %s\n",x,
770 current_module?current_module:"unknown"
772 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
773 if(sig_count<=1)
774 switch(x){
775 case SIGINT:
776 case SIGQUIT:
777 case SIGTERM:
778 case SIGKILL:
779 async_quit_request = 1;
780 return; // killed from keyboard (^C) or killed [-9]
781 case SIGILL:
782 #if CONFIG_RUNTIME_CPUDETECT
783 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
784 #else
785 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
786 #endif
787 case SIGFPE:
788 case SIGSEGV:
789 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
790 default:
791 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
792 #ifdef CONFIG_CRASH_DEBUG
793 if (crash_debug) {
794 int gdb_pid;
795 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
796 gdb_pid = fork();
797 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
798 if (gdb_pid == 0) { // We are the child
799 char spid[20];
800 snprintf(spid, sizeof(spid), "%i", getppid());
801 getch2_disable(); // allow terminal to work properly with gdb
802 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
803 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
804 } else if (gdb_pid < 0)
805 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
806 else {
807 waitpid(gdb_pid, NULL, 0);
809 if (x == SIGTRAP) return;
811 #endif
813 getch2_disable();
814 exit(1);
817 #include "cfg-mplayer.h"
819 static int cfg_include(m_option_t *conf, char *filename)
821 return m_config_parse_config_file(conf->priv, filename);
824 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
826 char *conffile;
827 int conffile_fd;
828 if (!disable_system_conf &&
829 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
830 exit_player(mpctx, EXIT_NONE);
831 if ((conffile = get_path("")) == NULL) {
832 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
833 } else {
834 #ifdef __MINGW32__
835 mkdir(conffile);
836 #else
837 mkdir(conffile, 0777);
838 #endif
839 free(conffile);
840 if ((conffile = get_path("config")) == NULL) {
841 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
842 } else {
843 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
844 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
845 write(conffile_fd, default_config, strlen(default_config));
846 close(conffile_fd);
848 if (!disable_user_conf &&
849 m_config_parse_config_file(conf, conffile) < 0)
850 exit_player(mpctx, EXIT_NONE);
851 free(conffile);
856 #define PROFILE_CFG_PROTOCOL "protocol."
858 static void load_per_protocol_config (m_config_t* conf, const char *const file)
860 char *str;
861 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
862 m_profile_t *p;
864 /* does filename actually uses a protocol ? */
865 str = strstr (file, "://");
866 if (!str)
867 return;
869 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
870 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
871 p = m_config_get_profile (conf, protocol);
872 if (p)
874 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
875 m_config_set_profile(conf,p);
879 #define PROFILE_CFG_EXTENSION "extension."
881 static void load_per_extension_config (m_config_t* conf, const char *const file)
883 char *str;
884 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
885 m_profile_t *p;
887 /* does filename actually have an extension ? */
888 str = strrchr (file, '.');
889 if (!str)
890 return;
892 sprintf (extension, PROFILE_CFG_EXTENSION);
893 strncat (extension, ++str, 7);
894 p = m_config_get_profile (conf, extension);
895 if (p)
897 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
898 m_config_set_profile(conf,p);
902 #define PROFILE_CFG_VO "vo."
903 #define PROFILE_CFG_AO "ao."
905 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
907 char profile[strlen (cfg) + strlen (out) + 1];
908 m_profile_t *p;
910 sprintf (profile, "%s%s", cfg, out);
911 p = m_config_get_profile (conf, profile);
912 if (p)
914 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
915 m_config_set_profile(conf,p);
920 * Tries to load a config file
921 * @return 0 if file was not found, 1 otherwise
923 static int try_load_config(m_config_t *conf, const char *file)
925 struct stat st;
926 if (stat(file, &st))
927 return 0;
928 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
929 m_config_parse_config_file (conf, file);
930 return 1;
933 static void load_per_file_config (m_config_t* conf, const char *const file)
935 char *confpath;
936 char cfg[PATH_MAX];
937 char *name;
939 if (strlen(file) > PATH_MAX - 14) {
940 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
941 return;
943 sprintf (cfg, "%s.conf", file);
945 name = strrchr(cfg, '/');
946 if (HAVE_DOS_PATHS) {
947 char *tmp = strrchr(cfg, '\\');
948 if (!name || tmp > name)
949 name = tmp;
950 tmp = strrchr(cfg, ':');
951 if (!name || tmp > name)
952 name = tmp;
954 if (!name)
955 name = cfg;
956 else
957 name++;
959 if (use_filedir_conf) {
960 char dircfg[PATH_MAX];
961 strcpy(dircfg, cfg);
962 strcpy(dircfg + (name - cfg), "mplayer.conf");
963 try_load_config(conf, dircfg);
965 if (try_load_config(conf, cfg))
966 return;
969 if ((confpath = get_path (name)) != NULL)
971 try_load_config(conf, confpath);
973 free (confpath);
977 /* When libmpdemux performs a blocking operation (network connection or
978 * cache filling) if the operation fails we use this function to check
979 * if it was interrupted by the user.
980 * The function returns a new value for eof. */
981 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
983 mp_cmd_t* cmd;
984 if((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
985 switch(cmd->id) {
986 case MP_CMD_QUIT:
987 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
988 case MP_CMD_PLAY_TREE_STEP: {
989 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
990 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
991 } break;
992 case MP_CMD_PLAY_TREE_UP_STEP: {
993 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
994 } break;
995 case MP_CMD_PLAY_ALT_SRC_STEP: {
996 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
997 } break;
999 mp_cmd_free(cmd);
1001 return stop_play;
1004 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1006 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1008 play_tree_add_bpf(entry,mpctx->filename);
1011 if(!entry) {
1012 entry = mpctx->playtree_iter->tree;
1013 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1014 return PT_NEXT_ENTRY;
1016 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1017 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1018 return PT_NEXT_ENTRY;
1021 play_tree_remove(entry,1,1);
1022 return PT_NEXT_SRC;
1024 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1025 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1026 entry = mpctx->playtree_iter->tree;
1027 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1028 return PT_NEXT_ENTRY;
1030 play_tree_remove(entry,1,1);
1032 return PT_NEXT_SRC;
1035 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1037 sub_data *subd;
1038 #ifdef CONFIG_ASS
1039 ASS_Track *asst = 0;
1040 #endif
1042 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1043 return;
1046 subd = sub_read_file(filename, fps);
1047 #ifdef CONFIG_ASS
1048 if (ass_enabled)
1049 #ifdef CONFIG_ICONV
1050 asst = ass_read_file(ass_library, filename, sub_cp);
1051 #else
1052 asst = ass_read_file(ass_library, filename, 0);
1053 #endif
1054 if (ass_enabled && subd && !asst)
1055 asst = ass_read_subdata(ass_library, subd, fps);
1057 if (!asst && !subd)
1058 #else
1059 if(!subd)
1060 #endif
1061 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR, "Cannot load subtitles: %s\n",
1062 filename_recode(filename));
1064 #ifdef CONFIG_ASS
1065 if (!asst && !subd) return;
1066 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1067 #else
1068 if (!subd) return;
1069 #endif
1070 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1071 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1072 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1073 filename_recode(filename));
1074 ++mpctx->set_of_sub_size;
1075 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1076 filename_recode(filename));
1079 void init_vo_spudec(struct MPContext *mpctx)
1081 if (vo_spudec)
1082 spudec_free(vo_spudec);
1083 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1084 vo_spudec = NULL;
1085 if (spudec_ifo) {
1086 unsigned int palette[16], width, height;
1087 current_module="spudec_init_vobsub";
1088 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1089 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1092 #ifdef CONFIG_DVDREAD
1093 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1094 current_module="spudec_init_dvdread";
1095 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1096 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1097 NULL, 0);
1099 #endif
1101 #ifdef CONFIG_DVDNAV
1102 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1103 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1104 current_module="spudec_init_dvdnav";
1105 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1107 #endif
1109 if (vo_spudec==NULL) {
1110 sh_sub_t *sh = (sh_sub_t *)mpctx->d_sub->sh;
1111 current_module="spudec_init_normal";
1112 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1113 spudec_set_font_factor(vo_spudec,font_factor);
1116 if (vo_spudec!=NULL) {
1117 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1118 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1123 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1124 * make it all work is to use the builtin SDL-bootstrap code, which
1125 * will be done automatically by replacing our main() if we include SDL.h.
1127 #if defined(__APPLE__) && defined(CONFIG_SDL)
1128 #include <SDL.h>
1129 #endif
1132 * \brief append a formatted string
1133 * \param buf buffer to print into
1134 * \param pos position of terminating 0 in buf
1135 * \param len maximum number of characters in buf, not including terminating 0
1136 * \param format printf format string
1138 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1140 va_list va;
1141 va_start(va, format);
1142 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1143 va_end(va);
1144 if (*pos >= len ) {
1145 buf[len] = 0;
1146 *pos = len;
1151 * \brief append time in the hh:mm:ss.f format
1152 * \param buf buffer to print into
1153 * \param pos position of terminating 0 in buf
1154 * \param len maximum number of characters in buf, not including terminating 0
1155 * \param time time value to convert/append
1157 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1158 long tenths = 10 * time;
1159 int f1 = tenths % 10;
1160 int ss = (tenths / 10) % 60;
1161 int mm = (tenths / 600) % 60;
1162 int hh = tenths / 36000;
1163 if (time <= 0) {
1164 saddf(buf, pos, len, "unknown");
1165 return;
1167 if (hh > 0)
1168 saddf(buf, pos, len, "%2d:", hh);
1169 if (hh > 0 || mm > 0)
1170 saddf(buf, pos, len, "%02d:", mm);
1171 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1174 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1176 struct MPOpts *opts = &mpctx->opts;
1177 sh_video_t * const sh_video = mpctx->sh_video;
1179 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1180 a_pos = playing_audio_pts(mpctx);
1181 if (mpctx->sh_audio && sh_video && at_frame) {
1182 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1183 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1184 && !mpctx->drop_message_shown) {
1185 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1186 mpctx->drop_message_shown = true;
1189 if (quiet)
1190 return;
1193 int width;
1194 char *line;
1195 unsigned pos = 0;
1196 get_screen_size();
1197 if (screen_width > 0)
1198 width = screen_width;
1199 else
1200 width = 80;
1201 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1202 /* Windows command line is broken (MinGW's rxvt works, but we
1203 * should not depend on that). */
1204 width--;
1205 #endif
1206 line = malloc(width + 1); // one additional char for the terminating null
1208 // Audio time
1209 if (mpctx->sh_audio) {
1210 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1211 if (!sh_video) {
1212 float len = demuxer_get_time_length(mpctx->demuxer);
1213 saddf(line, &pos, width, "(");
1214 sadd_hhmmssf(line, &pos, width, a_pos);
1215 saddf(line, &pos, width, ") of %.1f (", len);
1216 sadd_hhmmssf(line, &pos, width, len);
1217 saddf(line, &pos, width, ") ");
1221 // Video time
1222 if (sh_video)
1223 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1225 // A-V sync
1226 if (mpctx->sh_audio && sh_video)
1227 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1228 mpctx->last_av_difference, mpctx->total_avsync_change);
1230 // Video stats
1231 if (sh_video)
1232 saddf(line, &pos, width, "%3d/%3d ",
1233 (int)sh_video->num_frames,
1234 (int)sh_video->num_frames_decoded);
1236 // CPU usage
1237 if (sh_video) {
1238 if (sh_video->timer > 0.5)
1239 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1240 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1241 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1242 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1243 else
1244 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1245 } else if (mpctx->sh_audio) {
1246 if (mpctx->delay > 0.5)
1247 saddf(line, &pos, width, "%4.1f%% ",
1248 100.0*audio_time_usage/(double)mpctx->delay);
1249 else
1250 saddf(line, &pos, width, "??,?%% ");
1253 // VO stats
1254 if (sh_video)
1255 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1257 #ifdef CONFIG_STREAM_CACHE
1258 // cache stats
1259 if (stream_cache_size > 0)
1260 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1261 #endif
1263 // other
1264 if (opts->playback_speed != 1)
1265 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1267 // end
1268 if (erase_to_end_of_line) {
1269 line[pos] = 0;
1270 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1271 } else {
1272 memset(&line[pos], ' ', width - pos);
1273 line[width] = 0;
1274 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1276 free(line);
1280 * \brief build a chain of audio filters that converts the input format
1281 * to the ao's format, taking into account the current playback_speed.
1282 * \param sh_audio describes the requested input format of the chain.
1283 * \param ao_data describes the requested output format of the chain.
1285 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1287 struct MPOpts *opts = &mpctx->opts;
1288 int new_srate;
1289 int result;
1290 if (!sh_audio)
1292 mpctx->mixer.afilter = NULL;
1293 return 0;
1295 if(af_control_any_rev(sh_audio->afilter,
1296 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1297 &opts->playback_speed)) {
1298 new_srate = sh_audio->samplerate;
1299 } else {
1300 new_srate = sh_audio->samplerate * opts->playback_speed;
1301 if (new_srate != ao_data->samplerate) {
1302 // limits are taken from libaf/af_resample.c
1303 if (new_srate < 8000)
1304 new_srate = 8000;
1305 if (new_srate > 192000)
1306 new_srate = 192000;
1307 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1310 result = init_audio_filters(sh_audio, new_srate,
1311 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1312 mpctx->mixer.afilter = sh_audio->afilter;
1313 return result;
1317 typedef struct mp_osd_msg mp_osd_msg_t;
1318 struct mp_osd_msg {
1319 /// Previous message on the stack.
1320 mp_osd_msg_t* prev;
1321 /// Message text.
1322 char msg[128];
1323 int id,level,started;
1324 /// Display duration in ms.
1325 unsigned time;
1328 /// OSD message stack.
1329 static mp_osd_msg_t* osd_msg_stack = NULL;
1332 * \brief Add a message on the OSD message stack
1334 * If a message with the same id is already present in the stack
1335 * it is pulled on top of the stack, otherwise a new message is created.
1339 void set_osd_msg(int id, int level, int time, const char* fmt, ...) {
1340 mp_osd_msg_t *msg,*last=NULL;
1341 va_list va;
1342 int r;
1344 // look if the id is already in the stack
1345 for(msg = osd_msg_stack ; msg && msg->id != id ;
1346 last = msg, msg = msg->prev);
1347 // not found: alloc it
1348 if(!msg) {
1349 msg = calloc(1,sizeof(mp_osd_msg_t));
1350 msg->prev = osd_msg_stack;
1351 osd_msg_stack = msg;
1352 } else if(last) { // found, but it's not on top of the stack
1353 last->prev = msg->prev;
1354 msg->prev = osd_msg_stack;
1355 osd_msg_stack = msg;
1357 // write the msg
1358 va_start(va,fmt);
1359 r = vsnprintf(msg->msg, 128, fmt, va);
1360 va_end(va);
1361 if(r >= 128) msg->msg[127] = 0;
1362 // set id and time
1363 msg->id = id;
1364 msg->level = level;
1365 msg->time = time;
1370 * \brief Remove a message from the OSD stack
1372 * This function can be used to get rid of a message right away.
1376 void rm_osd_msg(int id) {
1377 mp_osd_msg_t *msg,*last=NULL;
1379 // Search for the msg
1380 for(msg = osd_msg_stack ; msg && msg->id != id ;
1381 last = msg, msg = msg->prev);
1382 if(!msg) return;
1384 // Detach it from the stack and free it
1385 if(last)
1386 last->prev = msg->prev;
1387 else
1388 osd_msg_stack = msg->prev;
1389 free(msg);
1393 * \brief Remove all messages from the OSD stack
1397 static void clear_osd_msgs(void) {
1398 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1399 while(msg) {
1400 prev = msg->prev;
1401 free(msg);
1402 msg = prev;
1404 osd_msg_stack = NULL;
1408 * \brief Get the current message from the OSD stack.
1410 * This function decrements the message timer and destroys the old ones.
1411 * The message that should be displayed is returned (if any).
1415 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1417 struct MPOpts *opts = &mpctx->opts;
1418 mp_osd_msg_t *msg,*prev,*last = NULL;
1419 static unsigned last_update = 0;
1420 unsigned now = GetTimerMS();
1421 unsigned diff;
1422 char hidden_dec_done = 0;
1424 if (mpctx->osd_visible) {
1425 // 36000000 means max timed visibility is 1 hour into the future, if
1426 // the difference is greater assume it's wrapped around from below 0
1427 if (mpctx->osd_visible - now > 36000000) {
1428 mpctx->osd_visible = 0;
1429 vo_osd_progbar_type = -1; // disable
1430 vo_osd_changed(OSDTYPE_PROGBAR);
1431 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1434 if (mpctx->osd_show_percentage_until - now > 36000000)
1435 mpctx->osd_show_percentage_until = 0;
1437 if(!last_update) last_update = now;
1438 diff = now >= last_update ? now - last_update : 0;
1440 last_update = now;
1442 // Look for the first message in the stack with high enough level.
1443 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1444 prev = msg->prev;
1445 if (msg->level > opts->osd_level && hidden_dec_done)
1446 continue;
1447 // The message has a high enough level or it is the first hidden one
1448 // in both cases we decrement the timer or kill it.
1449 if(!msg->started || msg->time > diff) {
1450 if(msg->started) msg->time -= diff;
1451 else msg->started = 1;
1452 // display it
1453 if (msg->level <= opts->osd_level)
1454 return msg;
1455 hidden_dec_done = 1;
1456 continue;
1458 // kill the message
1459 free(msg);
1460 if(last) {
1461 last->prev = prev;
1462 msg = last;
1463 } else {
1464 osd_msg_stack = prev;
1465 msg = NULL;
1468 // Nothing found
1469 return NULL;
1473 * \brief Display the OSD bar.
1475 * Display the OSD bar or fall back on a simple message.
1479 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1480 struct MPOpts *opts = &mpctx->opts;
1481 if (opts->osd_level < 1)
1482 return;
1484 if(mpctx->sh_video) {
1485 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1486 vo_osd_progbar_type = type;
1487 vo_osd_progbar_value = 256*(val-min)/(max-min);
1488 vo_osd_changed(OSDTYPE_PROGBAR);
1489 return;
1492 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1493 name, ROUND(100*(val-min)/(max-min)));
1498 * \brief Update the OSD message line.
1500 * This function displays the current message on the vo OSD or on the term.
1501 * If the stack is empty and the OSD level is high enough the timer
1502 * is displayed (only on the vo OSD).
1506 static void update_osd_msg(struct MPContext *mpctx)
1508 struct MPOpts *opts = &mpctx->opts;
1509 mp_osd_msg_t *msg;
1510 struct osd_state *osd = mpctx->osd;
1511 char osd_text_timer[128];
1513 if (mpctx->add_osd_seek_info) {
1514 double percentage;
1515 if (mpctx->timeline && mpctx->sh_video)
1516 percentage = mpctx->sh_video->pts * 100 /
1517 mpctx->timeline[mpctx->num_timeline_parts].start;
1518 else
1519 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1520 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1521 if (mpctx->sh_video)
1522 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1523 mpctx->add_osd_seek_info = false;
1526 // Look if we have a msg
1527 if((msg = get_osd_msg(mpctx))) {
1528 if (strcmp(osd->osd_text, msg->msg)) {
1529 strncpy(osd->osd_text, msg->msg, 127);
1530 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1531 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1533 return;
1536 if(mpctx->sh_video) {
1537 // fallback on the timer
1538 if (opts->osd_level >= 2) {
1539 int len;
1540 if (mpctx->timeline)
1541 len = mpctx->timeline[mpctx->num_timeline_parts].start;
1542 else
1543 len = demuxer_get_time_length(mpctx->demuxer);
1544 int percentage = -1;
1545 char percentage_text[10];
1546 int pts = demuxer_get_current_time(mpctx->demuxer);
1548 if (mpctx->osd_show_percentage_until)
1549 if (mpctx->timeline)
1550 percentage = mpctx->sh_video->pts * 100 /
1551 mpctx->timeline[mpctx->num_timeline_parts].start;
1552 else
1553 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1555 if (percentage >= 0)
1556 snprintf(percentage_text, 9, " (%d%%)", percentage);
1557 else
1558 percentage_text[0] = 0;
1560 if (opts->osd_level == 3)
1561 snprintf(osd_text_timer, 63,
1562 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1563 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1564 len/3600,(len/60)%60,len%60,percentage_text);
1565 else
1566 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1567 mpctx->osd_function,pts/3600,(pts/60)%60,
1568 pts%60,percentage_text);
1569 } else
1570 osd_text_timer[0]=0;
1572 if (strcmp(osd->osd_text, osd_text_timer)) {
1573 strncpy(osd->osd_text, osd_text_timer, 63);
1574 vo_osd_changed(OSDTYPE_OSD);
1576 return;
1579 // Clear the term osd line
1580 if (term_osd && osd->osd_text[0]) {
1581 osd->osd_text[0] = 0;
1582 printf("%s\n",term_osd_esc);
1586 ///@}
1587 // OSDMsgStack
1590 void reinit_audio_chain(struct MPContext *mpctx)
1592 struct MPOpts *opts = &mpctx->opts;
1593 if(mpctx->sh_audio){
1594 current_module="init_audio_codec";
1595 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1596 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1597 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // failed to init :(
1598 mpctx->d_audio->id = -2;
1599 return;
1600 } else
1601 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1602 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1605 //const ao_info_t *info=audio_out->info;
1606 current_module="af_preinit";
1607 ao_data.samplerate=force_srate;
1608 ao_data.channels=0;
1609 ao_data.format=audio_output_format;
1610 #if 1
1611 // first init to detect best values
1612 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1613 // input:
1614 mpctx->sh_audio->samplerate,
1615 // output:
1616 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1617 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Error at audio filter chain pre-init!\n");
1618 exit_player(mpctx, EXIT_ERROR);
1620 #endif
1621 current_module="ao2_init";
1622 if(!(mpctx->audio_out=init_best_audio_out(opts->audio_driver_list,
1623 0, // plugin flag
1624 ao_data.samplerate,
1625 ao_data.channels,
1626 ao_data.format,0))){
1627 // FAILED:
1628 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1629 uninit_player(mpctx, INITIALIZED_ACODEC); // close codec
1630 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1631 mpctx->d_audio->id = -2;
1632 return;
1633 } else {
1634 // SUCCESS:
1635 mpctx->initialized_flags|=INITIALIZED_AO;
1636 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1637 mpctx->audio_out->info->short_name,
1638 ao_data.samplerate, ao_data.channels,
1639 af_fmt2str_short(ao_data.format),
1640 af_fmt2bits(ao_data.format)/8 );
1641 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1642 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1643 if(strlen(mpctx->audio_out->info->comment) > 0)
1644 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1645 // init audio filters:
1646 #if 1
1647 current_module="af_init";
1648 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1649 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1650 // mp_msg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter / ao format! -> NOSOUND\n");
1651 // uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec & ao
1652 // sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1654 #endif
1656 mpctx->mixer.audio_out = mpctx->audio_out;
1657 mpctx->mixer.volstep = volstep;
1662 ///@}
1663 // Command2Property
1666 // Return pts value corresponding to the end point of audio written to the
1667 // ao so far.
1668 static double written_audio_pts(struct MPContext *mpctx)
1670 sh_audio_t *sh_audio = mpctx->sh_audio;
1671 demux_stream_t *d_audio = mpctx->d_audio;
1672 double buffered_output;
1673 // first calculate the end pts of audio that has been output by decoder
1674 double a_pts = sh_audio->pts;
1675 if (a_pts != MP_NOPTS_VALUE)
1676 // Good, decoder supports new way of calculating audio pts.
1677 // sh_audio->pts is the timestamp of the latest input packet with
1678 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1679 // the amount of bytes the decoder has written after that timestamp.
1680 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1681 else {
1682 // Decoder doesn't support new way of calculating pts (or we're
1683 // being called before it has decoded anything with known timestamp).
1684 // Use the old method of audio pts calculation: take the timestamp
1685 // of last packet with known pts the decoder has read data from,
1686 // and add amount of bytes read after the beginning of that packet
1687 // divided by input bps. This will be inaccurate if the input/output
1688 // ratio is not constant for every audio packet or if it is constant
1689 // but not accurately known in sh_audio->i_bps.
1691 a_pts = d_audio->pts;
1692 // ds_tell_pts returns bytes read after last timestamp from
1693 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1694 // it has read but not decoded
1695 if (sh_audio->i_bps)
1696 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1697 (double)sh_audio->i_bps;
1699 // Now a_pts hopefully holds the pts for end of audio from decoder.
1700 // Substract data in buffers between decoder and audio out.
1702 // Decoded but not filtered
1703 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1705 // Data buffered in audio filters, measured in bytes of "missing" output
1706 buffered_output = af_calc_delay(sh_audio->afilter);
1708 // Data that was ready for ao but was buffered because ao didn't fully
1709 // accept everything to internal buffers yet
1710 buffered_output += sh_audio->a_out_buffer_len;
1712 // Filters divide audio length by playback_speed, so multiply by it
1713 // to get the length in original units without speedup or slowdown
1714 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1716 return a_pts + mpctx->video_offset;
1719 // Return pts value corresponding to currently playing audio.
1720 double playing_audio_pts(struct MPContext *mpctx)
1722 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1723 mpctx->audio_out->get_delay();
1726 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1727 struct MPOpts *opts = &mpctx->opts;
1728 // check for frame-drop:
1729 current_module = "check_framedrop";
1730 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1731 static int dropped_frames;
1732 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1733 float d = delay-mpctx->delay;
1734 ++total_frame_cnt;
1735 // we should avoid dropping too many frames in sequence unless we
1736 // are too late. and we allow 100ms A-V delay here:
1737 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1738 && !mpctx->update_video_immediately) {
1739 ++drop_frame_cnt;
1740 ++dropped_frames;
1741 return frame_dropping;
1742 } else
1743 dropped_frames = 0;
1745 return 0;
1749 #ifdef HAVE_RTC
1750 int rtc_fd = -1;
1751 #endif
1753 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1755 #ifdef HAVE_RTC
1756 if (rtc_fd >= 0){
1757 // -------- RTC -----------
1758 current_module="sleep_rtc";
1759 while (time_frame > 0.000) {
1760 unsigned long rtc_ts;
1761 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1762 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1763 time_frame -= get_relative_time(mpctx);
1765 } else
1766 #endif
1768 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1769 // unnecessarily high CPU usage
1770 float margin = softsleep ? 0.011 : 0;
1771 current_module = "sleep_timer";
1772 while (time_frame > margin) {
1773 usec_sleep(1000000 * (time_frame - margin));
1774 time_frame -= get_relative_time(mpctx);
1776 if (softsleep){
1777 current_module = "sleep_soft";
1778 if (time_frame < 0)
1779 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1780 while (time_frame > 0)
1781 time_frame -= get_relative_time(mpctx); // burn the CPU
1784 return time_frame;
1787 #ifdef CONFIG_DVDNAV
1788 #ifndef FF_B_TYPE
1789 #define FF_B_TYPE 3
1790 #endif
1791 /// store decoded video image
1792 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1793 mp_image_t *from_mpi) {
1794 mp_image_t *mpi;
1796 /// Do not store B-frames
1797 if (from_mpi->pict_type == FF_B_TYPE)
1798 return to_mpi;
1800 if (to_mpi &&
1801 to_mpi->w == from_mpi->w &&
1802 to_mpi->h == from_mpi->h &&
1803 to_mpi->imgfmt == from_mpi->imgfmt)
1804 mpi = to_mpi;
1805 else {
1806 if (to_mpi)
1807 free_mp_image(to_mpi);
1808 if (from_mpi->w == 0 || from_mpi->h == 0)
1809 return NULL;
1810 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1813 copy_mpi(mpi,from_mpi);
1814 return mpi;
1817 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1818 struct MPOpts *opts = &ctx->opts;
1819 if (ctx->sh_video) {
1820 /// clear video pts
1821 ctx->d_video->pts = 0.0f;
1822 ctx->sh_video->pts = 0.0f;
1823 ctx->sh_video->i_pts = 0.0f;
1824 ctx->sh_video->last_pts = 0.0f;
1825 ctx->sh_video->num_buffered_pts = 0;
1826 ctx->sh_video->num_frames = 0;
1827 ctx->sh_video->num_frames_decoded = 0;
1828 ctx->sh_video->timer = 0.0f;
1829 ctx->sh_video->stream_delay = 0.0f;
1830 ctx->sh_video->timer = 0;
1831 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1834 if (ctx->sh_audio) {
1835 /// free audio packets and reset
1836 ds_free_packs(ctx->d_audio);
1837 audio_delay -= ctx->sh_audio->stream_delay;
1838 ctx->delay =- audio_delay;
1839 ctx->audio_out->reset();
1840 resync_audio_stream(ctx->sh_audio);
1843 if (ctx->d_sub) opts->sub_id = -2;
1845 audio_delay = 0.0f;
1847 /// clear all EOF related flags
1848 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1851 /// Restore last decoded DVDNAV (still frame)
1852 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
1853 int *in_size,
1854 unsigned char **start,
1855 mp_image_t *decoded_frame)
1857 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1858 return decoded_frame;
1860 /// a change occured in dvdnav stream
1861 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
1862 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
1863 mp_dvdnav_context_free(mpctx);
1864 mp_dvdnav_reset_stream(mpctx);
1865 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
1866 mp_dvdnav_cell_has_changed(mpctx->stream,1);
1869 if (*in_size < 0) {
1870 float len;
1872 /// Display still frame, if any
1873 if (mpctx->nav_smpi && !mpctx->nav_buffer)
1874 decoded_frame = mpctx->nav_smpi;
1876 /// increment video frame : continue playing after still frame
1877 len = demuxer_get_time_length(mpctx->demuxer);
1878 if (mpctx->sh_video->pts >= len &&
1879 mpctx->sh_video->pts > 0.0 && len > 0.0) {
1880 mp_dvdnav_skip_still(mpctx->stream);
1881 mp_dvdnav_skip_wait(mpctx->stream);
1883 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
1885 if (mpctx->nav_buffer) {
1886 *start = mpctx->nav_start;
1887 *in_size = mpctx->nav_in_size;
1888 if (mpctx->nav_start)
1889 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
1893 return decoded_frame;
1896 /// Save last decoded DVDNAV (still frame)
1897 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
1898 unsigned char *start,
1899 mp_image_t *decoded_frame)
1901 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1902 return;
1904 if (mpctx->nav_buffer)
1905 free(mpctx->nav_buffer);
1907 mpctx->nav_buffer = malloc(in_size);
1908 mpctx->nav_start = start;
1909 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
1910 if (mpctx->nav_buffer)
1911 memcpy(mpctx->nav_buffer,start,in_size);
1913 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
1914 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
1916 #endif /* CONFIG_DVDNAV */
1918 /* Modify video timing to match the audio timeline. There are two main
1919 * reasons this is needed. First, video and audio can start from different
1920 * positions at beginning of file or after a seek (MPlayer starts both
1921 * immediately even if they have different pts). Second, the file can have
1922 * audio timestamps that are inconsistent with the duration of the audio
1923 * packets, for example two consecutive timestamp values differing by
1924 * one second but only a packet with enough samples for half a second
1925 * of playback between them.
1927 static void adjust_sync(struct MPContext *mpctx, double frame_time)
1929 struct MPOpts *opts = &mpctx->opts;
1930 current_module = "av_sync";
1932 if (!mpctx->sh_audio)
1933 return;
1935 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
1936 double v_pts = mpctx->sh_video->pts;
1937 double av_delay = a_pts - v_pts;
1938 // Try to sync vo_flip() so it will *finish* at given time
1939 av_delay += mpctx->last_vo_flip_duration;
1940 av_delay -= audio_delay; // This much pts difference is desired
1942 double change = av_delay * 0.1;
1943 double max_change = default_max_pts_correction >= 0 ?
1944 default_max_pts_correction : frame_time * 0.1;
1945 if (change < -max_change)
1946 change = -max_change;
1947 else if (change > max_change)
1948 change = max_change;
1949 mpctx->delay += change;
1950 mpctx->total_avsync_change += change;
1953 static int fill_audio_out_buffers(struct MPContext *mpctx)
1955 struct MPOpts *opts = &mpctx->opts;
1956 unsigned int t;
1957 double tt;
1958 int playsize;
1959 int playflags=0;
1960 int audio_eof=0;
1961 int bytes_to_write;
1962 sh_audio_t * const sh_audio = mpctx->sh_audio;
1964 current_module="play_audio";
1966 while (1) {
1967 int sleep_time;
1968 // all the current uses of ao_data.pts seem to be in aos that handle
1969 // sync completely wrong; there should be no need to use ao_data.pts
1970 // in get_space()
1971 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
1972 bytes_to_write = mpctx->audio_out->get_space();
1973 if (mpctx->sh_video || bytes_to_write >= ao_data.outburst)
1974 break;
1976 // handle audio-only case:
1977 // this is where mplayer sleeps during audio-only playback
1978 // to avoid 100% CPU use
1979 sleep_time = (ao_data.outburst - bytes_to_write) * 1000 / ao_data.bps;
1980 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
1981 usec_sleep(sleep_time * 1000);
1984 while (bytes_to_write) {
1985 playsize = bytes_to_write;
1986 if (playsize > MAX_OUTBURST)
1987 playsize = MAX_OUTBURST;
1988 bytes_to_write -= playsize;
1990 // Fill buffer if needed:
1991 current_module="decode_audio";
1992 t = GetTimer();
1993 if (decode_audio(sh_audio, playsize) < 0) // EOF or error
1994 if (mpctx->d_audio->eof) {
1995 audio_eof = 1;
1996 if (sh_audio->a_out_buffer_len == 0)
1997 return 0;
1999 t = GetTimer() - t;
2000 tt = t*0.000001f; audio_time_usage+=tt;
2001 if (playsize > sh_audio->a_out_buffer_len) {
2002 playsize = sh_audio->a_out_buffer_len;
2003 if (audio_eof)
2004 playflags |= AOPLAY_FINAL_CHUNK;
2006 if (!playsize)
2007 break;
2009 // play audio:
2010 current_module="play_audio";
2012 // Is this pts value actually useful for the aos that access it?
2013 // They're obviously badly broken in the way they handle av sync;
2014 // would not having access to this make them more broken?
2015 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2016 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2018 if (playsize > 0) {
2019 sh_audio->a_out_buffer_len -= playsize;
2020 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2021 sh_audio->a_out_buffer_len);
2022 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2024 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2025 // Sanity check to avoid hanging in case current ao doesn't output
2026 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2027 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2028 sh_audio->a_out_buffer_len = 0;
2031 return 1;
2034 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2035 float *aq_sleep_time)
2037 struct MPOpts *opts = &mpctx->opts;
2038 int frame_time_remaining = 0;
2039 current_module="calc_sleep_time";
2041 *time_frame -= get_relative_time(mpctx); // reset timer
2043 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2044 float delay = mpctx->audio_out->get_delay();
2045 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2047 if (autosync) {
2049 * Adjust this raw delay value by calculating the expected
2050 * delay for this frame and generating a new value which is
2051 * weighted between the two. The higher autosync is, the
2052 * closer to the delay value gets to that which "-nosound"
2053 * would have used, and the longer it will take for A/V
2054 * sync to settle at the right value (but it eventually will.)
2055 * This settling time is very short for values below 100.
2057 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2058 float difference = delay - predicted;
2059 delay = predicted + difference / (float)autosync;
2062 *time_frame = delay - mpctx->delay / opts->playback_speed;
2064 // delay = amount of audio buffered in soundcard/driver
2065 if (delay > 0.25) delay=0.25; else
2066 if (delay < 0.10) delay=0.10;
2067 if (*time_frame > delay*0.6) {
2068 // sleep time too big - may cause audio drops (buffer underrun)
2069 frame_time_remaining = 1;
2070 *time_frame = delay*0.5;
2072 } else {
2073 // If we're lagging more than 200 ms behind the right playback rate,
2074 // don't try to "catch up".
2075 // If benchmark is set always output frames as fast as possible
2076 // without sleeping.
2077 if (*time_frame < -0.2 || benchmark)
2078 *time_frame = 0;
2081 *aq_sleep_time += *time_frame;
2084 //============================== SLEEP: ===================================
2086 // flag 256 means: libvo driver does its timing (dvb card)
2087 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2088 *time_frame = timing_sleep(mpctx, *time_frame);
2089 return frame_time_remaining;
2092 int reinit_video_chain(struct MPContext *mpctx)
2094 struct MPOpts *opts = &mpctx->opts;
2095 sh_video_t * const sh_video = mpctx->sh_video;
2096 double ar=-1.0;
2097 //================== Init VIDEO (codec & libvo) ==========================
2098 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2099 current_module="preinit_libvo";
2101 //shouldn't we set dvideo->id=-2 when we fail?
2102 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2103 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2104 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2105 goto err_out;
2107 mpctx->initialized_flags|=INITIALIZED_VO;
2110 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2111 mpctx->sh_video->stream_aspect = ar;
2112 current_module="init_video_filters";
2114 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2115 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2117 #ifdef CONFIG_MENU
2118 if(use_menu) {
2119 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2120 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2121 if(!vf_menu) {
2122 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2123 use_menu = 0;
2126 if(vf_menu)
2127 sh_video->vfilter = vf_menu;
2128 #endif
2130 #ifdef CONFIG_ASS
2131 if(ass_enabled) {
2132 int i;
2133 int insert = 1;
2134 if (opts->vf_settings)
2135 for (i = 0; opts->vf_settings[i].name; ++i)
2136 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2137 insert = 0;
2138 break;
2140 if (insert) {
2141 extern vf_info_t vf_info_ass;
2142 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2143 char* vf_arg[] = {"auto", "1", NULL};
2144 vf_instance_t* vf_ass = vf_open_plugin(opts, libass_vfs,sh_video->vfilter,"ass",vf_arg);
2145 if (vf_ass)
2146 sh_video->vfilter = vf_ass;
2147 else
2148 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2151 #endif
2153 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2155 #ifdef CONFIG_ASS
2156 if (ass_enabled)
2157 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2158 #endif
2160 current_module="init_video_codec";
2162 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2163 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2164 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2166 if(!sh_video->initialized){
2167 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2168 goto err_out;
2171 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2173 if (sh_video->codec)
2174 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2176 sh_video->last_pts = MP_NOPTS_VALUE;
2177 sh_video->num_buffered_pts = 0;
2178 sh_video->next_frame_time = 0;
2180 if(auto_quality>0){
2181 // Auto quality option enabled
2182 output_quality=get_video_quality_max(sh_video);
2183 if(auto_quality>output_quality) auto_quality=output_quality;
2184 else output_quality=auto_quality;
2185 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2186 set_video_quality(sh_video,output_quality);
2189 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2191 current_module="init_vo";
2193 return 1;
2195 err_out:
2196 mpctx->sh_video = mpctx->d_video->sh = NULL;
2197 return 0;
2200 static double update_video_nocorrect_pts(struct MPContext *mpctx,
2201 int *blit_frame)
2203 struct sh_video *sh_video = mpctx->sh_video;
2204 *blit_frame = 0;
2205 double frame_time = 0;
2206 while (1) {
2207 current_module = "filter_video";
2208 // In nocorrect-pts mode there is no way to properly time these frames
2209 if (vf_output_queued_frame(sh_video->vfilter))
2210 break;
2211 unsigned char *packet = NULL;
2212 frame_time = sh_video->next_frame_time;
2213 if (mpctx->update_video_immediately)
2214 frame_time = 0;
2215 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2216 &packet, force_fps);
2217 if (in_size < 0) {
2218 #ifdef CONFIG_DVDNAV
2219 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2220 if (mp_dvdnav_is_eof(mpctx->stream))
2221 return -1;
2222 if (mpctx->d_video)
2223 mpctx->d_video->eof = 0;
2224 if (mpctx->d_audio)
2225 mpctx->d_audio->eof = 0;
2226 mpctx->stream->eof = 0;
2227 } else
2228 #endif
2229 return -1;
2231 if (in_size > max_framesize)
2232 max_framesize = in_size;
2233 sh_video->timer += frame_time;
2234 if (mpctx->sh_audio)
2235 mpctx->delay -= frame_time;
2236 // video_read_frame can change fps (e.g. for ASF video)
2237 vo_fps = sh_video->fps;
2238 int framedrop_type = check_framedrop(mpctx, frame_time);
2239 current_module = "decode video";
2241 void *decoded_frame;
2242 #ifdef CONFIG_DVDNAV
2243 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2244 if (in_size >= 0 && !decoded_frame)
2245 #endif
2246 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2247 sh_video->pts);
2248 #ifdef CONFIG_DVDNAV
2249 // Save last still frame for future display
2250 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2251 #endif
2252 if (decoded_frame) {
2253 // These updates are done here for vf_expand OSD/subtitles
2254 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2255 update_teletext(sh_video, mpctx->demuxer, 0);
2256 update_osd_msg(mpctx);
2257 current_module = "filter video";
2258 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2259 break;
2262 *blit_frame = 1;
2263 return frame_time;
2266 static double update_video(struct MPContext *mpctx, int *blit_frame)
2268 struct sh_video *sh_video = mpctx->sh_video;
2269 struct vo *video_out = mpctx->video_out;
2270 *blit_frame = 0;
2271 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2272 mpctx->osd); // hack for vf_expand
2273 if (!mpctx->opts.correct_pts)
2274 return update_video_nocorrect_pts(mpctx, blit_frame);
2276 double pts;
2278 bool hit_eof = false;
2279 while (!video_out->frame_loaded) {
2280 current_module = "filter_video";
2281 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2282 break;
2283 if (hit_eof)
2284 return -1;
2285 // XXX Time used in this call is not counted in any performance
2286 // timer now, OSD time is not updated correctly for filter-added frames
2287 if (vf_output_queued_frame(sh_video->vfilter))
2288 break;
2289 unsigned char *packet = NULL;
2290 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2291 if (pts != MP_NOPTS_VALUE)
2292 pts += mpctx->video_offset;
2293 if (in_size < 0) {
2294 // try to extract last frames in case of decoder lag
2295 in_size = 0;
2296 pts = 1e300;
2297 hit_eof = true;
2299 if (in_size > max_framesize)
2300 max_framesize = in_size;
2301 current_module = "decode video";
2302 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2303 void *decoded_frame = decode_video(sh_video, packet, in_size,
2304 framedrop_type, pts);
2305 if (decoded_frame) {
2306 // These updates are done here for vf_expand OSD/subtitles
2307 update_subtitles(sh_video, mpctx->d_sub, mpctx->video_offset, 0);
2308 update_teletext(sh_video, mpctx->demuxer, 0);
2309 update_osd_msg(mpctx);
2310 current_module = "filter video";
2311 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2312 if (!video_out->config_ok)
2313 break; // We'd likely hang in this loop otherwise
2317 pts = video_out->next_pts;
2318 if (pts == MP_NOPTS_VALUE) {
2319 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2320 // Try to use decoder pts from before filters
2321 pts = sh_video->pts;
2322 if (pts == MP_NOPTS_VALUE)
2323 pts = sh_video->last_pts;
2325 sh_video->pts = pts;
2326 if (sh_video->last_pts == MP_NOPTS_VALUE)
2327 sh_video->last_pts = sh_video->pts;
2328 else if (sh_video->last_pts > sh_video->pts) {
2329 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2330 sh_video->pts, sh_video->last_pts);
2331 /* If the difference in pts is small treat it as jitter around the
2332 * right value (possibly caused by incorrect timestamp ordering) and
2333 * just show this frame immediately after the last one.
2334 * Treat bigger differences as timestamp resets and start counting
2335 * timing of later frames from the position of this one. */
2336 if (sh_video->last_pts - sh_video->pts > 0.5)
2337 sh_video->last_pts = sh_video->pts;
2338 else
2339 sh_video->pts = sh_video->last_pts;
2341 double frame_time = sh_video->pts - sh_video->last_pts;
2342 sh_video->last_pts = sh_video->pts;
2343 sh_video->timer += frame_time;
2344 if (mpctx->sh_audio)
2345 mpctx->delay -= frame_time;
2346 *blit_frame = 1;
2347 return frame_time;
2350 void pause_player(struct MPContext *mpctx)
2352 if (mpctx->paused)
2353 return;
2354 mpctx->paused = 1;
2355 mpctx->step_frames = 0;
2356 mpctx->time_frame -= get_relative_time(mpctx);
2358 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2359 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2361 if (mpctx->audio_out && mpctx->sh_audio)
2362 mpctx->audio_out->pause(); // pause audio, keep data if possible
2365 void unpause_player(struct MPContext *mpctx)
2367 if (!mpctx->paused)
2368 return;
2369 mpctx->paused = 0;
2371 if (mpctx->audio_out && mpctx->sh_audio)
2372 mpctx->audio_out->resume(); // resume audio
2373 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2374 && !mpctx->step_frames)
2375 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2376 (void)get_relative_time(mpctx); // ignore time that passed during pause
2379 void add_step_frame(struct MPContext *mpctx)
2381 mpctx->step_frames++;
2382 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2383 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2384 unpause_player(mpctx);
2387 static void pause_loop(struct MPContext *mpctx)
2389 mp_cmd_t* cmd;
2390 if (!quiet) {
2391 // Small hack to display the pause message on the OSD line.
2392 // The pause string is: "\n == PAUSE == \r" so we need to
2393 // take the first and the last char out
2394 if (term_osd && !mpctx->sh_video) {
2395 char msg[128] = _("\n ===== PAUSE =====\r");
2396 int mlen = strlen(msg);
2397 msg[mlen-1] = '\0';
2398 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2399 update_osd_msg(mpctx);
2400 } else
2401 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2402 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2405 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1, 1)) == NULL
2406 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2407 if (cmd) {
2408 cmd = mp_input_get_cmd(mpctx->input, 0,1,0);
2409 run_command(mpctx, cmd);
2410 mp_cmd_free(cmd);
2411 continue;
2413 if (mpctx->sh_video && mpctx->video_out)
2414 vo_check_events(mpctx->video_out);
2415 #ifdef CONFIG_MENU
2416 if (vf_menu)
2417 vf_menu_pause_update(vf_menu);
2418 #endif
2419 usec_sleep(20000);
2420 update_osd_msg(mpctx);
2421 int hack = vo_osd_changed(0);
2422 vo_osd_changed(hack);
2423 if (hack)
2424 break;
2429 // Find the right mute status and record position for new file position
2430 static void edl_seek_reset(MPContext *mpctx)
2432 mpctx->edl_muted = 0;
2433 next_edl_record = edl_records;
2435 while (next_edl_record) {
2436 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2437 break;
2439 if (next_edl_record->action == EDL_MUTE)
2440 mpctx->edl_muted = !mpctx->edl_muted;
2441 next_edl_record = next_edl_record->next;
2443 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2444 mixer_mute(&mpctx->mixer);
2448 // Execute EDL command for the current position if one exists
2449 static void edl_update(MPContext *mpctx)
2451 if (!next_edl_record)
2452 return;
2454 if (!mpctx->sh_video) {
2455 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2456 free_edl(edl_records);
2457 next_edl_record = NULL;
2458 edl_records = NULL;
2459 return;
2462 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2463 if (next_edl_record->action == EDL_SKIP) {
2464 mpctx->osd_function = OSD_FFW;
2465 mpctx->abs_seek_pos = 0;
2466 mpctx->rel_seek_secs = next_edl_record->length_sec;
2467 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2468 "[%f], length [%f]\n", next_edl_record->start_sec,
2469 next_edl_record->stop_sec, next_edl_record->length_sec);
2471 else if (next_edl_record->action == EDL_MUTE) {
2472 mpctx->edl_muted = !mpctx->edl_muted;
2473 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2474 mixer_mute(&mpctx->mixer);
2475 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2476 next_edl_record->start_sec );
2478 next_edl_record = next_edl_record->next;
2482 static void reinit_decoders(struct MPContext *mpctx)
2484 reinit_video_chain(mpctx);
2485 reinit_audio_chain(mpctx);
2486 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2489 static bool timeline_set_part(struct MPContext *mpctx, int i)
2491 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2492 struct timeline_part *n = mpctx->timeline + i;
2493 mpctx->timeline_part = i;
2494 mpctx->video_offset = n->start - n->source_start;
2495 if (n->source == p->source)
2496 return false;
2497 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2498 mpctx->demuxer = n->source->demuxer;
2499 mpctx->d_video = mpctx->demuxer->video;
2500 mpctx->d_audio = mpctx->demuxer->audio;
2501 mpctx->d_sub = mpctx->demuxer->sub;
2502 mpctx->sh_video = mpctx->d_video->sh;
2503 mpctx->sh_audio = mpctx->d_audio->sh;
2504 return true;
2507 // Given pts, switch playback to the corresponding part.
2508 // Return offset within that part.
2509 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2510 bool *need_reset)
2512 if (pts < 0)
2513 pts = 0;
2514 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2515 struct timeline_part *p = mpctx->timeline + i;
2516 if (pts < (p+1)->start) {
2517 *need_reset = timeline_set_part(mpctx, i);
2518 return pts - p->start + p->source_start;
2521 return -1;
2525 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2526 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2527 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2528 static int seek(MPContext *mpctx, double amount, int style)
2530 current_module = "seek";
2531 if (mpctx->stop_play == AT_END_OF_FILE)
2532 mpctx->stop_play = KEEP_PLAYING;
2533 if (mpctx->timeline && style & SEEK_FACTOR) {
2534 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2535 style &= ~SEEK_FACTOR;
2537 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2538 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2539 style |= SEEK_ABSOLUTE;
2540 if (amount > 0)
2541 style |= SEEK_FORWARD;
2542 else
2543 style |= SEEK_BACKWARD;
2544 amount += mpctx->sh_video->pts;
2547 /* At least the liba52 decoder wants to read from the input stream
2548 * during initialization, so reinit must be done after the demux_seek()
2549 * call that clears possible stream EOF. */
2550 bool need_reset = false;
2551 if (mpctx->timeline) {
2552 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2553 if (amount == -1) {
2554 mpctx->stop_play = AT_END_OF_FILE;
2555 // Clear audio from current position
2556 if (mpctx->sh_audio) {
2557 mpctx->audio_out->reset();
2558 mpctx->sh_audio->a_buffer_len = 0;
2559 mpctx->sh_audio->a_out_buffer_len = 0;
2561 return -1;
2564 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2565 if (need_reset)
2566 reinit_decoders(mpctx);
2567 if (seekresult == 0)
2568 return -1;
2570 if (mpctx->sh_video) {
2571 current_module = "seek_video_reset";
2572 resync_video_stream(mpctx->sh_video);
2573 vo_seek_reset(mpctx->video_out);
2574 mpctx->sh_video->num_buffered_pts = 0;
2575 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2576 mpctx->delay = 0;
2577 mpctx->time_frame = 0;
2578 mpctx->update_video_immediately = true;
2579 // Not all demuxers set d_video->pts during seek, so this value
2580 // (which is used by at least vobsub and edl code below) may
2581 // be completely wrong (probably 0).
2582 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2583 update_subtitles(mpctx->sh_video, mpctx->d_sub, mpctx->video_offset, 1);
2584 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2587 if (mpctx->sh_audio) {
2588 current_module = "seek_audio_reset";
2589 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2590 mpctx->sh_audio->a_buffer_len = 0;
2591 mpctx->sh_audio->a_out_buffer_len = 0;
2594 if (vo_vobsub && mpctx->sh_video) {
2595 current_module = "seek_vobsub_reset";
2596 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2599 edl_seek_reset(mpctx);
2601 mpctx->total_avsync_change = 0;
2602 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2603 drop_frame_cnt = 0;
2605 current_module = NULL;
2606 return 0;
2609 int get_current_chapter(struct MPContext *mpctx)
2611 if (!mpctx->chapters || !mpctx->sh_video)
2612 return demuxer_get_current_chapter(mpctx->demuxer);
2614 int i;
2615 double current_pts = mpctx->sh_video->pts;
2616 for (i = 1; i < mpctx->num_chapters; i++)
2617 if (current_pts < mpctx->chapters[i].start)
2618 break;
2619 return i - 1;
2622 // currently returns a string allocated with malloc, not talloc
2623 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2625 if (!mpctx->chapters || !mpctx->sh_video)
2626 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2627 return strdup(mpctx->chapters[chapter].name);
2630 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2631 char **chapter_name)
2633 if (!mpctx->chapters || !mpctx->sh_video)
2634 return demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
2635 chapter_name);
2636 if (chapter >= mpctx->num_chapters)
2637 return -1;
2638 if (chapter < 0)
2639 chapter = 0;
2640 *seek_pts = mpctx->chapters[chapter].start;
2641 if (chapter_name)
2642 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
2643 return chapter;
2646 static int find_ordered_chapter_sources(struct MPContext *mpctx,
2647 struct content_source *sources,
2648 int num_sources,
2649 unsigned char uid_map[][16])
2651 int num_filenames = 0;
2652 char **filenames = NULL;
2653 if (num_sources > 1) {
2654 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
2655 "other sources.\n");
2656 if (mpctx->stream->type != STREAMTYPE_FILE) {
2657 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
2658 "normal disk file. Will not search for related files.\n");
2659 } else {
2660 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
2661 "same directory to find referenced sources.\n");
2662 filenames = find_files(mpctx->demuxer->filename, ".mkv",
2663 &num_filenames);
2667 int num_left = num_sources - 1;
2668 for (int i = 0; i < num_filenames && num_left > 0; i++) {
2669 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
2670 filename_recode(filenames[i]));
2671 int format;
2672 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
2673 if (!s)
2674 continue;
2675 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
2676 mpctx->opts.audio_id,
2677 mpctx->opts.video_id,
2678 mpctx->opts.sub_id, filenames[i]);
2679 if (!d) {
2680 free_stream(s);
2681 continue;
2683 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
2684 for (int i = 1; i < num_sources; i++) {
2685 if (sources[i].demuxer)
2686 continue;
2687 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
2688 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
2689 i, filename_recode(d->filename));
2690 sources[i].stream = s;
2691 sources[i].demuxer = d;
2692 num_left--;
2693 goto match;
2697 free_demuxer(d);
2698 free_stream(s);
2699 continue;
2700 match:
2703 talloc_free(filenames);
2704 if (num_left) {
2705 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
2706 "There will be parts MISSING from the video!\n");
2707 for (int i = 1, j = 1; i < num_sources; i++)
2708 if (sources[i].demuxer) {
2709 sources[j] = sources[i];
2710 memcpy(uid_map[j], uid_map[i], 16);
2711 j++;
2714 return num_sources - num_left;
2717 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
2719 if (!mpctx->opts.ordered_chapters) {
2720 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
2721 "you have disabled support for them. Ignoring.\n");
2722 return;
2725 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
2726 "edit timeline.\n");
2728 struct demuxer *demuxer = mpctx->demuxer;
2729 struct matroska_data *m = &demuxer->matroska_data;
2731 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
2732 m->num_ordered_chapters);
2733 sources[0].stream = mpctx->stream;
2734 sources[0].demuxer = mpctx->demuxer;
2735 unsigned char uid_map[m->num_ordered_chapters][16];
2736 int num_sources = 1;
2737 memcpy(uid_map[0], m->segment_uid, 16);
2739 for (int i = 0; i < m->num_ordered_chapters; i++) {
2740 struct matroska_chapter *c = m->ordered_chapters + i;
2741 if (!c->has_segment_uid)
2742 memcpy(c->segment_uid, m->segment_uid, 16);
2744 for (int j = 0; j < num_sources; j++)
2745 if (!memcmp(c->segment_uid, uid_map[j], 16))
2746 goto found1;
2747 memcpy(uid_map[num_sources], c->segment_uid, 16);
2748 sources[num_sources] = (struct content_source){};
2749 num_sources++;
2750 found1:
2754 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
2755 uid_map);
2758 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
2759 m->num_ordered_chapters + 1);
2760 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
2761 m->num_ordered_chapters);
2762 uint64_t starttime = 0;
2763 uint64_t missing_time = 0;
2764 int part_count = 0;
2765 int num_chapters = 0;
2766 uint64_t prev_part_offset;
2767 for (int i = 0; i < m->num_ordered_chapters; i++) {
2768 struct matroska_chapter *c = m->ordered_chapters + i;
2770 int j;
2771 for (j = 0; j < num_sources; j++) {
2772 if (!memcmp(c->segment_uid, uid_map[j], 16))
2773 goto found2;
2775 missing_time += c->end - c->start;
2776 continue;
2777 found2:;
2778 chapters[num_chapters].start = starttime / 1000.;
2779 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
2780 /* Only add a separate part if the time or file actually changes.
2781 * Matroska files have chapter divisions that are redundant from
2782 * timeline point of view because the same chapter structure is used
2783 * both to specify the timeline and for normal chapter information.
2784 * Removing a missing inserted external chapter can also cause this. */
2785 if (part_count == 0 || c->start != starttime + prev_part_offset
2786 || sources + j != timeline[part_count - 1].source) {
2787 timeline[part_count].source = sources + j;
2788 timeline[part_count].start = chapters[num_chapters].start;
2789 timeline[part_count].source_start = c->start / 1000.;
2790 prev_part_offset = c->start - starttime;
2791 part_count++;
2793 starttime += c->end - c->start;
2794 num_chapters++;
2796 timeline[part_count].start = starttime / 1000.;
2798 if (!part_count) {
2799 // None of the parts come from the file itself???
2800 talloc_free(sources);
2801 talloc_free(timeline);
2802 talloc_free(chapters);
2803 return;
2806 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
2807 "sources. Total length %.3f seconds.\n", part_count, num_sources,
2808 timeline[part_count].start);
2809 if (missing_time)
2810 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
2811 "from the timeline!\n", missing_time / 1000.);
2812 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
2813 for (int i = 0; i < num_sources; i++)
2814 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
2815 filename_recode(sources[i].demuxer->filename));
2816 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
2817 "source_start, source):\n");
2818 for (int i = 0; i < part_count; i++) {
2819 struct timeline_part *p = timeline + i;
2820 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
2821 p->source_start, p->source - sources);
2823 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
2824 mpctx->sources = sources;
2825 mpctx->num_sources = num_sources;
2826 mpctx->timeline = timeline;
2827 mpctx->num_timeline_parts = part_count;
2828 mpctx->num_chapters = num_chapters;
2829 mpctx->chapters = chapters;
2831 mpctx->timeline_part = 0;
2832 mpctx->video_offset = timeline[0].source_start;
2833 mpctx->demuxer = timeline[0].source->demuxer;
2837 static int read_keys(void *ctx, int fd)
2839 getch2(ctx);
2840 return mplayer_get_key(ctx, 0);
2844 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
2845 * file for some tools to link against. */
2846 #ifndef DISABLE_MAIN
2847 int main(int argc,char* argv[]){
2850 char * mem_ptr;
2852 // movie info:
2854 /* Flag indicating whether MPlayer should exit without playing anything. */
2855 int opt_exit = 0;
2857 //float a_frame=0; // Audio
2859 int i;
2861 struct MPContext *mpctx = &(struct MPContext){
2862 .osd_function = OSD_PLAY,
2863 .begin_skip = MP_NOPTS_VALUE,
2864 .play_tree_step = 1,
2865 .global_sub_pos = -1,
2866 .set_of_sub_pos = -1,
2867 .file_format = DEMUXER_TYPE_UNKNOWN,
2868 .last_dvb_step = 1,
2871 InitTimer();
2872 srand(GetTimerMS());
2874 mp_msg_init();
2876 #ifdef CONFIG_X11
2877 mpctx->x11_state = vo_x11_init_state();
2878 #endif
2879 struct MPOpts *opts = &mpctx->opts;
2880 set_default_mplayer_options(opts);
2881 // Create the config context and register the options
2882 mpctx->mconfig = m_config_new(opts, cfg_include);
2883 m_config_register_options(mpctx->mconfig,mplayer_opts);
2884 mp_input_register_options(mpctx->mconfig);
2886 // Preparse the command line
2887 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
2889 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
2890 set_path_env();
2891 #endif
2893 #ifdef CONFIG_TV
2894 stream_tv_defaults.immediate = 1;
2895 #endif
2897 parse_cfgfiles(mpctx, mpctx->mconfig);
2899 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
2900 if(mpctx->playtree == NULL)
2901 opt_exit = 1;
2902 else {
2903 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
2904 if(mpctx->playtree) {
2905 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
2906 if(mpctx->playtree_iter) {
2907 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
2908 play_tree_iter_free(mpctx->playtree_iter);
2909 mpctx->playtree_iter = NULL;
2911 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
2915 mpctx->key_fifo = mp_fifo_create(opts);
2917 print_version("MPlayer");
2919 #if defined(__MINGW32__) || defined(__CYGWIN__)
2921 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
2922 BOOL WINAPI (*setDEP)(DWORD) = NULL;
2923 if (kernel32)
2924 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
2925 if (setDEP) setDEP(3);
2927 // stop Windows from showing all kinds of annoying error dialogs
2928 SetErrorMode(0x8003);
2929 // request 1ms timer resolution
2930 timeBeginPeriod(1);
2931 #endif
2933 #ifdef CONFIG_PRIORITY
2934 set_priority();
2935 #endif
2937 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
2938 list_video_out();
2939 opt_exit = 1;
2942 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
2943 list_audio_out();
2944 opt_exit = 1;
2947 /* Check codecs.conf. */
2948 if(!codecs_file || !parse_codec_cfg(codecs_file)){
2949 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
2950 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
2951 if(!parse_codec_cfg(NULL)){
2952 exit_player_with_rc(mpctx, EXIT_NONE, 0);
2954 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
2957 free( mem_ptr ); // release the buffer created by get_path()
2960 #if 0
2961 if(video_codec_list){
2962 int i;
2963 video_codec=video_codec_list[0];
2964 for(i=0;video_codec_list[i];i++)
2965 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
2967 #endif
2968 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
2969 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
2970 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
2971 list_codecs(1);
2972 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2973 opt_exit = 1;
2975 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
2976 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
2977 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
2978 list_codecs(0);
2979 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2980 opt_exit = 1;
2982 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
2983 vfm_help();
2984 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2985 opt_exit = 1;
2987 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
2988 afm_help();
2989 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2990 opt_exit = 1;
2992 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
2993 af_help();
2994 printf("\n");
2995 opt_exit = 1;
2997 #ifdef CONFIG_X11
2998 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
2999 fstype_help();
3000 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3001 opt_exit = 1;
3003 #endif
3004 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
3005 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
3006 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
3007 demuxer_help();
3008 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3009 opt_exit = 1;
3011 if(list_properties) {
3012 property_print_help();
3013 opt_exit = 1;
3016 if(opt_exit)
3017 exit_player(mpctx, EXIT_NONE);
3019 if(!mpctx->filename && !player_idle_mode){
3020 // no file/vcd/dvd -> show HELP:
3021 mp_msg(MSGT_CPLAYER, MSGL_INFO, help_text);
3022 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3025 /* Display what configure line was used */
3026 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3028 // Many users forget to include command line in bugreports...
3029 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3030 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3031 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3032 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3035 //------ load global data first ------
3037 mpctx->osd = osd_create();
3039 // check font
3040 #ifdef CONFIG_FREETYPE
3041 init_freetype();
3042 #endif
3043 #ifdef CONFIG_FONTCONFIG
3044 if(font_fontconfig <= 0)
3046 #endif
3047 #ifdef CONFIG_BITMAP_FONT
3048 if(font_name){
3049 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3050 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3051 filename_recode(font_name));
3052 } else {
3053 // try default:
3054 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3055 free(mem_ptr); // release the buffer created by get_path()
3056 if(!vo_font)
3057 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3059 if (sub_font_name)
3060 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3061 else
3062 mpctx->osd->sub_font = vo_font;
3063 #endif
3064 #ifdef CONFIG_FONTCONFIG
3066 #endif
3068 #ifdef CONFIG_ASS
3069 ass_library = ass_init();
3070 #endif
3072 #ifdef HAVE_RTC
3073 if(!nortc)
3075 // seteuid(0); /* Can't hurt to try to get root here */
3076 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3077 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3078 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3079 else {
3080 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3082 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3083 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3084 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3085 close (rtc_fd);
3086 rtc_fd = -1;
3087 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3088 /* variable only by the root */
3089 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3090 close (rtc_fd);
3091 rtc_fd = -1;
3092 } else
3093 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3096 if(rtc_fd<0)
3097 #endif /* HAVE_RTC */
3098 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3099 softsleep?"software":timer_name);
3101 #ifdef HAVE_TERMCAP
3102 load_termcap(NULL); // load key-codes
3103 #endif
3105 // ========== Init keyboard FIFO (connection to libvo) ============
3107 // Init input system
3108 current_module = "init_input";
3109 mpctx->input = mp_input_init(&opts->input);
3110 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3111 if(slave_mode)
3112 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3113 else if(!noconsolecontrols)
3114 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3115 // Set the libstream interrupt callback
3116 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3118 #ifdef CONFIG_MENU
3119 if(use_menu) {
3120 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3121 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3122 else {
3123 menu_cfg = get_path("menu.conf");
3124 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3125 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3126 else {
3127 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3128 MPLAYER_CONFDIR "/menu.conf"))
3129 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3130 else {
3131 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3132 use_menu = 0;
3137 #endif
3139 current_module = NULL;
3141 /// Catch signals
3142 #ifndef __MINGW32__
3143 signal(SIGCHLD,child_sighandler);
3144 #endif
3146 #ifdef CONFIG_CRASH_DEBUG
3147 prog_path = argv[0];
3148 #endif
3149 //========= Catch terminate signals: ================
3150 // terminate requests:
3151 signal(SIGTERM,exit_sighandler); // kill
3152 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3154 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3156 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3157 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3158 #ifdef CONFIG_SIGHANDLER
3159 // fatal errors:
3160 signal(SIGBUS,exit_sighandler); // bus error
3161 signal(SIGSEGV,exit_sighandler); // segfault
3162 signal(SIGILL,exit_sighandler); // illegal instruction
3163 signal(SIGFPE,exit_sighandler); // floating point exc.
3164 signal(SIGABRT,exit_sighandler); // abort()
3165 #ifdef CONFIG_CRASH_DEBUG
3166 if (crash_debug)
3167 signal(SIGTRAP,exit_sighandler);
3168 #endif
3169 #endif
3171 // ******************* Now, let's see the per-file stuff ********************
3173 play_next_file:
3175 // init global sub numbers
3176 mpctx->global_sub_size = 0;
3177 { int i; for (i = 0; i < SUB_SOURCES; i++) mpctx->global_sub_indices[i] = -1; }
3179 if (mpctx->filename) {
3180 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3181 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3182 load_per_file_config (mpctx->mconfig, mpctx->filename);
3185 if (opts->video_driver_list)
3186 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3187 if (opts->audio_driver_list)
3188 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3190 // We must enable getch2 here to be able to interrupt network connection
3191 // or cache filling
3192 if(!noconsolecontrols && !slave_mode){
3193 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3194 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3195 else
3196 getch2_enable(); // prepare stdin for hotkeys...
3197 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3198 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3201 // =================== GUI idle loop (STOP state) ===========================
3202 while (player_idle_mode && !mpctx->filename) {
3203 play_tree_t * entry = NULL;
3204 mp_cmd_t * cmd;
3205 while (!(cmd = mp_input_get_cmd(mpctx->input, 0,1,0))) { // wait for command
3206 if (mpctx->video_out)
3207 vo_check_events(mpctx->video_out);
3208 usec_sleep(20000);
3210 switch (cmd->id) {
3211 case MP_CMD_LOADFILE:
3212 // prepare a tree entry with the new filename
3213 entry = play_tree_new();
3214 play_tree_add_file(entry, cmd->args[0].v.s);
3215 // The entry is added to the main playtree after the switch().
3216 break;
3217 case MP_CMD_LOADLIST:
3218 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3219 break;
3220 case MP_CMD_QUIT:
3221 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3222 break;
3223 case MP_CMD_GET_PROPERTY:
3224 case MP_CMD_SET_PROPERTY:
3225 case MP_CMD_STEP_PROPERTY:
3226 run_command(mpctx, cmd);
3227 break;
3230 mp_cmd_free(cmd);
3232 if (entry) { // user entered a command that gave a valid entry
3233 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3234 play_tree_free_list(mpctx->playtree->child, 1);
3235 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3237 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3239 play_tree_set_child(mpctx->playtree, entry);
3241 /* Make iterator start at the top the of tree. */
3242 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3243 if (!mpctx->playtree_iter) continue;
3245 // find the first real item in the tree
3246 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3247 // no items!
3248 play_tree_iter_free(mpctx->playtree_iter);
3249 mpctx->playtree_iter = NULL;
3250 continue; // wait for next command
3252 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3255 //---------------------------------------------------------------------------
3257 if(mpctx->filename)
3258 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3259 filename_recode(mpctx->filename));
3261 if (edl_filename) {
3262 if (edl_records) free_edl(edl_records);
3263 next_edl_record = edl_records = edl_parse_file();
3265 if (edl_output_filename) {
3266 if (edl_fd) fclose(edl_fd);
3267 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3269 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3270 filename_recode(edl_output_filename));
3274 //==================== Open VOB-Sub ============================
3276 current_module="vobsub";
3277 if (vobsub_name){
3278 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3279 if(vo_vobsub==NULL)
3280 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3281 filename_recode(vobsub_name));
3282 } else if (sub_auto && mpctx->filename){
3283 /* try to autodetect vobsub from movie filename ::atmos */
3284 char *buf = strdup(mpctx->filename), *psub;
3285 char *pdot = strrchr(buf, '.');
3286 char *pslash = strrchr(buf, '/');
3287 #if defined(__MINGW32__) || defined(__CYGWIN__)
3288 if (!pslash) pslash = strrchr(buf, '\\');
3289 #endif
3290 if (pdot && (!pslash || pdot > pslash))
3291 *pdot = '\0';
3292 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3293 /* try from ~/.mplayer/sub */
3294 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3295 char *bname;
3296 int l;
3297 bname = strrchr(buf,'/');
3298 #if defined(__MINGW32__) || defined(__CYGWIN__)
3299 if(!bname) bname = strrchr(buf,'\\');
3300 #endif
3301 if(bname) bname++;
3302 else bname = buf;
3303 l = strlen(psub) + strlen(bname) + 1;
3304 psub = realloc(psub,l);
3305 strcat(psub,bname);
3306 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3307 free(psub);
3309 free(buf);
3311 if(vo_vobsub){
3312 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3313 vobsub_set_from_lang(vo_vobsub, dvdsub_lang);
3314 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3316 // setup global sub numbering
3317 mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] = mpctx->global_sub_size; // the global # of the first vobsub.
3318 mpctx->global_sub_size += vobsub_get_indexes_count(vo_vobsub);
3321 //============ Open & Sync STREAM --- fork cache2 ====================
3323 mpctx->stream=NULL;
3324 mpctx->demuxer=NULL;
3325 if (mpctx->d_audio) {
3326 //free_demuxer_stream(mpctx->d_audio);
3327 mpctx->d_audio=NULL;
3329 if (mpctx->d_video) {
3330 //free_demuxer_stream(d_video);
3331 mpctx->d_video=NULL;
3333 mpctx->sh_audio=NULL;
3334 mpctx->sh_video=NULL;
3336 current_module="open_stream";
3337 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3338 if(!mpctx->stream) { // error...
3339 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3340 goto goto_next_file;
3342 mpctx->initialized_flags|=INITIALIZED_STREAM;
3344 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3345 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3346 "playlist support will not be used automatically.\n"
3347 "MPlayer's playlist code is unsafe and should only be used with "
3348 "trusted sources.\nPlayback will probably fail.\n\n");
3349 #if 0
3350 play_tree_t* entry;
3351 // Handle playlist
3352 current_module="handle_playlist";
3353 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3354 filename_recode(mpctx->filename));
3355 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3356 mpctx->eof=playtree_add_playlist(mpctx, entry);
3357 goto goto_next_file;
3358 #endif
3360 mpctx->stream->start_pos+=seek_to_byte;
3362 if(stream_dump_type==5){
3363 unsigned char buf[4096];
3364 int len;
3365 FILE *f;
3366 current_module="dumpstream";
3367 if(mpctx->stream->type==STREAMTYPE_STREAM && mpctx->stream->fd<0){
3368 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot dump this stream - no file descriptor available.\n");
3369 exit_player(mpctx, EXIT_ERROR);
3371 stream_reset(mpctx->stream);
3372 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3373 f=fopen(stream_dump_name,"wb");
3374 if(!f){
3375 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3376 exit_player(mpctx, EXIT_ERROR);
3378 if (dvd_chapter > 1) {
3379 int chapter = dvd_chapter - 1;
3380 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3382 while(!mpctx->stream->eof && !async_quit_request){
3383 len=stream_read(mpctx->stream,buf,4096);
3384 if(len>0) {
3385 if(fwrite(buf,len,1,f) != 1) {
3386 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3387 exit_player(mpctx, EXIT_ERROR);
3390 if(dvd_last_chapter > 0) {
3391 int chapter = -1;
3392 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3393 &chapter) == STREAM_OK && chapter + 1 > dvd_last_chapter)
3394 break;
3397 if(fclose(f)) {
3398 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",stream_dump_name);
3399 exit_player(mpctx, EXIT_ERROR);
3401 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3402 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3405 #ifdef CONFIG_DVDREAD
3406 if(mpctx->stream->type==STREAMTYPE_DVD){
3407 current_module="dvd lang->id";
3408 if(opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,audio_lang);
3409 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3410 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,dvdsub_lang);
3411 // setup global sub numbering
3412 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3413 mpctx->global_sub_size += dvd_number_of_subs(mpctx->stream);
3414 current_module=NULL;
3416 #endif
3418 #ifdef CONFIG_DVDNAV
3419 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3420 current_module="dvdnav lang->id";
3421 if(opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,audio_lang);
3422 if(dvdsub_lang && opts->sub_id==-2) opts->sub_id=-1;
3423 if(dvdsub_lang && opts->sub_id==-1) opts->sub_id=mp_dvdnav_sid_from_lang(mpctx->stream,dvdsub_lang);
3424 // setup global sub numbering
3425 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3426 mpctx->global_sub_size += mp_dvdnav_number_of_subs(mpctx->stream);
3427 current_module=NULL;
3429 #endif
3431 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3432 goto_enable_cache:
3433 if(stream_cache_size>0){
3434 current_module="enable_cache";
3435 if(!stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3436 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3437 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0)))
3438 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3441 //============ Open DEMUXERS --- DETECT file type =======================
3442 current_module="demux_open";
3444 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3446 // HACK to get MOV Reference Files working
3448 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3450 unsigned char* playlist_entry;
3451 play_tree_t *list = NULL, *entry = NULL;
3453 current_module="handle_demux_playlist";
3454 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3456 char *temp, *bname;
3458 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3459 filename_recode(playlist_entry));
3461 bname=mp_basename(playlist_entry);
3462 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3463 continue;
3465 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3466 continue;
3468 entry = play_tree_new();
3470 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3472 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3473 if (temp)
3475 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3476 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3477 strcat(temp, playlist_entry);
3478 if (!strcmp(temp, mpctx->filename)) {
3479 free(temp);
3480 continue;
3482 play_tree_add_file(entry,temp);
3483 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3484 free(temp);
3487 else
3488 play_tree_add_file(entry,playlist_entry);
3490 if(!list)
3491 list = entry;
3492 else
3493 play_tree_append_entry(list,entry);
3495 free_demuxer(mpctx->demuxer);
3496 mpctx->demuxer = NULL;
3498 if (list)
3500 entry = play_tree_new();
3501 play_tree_set_child(entry,list);
3502 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3503 goto goto_next_file;
3507 if(!mpctx->demuxer)
3508 goto goto_next_file;
3510 if (mpctx->demuxer->matroska_data.ordered_chapters)
3511 build_ordered_chapter_timeline(mpctx);
3513 if (!mpctx->sources) {
3514 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3515 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3516 .demuxer = mpctx->demuxer};
3517 mpctx->num_sources = 1;
3520 if(dvd_chapter>1) {
3521 double pts;
3522 if (seek_chapter(mpctx, dvd_chapter-1, &pts, NULL) >= 0 && pts > -1.0)
3523 seek(mpctx, pts, SEEK_ABSOLUTE);
3526 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3528 if (mpctx->stream->type != STREAMTYPE_DVD && mpctx->stream->type != STREAMTYPE_DVDNAV) {
3529 int i;
3530 int maxid = -1;
3531 // setup global sub numbering
3532 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3533 for (i = 0; i < MAX_S_STREAMS; i++)
3534 if (mpctx->demuxer->s_streams[i])
3535 maxid = FFMAX(maxid, mpctx->demuxer->s_streams[i]->sid);
3536 mpctx->global_sub_size += maxid + 1;
3538 // Make opts->sub_id always selectable if set.
3539 if (mpctx->global_sub_size <= mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id)
3540 mpctx->global_sub_size = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id + 1;
3542 #ifdef CONFIG_ASS
3543 if (ass_enabled && ass_library) {
3544 for (int j = 0; j < mpctx->num_sources; j++) {
3545 struct demuxer *d = mpctx->sources[j].demuxer;
3546 for (int i = 0; i < d->num_attachments; i++) {
3547 struct demux_attachment *att = d->attachments + i;
3548 if (extract_embedded_fonts
3549 && att->name && att->type && att->data && att->data_size
3550 && (strcmp(att->type, "application/x-truetype-font") == 0
3551 || strcmp(att->type, "application/x-font") == 0))
3552 ass_add_font(ass_library, att->name, att->data, att->data_size);
3556 #endif
3558 current_module="demux_open2";
3560 //file_format=demuxer->file_format;
3562 mpctx->d_audio=mpctx->demuxer->audio;
3563 mpctx->d_video=mpctx->demuxer->video;
3564 mpctx->d_sub=mpctx->demuxer->sub;
3566 // select audio stream
3567 select_audio(mpctx->demuxer, opts->audio_id, audio_lang);
3569 // DUMP STREAMS:
3570 if((stream_dump_type)&&(stream_dump_type<4)){
3571 FILE *f;
3572 demux_stream_t *ds=NULL;
3573 current_module="dump";
3574 // select stream to dump
3575 switch(stream_dump_type){
3576 case 1: ds=mpctx->d_audio;break;
3577 case 2: ds=mpctx->d_video;break;
3578 case 3: ds=mpctx->d_sub;break;
3580 if(!ds){
3581 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3582 exit_player(mpctx, EXIT_ERROR);
3584 // disable other streams:
3585 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3586 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3587 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3588 // let's dump it!
3589 f=fopen(stream_dump_name,"wb");
3590 if(!f){
3591 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3592 exit_player(mpctx, EXIT_ERROR);
3594 while(!ds->eof){
3595 unsigned char* start;
3596 int in_size=ds_get_packet(ds,&start);
3597 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3598 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3599 if(in_size>0) fwrite(start,in_size,1,f);
3600 if(dvd_last_chapter>0) {
3601 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3602 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3603 break;
3606 fclose(f);
3607 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3608 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3611 mpctx->sh_audio=mpctx->d_audio->sh;
3612 mpctx->sh_video=mpctx->d_video->sh;
3614 if(mpctx->sh_video){
3616 current_module="video_read_properties";
3617 if(!video_read_properties(mpctx->sh_video)) {
3618 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3619 mpctx->sh_video=mpctx->d_video->sh=NULL;
3620 } else {
3621 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3622 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3623 mpctx->sh_video->fps,mpctx->sh_video->frametime
3626 /* need to set fps here for output encoders to pick it up in their init */
3627 if(force_fps){
3628 mpctx->sh_video->fps=force_fps;
3629 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3631 vo_fps = mpctx->sh_video->fps;
3633 if(!mpctx->sh_video->fps && !force_fps){
3634 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
3635 mpctx->sh_video=mpctx->d_video->sh=NULL;
3641 if(!mpctx->sh_video && !mpctx->sh_audio){
3642 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
3643 #ifdef CONFIG_DVBIN
3644 if(mpctx->stream->type == STREAMTYPE_DVB)
3646 int dir;
3647 int v = mpctx->last_dvb_step;
3648 if(v > 0)
3649 dir = DVB_CHANNEL_HIGHER;
3650 else
3651 dir = DVB_CHANNEL_LOWER;
3653 if(dvb_step_channel(mpctx->stream, dir)) {
3654 mpctx->stop_play = PT_NEXT_ENTRY;
3655 mpctx->dvbin_reopen = 1;
3658 #endif
3659 goto goto_next_file; // exit_player(_("Fatal error"));
3662 /* display clip info */
3663 demux_info_print(mpctx->demuxer);
3665 //================== Read SUBTITLES (DVD & TEXT) ==========================
3666 if(vo_spudec==NULL && mpctx->sh_video &&
3667 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3668 init_vo_spudec(mpctx);
3671 if(mpctx->sh_video) {
3672 // after reading video params we should load subtitles because
3673 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3674 // check .sub
3675 current_module="read_subtitles_file";
3676 if(sub_name){
3677 for (i = 0; sub_name[i] != NULL; ++i)
3678 add_subtitles(mpctx, sub_name[i], mpctx->sh_video->fps, 0);
3680 if(sub_auto) { // auto load sub file ...
3681 char *psub = get_path( "sub/" );
3682 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
3683 int i = 0;
3684 free(psub); // release the buffer created by get_path() above
3685 while (tmp[i]) {
3686 add_subtitles(mpctx, tmp[i], mpctx->sh_video->fps, 1);
3687 free(tmp[i++]);
3689 free(tmp);
3691 if (mpctx->set_of_sub_size > 0) {
3692 // setup global sub numbering
3693 mpctx->global_sub_indices[SUB_SOURCE_SUBS] = mpctx->global_sub_size; // the global # of the first sub.
3694 mpctx->global_sub_size += mpctx->set_of_sub_size;
3698 if (mpctx->global_sub_size) {
3699 // find the best sub to use
3700 int vobsub_index_id = vobsub_get_index_by_id(vo_vobsub, vobsub_id);
3701 mpctx->global_sub_pos = -1; // no subs by default
3702 if (vobsub_index_id >= 0) {
3703 // if user asks for a vobsub id, use that first.
3704 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] + vobsub_index_id;
3705 } else if (opts->sub_id >= 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3706 // if user asks for a dvd sub id, use that next.
3707 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3708 } else if (mpctx->global_sub_indices[SUB_SOURCE_SUBS] >= 0) {
3709 // if there are text subs to use, use those. (autosubs come last here)
3710 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_SUBS];
3711 } else if (opts->sub_id < 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
3712 // finally select subs by language and container hints
3713 if (opts->sub_id < 0 && dvdsub_lang)
3714 opts->sub_id = demuxer_sub_track_by_lang(mpctx->demuxer, dvdsub_lang);
3715 if (opts->sub_id < 0)
3716 opts->sub_id = demuxer_default_sub_track(mpctx->demuxer);
3717 if (opts->sub_id >= 0)
3718 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + opts->sub_id;
3720 // rather than duplicate code, use the SUB_SELECT handler to init the right one.
3721 mpctx->global_sub_pos--;
3722 mp_property_do("sub",M_PROPERTY_STEP_UP,NULL, mpctx);
3723 if(subdata)
3724 switch (stream_dump_type) {
3725 case 3: list_sub_file(subdata); break;
3726 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3727 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3728 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3729 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3730 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3734 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
3735 filename_recode(mpctx->filename));
3736 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
3737 if (mpctx->sh_video) {
3738 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3739 if (mpctx->sh_video->format >= 0x20202020)
3740 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
3741 else
3742 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
3743 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
3744 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
3745 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
3746 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
3747 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
3749 if (mpctx->sh_audio) {
3750 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3751 if (mpctx->sh_audio->format >= 0x20202020)
3752 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
3753 else
3754 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
3755 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
3756 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
3757 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
3759 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2lf\n", demuxer_get_time_length(mpctx->demuxer));
3760 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
3761 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
3762 if (mpctx->demuxer) {
3763 if (mpctx->demuxer->num_chapters == 0)
3764 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
3765 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
3768 if(!mpctx->sh_video) goto main; // audio-only
3770 if(!reinit_video_chain(mpctx)) {
3771 if(!mpctx->sh_video){
3772 if(!mpctx->sh_audio) goto goto_next_file;
3773 goto main; // exit_player(_("Fatal error"));
3777 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
3778 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3780 #ifdef CONFIG_FREETYPE
3781 force_load_font = 1;
3782 #endif
3784 //================== MAIN: ==========================
3785 main:
3786 current_module="main";
3788 if(playing_msg) {
3789 char* msg = property_expand_string(mpctx, playing_msg);
3790 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
3791 free(msg);
3795 // Disable the term OSD in verbose mode
3796 if(verbose) term_osd = 0;
3799 //int frame_corr_num=0; //
3800 //float v_frame=0; // Video
3801 //float num_frames=0; // number of frames played
3803 int frame_time_remaining=0; // flag
3804 int blit_frame=0;
3806 // Make sure old OSD does not stay around,
3807 // e.g. with -fixed-vo and same-resolution files
3808 clear_osd_msgs();
3809 update_osd_msg(mpctx);
3811 //================ SETUP AUDIO ==========================
3813 if(mpctx->sh_audio){
3814 reinit_audio_chain(mpctx);
3815 if (mpctx->sh_audio && mpctx->sh_audio->codec)
3816 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
3819 current_module="av_init";
3821 if(mpctx->sh_video){
3822 mpctx->sh_video->timer=0;
3823 if (! ignore_start)
3824 audio_delay += mpctx->sh_video->stream_delay;
3826 if(mpctx->sh_audio){
3827 if (start_volume >= 0)
3828 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
3829 if (! ignore_start)
3830 audio_delay -= mpctx->sh_audio->stream_delay;
3831 mpctx->delay=-audio_delay;
3834 if(!mpctx->sh_audio){
3835 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
3836 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
3837 ds_free_packs(mpctx->d_audio); // free buffered chunks
3838 //mpctx->d_audio->id=-2; // do not read audio chunks
3839 //uninit_player(mpctx, INITIALIZED_AO); // close device
3841 if(!mpctx->sh_video){
3842 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
3843 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
3844 ds_free_packs(mpctx->d_video);
3845 mpctx->d_video->id=-2;
3846 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
3849 if (!mpctx->sh_video && !mpctx->sh_audio)
3850 goto goto_next_file;
3852 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
3853 if(force_fps && mpctx->sh_video){
3854 vo_fps = mpctx->sh_video->fps=force_fps;
3855 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3856 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
3859 mp_input_set_section(mpctx->input, NULL);
3860 //TODO: add desired (stream-based) sections here
3861 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
3862 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
3864 //==================== START PLAYING =======================
3866 if(opts->loop_times>1) opts->loop_times--; else
3867 if(opts->loop_times==1) opts->loop_times = -1;
3869 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
3871 total_time_usage_start=GetTimer();
3872 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
3873 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
3874 play_n_frames=play_n_frames_mf;
3876 if(play_n_frames==0){
3877 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
3880 if (seek_to_sec) {
3881 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
3882 end_at.pos += seek_to_sec;
3885 if (end_at.type == END_AT_SIZE) {
3886 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
3887 end_at.type = END_AT_NONE;
3890 #ifdef CONFIG_DVDNAV
3891 mp_dvdnav_context_free(mpctx);
3892 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3893 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
3894 mp_dvdnav_cell_has_changed(mpctx->stream,1);
3896 #endif
3898 get_relative_time(mpctx); // reset current delta
3899 mpctx->time_frame = 0;
3900 mpctx->drop_message_shown = 0;
3901 mpctx->update_video_immediately = true;
3902 mpctx->total_avsync_change = 0;
3903 // Make sure VO knows current pause state
3904 if (mpctx->sh_video)
3905 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
3906 NULL);
3908 while(!mpctx->stop_play){
3909 float aq_sleep_time=0;
3911 if(dvd_last_chapter>0) {
3912 int cur_chapter = get_current_chapter(mpctx);
3913 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3914 goto goto_next_file;
3917 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
3918 mpctx->sh_audio = mpctx->d_audio->sh;
3919 mpctx->sh_audio->ds = mpctx->d_audio;
3920 reinit_audio_chain(mpctx);
3923 /*========================== PLAY AUDIO ============================*/
3925 if (mpctx->sh_audio && !mpctx->paused)
3926 if (!fill_audio_out_buffers(mpctx))
3927 // at eof, all audio at least written to ao
3928 if (!mpctx->sh_video)
3929 mpctx->stop_play = AT_END_OF_FILE;
3932 if(!mpctx->sh_video) {
3933 // handle audio-only case:
3934 double a_pos=0;
3935 // sh_audio can be NULL due to video stream switching
3936 // TODO: handle this better
3937 if (mpctx->sh_audio)
3938 a_pos = playing_audio_pts(mpctx);
3940 print_status(mpctx, a_pos, false);
3942 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
3943 mpctx->stop_play = PT_NEXT_ENTRY;
3944 update_osd_msg(mpctx);
3946 } else {
3948 /*========================== PLAY VIDEO ============================*/
3950 vo_pts=mpctx->sh_video->timer*90000.0;
3951 vo_fps=mpctx->sh_video->fps;
3953 if (!mpctx->video_out->frame_loaded) {
3954 double frame_time = update_video(mpctx, &blit_frame);
3955 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
3956 if (mpctx->sh_video->vf_initialized < 0) {
3957 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
3958 mpctx->stop_play = PT_NEXT_ENTRY;
3959 goto goto_next_file;
3961 if (blit_frame) {
3962 struct vf_instance *vf = mpctx->sh_video->vfilter;
3963 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3964 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3965 vo_osd_changed(0);
3967 if (frame_time < 0)
3968 mpctx->stop_play = AT_END_OF_FILE;
3969 else {
3970 if (mpctx->update_video_immediately) {
3971 // Show this frame immediately, rest normally
3972 mpctx->update_video_immediately = false;
3973 } else {
3974 mpctx->time_frame += frame_time / opts->playback_speed;
3975 adjust_sync(mpctx, frame_time);
3979 if (mpctx->timeline) {
3980 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
3981 if (mpctx->sh_video->pts >= next->start
3982 || mpctx->stop_play == AT_END_OF_FILE
3983 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3984 seek(mpctx, next->start, SEEK_ABSOLUTE);
3985 continue;
3989 // ==========================================================================
3991 // current_module="draw_osd";
3992 // if(vo_config_count) mpctx->video_out->draw_osd();
3994 current_module="vo_check_events";
3995 vo_check_events(mpctx->video_out);
3997 #ifdef CONFIG_X11
3998 if (stop_xscreensaver) {
3999 current_module = "stop_xscreensaver";
4000 xscreensaver_heartbeat(mpctx->x11_state);
4002 #endif
4003 if (heartbeat_cmd) {
4004 static unsigned last_heartbeat;
4005 unsigned now = GetTimerMS();
4006 if (now - last_heartbeat > 30000) {
4007 last_heartbeat = now;
4008 system(heartbeat_cmd);
4012 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4014 //====================== FLIP PAGE (VIDEO BLT): =========================
4016 current_module="flip_page";
4017 if (!frame_time_remaining && blit_frame) {
4018 unsigned int t2=GetTimer();
4020 vo_flip_page(mpctx->video_out);
4022 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4023 vout_time_usage += mpctx->last_vo_flip_duration;
4024 print_status(mpctx, MP_NOPTS_VALUE, true);
4026 else
4027 print_status(mpctx, MP_NOPTS_VALUE, false);
4029 //============================ Auto QUALITY ============================
4031 /*Output quality adjustments:*/
4032 if(auto_quality>0){
4033 current_module="autoq";
4034 // float total=0.000001f * (GetTimer()-aq_total_time);
4035 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4036 if(output_quality<auto_quality && aq_sleep_time>0)
4037 ++output_quality;
4038 else
4039 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4040 if(output_quality>1 && aq_sleep_time<0)
4041 --output_quality;
4042 else
4043 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4044 output_quality=0;
4045 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4046 set_video_quality(mpctx->sh_video,output_quality);
4049 if (!frame_time_remaining && blit_frame) {
4050 if (play_n_frames >= 0) {
4051 --play_n_frames;
4052 if (play_n_frames <= 0)
4053 mpctx->stop_play = PT_NEXT_ENTRY;
4055 if (mpctx->step_frames > 0) {
4056 mpctx->step_frames--;
4057 if (mpctx->step_frames == 0)
4058 pause_player(mpctx);
4063 // FIXME: add size based support for -endpos
4064 if (end_at.type == END_AT_TIME &&
4065 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4066 mpctx->stop_play = PT_NEXT_ENTRY;
4068 } // end if(mpctx->sh_video)
4070 #ifdef CONFIG_DVDNAV
4071 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4072 nav_highlight_t hl;
4073 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4074 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4075 vo_osd_changed (OSDTYPE_DVDNAV);
4077 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4078 double ar = -1.0;
4079 if (stream_control (mpctx->demuxer->stream,
4080 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4081 != STREAM_UNSUPPORTED)
4082 mpctx->sh_video->stream_aspect = ar;
4085 #endif
4087 //================= Keyboard events, SEEKing ====================
4089 current_module="key_events";
4092 while (1) {
4093 mp_cmd_t* cmd;
4094 while ((cmd = mp_input_get_cmd(mpctx->input, 0,0,0)) != NULL) {
4095 run_command(mpctx, cmd);
4096 mp_cmd_free(cmd);
4097 if (mpctx->stop_play)
4098 break;
4100 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4101 || mpctx->abs_seek_pos)
4102 break;
4103 if (mpctx->sh_video) {
4104 update_osd_msg(mpctx);
4105 int hack = vo_osd_changed(0);
4106 vo_osd_changed(hack);
4107 if (hack)
4108 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4109 add_step_frame(mpctx);
4110 break;
4112 else
4113 vo_osd_changed(0);
4115 pause_loop(mpctx);
4119 // handle -sstep
4120 if (step_sec > 0 && !mpctx->paused) {
4121 mpctx->osd_function=OSD_FFW;
4122 mpctx->rel_seek_secs+=step_sec;
4125 edl_update(mpctx);
4127 /* Looping. */
4128 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4129 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4131 if(opts->loop_times>1) opts->loop_times--; else
4132 if(opts->loop_times==1) opts->loop_times=-1;
4133 play_n_frames=play_n_frames_mf;
4134 mpctx->stop_play=0;
4135 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4138 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4139 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4141 mpctx->rel_seek_secs=0;
4142 mpctx->abs_seek_pos=0;
4145 } // while(!mpctx->stop_play)
4147 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4149 #ifdef CONFIG_DVBIN
4150 if(mpctx->dvbin_reopen)
4152 mpctx->stop_play = 0;
4153 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4154 cache_uninit(mpctx->stream);
4155 mpctx->dvbin_reopen = 0;
4156 goto goto_enable_cache;
4158 #endif
4161 goto_next_file: // don't jump here after ao/vo/getch initialization!
4163 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4165 if(benchmark){
4166 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4167 double total_time_usage;
4168 total_time_usage_start=GetTimer()-total_time_usage_start;
4169 total_time_usage = (float)total_time_usage_start*0.000001;
4170 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4171 video_time_usage,vout_time_usage,audio_time_usage,
4172 total_time_usage-tot,total_time_usage);
4173 if(total_time_usage>0.0)
4174 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4175 100.0*video_time_usage/total_time_usage,
4176 100.0*vout_time_usage/total_time_usage,
4177 100.0*audio_time_usage/total_time_usage,
4178 100.0*(total_time_usage-tot)/total_time_usage,
4179 100.0);
4180 if(total_frame_cnt && frame_dropping)
4181 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4182 total_frame_cnt-drop_frame_cnt,
4183 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4184 drop_frame_cnt,
4185 100*drop_frame_cnt/total_frame_cnt,
4186 total_frame_cnt,
4187 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4190 // time to uninit all, except global stuff:
4191 uninit_player(mpctx, INITIALIZED_ALL-(opts->fixed_vo?INITIALIZED_VO:0));
4193 if(mpctx->set_of_sub_size > 0) {
4194 current_module="sub_free";
4195 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4196 sub_free(mpctx->set_of_subtitles[i]);
4197 #ifdef CONFIG_ASS
4198 if(mpctx->set_of_ass_tracks[i])
4199 ass_free_track( mpctx->set_of_ass_tracks[i] );
4200 #endif
4202 mpctx->set_of_sub_size = 0;
4204 vo_sub_last = vo_sub=NULL;
4205 subdata=NULL;
4206 #ifdef CONFIG_ASS
4207 ass_track = NULL;
4208 if(ass_library)
4209 ass_clear_fonts(ass_library);
4210 #endif
4212 if (!mpctx->stop_play) // In case some goto jumped here...
4213 mpctx->stop_play = PT_NEXT_ENTRY;
4215 int playtree_direction = 1;
4217 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4218 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4219 play_tree_iter_free(mpctx->playtree_iter);
4220 mpctx->playtree_iter = NULL;
4222 mpctx->play_tree_step = 1;
4223 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4224 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4225 if(mpctx->playtree_iter) {
4226 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4227 play_tree_iter_free(mpctx->playtree_iter);
4228 mpctx->playtree_iter = NULL;
4231 } else if (mpctx->stop_play == PT_STOP) {
4232 play_tree_iter_free(mpctx->playtree_iter);
4233 mpctx->playtree_iter = NULL;
4234 } else { // NEXT PREV SRC
4235 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4238 while(mpctx->playtree_iter != NULL) {
4239 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4240 if(mpctx->filename == NULL) {
4241 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4242 play_tree_iter_free(mpctx->playtree_iter);
4243 mpctx->playtree_iter = NULL;
4245 } else
4246 break;
4249 if(mpctx->playtree_iter != NULL || player_idle_mode){
4250 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4251 mpctx->stop_play = 0;
4252 goto play_next_file;
4256 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4258 return 1;
4260 #endif /* DISABLE_MAIN */