Sync libdvdcss with their latest SVN.
[mplayer/glamo.git] / mplayer.c
blobc7b13fcb2548ea366cb652e07f612132ecba5ec7
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 /// \file
20 /// \ingroup Properties Command2Property OSDMsgStack
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include "config.h"
26 #if defined(__MINGW32__) || defined(__CYGWIN__)
27 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
28 #include <windows.h>
29 #endif
30 #include <string.h>
31 #include <unistd.h>
33 // #include <sys/mman.h>
34 #include <sys/types.h>
35 #ifndef __MINGW32__
36 #include <sys/ioctl.h>
37 #include <sys/wait.h>
38 #else
39 #define SIGHUP 1 /* hangup */
40 #define SIGQUIT 3 /* quit */
41 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
42 #define SIGBUS 10 /* bus error */
43 #define SIGPIPE 13 /* broken pipe */
44 #endif
46 #include <sys/time.h>
47 #include <sys/stat.h>
49 #include <signal.h>
50 #include <time.h>
51 #include <fcntl.h>
52 #include <limits.h>
54 #include <errno.h>
56 #include "mp_msg.h"
58 #define HELP_MP_DEFINE_STATIC
59 #include "help_mp.h"
61 #include "m_option.h"
62 #include "m_config.h"
63 #include "m_property.h"
64 #include "mplayer.h"
65 #include "access_mpcontext.h"
67 #include "cfg-mplayer-def.h"
69 #include "libavutil/intreadwrite.h"
70 #include "libavutil/avstring.h"
72 #include "subreader.h"
74 #include "libvo/video_out.h"
76 #include "libvo/font_load.h"
77 #include "libvo/sub.h"
79 #ifdef CONFIG_X11
80 #include "libvo/x11_common.h"
81 #endif
83 #include "libao2/audio_out.h"
85 #include "codec-cfg.h"
87 #include "edl.h"
88 #include "spudec.h"
89 #include "vobsub.h"
91 #include "osdep/getch2.h"
92 #include "osdep/timer.h"
94 #include "gui/interface.h"
96 #include "input/input.h"
98 int slave_mode=0;
99 int player_idle_mode=0;
100 int quiet=0;
101 int enable_mouse_movements=0;
102 float start_volume = -1;
104 #include "osdep/priority.h"
106 char *heartbeat_cmd;
108 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
110 #ifdef HAVE_RTC
111 #ifdef __linux__
112 #include <linux/rtc.h>
113 #else
114 #include <rtc.h>
115 #define RTC_IRQP_SET RTCIO_IRQP_SET
116 #define RTC_PIE_ON RTCIO_PIE_ON
117 #endif /* __linux__ */
118 #endif /* HAVE_RTC */
120 #include "stream/tv.h"
121 #include "stream/stream_radio.h"
122 #ifdef CONFIG_DVBIN
123 #include "stream/dvbin.h"
124 #endif
125 #include "stream/cache2.h"
127 //**************************************************************************//
128 // Playtree
129 //**************************************************************************//
130 #include "playtree.h"
131 #include "playtreeparser.h"
133 //**************************************************************************//
134 // Config
135 //**************************************************************************//
136 #include "parser-cfg.h"
137 #include "parser-mpcmd.h"
139 m_config_t* mconfig;
141 //**************************************************************************//
142 // Config file
143 //**************************************************************************//
145 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
147 static int cfg_include(m_option_t *conf, char *filename){
148 return m_config_parse_config_file(mconfig, filename);
151 #include "path.h"
153 //**************************************************************************//
154 //**************************************************************************//
155 // Input media streaming & demultiplexer:
156 //**************************************************************************//
158 static int max_framesize=0;
160 #include "stream/stream.h"
161 #include "libmpdemux/demuxer.h"
162 #include "libmpdemux/stheader.h"
164 #ifdef CONFIG_DVDREAD
165 #include "stream/stream_dvd.h"
166 #endif
167 #include "stream/stream_dvdnav.h"
169 #include "libmpcodecs/dec_audio.h"
170 #include "libmpcodecs/dec_video.h"
171 #include "libmpcodecs/mp_image.h"
172 #include "libmpcodecs/vf.h"
173 #include "libmpcodecs/vd.h"
175 #include "mixer.h"
177 #include "mp_core.h"
179 //**************************************************************************//
180 //**************************************************************************//
182 // Common FIFO functions, and keyboard/event FIFO code
183 #include "mp_fifo.h"
184 int noconsolecontrols=0;
185 //**************************************************************************//
187 // Not all functions in mplayer.c take the context as an argument yet
188 static MPContext mpctx_s = {
189 .osd_function = OSD_PLAY,
190 .begin_skip = MP_NOPTS_VALUE,
191 .play_tree_step = 1,
192 .global_sub_pos = -1,
193 .set_of_sub_pos = -1,
194 .file_format = DEMUXER_TYPE_UNKNOWN,
195 .loop_times = -1,
196 #ifdef CONFIG_DVBIN
197 .last_dvb_step = 1,
198 #endif
201 static MPContext *mpctx = &mpctx_s;
203 int fixed_vo=0;
205 // benchmark:
206 double video_time_usage=0;
207 double vout_time_usage=0;
208 static double audio_time_usage=0;
209 static int total_time_usage_start=0;
210 static int total_frame_cnt=0;
211 static int drop_frame_cnt=0; // total number of dropped frames
212 int benchmark=0;
214 // options:
215 #define DEFAULT_STARTUP_DECODE_RETRY 8
216 int auto_quality=0;
217 static int output_quality=0;
219 float playback_speed=1.0;
221 int use_gui=0;
223 #ifdef CONFIG_GUI
224 int enqueue=0;
225 #endif
227 static int list_properties = 0;
229 int osd_level=1;
230 // if nonzero, hide current OSD contents when GetTimerMS() reaches this
231 unsigned int osd_visible;
232 int osd_duration = 1000;
234 int term_osd = 1;
235 static char* term_osd_esc = "\x1b[A\r\x1b[K";
236 static char* playing_msg = NULL;
237 // seek:
238 static double seek_to_sec;
239 static off_t seek_to_byte=0;
240 static off_t step_sec=0;
241 static int loop_seek=0;
243 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
245 // A/V sync:
246 int autosync=0; // 30 might be a good default value.
248 // may be changed by GUI: (FIXME!)
249 float rel_seek_secs=0;
250 int abs_seek_pos=0;
252 // codecs:
253 char **audio_codec_list=NULL; // override audio codec
254 char **video_codec_list=NULL; // override video codec
255 char **audio_fm_list=NULL; // override audio codec family
256 char **video_fm_list=NULL; // override video codec family
258 // demuxer:
259 extern char *demuxer_name; // override demuxer
260 extern char *audio_demuxer_name; // override audio demuxer
261 extern char *sub_demuxer_name; // override sub demuxer
263 // streaming:
264 int audio_id=-1;
265 int video_id=-1;
266 int dvdsub_id=-1;
267 // this dvdsub_id was selected via slang
268 // use this to allow dvdnav to follow -slang across stream resets,
269 // in particular the subtitle ID for a language changes
270 int dvdsub_lang_id;
271 int vobsub_id=-1;
272 char* audio_lang=NULL;
273 char* dvdsub_lang=NULL;
274 static char* spudec_ifo=NULL;
275 char* filename=NULL; //"MI2-Trailer.avi";
276 int forced_subs_only=0;
277 int file_filter=1;
279 // cache2:
280 int stream_cache_size=-1;
281 #ifdef CONFIG_STREAM_CACHE
282 extern int cache_fill_status;
284 float stream_cache_min_percent=20.0;
285 float stream_cache_seek_min_percent=50.0;
286 #else
287 #define cache_fill_status 0
288 #endif
290 // dump:
291 static char *stream_dump_name="stream.dump";
292 int stream_dump_type=0;
294 // A-V sync:
295 static float default_max_pts_correction=-1;//0.01f;
296 static float max_pts_correction=0;//default_max_pts_correction;
297 static float c_total=0;
298 float audio_delay=0;
299 static int ignore_start=0;
301 static int softsleep=0;
303 double force_fps=0;
304 static int force_srate=0;
305 static int audio_output_format=-1; // AF_FORMAT_UNKNOWN
306 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
307 static int play_n_frames=-1;
308 static int play_n_frames_mf=-1;
310 // screen info:
311 char** video_driver_list=NULL;
312 char** audio_driver_list=NULL;
314 // sub:
315 char *font_name=NULL;
316 char *sub_font_name=NULL;
317 extern int font_fontconfig;
318 float font_factor=0.75;
319 char **sub_name=NULL;
320 float sub_delay=0;
321 float sub_fps=0;
322 int sub_auto = 1;
323 char *vobsub_name=NULL;
324 /*DSP!!char *dsp=NULL;*/
325 int subcc_enabled=0;
326 int suboverlap_enabled = 1;
328 #include "libass/ass_mp.h"
330 char* current_module=NULL; // for debugging
333 // ---
335 #ifdef CONFIG_MENU
336 #include "m_struct.h"
337 #include "libmenu/menu.h"
338 extern vf_info_t vf_info_menu;
339 static vf_info_t* libmenu_vfs[] = {
340 &vf_info_menu,
341 NULL
343 static vf_instance_t* vf_menu = NULL;
344 int use_menu = 0;
345 static char* menu_cfg = NULL;
346 static char* menu_root = "main";
347 #endif
350 #ifdef HAVE_RTC
351 static int nortc = 1;
352 static char* rtc_device;
353 #endif
355 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
356 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
357 short edl_decision = 0; ///< 1 when an EDL operation has been made.
358 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
359 int use_filedir_conf;
360 int use_filename_title;
362 static unsigned int initialized_flags=0;
363 #include "mpcommon.h"
364 #include "command.h"
366 #include "metadata.h"
368 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
370 const void *mpctx_get_video_out(MPContext *mpctx)
372 return mpctx->video_out;
375 const void *mpctx_get_audio_out(MPContext *mpctx)
377 return mpctx->audio_out;
380 void *mpctx_get_demuxer(MPContext *mpctx)
382 return mpctx->demuxer;
385 void *mpctx_get_playtree_iter(MPContext *mpctx)
387 return mpctx->playtree_iter;
390 void *mpctx_get_mixer(MPContext *mpctx)
392 return &mpctx->mixer;
395 int mpctx_get_global_sub_size(MPContext *mpctx)
397 return mpctx->global_sub_size;
400 int mpctx_get_osd_function(MPContext *mpctx)
402 return mpctx->osd_function;
405 static int is_valid_metadata_type (metadata_t type) {
406 switch (type)
408 /* check for valid video stream */
409 case META_VIDEO_CODEC:
410 case META_VIDEO_BITRATE:
411 case META_VIDEO_RESOLUTION:
413 if (!mpctx->sh_video)
414 return 0;
415 break;
418 /* check for valid audio stream */
419 case META_AUDIO_CODEC:
420 case META_AUDIO_BITRATE:
421 case META_AUDIO_SAMPLES:
423 if (!mpctx->sh_audio)
424 return 0;
425 break;
428 /* check for valid demuxer */
429 case META_INFO_TITLE:
430 case META_INFO_ARTIST:
431 case META_INFO_ALBUM:
432 case META_INFO_YEAR:
433 case META_INFO_COMMENT:
434 case META_INFO_TRACK:
435 case META_INFO_GENRE:
437 if (!mpctx->demuxer)
438 return 0;
439 break;
442 default:
443 break;
446 return 1;
449 static char *get_demuxer_info (char *tag) {
450 char **info = mpctx->demuxer->info;
451 int n;
453 if (!info || !tag)
454 return NULL;
456 for (n = 0; info[2*n] != NULL ; n++)
457 if (!strcasecmp (info[2*n], tag))
458 break;
460 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
463 char *get_metadata (metadata_t type) {
464 char *meta = NULL;
465 sh_audio_t * const sh_audio = mpctx->sh_audio;
466 sh_video_t * const sh_video = mpctx->sh_video;
468 if (!is_valid_metadata_type (type))
469 return NULL;
471 switch (type)
473 case META_NAME:
475 return strdup (mp_basename2 (filename));
478 case META_VIDEO_CODEC:
480 if (sh_video->format == 0x10000001)
481 meta = strdup ("mpeg1");
482 else if (sh_video->format == 0x10000002)
483 meta = strdup ("mpeg2");
484 else if (sh_video->format == 0x10000004)
485 meta = strdup ("mpeg4");
486 else if (sh_video->format == 0x10000005)
487 meta = strdup ("h264");
488 else if (sh_video->format >= 0x20202020)
490 meta = malloc (8);
491 sprintf (meta, "%.4s", (char *) &sh_video->format);
493 else
495 meta = malloc (8);
496 sprintf (meta, "0x%08X", sh_video->format);
498 return meta;
501 case META_VIDEO_BITRATE:
503 meta = malloc (16);
504 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
505 return meta;
508 case META_VIDEO_RESOLUTION:
510 meta = malloc (16);
511 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
512 return meta;
515 case META_AUDIO_CODEC:
517 if (sh_audio->codec && sh_audio->codec->name)
518 meta = strdup (sh_audio->codec->name);
519 return meta;
522 case META_AUDIO_BITRATE:
524 meta = malloc (16);
525 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
526 return meta;
529 case META_AUDIO_SAMPLES:
531 meta = malloc (16);
532 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
533 return meta;
536 /* check for valid demuxer */
537 case META_INFO_TITLE:
538 return get_demuxer_info ("Title");
540 case META_INFO_ARTIST:
541 return get_demuxer_info ("Artist");
543 case META_INFO_ALBUM:
544 return get_demuxer_info ("Album");
546 case META_INFO_YEAR:
547 return get_demuxer_info ("Year");
549 case META_INFO_COMMENT:
550 return get_demuxer_info ("Comment");
552 case META_INFO_TRACK:
553 return get_demuxer_info ("Track");
555 case META_INFO_GENRE:
556 return get_demuxer_info ("Genre");
558 default:
559 break;
562 return meta;
565 /// step size of mixer changes
566 int volstep = 3;
568 #ifdef CONFIG_DVDNAV
569 static void mp_dvdnav_context_free(MPContext *ctx){
570 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
571 ctx->nav_smpi = NULL;
572 if (ctx->nav_buffer) free(ctx->nav_buffer);
573 ctx->nav_buffer = NULL;
574 ctx->nav_start = NULL;
575 ctx->nav_in_size = 0;
577 #endif
579 void uninit_player(unsigned int mask){
580 mask &= initialized_flags;
582 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
584 if(mask&INITIALIZED_ACODEC){
585 initialized_flags&=~INITIALIZED_ACODEC;
586 current_module="uninit_acodec";
587 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
588 #ifdef CONFIG_GUI
589 if (use_gui) guiGetEvent(guiSetAfilter, (char *)NULL);
590 #endif
591 mpctx->sh_audio=NULL;
592 mpctx->mixer.afilter = NULL;
595 if(mask&INITIALIZED_VCODEC){
596 initialized_flags&=~INITIALIZED_VCODEC;
597 current_module="uninit_vcodec";
598 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
599 mpctx->sh_video=NULL;
600 #ifdef CONFIG_MENU
601 vf_menu=NULL;
602 #endif
605 if(mask&INITIALIZED_DEMUXER){
606 initialized_flags&=~INITIALIZED_DEMUXER;
607 current_module="free_demuxer";
608 if(mpctx->demuxer){
609 mpctx->stream=mpctx->demuxer->stream;
610 free_demuxer(mpctx->demuxer);
612 mpctx->demuxer=NULL;
615 // kill the cache process:
616 if(mask&INITIALIZED_STREAM){
617 initialized_flags&=~INITIALIZED_STREAM;
618 current_module="uninit_stream";
619 if(mpctx->stream) free_stream(mpctx->stream);
620 mpctx->stream=NULL;
623 if(mask&INITIALIZED_VO){
624 initialized_flags&=~INITIALIZED_VO;
625 current_module="uninit_vo";
626 mpctx->video_out->uninit();
627 mpctx->video_out=NULL;
628 #ifdef CONFIG_DVDNAV
629 mp_dvdnav_context_free(mpctx);
630 #endif
633 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
634 if(mask&INITIALIZED_GETCH2){
635 initialized_flags&=~INITIALIZED_GETCH2;
636 current_module="uninit_getch2";
637 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
638 // restore terminal:
639 getch2_disable();
642 if(mask&INITIALIZED_VOBSUB){
643 initialized_flags&=~INITIALIZED_VOBSUB;
644 current_module="uninit_vobsub";
645 if(vo_vobsub) vobsub_close(vo_vobsub);
646 vo_vobsub=NULL;
649 if (mask&INITIALIZED_SPUDEC){
650 initialized_flags&=~INITIALIZED_SPUDEC;
651 current_module="uninit_spudec";
652 spudec_free(vo_spudec);
653 vo_spudec=NULL;
656 if(mask&INITIALIZED_AO){
657 initialized_flags&=~INITIALIZED_AO;
658 current_module="uninit_ao";
659 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
660 if (mpctx->audio_out) mpctx->audio_out->uninit(mpctx->eof?0:1);
661 mpctx->audio_out=NULL;
664 #ifdef CONFIG_GUI
665 if(mask&INITIALIZED_GUI){
666 initialized_flags&=~INITIALIZED_GUI;
667 current_module="uninit_gui";
668 guiDone();
670 #endif
672 if(mask&INITIALIZED_INPUT){
673 initialized_flags&=~INITIALIZED_INPUT;
674 current_module="uninit_input";
675 mp_input_uninit();
676 #ifdef CONFIG_MENU
677 if (use_menu)
678 menu_uninit();
679 #endif
682 current_module=NULL;
685 void exit_player_with_rc(enum exit_reason how, int rc)
688 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
689 uninit_player(INITIALIZED_ALL);
690 #if defined(__MINGW32__) || defined(__CYGWIN__)
691 timeEndPeriod(1);
692 #endif
693 #ifdef CONFIG_X11
694 #ifdef CONFIG_GUI
695 if ( !use_gui )
696 #endif
697 vo_uninit(); // Close the X11 connection (if any is open).
698 #endif
700 #ifdef CONFIG_FREETYPE
701 current_module="uninit_font";
702 if (sub_font && sub_font != vo_font) free_font_desc(sub_font);
703 sub_font = NULL;
704 if (vo_font) free_font_desc(vo_font);
705 vo_font = NULL;
706 done_freetype();
707 #endif
708 free_osd_list();
710 #ifdef CONFIG_ASS
711 ass_library_done(ass_library);
712 ass_library = NULL;
713 #endif
715 current_module="exit_player";
717 // free mplayer config
718 if(mconfig)
719 m_config_free(mconfig);
720 mconfig = NULL;
722 if(mpctx->playtree_iter)
723 play_tree_iter_free(mpctx->playtree_iter);
724 mpctx->playtree_iter = NULL;
725 if(mpctx->playtree)
726 play_tree_free(mpctx->playtree, 1);
727 mpctx->playtree = NULL;
730 if(edl_records != NULL) free(edl_records); // free mem allocated for EDL
731 edl_records = NULL;
732 switch(how) {
733 case EXIT_QUIT:
734 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_ExitingHow,MSGTR_Exit_quit);
735 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
736 break;
737 case EXIT_EOF:
738 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_ExitingHow,MSGTR_Exit_eof);
739 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
740 break;
741 case EXIT_ERROR:
742 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_ExitingHow,MSGTR_Exit_error);
743 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
744 break;
745 default:
746 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
748 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
750 exit(rc);
753 void exit_player(enum exit_reason how)
755 exit_player_with_rc(how, 1);
758 #ifndef __MINGW32__
759 static void child_sighandler(int x){
760 pid_t pid;
761 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
763 #endif
765 #ifdef CONFIG_CRASH_DEBUG
766 static char *prog_path;
767 static int crash_debug = 0;
768 #endif
770 static void exit_sighandler(int x){
771 static int sig_count=0;
772 #ifdef CONFIG_CRASH_DEBUG
773 if (!crash_debug || x != SIGTRAP)
774 #endif
775 ++sig_count;
776 if(initialized_flags==0 && sig_count>1) exit(1);
777 if(sig_count==5)
779 /* We're crashing bad and can't uninit cleanly :(
780 * by popular request, we make one last (dirty)
781 * effort to restore the user's
782 * terminal. */
783 getch2_disable();
784 exit(1);
786 if(sig_count==6) exit(1);
787 if(sig_count>6){
788 // can't stop :(
789 #ifndef __MINGW32__
790 kill(getpid(),SIGKILL);
791 #endif
793 mp_msg(MSGT_CPLAYER,MSGL_FATAL,"\n" MSGTR_IntBySignal,x,
794 current_module?current_module:"unknown"
796 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
797 if(sig_count<=1)
798 switch(x){
799 case SIGINT:
800 case SIGQUIT:
801 case SIGTERM:
802 case SIGKILL:
803 async_quit_request = 1;
804 return; // killed from keyboard (^C) or killed [-9]
805 case SIGILL:
806 #if CONFIG_RUNTIME_CPUDETECT
807 mp_msg(MSGT_CPLAYER,MSGL_FATAL,MSGTR_Exit_SIGILL_RTCpuSel);
808 #else
809 mp_msg(MSGT_CPLAYER,MSGL_FATAL,MSGTR_Exit_SIGILL);
810 #endif
811 case SIGFPE:
812 case SIGSEGV:
813 mp_msg(MSGT_CPLAYER,MSGL_FATAL,MSGTR_Exit_SIGSEGV_SIGFPE);
814 default:
815 mp_msg(MSGT_CPLAYER,MSGL_FATAL,MSGTR_Exit_SIGCRASH);
816 #ifdef CONFIG_CRASH_DEBUG
817 if (crash_debug) {
818 int gdb_pid;
819 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
820 gdb_pid = fork();
821 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
822 if (gdb_pid == 0) { // We are the child
823 char spid[20];
824 snprintf(spid, sizeof(spid), "%i", getppid());
825 getch2_disable(); // allow terminal to work properly with gdb
826 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
827 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
828 } else if (gdb_pid < 0)
829 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
830 else {
831 waitpid(gdb_pid, NULL, 0);
833 if (x == SIGTRAP) return;
835 #endif
837 getch2_disable();
838 exit(1);
841 #include "cfg-mplayer.h"
843 static void parse_cfgfiles( m_config_t* conf )
845 char *conffile;
846 int conffile_fd;
847 if (!disable_system_conf &&
848 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
849 exit_player(EXIT_NONE);
850 if ((conffile = get_path("")) == NULL) {
851 mp_msg(MSGT_CPLAYER,MSGL_WARN,MSGTR_NoHomeDir);
852 } else {
853 #ifdef __MINGW32__
854 mkdir(conffile);
855 #else
856 mkdir(conffile, 0777);
857 #endif
858 free(conffile);
859 if ((conffile = get_path("config")) == NULL) {
860 mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_GetpathProblem);
861 } else {
862 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
863 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_CreatingCfgFile, conffile);
864 write(conffile_fd, default_config, strlen(default_config));
865 close(conffile_fd);
867 if (!disable_user_conf &&
868 m_config_parse_config_file(conf, conffile) < 0)
869 exit_player(EXIT_NONE);
870 free(conffile);
875 #define PROFILE_CFG_PROTOCOL "protocol."
877 static void load_per_protocol_config (m_config_t* conf, const char *const file)
879 char *str;
880 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
881 m_profile_t *p;
883 /* does filename actually uses a protocol ? */
884 str = strstr (file, "://");
885 if (!str)
886 return;
888 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
889 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
890 p = m_config_get_profile (conf, protocol);
891 if (p)
893 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_LoadingProtocolProfile, protocol);
894 m_config_set_profile(conf,p);
898 #define PROFILE_CFG_EXTENSION "extension."
900 static void load_per_extension_config (m_config_t* conf, const char *const file)
902 char *str;
903 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
904 m_profile_t *p;
906 /* does filename actually have an extension ? */
907 str = strrchr (filename, '.');
908 if (!str)
909 return;
911 sprintf (extension, PROFILE_CFG_EXTENSION);
912 strncat (extension, ++str, 7);
913 p = m_config_get_profile (conf, extension);
914 if (p)
916 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_LoadingExtensionProfile, extension);
917 m_config_set_profile(conf,p);
921 #define PROFILE_CFG_VO "vo."
922 #define PROFILE_CFG_AO "ao."
924 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
926 char profile[strlen (cfg) + strlen (out) + 1];
927 m_profile_t *p;
929 sprintf (profile, "%s%s", cfg, out);
930 p = m_config_get_profile (conf, profile);
931 if (p)
933 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_LoadingExtensionProfile, profile);
934 m_config_set_profile(conf,p);
939 * Tries to load a config file
940 * @return 0 if file was not found, 1 otherwise
942 static int try_load_config(m_config_t *conf, const char *file)
944 struct stat st;
945 if (stat(file, &st))
946 return 0;
947 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_LoadingConfig, file);
948 m_config_parse_config_file (conf, file);
949 return 1;
952 static void load_per_file_config (m_config_t* conf, const char *const file)
954 char *confpath;
955 char cfg[PATH_MAX];
956 char *name;
958 if (strlen(file) > PATH_MAX - 14) {
959 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
960 return;
962 sprintf (cfg, "%s.conf", file);
964 name = strrchr(cfg, '/');
965 if (HAVE_DOS_PATHS) {
966 char *tmp = strrchr(cfg, '\\');
967 if (!name || tmp > name)
968 name = tmp;
969 tmp = strrchr(cfg, ':');
970 if (!name || tmp > name)
971 name = tmp;
973 if (!name)
974 name = cfg;
975 else
976 name++;
978 if (use_filedir_conf) {
979 char dircfg[PATH_MAX];
980 strcpy(dircfg, cfg);
981 strcpy(dircfg + (name - cfg), "mplayer.conf");
982 try_load_config(conf, dircfg);
984 if (try_load_config(conf, cfg))
985 return;
988 if ((confpath = get_path (name)) != NULL)
990 try_load_config(conf, confpath);
992 free (confpath);
996 /* When libmpdemux performs a blocking operation (network connection or
997 * cache filling) if the operation fails we use this function to check
998 * if it was interrupted by the user.
999 * The function returns a new value for eof. */
1000 static int libmpdemux_was_interrupted(int eof) {
1001 mp_cmd_t* cmd;
1002 if((cmd = mp_input_get_cmd(0,0,0)) != NULL) {
1003 switch(cmd->id) {
1004 case MP_CMD_QUIT:
1005 exit_player_with_rc(EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1006 case MP_CMD_PLAY_TREE_STEP: {
1007 eof = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1008 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1009 } break;
1010 case MP_CMD_PLAY_TREE_UP_STEP: {
1011 eof = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1012 } break;
1013 case MP_CMD_PLAY_ALT_SRC_STEP: {
1014 eof = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1015 } break;
1017 mp_cmd_free(cmd);
1019 return eof;
1022 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1024 static int playtree_add_playlist(play_tree_t* entry)
1026 play_tree_add_bpf(entry,filename);
1028 #ifdef CONFIG_GUI
1029 if (use_gui) {
1030 if (entry) {
1031 import_playtree_playlist_into_gui(entry, mconfig);
1032 play_tree_free_list(entry,1);
1034 } else
1035 #endif
1037 if(!entry) {
1038 entry = mpctx->playtree_iter->tree;
1039 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1040 return PT_NEXT_ENTRY;
1042 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1043 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1044 return PT_NEXT_ENTRY;
1047 play_tree_remove(entry,1,1);
1048 return PT_NEXT_SRC;
1050 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1051 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1052 entry = mpctx->playtree_iter->tree;
1053 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1054 return PT_NEXT_ENTRY;
1056 play_tree_remove(entry,1,1);
1058 return PT_NEXT_SRC;
1061 void add_subtitles(char *filename, float fps, int noerr)
1063 sub_data *subd;
1064 #ifdef CONFIG_ASS
1065 ass_track_t *asst = 0;
1066 #endif
1068 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1069 return;
1072 subd = sub_read_file(filename, fps);
1073 #ifdef CONFIG_ASS
1074 if (ass_enabled)
1075 #ifdef CONFIG_ICONV
1076 asst = ass_read_stream(ass_library, filename, sub_cp);
1077 #else
1078 asst = ass_read_stream(ass_library, filename, 0);
1079 #endif
1080 if (ass_enabled && subd && !asst)
1081 asst = ass_read_subdata(ass_library, subd, fps);
1083 if (!asst && !subd)
1084 #else
1085 if(!subd)
1086 #endif
1087 mp_msg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR, MSGTR_CantLoadSub,
1088 filename_recode(filename));
1090 #ifdef CONFIG_ASS
1091 if (!asst && !subd) return;
1092 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1093 #else
1094 if (!subd) return;
1095 #endif
1096 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1097 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1098 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1099 filename_recode(filename));
1100 ++mpctx->set_of_sub_size;
1101 mp_msg(MSGT_CPLAYER, MSGL_INFO, MSGTR_AddedSubtitleFile, mpctx->set_of_sub_size,
1102 filename_recode(filename));
1105 // FIXME: if/when the GUI calls this, global sub numbering gets (potentially) broken.
1106 void update_set_of_subtitles(void)
1107 // subdata was changed, set_of_sub... have to be updated.
1109 sub_data ** const set_of_subtitles = mpctx->set_of_subtitles;
1110 int i;
1111 if (mpctx->set_of_sub_size > 0 && subdata == NULL) { // *subdata was deleted
1112 for (i = mpctx->set_of_sub_pos + 1; i < mpctx->set_of_sub_size; ++i)
1113 set_of_subtitles[i-1] = set_of_subtitles[i];
1114 set_of_subtitles[mpctx->set_of_sub_size-1] = NULL;
1115 --mpctx->set_of_sub_size;
1116 if (mpctx->set_of_sub_size > 0) subdata = set_of_subtitles[mpctx->set_of_sub_pos=0];
1118 else if (mpctx->set_of_sub_size > 0 && subdata != NULL) { // *subdata was changed
1119 set_of_subtitles[mpctx->set_of_sub_pos] = subdata;
1121 else if (mpctx->set_of_sub_size <= 0 && subdata != NULL) { // *subdata was added
1122 set_of_subtitles[mpctx->set_of_sub_pos=mpctx->set_of_sub_size] = subdata;
1123 ++mpctx->set_of_sub_size;
1127 void init_vo_spudec(void) {
1128 if (vo_spudec)
1129 spudec_free(vo_spudec);
1130 initialized_flags &= ~INITIALIZED_SPUDEC;
1131 vo_spudec = NULL;
1133 // we currently can't work without video stream
1134 if (!mpctx->sh_video)
1135 return;
1137 if (spudec_ifo) {
1138 unsigned int palette[16], width, height;
1139 current_module="spudec_init_vobsub";
1140 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1141 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1144 #ifdef CONFIG_DVDREAD
1145 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1146 current_module="spudec_init_dvdread";
1147 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1148 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1149 NULL, 0);
1151 #endif
1153 #ifdef CONFIG_DVDNAV
1154 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1155 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1156 current_module="spudec_init_dvdnav";
1157 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1159 #endif
1161 if (vo_spudec==NULL) {
1162 sh_sub_t *sh = (sh_sub_t *)mpctx->d_sub->sh;
1163 current_module="spudec_init_normal";
1164 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1165 spudec_set_font_factor(vo_spudec,font_factor);
1168 if (vo_spudec!=NULL) {
1169 initialized_flags|=INITIALIZED_SPUDEC;
1170 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1175 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1176 * make it all work is to use the builtin SDL-bootstrap code, which
1177 * will be done automatically by replacing our main() if we include SDL.h.
1179 #if defined(__APPLE__) && defined(CONFIG_SDL)
1180 #ifdef CONFIG_SDL_SDL_H
1181 #include <SDL/SDL.h>
1182 #else
1183 #include <SDL.h>
1184 #endif
1185 #endif
1188 * \brief append a formatted string
1189 * \param buf buffer to print into
1190 * \param pos position of terminating 0 in buf
1191 * \param len maximum number of characters in buf, not including terminating 0
1192 * \param format printf format string
1194 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1196 va_list va;
1197 va_start(va, format);
1198 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1199 va_end(va);
1200 if (*pos >= len ) {
1201 buf[len] = 0;
1202 *pos = len;
1207 * \brief append time in the hh:mm:ss.f format
1208 * \param buf buffer to print into
1209 * \param pos position of terminating 0 in buf
1210 * \param len maximum number of characters in buf, not including terminating 0
1211 * \param time time value to convert/append
1213 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1214 int64_t tenths = 10 * time;
1215 int f1 = tenths % 10;
1216 int ss = (tenths / 10) % 60;
1217 int mm = (tenths / 600) % 60;
1218 int hh = tenths / 36000;
1219 if (time <= 0) {
1220 saddf(buf, pos, len, "unknown");
1221 return;
1223 if (hh > 0)
1224 saddf(buf, pos, len, "%2d:", hh);
1225 if (hh > 0 || mm > 0)
1226 saddf(buf, pos, len, "%02d:", mm);
1227 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1231 * \brief print the status line
1232 * \param a_pos audio position
1233 * \param a_v A-V desynchronization
1234 * \param corr amount out A-V synchronization
1236 static void print_status(float a_pos, float a_v, float corr)
1238 sh_video_t * const sh_video = mpctx->sh_video;
1239 int width;
1240 char *line;
1241 unsigned pos = 0;
1242 get_screen_size();
1243 if (screen_width > 0)
1244 width = screen_width;
1245 else
1246 width = 80;
1247 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1248 /* Windows command line is broken (MinGW's rxvt works, but we
1249 * should not depend on that). */
1250 width--;
1251 #endif
1252 line = malloc(width + 1); // one additional char for the terminating null
1254 // Audio time
1255 if (mpctx->sh_audio) {
1256 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1257 if (!sh_video) {
1258 float len = demuxer_get_time_length(mpctx->demuxer);
1259 saddf(line, &pos, width, "(");
1260 sadd_hhmmssf(line, &pos, width, a_pos);
1261 saddf(line, &pos, width, ") of %.1f (", len);
1262 sadd_hhmmssf(line, &pos, width, len);
1263 saddf(line, &pos, width, ") ");
1267 // Video time
1268 if (sh_video)
1269 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1271 // A-V sync
1272 if (mpctx->sh_audio && sh_video)
1273 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ", a_v, corr);
1275 // Video stats
1276 if (sh_video)
1277 saddf(line, &pos, width, "%3d/%3d ",
1278 (int)sh_video->num_frames,
1279 (int)sh_video->num_frames_decoded);
1281 // CPU usage
1282 if (sh_video) {
1283 if (sh_video->timer > 0.5)
1284 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1285 (int)(100.0*video_time_usage*playback_speed/(double)sh_video->timer),
1286 (int)(100.0*vout_time_usage*playback_speed/(double)sh_video->timer),
1287 (100.0*audio_time_usage*playback_speed/(double)sh_video->timer));
1288 else
1289 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1290 } else if (mpctx->sh_audio) {
1291 if (mpctx->delay > 0.5)
1292 saddf(line, &pos, width, "%4.1f%% ",
1293 100.0*audio_time_usage/(double)mpctx->delay);
1294 else
1295 saddf(line, &pos, width, "??,?%% ");
1298 // VO stats
1299 if (sh_video)
1300 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1302 #ifdef CONFIG_STREAM_CACHE
1303 // cache stats
1304 if (stream_cache_size > 0)
1305 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1306 #endif
1308 // other
1309 if (playback_speed != 1)
1310 saddf(line, &pos, width, "%4.2fx ", playback_speed);
1312 // end
1313 if (erase_to_end_of_line) {
1314 line[pos] = 0;
1315 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1316 } else {
1317 memset(&line[pos], ' ', width - pos);
1318 line[width] = 0;
1319 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1321 free(line);
1325 * \brief build a chain of audio filters that converts the input format
1326 * to the ao's format, taking into account the current playback_speed.
1327 * \param sh_audio describes the requested input format of the chain.
1328 * \param ao_data describes the requested output format of the chain.
1330 int build_afilter_chain(sh_audio_t *sh_audio, ao_data_t *ao_data)
1332 int new_srate;
1333 int result;
1334 if (!sh_audio)
1336 #ifdef CONFIG_GUI
1337 if (use_gui) guiGetEvent(guiSetAfilter, (char *)NULL);
1338 #endif
1339 mpctx->mixer.afilter = NULL;
1340 return 0;
1342 if(af_control_any_rev(sh_audio->afilter,
1343 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1344 &playback_speed)) {
1345 new_srate = sh_audio->samplerate;
1346 } else {
1347 new_srate = sh_audio->samplerate * playback_speed;
1348 if (new_srate != ao_data->samplerate) {
1349 // limits are taken from libaf/af_resample.c
1350 if (new_srate < 8000)
1351 new_srate = 8000;
1352 if (new_srate > 192000)
1353 new_srate = 192000;
1354 playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1357 result = init_audio_filters(sh_audio, new_srate,
1358 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1359 mpctx->mixer.afilter = sh_audio->afilter;
1360 #ifdef CONFIG_GUI
1361 if (use_gui) guiGetEvent(guiSetAfilter, (char *)sh_audio->afilter);
1362 #endif
1363 return result;
1367 typedef struct mp_osd_msg mp_osd_msg_t;
1368 struct mp_osd_msg {
1369 /// Previous message on the stack.
1370 mp_osd_msg_t* prev;
1371 /// Message text.
1372 char msg[128];
1373 int id,level,started;
1374 /// Display duration in ms.
1375 unsigned time;
1378 /// OSD message stack.
1379 static mp_osd_msg_t* osd_msg_stack = NULL;
1382 * \brief Add a message on the OSD message stack
1384 * If a message with the same id is already present in the stack
1385 * it is pulled on top of the stack, otherwise a new message is created.
1389 void set_osd_msg(int id, int level, int time, const char* fmt, ...) {
1390 mp_osd_msg_t *msg,*last=NULL;
1391 va_list va;
1392 int r;
1394 // look if the id is already in the stack
1395 for(msg = osd_msg_stack ; msg && msg->id != id ;
1396 last = msg, msg = msg->prev);
1397 // not found: alloc it
1398 if(!msg) {
1399 msg = calloc(1,sizeof(mp_osd_msg_t));
1400 msg->prev = osd_msg_stack;
1401 osd_msg_stack = msg;
1402 } else if(last) { // found, but it's not on top of the stack
1403 last->prev = msg->prev;
1404 msg->prev = osd_msg_stack;
1405 osd_msg_stack = msg;
1407 // write the msg
1408 va_start(va,fmt);
1409 r = vsnprintf(msg->msg, 128, fmt, va);
1410 va_end(va);
1411 if(r >= 128) msg->msg[127] = 0;
1412 // set id and time
1413 msg->id = id;
1414 msg->level = level;
1415 msg->time = time;
1420 * \brief Remove a message from the OSD stack
1422 * This function can be used to get rid of a message right away.
1426 void rm_osd_msg(int id) {
1427 mp_osd_msg_t *msg,*last=NULL;
1429 // Search for the msg
1430 for(msg = osd_msg_stack ; msg && msg->id != id ;
1431 last = msg, msg = msg->prev);
1432 if(!msg) return;
1434 // Detach it from the stack and free it
1435 if(last)
1436 last->prev = msg->prev;
1437 else
1438 osd_msg_stack = msg->prev;
1439 free(msg);
1443 * \brief Remove all messages from the OSD stack
1447 static void clear_osd_msgs(void) {
1448 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1449 while(msg) {
1450 prev = msg->prev;
1451 free(msg);
1452 msg = prev;
1454 osd_msg_stack = NULL;
1458 * \brief Get the current message from the OSD stack.
1460 * This function decrements the message timer and destroys the old ones.
1461 * The message that should be displayed is returned (if any).
1465 static mp_osd_msg_t* get_osd_msg(void) {
1466 mp_osd_msg_t *msg,*prev,*last = NULL;
1467 static unsigned last_update = 0;
1468 unsigned now = GetTimerMS();
1469 unsigned diff;
1470 char hidden_dec_done = 0;
1472 if (osd_visible) {
1473 // 36000000 means max timed visibility is 1 hour into the future, if
1474 // the difference is greater assume it's wrapped around from below 0
1475 if (osd_visible - now > 36000000) {
1476 osd_visible = 0;
1477 vo_osd_progbar_type = -1; // disable
1478 vo_osd_changed(OSDTYPE_PROGBAR);
1479 if (mpctx->osd_function != OSD_PAUSE)
1480 mpctx->osd_function = OSD_PLAY;
1484 if(!last_update) last_update = now;
1485 diff = now >= last_update ? now - last_update : 0;
1487 last_update = now;
1489 // Look for the first message in the stack with high enough level.
1490 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1491 prev = msg->prev;
1492 if(msg->level > osd_level && hidden_dec_done) continue;
1493 // The message has a high enough level or it is the first hidden one
1494 // in both cases we decrement the timer or kill it.
1495 if(!msg->started || msg->time > diff) {
1496 if(msg->started) msg->time -= diff;
1497 else msg->started = 1;
1498 // display it
1499 if(msg->level <= osd_level) return msg;
1500 hidden_dec_done = 1;
1501 continue;
1503 // kill the message
1504 free(msg);
1505 if(last) {
1506 last->prev = prev;
1507 msg = last;
1508 } else {
1509 osd_msg_stack = prev;
1510 msg = NULL;
1513 // Nothing found
1514 return NULL;
1518 * \brief Display the OSD bar.
1520 * Display the OSD bar or fall back on a simple message.
1524 void set_osd_bar(int type,const char* name,double min,double max,double val) {
1526 if(osd_level < 1) return;
1528 if(mpctx->sh_video) {
1529 osd_visible = (GetTimerMS() + 1000) | 1;
1530 vo_osd_progbar_type = type;
1531 vo_osd_progbar_value = 256*(val-min)/(max-min);
1532 vo_osd_changed(OSDTYPE_PROGBAR);
1533 return;
1536 set_osd_msg(OSD_MSG_BAR,1,osd_duration,"%s: %d %%",
1537 name,ROUND(100*(val-min)/(max-min)));
1541 * \brief Display text subtitles on the OSD
1543 void set_osd_subtitle(subtitle *subs) {
1544 int i;
1545 vo_sub = subs;
1546 vo_osd_changed(OSDTYPE_SUBTITLE);
1547 if (!mpctx->sh_video) {
1548 // reverse order, since newest set_osd_msg is displayed first
1549 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1550 if (!subs || i >= subs->lines || !subs->text[i])
1551 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1552 else {
1553 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1554 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1555 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1562 * \brief Update the OSD message line.
1564 * This function displays the current message on the vo OSD or on the term.
1565 * If the stack is empty and the OSD level is high enough the timer
1566 * is displayed (only on the vo OSD).
1570 static void update_osd_msg(void) {
1571 mp_osd_msg_t *msg;
1572 static char osd_text[128] = "";
1573 static char osd_text_timer[128];
1575 // we need some mem for vo_osd_text
1576 vo_osd_text = (unsigned char*)osd_text;
1578 // Look if we have a msg
1579 if((msg = get_osd_msg())) {
1580 if(strcmp(osd_text,msg->msg)) {
1581 strncpy((char*)osd_text, msg->msg, 127);
1582 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1583 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1585 return;
1588 if(mpctx->sh_video) {
1589 // fallback on the timer
1590 if(osd_level>=2) {
1591 int len = demuxer_get_time_length(mpctx->demuxer);
1592 int percentage = -1;
1593 char percentage_text[10];
1594 int pts = demuxer_get_current_time(mpctx->demuxer);
1596 if (mpctx->osd_show_percentage)
1597 percentage = demuxer_get_percent_pos(mpctx->demuxer);
1599 if (percentage >= 0)
1600 snprintf(percentage_text, 9, " (%d%%)", percentage);
1601 else
1602 percentage_text[0] = 0;
1604 if (osd_level == 3)
1605 snprintf(osd_text_timer, 63,
1606 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1607 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1608 len/3600,(len/60)%60,len%60,percentage_text);
1609 else
1610 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1611 mpctx->osd_function,pts/3600,(pts/60)%60,
1612 pts%60,percentage_text);
1613 } else
1614 osd_text_timer[0]=0;
1616 // always decrement the percentage timer
1617 if(mpctx->osd_show_percentage)
1618 mpctx->osd_show_percentage--;
1620 if(strcmp(osd_text,osd_text_timer)) {
1621 strncpy(osd_text, osd_text_timer, 63);
1622 vo_osd_changed(OSDTYPE_OSD);
1624 return;
1627 // Clear the term osd line
1628 if(term_osd && osd_text[0]) {
1629 osd_text[0] = 0;
1630 printf("%s\n",term_osd_esc);
1634 ///@}
1635 // OSDMsgStack
1638 void reinit_audio_chain(void) {
1639 if (!mpctx->sh_audio)
1640 return;
1641 current_module="init_audio_codec";
1642 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1643 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1644 goto init_error;
1646 initialized_flags|=INITIALIZED_ACODEC;
1647 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1650 current_module="af_preinit";
1651 ao_data.samplerate=force_srate;
1652 ao_data.channels=0;
1653 ao_data.format=audio_output_format;
1654 // first init to detect best values
1655 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1656 // input:
1657 mpctx->sh_audio->samplerate,
1658 // output:
1659 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1660 mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_AudioFilterChainPreinitError);
1661 exit_player(EXIT_ERROR);
1663 current_module="ao2_init";
1664 mpctx->audio_out = init_best_audio_out(audio_driver_list,
1665 0, // plugin flag
1666 ao_data.samplerate,
1667 ao_data.channels,
1668 ao_data.format, 0);
1669 if(!mpctx->audio_out){
1670 mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_CannotInitAO);
1671 goto init_error;
1673 initialized_flags|=INITIALIZED_AO;
1674 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1675 mpctx->audio_out->info->short_name,
1676 ao_data.samplerate, ao_data.channels,
1677 af_fmt2str_short(ao_data.format),
1678 af_fmt2bits(ao_data.format)/8 );
1679 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1680 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1681 if(strlen(mpctx->audio_out->info->comment) > 0)
1682 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1683 // init audio filters:
1684 current_module="af_init";
1685 if(!build_afilter_chain(mpctx->sh_audio, &ao_data)) {
1686 mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_NoMatchingFilter);
1687 goto init_error;
1689 mpctx->mixer.audio_out = mpctx->audio_out;
1690 mpctx->mixer.volstep = volstep;
1691 return;
1693 init_error:
1694 uninit_player(INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1695 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1696 mpctx->d_audio->id = -2;
1700 ///@}
1701 // Command2Property
1704 // Return pts value corresponding to the end point of audio written to the
1705 // ao so far.
1706 static double written_audio_pts(sh_audio_t *sh_audio, demux_stream_t *d_audio)
1708 double buffered_output;
1709 // first calculate the end pts of audio that has been output by decoder
1710 double a_pts = sh_audio->pts;
1711 if (a_pts != MP_NOPTS_VALUE)
1712 // Good, decoder supports new way of calculating audio pts.
1713 // sh_audio->pts is the timestamp of the latest input packet with
1714 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1715 // the amount of bytes the decoder has written after that timestamp.
1716 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1717 else {
1718 // Decoder doesn't support new way of calculating pts (or we're
1719 // being called before it has decoded anything with known timestamp).
1720 // Use the old method of audio pts calculation: take the timestamp
1721 // of last packet with known pts the decoder has read data from,
1722 // and add amount of bytes read after the beginning of that packet
1723 // divided by input bps. This will be inaccurate if the input/output
1724 // ratio is not constant for every audio packet or if it is constant
1725 // but not accurately known in sh_audio->i_bps.
1727 a_pts = d_audio->pts;
1728 // ds_tell_pts returns bytes read after last timestamp from
1729 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1730 // it has read but not decoded
1731 if (sh_audio->i_bps)
1732 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1733 (double)sh_audio->i_bps;
1735 // Now a_pts hopefully holds the pts for end of audio from decoder.
1736 // Substract data in buffers between decoder and audio out.
1738 // Decoded but not filtered
1739 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1741 // Data buffered in audio filters, measured in bytes of "missing" output
1742 buffered_output = af_calc_delay(sh_audio->afilter);
1744 // Data that was ready for ao but was buffered because ao didn't fully
1745 // accept everything to internal buffers yet
1746 buffered_output += sh_audio->a_out_buffer_len;
1748 // Filters divide audio length by playback_speed, so multiply by it
1749 // to get the length in original units without speedup or slowdown
1750 a_pts -= buffered_output * playback_speed / ao_data.bps;
1752 return a_pts;
1755 // Return pts value corresponding to currently playing audio.
1756 double playing_audio_pts(sh_audio_t *sh_audio, demux_stream_t *d_audio,
1757 const ao_functions_t *audio_out)
1759 return written_audio_pts(sh_audio, d_audio) - playback_speed *
1760 audio_out->get_delay();
1763 static int check_framedrop(double frame_time) {
1764 // check for frame-drop:
1765 current_module = "check_framedrop";
1766 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1767 static int dropped_frames;
1768 float delay = playback_speed*mpctx->audio_out->get_delay();
1769 float d = delay-mpctx->delay;
1770 ++total_frame_cnt;
1771 // we should avoid dropping too many frames in sequence unless we
1772 // are too late. and we allow 100ms A-V delay here:
1773 if (d < -dropped_frames*frame_time-0.100 &&
1774 mpctx->osd_function != OSD_PAUSE) {
1775 ++drop_frame_cnt;
1776 ++dropped_frames;
1777 return frame_dropping;
1778 } else
1779 dropped_frames = 0;
1781 return 0;
1784 static int generate_video_frame(sh_video_t *sh_video, demux_stream_t *d_video)
1786 unsigned char *start;
1787 int in_size;
1788 int hit_eof=0;
1789 double pts;
1791 while (1) {
1792 int drop_frame = check_framedrop(sh_video->frametime);
1793 void *decoded_frame;
1794 current_module = "decode video";
1795 // XXX Time used in this call is not counted in any performance
1796 // timer now, OSD is not updated correctly for filter-added frames
1797 if (vf_output_queued_frame(sh_video->vfilter))
1798 break;
1799 current_module = "video_read_frame";
1800 in_size = ds_get_packet_pts(d_video, &start, &pts);
1801 if (in_size < 0) {
1802 // try to extract last frames in case of decoder lag
1803 in_size = 0;
1804 pts = MP_NOPTS_VALUE;
1805 hit_eof = 1;
1807 if (in_size > max_framesize)
1808 max_framesize = in_size;
1809 current_module = "decode video";
1810 decoded_frame = decode_video(sh_video, start, in_size, drop_frame, pts);
1811 if (decoded_frame) {
1812 update_subtitles(sh_video, sh_video->pts, mpctx->d_sub, 0);
1813 update_teletext(sh_video, mpctx->demuxer, 0);
1814 update_osd_msg();
1815 current_module = "filter video";
1816 if (filter_video(sh_video, decoded_frame, sh_video->pts))
1817 break;
1818 } else if (drop_frame)
1819 return -1;
1820 if (hit_eof)
1821 return 0;
1823 return 1;
1826 #ifdef HAVE_RTC
1827 int rtc_fd = -1;
1828 #endif
1830 static float timing_sleep(float time_frame)
1832 #ifdef HAVE_RTC
1833 if (rtc_fd >= 0){
1834 // -------- RTC -----------
1835 current_module="sleep_rtc";
1836 while (time_frame > 0.000) {
1837 unsigned long rtc_ts;
1838 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1839 mp_msg(MSGT_CPLAYER, MSGL_ERR, MSGTR_LinuxRTCReadError, strerror(errno));
1840 time_frame -= GetRelativeTime();
1842 } else
1843 #endif
1845 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1846 // unnecessarily high CPU usage
1847 float margin = softsleep ? 0.011 : 0;
1848 current_module = "sleep_timer";
1849 while (time_frame > margin) {
1850 usec_sleep(1000000 * (time_frame - margin));
1851 time_frame -= GetRelativeTime();
1853 if (softsleep){
1854 current_module = "sleep_soft";
1855 if (time_frame < 0)
1856 mp_msg(MSGT_AVSYNC, MSGL_WARN, MSGTR_SoftsleepUnderflow);
1857 while (time_frame > 0)
1858 time_frame-=GetRelativeTime(); // burn the CPU
1861 return time_frame;
1864 static void select_subtitle(MPContext *mpctx)
1866 // find the best sub to use
1867 int vobsub_index_id = vobsub_get_index_by_id(vo_vobsub, vobsub_id);
1868 mpctx->global_sub_pos = -1; // no subs by default
1869 if (vobsub_index_id >= 0) {
1870 // if user asks for a vobsub id, use that first.
1871 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] + vobsub_index_id;
1872 } else if (dvdsub_id >= 0 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
1873 // if user asks for a dvd sub id, use that next.
1874 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + dvdsub_id;
1875 } else if (mpctx->global_sub_indices[SUB_SOURCE_SUBS] >= 0) {
1876 // if there are text subs to use, use those. (autosubs come last here)
1877 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_SUBS];
1878 } else if (dvdsub_id == -1 && mpctx->global_sub_indices[SUB_SOURCE_DEMUX] >= 0) {
1879 // finally select subs by language and container hints
1880 if (dvdsub_id == -1 && dvdsub_lang)
1881 dvdsub_id = demuxer_sub_track_by_lang(mpctx->demuxer, dvdsub_lang);
1882 if (dvdsub_id == -1)
1883 dvdsub_id = demuxer_default_sub_track(mpctx->demuxer);
1884 if (dvdsub_id >= 0)
1885 mpctx->global_sub_pos = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + dvdsub_id;
1887 // rather than duplicate code, use the SUB_SELECT handler to init the right one.
1888 mpctx->global_sub_pos--;
1889 mp_property_do("sub",M_PROPERTY_STEP_UP,NULL, mpctx);
1892 #ifdef CONFIG_DVDNAV
1893 #ifndef FF_B_TYPE
1894 #define FF_B_TYPE 3
1895 #endif
1896 /// store decoded video image
1897 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1898 mp_image_t *from_mpi) {
1899 mp_image_t *mpi;
1901 /// Do not store B-frames
1902 if (from_mpi->pict_type == FF_B_TYPE)
1903 return to_mpi;
1905 if (to_mpi &&
1906 to_mpi->w == from_mpi->w &&
1907 to_mpi->h == from_mpi->h &&
1908 to_mpi->imgfmt == from_mpi->imgfmt)
1909 mpi = to_mpi;
1910 else {
1911 if (to_mpi)
1912 free_mp_image(to_mpi);
1913 if (from_mpi->w == 0 || from_mpi->h == 0)
1914 return NULL;
1915 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1918 copy_mpi(mpi,from_mpi);
1919 return mpi;
1922 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1923 if (ctx->sh_video) {
1924 /// clear video pts
1925 ctx->d_video->pts = 0.0f;
1926 ctx->sh_video->pts = 0.0f;
1927 ctx->sh_video->i_pts = 0.0f;
1928 ctx->sh_video->last_pts = 0.0f;
1929 ctx->sh_video->num_buffered_pts = 0;
1930 ctx->sh_video->num_frames = 0;
1931 ctx->sh_video->num_frames_decoded = 0;
1932 ctx->sh_video->timer = 0.0f;
1933 ctx->sh_video->stream_delay = 0.0f;
1934 ctx->sh_video->timer = 0;
1935 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1938 if (ctx->sh_audio) {
1939 /// free audio packets and reset
1940 ds_free_packs(ctx->d_audio);
1941 audio_delay -= ctx->sh_audio->stream_delay;
1942 ctx->delay =- audio_delay;
1943 ctx->audio_out->reset();
1944 resync_audio_stream(ctx->sh_audio);
1947 audio_delay = 0.0f;
1948 mpctx->global_sub_size = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + mp_dvdnav_number_of_subs(mpctx->stream);
1949 if (dvdsub_lang && dvdsub_id == dvdsub_lang_id) {
1950 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, dvdsub_lang);
1951 if (dvdsub_lang_id != dvdsub_id) {
1952 dvdsub_id = dvdsub_lang_id;
1953 select_subtitle(ctx);
1957 /// clear all EOF related flags
1958 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
1961 /// Restore last decoded DVDNAV (still frame)
1962 static mp_image_t *mp_dvdnav_restore_smpi(int *in_size,
1963 unsigned char **start,
1964 mp_image_t *decoded_frame)
1966 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
1967 return decoded_frame;
1969 /// a change occured in dvdnav stream
1970 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
1971 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
1972 mp_dvdnav_context_free(mpctx);
1973 mp_dvdnav_reset_stream(mpctx);
1974 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
1975 mp_dvdnav_cell_has_changed(mpctx->stream,1);
1978 if (*in_size < 0) {
1979 float len;
1981 /// Display still frame, if any
1982 if (mpctx->nav_smpi && !mpctx->nav_buffer)
1983 decoded_frame = mpctx->nav_smpi;
1985 /// increment video frame : continue playing after still frame
1986 len = demuxer_get_time_length(mpctx->demuxer);
1987 if (mpctx->sh_video->pts >= len &&
1988 mpctx->sh_video->pts > 0.0 && len > 0.0) {
1989 mp_dvdnav_skip_still(mpctx->stream);
1990 mp_dvdnav_skip_wait(mpctx->stream);
1992 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
1994 if (mpctx->nav_buffer) {
1995 *start = mpctx->nav_start;
1996 *in_size = mpctx->nav_in_size;
1997 if (mpctx->nav_start)
1998 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2002 return decoded_frame;
2005 /// Save last decoded DVDNAV (still frame)
2006 static void mp_dvdnav_save_smpi(int in_size,
2007 unsigned char *start,
2008 mp_image_t *decoded_frame)
2010 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2011 return;
2013 if (mpctx->nav_buffer)
2014 free(mpctx->nav_buffer);
2016 mpctx->nav_buffer = malloc(in_size);
2017 mpctx->nav_start = start;
2018 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2019 if (mpctx->nav_buffer)
2020 memcpy(mpctx->nav_buffer,start,in_size);
2022 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2023 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2025 #endif /* CONFIG_DVDNAV */
2027 static void adjust_sync_and_print_status(int between_frames, float timing_error)
2029 current_module="av_sync";
2031 if(mpctx->sh_audio){
2032 double a_pts, v_pts;
2034 if (autosync)
2036 * If autosync is enabled, the value for delay must be calculated
2037 * a bit differently. It is set only to the difference between
2038 * the audio and video timers. Any attempt to include the real
2039 * or corrected delay causes the pts_correction code below to
2040 * try to correct for the changes in delay which autosync is
2041 * trying to measure. This keeps the two from competing, but still
2042 * allows the code to correct for PTS drift *only*. (Using a delay
2043 * value here, even a "corrected" one, would be incompatible with
2044 * autosync mode.)
2046 a_pts = written_audio_pts(mpctx->sh_audio, mpctx->d_audio) - mpctx->delay;
2047 else
2048 a_pts = playing_audio_pts(mpctx->sh_audio, mpctx->d_audio, mpctx->audio_out);
2050 v_pts = mpctx->sh_video->pts;
2053 static int drop_message=0;
2054 double AV_delay = a_pts - audio_delay - v_pts;
2055 double x;
2056 if (AV_delay>0.5 && drop_frame_cnt>50 && drop_message==0){
2057 ++drop_message;
2058 mp_msg(MSGT_AVSYNC,MSGL_WARN,MSGTR_SystemTooSlow);
2060 if (autosync)
2061 x = AV_delay*0.1f;
2062 else
2063 /* Do not correct target time for the next frame if this frame
2064 * was late not because of wrong target time but because the
2065 * target time could not be met */
2066 x = (AV_delay + timing_error * playback_speed) * 0.1f;
2067 if (x < -max_pts_correction)
2068 x = -max_pts_correction;
2069 else if (x> max_pts_correction)
2070 x = max_pts_correction;
2071 if (default_max_pts_correction >= 0)
2072 max_pts_correction = default_max_pts_correction;
2073 else
2074 max_pts_correction = mpctx->sh_video->frametime*0.10; // +-10% of time
2075 if (!between_frames) {
2076 mpctx->delay+=x;
2077 c_total+=x;
2079 if(!quiet)
2080 print_status(a_pts - audio_delay, AV_delay, c_total);
2083 } else {
2084 // No audio:
2086 if (!quiet)
2087 print_status(0, 0, 0);
2091 static int fill_audio_out_buffers(void)
2093 unsigned int t;
2094 double tt;
2095 int playsize;
2096 int playflags=0;
2097 int audio_eof=0;
2098 int bytes_to_write;
2099 sh_audio_t * const sh_audio = mpctx->sh_audio;
2101 current_module="play_audio";
2103 while (1) {
2104 int sleep_time;
2105 // all the current uses of ao_data.pts seem to be in aos that handle
2106 // sync completely wrong; there should be no need to use ao_data.pts
2107 // in get_space()
2108 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2109 bytes_to_write = mpctx->audio_out->get_space();
2110 if (mpctx->sh_video || bytes_to_write >= ao_data.outburst)
2111 break;
2113 // handle audio-only case:
2114 // this is where mplayer sleeps during audio-only playback
2115 // to avoid 100% CPU use
2116 sleep_time = (ao_data.outburst - bytes_to_write) * 1000 / ao_data.bps;
2117 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2118 usec_sleep(sleep_time * 1000);
2121 while (bytes_to_write) {
2122 playsize = bytes_to_write;
2123 if (playsize > MAX_OUTBURST)
2124 playsize = MAX_OUTBURST;
2125 bytes_to_write -= playsize;
2127 // Fill buffer if needed:
2128 current_module="decode_audio";
2129 t = GetTimer();
2130 if (decode_audio(sh_audio, playsize) < 0) // EOF or error
2131 if (mpctx->d_audio->eof) {
2132 audio_eof = 1;
2133 if (sh_audio->a_out_buffer_len == 0)
2134 return 0;
2136 t = GetTimer() - t;
2137 tt = t*0.000001f; audio_time_usage+=tt;
2138 if (playsize > sh_audio->a_out_buffer_len) {
2139 playsize = sh_audio->a_out_buffer_len;
2140 if (audio_eof)
2141 playflags |= AOPLAY_FINAL_CHUNK;
2143 if (!playsize)
2144 break;
2146 // play audio:
2147 current_module="play_audio";
2149 // Is this pts value actually useful for the aos that access it?
2150 // They're obviously badly broken in the way they handle av sync;
2151 // would not having access to this make them more broken?
2152 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2153 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2155 if (playsize > 0) {
2156 sh_audio->a_out_buffer_len -= playsize;
2157 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2158 sh_audio->a_out_buffer_len);
2159 mpctx->delay += playback_speed*playsize/(double)ao_data.bps;
2161 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2162 // Sanity check to avoid hanging in case current ao doesn't output
2163 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2164 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2165 sh_audio->a_out_buffer_len = 0;
2168 return 1;
2171 static int sleep_until_update(float *time_frame, float *aq_sleep_time)
2173 int frame_time_remaining = 0;
2174 current_module="calc_sleep_time";
2176 *time_frame -= GetRelativeTime(); // reset timer
2178 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2179 float delay = mpctx->audio_out->get_delay();
2180 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2182 if (autosync) {
2184 * Adjust this raw delay value by calculating the expected
2185 * delay for this frame and generating a new value which is
2186 * weighted between the two. The higher autosync is, the
2187 * closer to the delay value gets to that which "-nosound"
2188 * would have used, and the longer it will take for A/V
2189 * sync to settle at the right value (but it eventually will.)
2190 * This settling time is very short for values below 100.
2192 float predicted = mpctx->delay / playback_speed + *time_frame;
2193 float difference = delay - predicted;
2194 delay = predicted + difference / (float)autosync;
2197 *time_frame = delay - mpctx->delay / playback_speed;
2199 // delay = amount of audio buffered in soundcard/driver
2200 if (delay > 0.25) delay=0.25; else
2201 if (delay < 0.10) delay=0.10;
2202 if (*time_frame > delay*0.6) {
2203 // sleep time too big - may cause audio drops (buffer underrun)
2204 frame_time_remaining = 1;
2205 *time_frame = delay*0.5;
2207 } else {
2208 // If we're lagging more than 200 ms behind the right playback rate,
2209 // don't try to "catch up".
2210 // If benchmark is set always output frames as fast as possible
2211 // without sleeping.
2212 if (*time_frame < -0.2 || benchmark)
2213 *time_frame = 0;
2216 *aq_sleep_time += *time_frame;
2219 //============================== SLEEP: ===================================
2221 // flag 256 means: libvo driver does its timing (dvb card)
2222 if (*time_frame > 0.001 && !(vo_flags&256))
2223 *time_frame = timing_sleep(*time_frame);
2224 return frame_time_remaining;
2227 int reinit_video_chain(void) {
2228 sh_video_t * const sh_video = mpctx->sh_video;
2229 double ar=-1.0;
2230 //================== Init VIDEO (codec & libvo) ==========================
2231 if(!fixed_vo || !(initialized_flags&INITIALIZED_VO)){
2232 current_module="preinit_libvo";
2234 //shouldn't we set dvideo->id=-2 when we fail?
2235 vo_config_count=0;
2236 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2237 if(!(mpctx->video_out=init_best_video_out(video_driver_list))){
2238 mp_msg(MSGT_CPLAYER,MSGL_FATAL,MSGTR_ErrorInitializingVODevice);
2239 goto err_out;
2241 initialized_flags|=INITIALIZED_VO;
2244 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2245 mpctx->sh_video->stream_aspect = ar;
2246 current_module="init_video_filters";
2248 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2249 sh_video->vfilter=(void*)vf_open_filter(NULL,"vo",vf_arg);
2251 #ifdef CONFIG_MENU
2252 if(use_menu) {
2253 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2254 vf_menu = vf_open_plugin(libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2255 if(!vf_menu) {
2256 mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_CantOpenLibmenuFilterWithThisRootMenu,menu_root);
2257 use_menu = 0;
2260 if(vf_menu)
2261 sh_video->vfilter=(void*)vf_menu;
2262 #endif
2264 #ifdef CONFIG_ASS
2265 if(ass_enabled) {
2266 int i;
2267 int insert = 1;
2268 if (vf_settings)
2269 for (i = 0; vf_settings[i].name; ++i)
2270 if (strcmp(vf_settings[i].name, "ass") == 0) {
2271 insert = 0;
2272 break;
2274 if (insert) {
2275 extern vf_info_t vf_info_ass;
2276 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2277 char* vf_arg[] = {"auto", "1", NULL};
2278 vf_instance_t* vf_ass = vf_open_plugin(libass_vfs,sh_video->vfilter,"ass",vf_arg);
2279 if (vf_ass)
2280 sh_video->vfilter=(void*)vf_ass;
2281 else
2282 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2285 #endif
2287 sh_video->vfilter=(void*)append_filters(sh_video->vfilter);
2289 #ifdef CONFIG_ASS
2290 if (ass_enabled)
2291 ((vf_instance_t *)sh_video->vfilter)->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2292 #endif
2294 current_module="init_video_codec";
2296 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2297 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2298 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2300 if(!sh_video->initialized){
2301 if(!fixed_vo) uninit_player(INITIALIZED_VO);
2302 goto err_out;
2305 initialized_flags|=INITIALIZED_VCODEC;
2307 if (sh_video->codec)
2308 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2310 sh_video->last_pts = MP_NOPTS_VALUE;
2311 sh_video->num_buffered_pts = 0;
2312 sh_video->next_frame_time = 0;
2314 if(auto_quality>0){
2315 // Auto quality option enabled
2316 output_quality=get_video_quality_max(sh_video);
2317 if(auto_quality>output_quality) auto_quality=output_quality;
2318 else output_quality=auto_quality;
2319 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2320 set_video_quality(sh_video,output_quality);
2323 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2325 current_module="init_vo";
2327 return 1;
2329 err_out:
2330 mpctx->sh_video = mpctx->d_video->sh = NULL;
2331 return 0;
2334 static double update_video(int *blit_frame)
2336 sh_video_t * const sh_video = mpctx->sh_video;
2337 //-------------------- Decode a frame: -----------------------
2338 double frame_time;
2339 *blit_frame = 0; // Don't blit if we hit EOF
2340 if (!correct_pts) {
2341 unsigned char* start=NULL;
2342 void *decoded_frame = NULL;
2343 int drop_frame=0;
2344 int in_size;
2346 current_module = "video_read_frame";
2347 frame_time = sh_video->next_frame_time;
2348 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2349 &start, force_fps);
2350 #ifdef CONFIG_DVDNAV
2351 /// wait, still frame or EOF
2352 if (mpctx->stream->type == STREAMTYPE_DVDNAV && in_size < 0) {
2353 if (mp_dvdnav_is_eof(mpctx->stream))
2354 return -1;
2355 if (mpctx->d_video)
2356 mpctx->d_video->eof = 0;
2357 if (mpctx->d_audio)
2358 mpctx->d_audio->eof = 0;
2359 mpctx->stream->eof = 0;
2360 } else
2361 #endif
2362 if (in_size < 0)
2363 return -1;
2364 if (in_size > max_framesize)
2365 max_framesize = in_size; // stats
2366 sh_video->timer += frame_time;
2367 if (mpctx->sh_audio)
2368 mpctx->delay -= frame_time;
2369 // video_read_frame can change fps (e.g. for ASF video)
2370 vo_fps = sh_video->fps;
2371 drop_frame = check_framedrop(frame_time);
2372 update_subtitles(sh_video, sh_video->pts, mpctx->d_sub, 0);
2373 update_teletext(sh_video, mpctx->demuxer, 0);
2374 update_osd_msg();
2375 current_module = "decode_video";
2376 #ifdef CONFIG_DVDNAV
2377 decoded_frame = mp_dvdnav_restore_smpi(&in_size,&start,decoded_frame);
2378 /// still frame has been reached, no need to decode
2379 if (in_size > 0 && !decoded_frame)
2380 #endif
2381 decoded_frame = decode_video(sh_video, start, in_size, drop_frame,
2382 sh_video->pts);
2383 #ifdef CONFIG_DVDNAV
2384 /// save back last still frame for future display
2385 mp_dvdnav_save_smpi(in_size,start,decoded_frame);
2386 #endif
2387 current_module = "filter_video";
2388 *blit_frame = (decoded_frame && filter_video(sh_video, decoded_frame,
2389 sh_video->pts));
2391 else {
2392 int res = generate_video_frame(sh_video, mpctx->d_video);
2393 if (!res)
2394 return -1;
2395 ((vf_instance_t *)sh_video->vfilter)->control(sh_video->vfilter,
2396 VFCTRL_GET_PTS, &sh_video->pts);
2397 if (sh_video->pts == MP_NOPTS_VALUE) {
2398 mp_msg(MSGT_CPLAYER, MSGL_ERR, "pts after filters MISSING\n");
2399 sh_video->pts = sh_video->last_pts;
2401 if (sh_video->last_pts == MP_NOPTS_VALUE)
2402 sh_video->last_pts= sh_video->pts;
2403 else if (sh_video->last_pts > sh_video->pts) {
2404 // make a guess whether this is some kind of discontinuity
2405 // we should jump along with or some wron timestamps we
2406 // should replace instead
2407 if (sh_video->pts < sh_video->last_pts - 20 * sh_video->frametime)
2408 sh_video->last_pts = sh_video->pts;
2409 else
2410 sh_video->pts = sh_video->last_pts + sh_video->frametime;
2411 mp_msg(MSGT_CPLAYER, MSGL_V, "pts value < previous\n");
2413 frame_time = sh_video->pts - sh_video->last_pts;
2414 sh_video->last_pts = sh_video->pts;
2415 sh_video->timer += frame_time;
2416 if(mpctx->sh_audio)
2417 mpctx->delay -= frame_time;
2418 *blit_frame = res > 0;
2420 return frame_time;
2423 static void pause_loop(void)
2425 mp_cmd_t* cmd;
2426 if (!quiet) {
2427 // Small hack to display the pause message on the OSD line.
2428 // The pause string is: "\n == PAUSE == \r" so we need to
2429 // take the first and the last char out
2430 if (term_osd && !mpctx->sh_video) {
2431 char msg[128] = MSGTR_Paused;
2432 int mlen = strlen(msg);
2433 msg[mlen-1] = '\0';
2434 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2435 update_osd_msg();
2436 } else
2437 mp_msg(MSGT_CPLAYER,MSGL_STATUS,MSGTR_Paused);
2438 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2440 #ifdef CONFIG_GUI
2441 if (use_gui)
2442 guiGetEvent(guiCEvent, (char *)guiSetPause);
2443 #endif
2444 if (mpctx->video_out && mpctx->sh_video && vo_config_count)
2445 mpctx->video_out->control(VOCTRL_PAUSE, NULL);
2447 if (mpctx->audio_out && mpctx->sh_audio)
2448 mpctx->audio_out->pause(); // pause audio, keep data if possible
2450 while ( (cmd = mp_input_get_cmd(20, 1, 1)) == NULL || cmd->pausing == 4) {
2451 if (cmd) {
2452 cmd = mp_input_get_cmd(0,1,0);
2453 run_command(mpctx, cmd);
2454 mp_cmd_free(cmd);
2455 continue;
2457 if (mpctx->sh_video && mpctx->video_out && vo_config_count)
2458 mpctx->video_out->check_events();
2459 #ifdef CONFIG_GUI
2460 if (use_gui) {
2461 guiEventHandling();
2462 guiGetEvent(guiReDraw, NULL);
2463 if (guiIntfStruct.Playing!=2 || (rel_seek_secs || abs_seek_pos))
2464 break;
2466 #endif
2467 #ifdef CONFIG_MENU
2468 if (vf_menu)
2469 vf_menu_pause_update(vf_menu);
2470 #endif
2471 usec_sleep(20000);
2473 if (cmd && cmd->id == MP_CMD_PAUSE) {
2474 cmd = mp_input_get_cmd(0,1,0);
2475 mp_cmd_free(cmd);
2477 mpctx->osd_function=OSD_PLAY;
2478 if (mpctx->audio_out && mpctx->sh_audio) {
2479 if (mpctx->eof) // do not play remaining audio if we e.g. switch to the next file
2480 mpctx->audio_out->reset();
2481 else
2482 mpctx->audio_out->resume(); // resume audio
2484 if (mpctx->video_out && mpctx->sh_video && vo_config_count)
2485 mpctx->video_out->control(VOCTRL_RESUME, NULL); // resume video
2486 (void)GetRelativeTime(); // ignore time that passed during pause
2487 #ifdef CONFIG_GUI
2488 if (use_gui) {
2489 if (guiIntfStruct.Playing == guiSetStop)
2490 mpctx->eof = 1;
2491 else
2492 guiGetEvent(guiCEvent, (char *)guiSetPlay);
2494 #endif
2498 // Find the right mute status and record position for new file position
2499 static void edl_seek_reset(MPContext *mpctx)
2501 mpctx->edl_muted = 0;
2502 next_edl_record = edl_records;
2504 while (next_edl_record) {
2505 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2506 break;
2508 if (next_edl_record->action == EDL_MUTE)
2509 mpctx->edl_muted = !mpctx->edl_muted;
2510 next_edl_record = next_edl_record->next;
2512 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2513 mixer_mute(&mpctx->mixer);
2517 // Execute EDL command for the current position if one exists
2518 static void edl_update(MPContext *mpctx)
2520 if (!next_edl_record)
2521 return;
2523 if (!mpctx->sh_video) {
2524 mp_msg(MSGT_CPLAYER, MSGL_ERR, MSGTR_EdlNOsh_video);
2525 free_edl(edl_records);
2526 next_edl_record = NULL;
2527 edl_records = NULL;
2528 return;
2531 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2532 if (next_edl_record->action == EDL_SKIP) {
2533 mpctx->osd_function = OSD_FFW;
2534 abs_seek_pos = 0;
2535 rel_seek_secs = next_edl_record->length_sec;
2536 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2537 "[%f], length [%f]\n", next_edl_record->start_sec,
2538 next_edl_record->stop_sec, next_edl_record->length_sec);
2539 edl_decision = 1;
2541 else if (next_edl_record->action == EDL_MUTE) {
2542 mpctx->edl_muted = !mpctx->edl_muted;
2543 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2544 mixer_mute(&mpctx->mixer);
2545 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2546 next_edl_record->start_sec );
2548 next_edl_record = next_edl_record->next;
2553 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2554 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2555 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2556 static int seek(MPContext *mpctx, double amount, int style)
2558 current_module = "seek";
2559 if (demux_seek(mpctx->demuxer, amount, audio_delay, style) == 0)
2560 return -1;
2562 mpctx->startup_decode_retry = DEFAULT_STARTUP_DECODE_RETRY;
2563 if (mpctx->sh_video) {
2564 current_module = "seek_video_reset";
2565 if (vo_config_count)
2566 mpctx->video_out->control(VOCTRL_RESET, NULL);
2567 mpctx->num_buffered_frames = 0;
2568 mpctx->delay = 0;
2569 mpctx->time_frame = 0;
2570 // Not all demuxers set d_video->pts during seek, so this value
2571 // (which is used by at least vobsub and edl code below) may
2572 // be completely wrong (probably 0).
2573 mpctx->sh_video->pts = mpctx->d_video->pts;
2574 update_subtitles(mpctx->sh_video, mpctx->sh_video->pts, mpctx->d_sub, 1);
2575 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2578 if (mpctx->sh_audio) {
2579 current_module = "seek_audio_reset";
2580 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2581 if (!mpctx->sh_video)
2582 update_subtitles(NULL, mpctx->sh_audio->pts, mpctx->d_sub, 1);
2585 if (vo_vobsub && mpctx->sh_video) {
2586 current_module = "seek_vobsub_reset";
2587 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2590 #if defined(CONFIG_ASS) && defined(LIBASS_VERSION) && LIBASS_VERSION >= 0x00910000
2591 if (ass_enabled && mpctx->d_sub->sh && ((sh_sub_t *)mpctx->d_sub->sh)->ass_track)
2592 ass_flush_events(((sh_sub_t *)mpctx->d_sub->sh)->ass_track);
2593 #endif
2595 edl_seek_reset(mpctx);
2597 c_total = 0;
2598 max_pts_correction = 0.1;
2599 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2600 drop_frame_cnt = 0;
2602 current_module = NULL;
2603 return 0;
2606 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
2607 * file for some tools to link against. */
2608 #ifndef DISABLE_MAIN
2609 int main(int argc,char* argv[]){
2612 char * mem_ptr;
2614 // movie info:
2616 /* Flag indicating whether MPlayer should exit without playing anything. */
2617 int opt_exit = 0;
2619 //float a_frame=0; // Audio
2621 int i;
2623 int gui_no_filename=0;
2625 InitTimer();
2626 srand(GetTimerMS());
2628 mp_msg_init();
2630 // Create the config context and register the options
2631 mconfig = m_config_new();
2632 m_config_register_options(mconfig,mplayer_opts);
2633 mp_input_register_options(mconfig);
2635 // Preparse the command line
2636 m_config_preparse_command_line(mconfig,argc,argv);
2638 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
2639 set_path_env();
2640 #endif
2642 #ifdef CONFIG_TV
2643 stream_tv_defaults.immediate = 1;
2644 #endif
2646 if (argc > 1 && argv[1] &&
2647 (!strcmp(argv[1], "-gui") || !strcmp(argv[1], "-nogui"))) {
2648 use_gui = !strcmp(argv[1], "-gui");
2649 } else
2650 if ( argv[0] )
2652 char *base = strrchr(argv[0], '/');
2653 if (!base)
2654 base = strrchr(argv[0], '\\');
2655 if (!base)
2656 base = argv[0];
2657 if(strstr(base, "gmplayer"))
2658 use_gui=1;
2661 parse_cfgfiles(mconfig);
2663 #ifdef CONFIG_GUI
2664 if ( use_gui ) cfg_read();
2665 #endif
2667 mpctx->playtree = m_config_parse_mp_command_line(mconfig, argc, argv);
2668 if(mpctx->playtree == NULL)
2669 opt_exit = 1;
2670 else {
2671 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
2672 if(mpctx->playtree) {
2673 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mconfig);
2674 if(mpctx->playtree_iter) {
2675 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
2676 play_tree_iter_free(mpctx->playtree_iter);
2677 mpctx->playtree_iter = NULL;
2679 filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
2684 print_version("MPlayer");
2686 #if defined(__MINGW32__) || defined(__CYGWIN__)
2687 #ifdef CONFIG_GUI
2688 void *runningmplayer = FindWindow("MPlayer GUI for Windows", "MPlayer for Windows");
2689 if(runningmplayer && filename && use_gui){
2690 COPYDATASTRUCT csData;
2691 char file[MAX_PATH];
2692 char *filepart = filename;
2693 if(GetFullPathName(filename, MAX_PATH, file, &filepart)){
2694 csData.dwData = 0;
2695 csData.cbData = strlen(file)*2;
2696 csData.lpData = file;
2697 SendMessage(runningmplayer, WM_COPYDATA, (WPARAM)runningmplayer, (LPARAM)&csData);
2700 #endif
2703 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
2704 BOOL WINAPI (*setDEP)(DWORD) = NULL;
2705 if (kernel32)
2706 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
2707 if (setDEP) setDEP(3);
2709 // stop Windows from showing all kinds of annoying error dialogs
2710 SetErrorMode(0x8003);
2711 // request 1ms timer resolution
2712 timeBeginPeriod(1);
2713 #endif
2715 #ifdef CONFIG_PRIORITY
2716 set_priority();
2717 #endif
2719 if (codec_path)
2720 set_codec_path(codec_path);
2722 #ifndef CONFIG_GUI
2723 if(use_gui){
2724 mp_msg(MSGT_CPLAYER,MSGL_WARN,MSGTR_NoGui);
2725 use_gui=0;
2727 #else
2728 #if !defined(__MINGW32__) && !defined(__CYGWIN__)
2729 if(use_gui && !vo_init()){
2730 mp_msg(MSGT_CPLAYER,MSGL_WARN,MSGTR_GuiNeedsX);
2731 use_gui=0;
2733 #endif
2734 if (use_gui && mpctx->playtree_iter){
2735 char cwd[PATH_MAX+2];
2736 // Free Playtree and Playtree-Iter as it's not used by the GUI.
2737 play_tree_iter_free(mpctx->playtree_iter);
2738 mpctx->playtree_iter=NULL;
2740 if (getcwd(cwd, PATH_MAX) != (char *)NULL)
2742 strcat(cwd, "/");
2743 // Prefix relative paths with current working directory
2744 play_tree_add_bpf(mpctx->playtree, cwd);
2746 // Import initital playtree into GUI.
2747 import_initial_playtree_into_gui(mpctx->playtree, mconfig, enqueue);
2749 #endif /* CONFIG_GUI */
2751 if(video_driver_list && strcmp(video_driver_list[0],"help")==0){
2752 list_video_out();
2753 opt_exit = 1;
2756 if(audio_driver_list && strcmp(audio_driver_list[0],"help")==0){
2757 list_audio_out();
2758 opt_exit = 1;
2761 /* Check codecs.conf. */
2762 if(!codecs_file || !parse_codec_cfg(codecs_file)){
2763 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
2764 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
2765 if(!parse_codec_cfg(NULL)){
2766 exit_player_with_rc(EXIT_NONE, 0);
2768 mp_msg(MSGT_CPLAYER,MSGL_V,MSGTR_BuiltinCodecsConf);
2771 free( mem_ptr ); // release the buffer created by get_path()
2774 #if 0
2775 if(video_codec_list){
2776 int i;
2777 video_codec=video_codec_list[0];
2778 for(i=0;video_codec_list[i];i++)
2779 mp_msg(MSGT_FIXME,MSGL_FIXME,"vc#%d: '%s'\n",i,video_codec_list[i]);
2781 #endif
2782 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
2783 mp_msg(MSGT_CPLAYER, MSGL_INFO, MSGTR_AvailableAudioCodecs);
2784 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
2785 list_codecs(1);
2786 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2787 opt_exit = 1;
2789 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
2790 mp_msg(MSGT_CPLAYER, MSGL_INFO, MSGTR_AvailableVideoCodecs);
2791 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
2792 list_codecs(0);
2793 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2794 opt_exit = 1;
2796 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
2797 vfm_help();
2798 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2799 opt_exit = 1;
2801 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
2802 afm_help();
2803 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2804 opt_exit = 1;
2806 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
2807 af_help();
2808 printf("\n");
2809 opt_exit = 1;
2811 #ifdef CONFIG_X11
2812 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
2813 fstype_help();
2814 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
2815 opt_exit = 1;
2817 #endif
2818 if((demuxer_name && strcmp(demuxer_name,"help")==0) ||
2819 (audio_demuxer_name && strcmp(audio_demuxer_name,"help")==0) ||
2820 (sub_demuxer_name && strcmp(sub_demuxer_name,"help")==0)){
2821 demuxer_help();
2822 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
2823 opt_exit = 1;
2825 if(list_properties) {
2826 property_print_help();
2827 opt_exit = 1;
2830 if(opt_exit)
2831 exit_player(EXIT_NONE);
2833 if (player_idle_mode && use_gui) {
2834 mp_msg(MSGT_CPLAYER, MSGL_FATAL, MSGTR_NoIdleAndGui);
2835 exit_player_with_rc(EXIT_NONE, 1);
2838 if(!filename && !player_idle_mode){
2839 if(!use_gui){
2840 // no file/vcd/dvd -> show HELP:
2841 mp_msg(MSGT_CPLAYER, MSGL_INFO, help_text);
2842 exit_player_with_rc(EXIT_NONE, 0);
2843 } else gui_no_filename=1;
2846 /* Display what configure line was used */
2847 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
2849 // Many users forget to include command line in bugreports...
2850 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
2851 mp_msg(MSGT_CPLAYER, MSGL_INFO, MSGTR_CommandLine);
2852 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
2853 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
2856 //------ load global data first ------
2858 // check font
2859 #ifdef CONFIG_FREETYPE
2860 init_freetype();
2861 #endif
2862 #ifdef CONFIG_FONTCONFIG
2863 if(font_fontconfig <= 0)
2865 #endif
2866 #ifdef CONFIG_BITMAP_FONT
2867 if(font_name){
2868 vo_font=read_font_desc(font_name,font_factor,verbose>1);
2869 if(!vo_font) mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_CantLoadFont,
2870 filename_recode(font_name));
2871 } else {
2872 // try default:
2873 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
2874 free(mem_ptr); // release the buffer created by get_path()
2875 if(!vo_font)
2876 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
2878 if (sub_font_name)
2879 sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
2880 else
2881 sub_font = vo_font;
2882 #endif
2883 #ifdef CONFIG_FONTCONFIG
2885 #endif
2887 vo_init_osd();
2889 #ifdef CONFIG_ASS
2890 ass_library = ass_init();
2891 #endif
2893 #ifdef HAVE_RTC
2894 if(!nortc)
2896 // seteuid(0); /* Can't hurt to try to get root here */
2897 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
2898 mp_msg(MSGT_CPLAYER, MSGL_WARN, MSGTR_RTCDeviceNotOpenable,
2899 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
2900 else {
2901 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
2903 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
2904 mp_msg(MSGT_CPLAYER, MSGL_WARN, MSGTR_LinuxRTCInitErrorIrqpSet, irqp, strerror(errno));
2905 mp_msg(MSGT_CPLAYER, MSGL_HINT, MSGTR_IncreaseRTCMaxUserFreq, irqp);
2906 close (rtc_fd);
2907 rtc_fd = -1;
2908 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
2909 /* variable only by the root */
2910 mp_msg(MSGT_CPLAYER, MSGL_ERR, MSGTR_LinuxRTCInitErrorPieOn, strerror(errno));
2911 close (rtc_fd);
2912 rtc_fd = -1;
2913 } else
2914 mp_msg(MSGT_CPLAYER, MSGL_V, MSGTR_UsingRTCTiming, irqp);
2917 #ifdef CONFIG_GUI
2918 // breaks DGA and SVGAlib and VESA drivers: --A'rpi
2919 // and now ? -- Pontscho
2920 if(use_gui) setuid( getuid() ); // strongly test, please check this.
2921 #endif
2922 if(rtc_fd<0)
2923 #endif /* HAVE_RTC */
2924 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
2925 softsleep?"software":timer_name);
2927 #ifdef HAVE_TERMCAP
2928 if ( !use_gui ) load_termcap(NULL); // load key-codes
2929 #endif
2931 // ========== Init keyboard FIFO (connection to libvo) ============
2933 // Init input system
2934 current_module = "init_input";
2935 mp_input_init(use_gui);
2936 mp_input_add_key_fd(-1,0,mplayer_get_key,NULL);
2937 if(slave_mode)
2938 mp_input_add_cmd_fd(0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
2939 else if(!noconsolecontrols)
2940 mp_input_add_event_fd(0, getch2);
2941 // Set the libstream interrupt callback
2942 stream_set_interrupt_callback(mp_input_check_interrupt);
2944 #ifdef CONFIG_MENU
2945 if(use_menu) {
2946 if(menu_cfg && menu_init(mpctx, menu_cfg))
2947 mp_msg(MSGT_CPLAYER, MSGL_V, MSGTR_MenuInitialized, menu_cfg);
2948 else {
2949 menu_cfg = get_path("menu.conf");
2950 if(menu_init(mpctx, menu_cfg))
2951 mp_msg(MSGT_CPLAYER, MSGL_V, MSGTR_MenuInitialized, menu_cfg);
2952 else {
2953 if(menu_init(mpctx, MPLAYER_CONFDIR "/menu.conf"))
2954 mp_msg(MSGT_CPLAYER, MSGL_V, MSGTR_MenuInitialized, MPLAYER_CONFDIR"/menu.conf");
2955 else {
2956 mp_msg(MSGT_CPLAYER, MSGL_ERR, MSGTR_MenuInitFailed);
2957 use_menu = 0;
2962 #endif
2964 initialized_flags|=INITIALIZED_INPUT;
2965 current_module = NULL;
2967 /// Catch signals
2968 #ifndef __MINGW32__
2969 signal(SIGCHLD,child_sighandler);
2970 #endif
2972 #ifdef CONFIG_CRASH_DEBUG
2973 prog_path = argv[0];
2974 #endif
2975 //========= Catch terminate signals: ================
2976 // terminate requests:
2977 signal(SIGTERM,exit_sighandler); // kill
2978 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
2980 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
2982 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
2983 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
2984 #ifdef CONFIG_SIGHANDLER
2985 // fatal errors:
2986 signal(SIGBUS,exit_sighandler); // bus error
2987 signal(SIGSEGV,exit_sighandler); // segfault
2988 signal(SIGILL,exit_sighandler); // illegal instruction
2989 signal(SIGFPE,exit_sighandler); // floating point exc.
2990 signal(SIGABRT,exit_sighandler); // abort()
2991 #ifdef CONFIG_CRASH_DEBUG
2992 if (crash_debug)
2993 signal(SIGTRAP,exit_sighandler);
2994 #endif
2995 #endif
2997 #ifdef CONFIG_GUI
2998 if(use_gui){
2999 guiInit();
3000 guiGetEvent(guiSetContext, mpctx);
3001 initialized_flags|=INITIALIZED_GUI;
3002 guiGetEvent( guiCEvent,(char *)((gui_no_filename) ? 0 : 1) );
3004 #endif
3006 // ******************* Now, let's see the per-file stuff ********************
3008 play_next_file:
3010 // init global sub numbers
3011 mpctx->global_sub_size = 0;
3012 { int i; for (i = 0; i < SUB_SOURCES; i++) mpctx->global_sub_indices[i] = -1; }
3014 if (filename) {
3015 load_per_protocol_config (mconfig, filename);
3016 load_per_extension_config (mconfig, filename);
3017 load_per_file_config (mconfig, filename);
3020 if (video_driver_list)
3021 load_per_output_config (mconfig, PROFILE_CFG_VO, video_driver_list[0]);
3022 if (audio_driver_list)
3023 load_per_output_config (mconfig, PROFILE_CFG_AO, audio_driver_list[0]);
3025 // We must enable getch2 here to be able to interrupt network connection
3026 // or cache filling
3027 if(!noconsolecontrols && !slave_mode){
3028 if(initialized_flags&INITIALIZED_GETCH2)
3029 mp_msg(MSGT_CPLAYER,MSGL_WARN,MSGTR_Getch2InitializedTwice);
3030 else
3031 getch2_enable(); // prepare stdin for hotkeys...
3032 initialized_flags|=INITIALIZED_GETCH2;
3033 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3036 // =================== GUI idle loop (STOP state) ===========================
3037 #ifdef CONFIG_GUI
3038 if ( use_gui ) {
3039 mpctx->file_format=DEMUXER_TYPE_UNKNOWN;
3040 guiGetEvent( guiSetDefaults,0 );
3041 while ( guiIntfStruct.Playing != 1 )
3043 mp_cmd_t* cmd;
3044 usec_sleep(20000);
3045 guiEventHandling();
3046 guiGetEvent( guiReDraw,NULL );
3047 if ( (cmd = mp_input_get_cmd(0,0,0)) != NULL) {
3048 guiGetEvent(guiIEvent, (char *)cmd->id);
3049 mp_cmd_free(cmd);
3052 guiGetEvent( guiSetParameters,NULL );
3053 if ( guiIntfStruct.StreamType == STREAMTYPE_STREAM )
3055 play_tree_t * entry = play_tree_new();
3056 play_tree_add_file( entry,guiIntfStruct.Filename );
3057 if ( mpctx->playtree ) play_tree_free_list( mpctx->playtree->child,1 );
3058 else mpctx->playtree=play_tree_new();
3059 play_tree_set_child( mpctx->playtree,entry );
3060 if(mpctx->playtree)
3062 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mconfig);
3063 if(mpctx->playtree_iter)
3065 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY)
3067 play_tree_iter_free(mpctx->playtree_iter);
3068 mpctx->playtree_iter = NULL;
3070 filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3075 #endif /* CONFIG_GUI */
3077 while (player_idle_mode && !filename) {
3078 play_tree_t * entry = NULL;
3079 mp_cmd_t * cmd;
3080 if (mpctx->video_out && vo_config_count)
3081 mpctx->video_out->control(VOCTRL_PAUSE, NULL);
3082 while (!(cmd = mp_input_get_cmd(0,1,0))) { // wait for command
3083 if (mpctx->video_out && vo_config_count) mpctx->video_out->check_events();
3084 usec_sleep(20000);
3086 switch (cmd->id) {
3087 case MP_CMD_LOADFILE:
3088 // prepare a tree entry with the new filename
3089 entry = play_tree_new();
3090 play_tree_add_file(entry, cmd->args[0].v.s);
3091 // The entry is added to the main playtree after the switch().
3092 break;
3093 case MP_CMD_LOADLIST:
3094 entry = parse_playlist_file(cmd->args[0].v.s);
3095 break;
3096 case MP_CMD_QUIT:
3097 exit_player_with_rc(EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3098 break;
3099 case MP_CMD_GET_PROPERTY:
3100 case MP_CMD_SET_PROPERTY:
3101 case MP_CMD_STEP_PROPERTY:
3102 run_command(mpctx, cmd);
3103 break;
3106 mp_cmd_free(cmd);
3108 if (entry) { // user entered a command that gave a valid entry
3109 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3110 play_tree_free_list(mpctx->playtree->child, 1);
3111 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3113 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3115 play_tree_set_child(mpctx->playtree, entry);
3117 /* Make iterator start at the top the of tree. */
3118 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mconfig);
3119 if (!mpctx->playtree_iter) continue;
3121 // find the first real item in the tree
3122 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3123 // no items!
3124 play_tree_iter_free(mpctx->playtree_iter);
3125 mpctx->playtree_iter = NULL;
3126 continue; // wait for next command
3128 filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3131 //---------------------------------------------------------------------------
3133 if (mpctx->video_out && vo_config_count)
3134 mpctx->video_out->control(VOCTRL_RESUME, NULL);
3136 if(filename) {
3137 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_Playing,
3138 filename_recode(filename));
3139 if(use_filename_title && vo_wintitle == NULL)
3140 vo_wintitle = strdup ( mp_basename2 (filename));
3143 if (edl_filename) {
3144 if (edl_records) free_edl(edl_records);
3145 next_edl_record = edl_records = edl_parse_file();
3147 if (edl_output_filename) {
3148 if (edl_fd) fclose(edl_fd);
3149 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3151 mp_msg(MSGT_CPLAYER, MSGL_ERR, MSGTR_EdlCantOpenForWrite,
3152 filename_recode(edl_output_filename));
3156 //==================== Open VOB-Sub ============================
3158 current_module="vobsub";
3159 if (vobsub_name){
3160 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3161 if(vo_vobsub==NULL)
3162 mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_CantLoadSub,
3163 filename_recode(vobsub_name));
3164 } else if (sub_auto && filename){
3165 /* try to autodetect vobsub from movie filename ::atmos */
3166 char *buf = strdup(filename), *psub;
3167 char *pdot = strrchr(buf, '.');
3168 char *pslash = strrchr(buf, '/');
3169 #if defined(__MINGW32__) || defined(__CYGWIN__)
3170 if (!pslash) pslash = strrchr(buf, '\\');
3171 #endif
3172 if (pdot && (!pslash || pdot > pslash))
3173 *pdot = '\0';
3174 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3175 /* try from ~/.mplayer/sub */
3176 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3177 char *bname;
3178 int l;
3179 bname = strrchr(buf,'/');
3180 #if defined(__MINGW32__) || defined(__CYGWIN__)
3181 if(!bname) bname = strrchr(buf,'\\');
3182 #endif
3183 if(bname) bname++;
3184 else bname = buf;
3185 l = strlen(psub) + strlen(bname) + 1;
3186 psub = realloc(psub,l);
3187 strcat(psub,bname);
3188 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3189 free(psub);
3191 free(buf);
3193 if(vo_vobsub){
3194 initialized_flags|=INITIALIZED_VOBSUB;
3195 vobsub_set_from_lang(vo_vobsub, dvdsub_lang);
3196 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3198 // setup global sub numbering
3199 mpctx->global_sub_indices[SUB_SOURCE_VOBSUB] = mpctx->global_sub_size; // the global # of the first vobsub.
3200 mpctx->global_sub_size += vobsub_get_indexes_count(vo_vobsub);
3203 //============ Open & Sync STREAM --- fork cache2 ====================
3205 mpctx->stream=NULL;
3206 mpctx->demuxer=NULL;
3207 if (mpctx->d_audio) {
3208 //free_demuxer_stream(mpctx->d_audio);
3209 mpctx->d_audio=NULL;
3211 if (mpctx->d_video) {
3212 //free_demuxer_stream(d_video);
3213 mpctx->d_video=NULL;
3215 mpctx->sh_audio=NULL;
3216 mpctx->sh_video=NULL;
3218 current_module="open_stream";
3219 mpctx->stream=open_stream(filename,0,&mpctx->file_format);
3220 if(!mpctx->stream) { // error...
3221 mpctx->eof = libmpdemux_was_interrupted(PT_NEXT_ENTRY);
3222 goto goto_next_file;
3224 initialized_flags|=INITIALIZED_STREAM;
3226 #ifdef CONFIG_GUI
3227 if ( use_gui ) guiGetEvent( guiSetStream,(char *)mpctx->stream );
3228 #endif
3230 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3231 play_tree_t* entry;
3232 // Handle playlist
3233 current_module="handle_playlist";
3234 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3235 filename_recode(filename));
3236 entry = parse_playtree(mpctx->stream,0);
3237 mpctx->eof=playtree_add_playlist(entry);
3238 goto goto_next_file;
3240 mpctx->stream->start_pos+=seek_to_byte;
3242 if(stream_dump_type==5){
3243 unsigned char buf[4096];
3244 int len;
3245 FILE *f;
3246 current_module="dumpstream";
3247 stream_reset(mpctx->stream);
3248 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3249 f=fopen(stream_dump_name,"wb");
3250 if(!f){
3251 mp_msg(MSGT_CPLAYER,MSGL_FATAL,MSGTR_CantOpenDumpfile);
3252 exit_player(EXIT_ERROR);
3254 if (dvd_chapter > 1) {
3255 int chapter = dvd_chapter - 1;
3256 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3258 while(!mpctx->stream->eof && !async_quit_request){
3259 len=stream_read(mpctx->stream,buf,4096);
3260 if(len>0) {
3261 if(fwrite(buf,len,1,f) != 1) {
3262 mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_ErrorWritingFile,stream_dump_name);
3263 exit_player(EXIT_ERROR);
3266 if(dvd_last_chapter > 0) {
3267 int chapter = -1;
3268 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3269 &chapter) == STREAM_OK && chapter + 1 > dvd_last_chapter)
3270 break;
3273 if(fclose(f)) {
3274 mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_ErrorWritingFile,stream_dump_name);
3275 exit_player(EXIT_ERROR);
3277 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_CoreDumped);
3278 exit_player_with_rc(EXIT_EOF, 0);
3281 #ifdef CONFIG_DVDREAD
3282 if(mpctx->stream->type==STREAMTYPE_DVD){
3283 current_module="dvd lang->id";
3284 if(audio_id==-1) audio_id=dvd_aid_from_lang(mpctx->stream,audio_lang);
3285 if(dvdsub_lang && dvdsub_id==-1) dvdsub_id=dvd_sid_from_lang(mpctx->stream,dvdsub_lang);
3286 // setup global sub numbering
3287 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3288 mpctx->global_sub_size += dvd_number_of_subs(mpctx->stream);
3289 current_module=NULL;
3291 #endif
3293 #ifdef CONFIG_DVDNAV
3294 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3295 current_module="dvdnav lang->id";
3296 if(audio_id==-1) audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,audio_lang);
3297 dvdsub_lang_id = -3;
3298 if(dvdsub_lang && dvdsub_id==-1)
3299 dvdsub_lang_id=dvdsub_id=mp_dvdnav_sid_from_lang(mpctx->stream,dvdsub_lang);
3300 // setup global sub numbering
3301 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3302 mpctx->global_sub_size += mp_dvdnav_number_of_subs(mpctx->stream);
3303 current_module=NULL;
3305 #endif
3307 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3308 goto_enable_cache:
3309 if(stream_cache_size>0){
3310 int res;
3311 current_module="enable_cache";
3312 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3313 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3314 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3315 if(res == 0)
3316 if((mpctx->eof = libmpdemux_was_interrupted(PT_NEXT_ENTRY))) goto goto_next_file;
3319 //============ Open DEMUXERS --- DETECT file type =======================
3320 current_module="demux_open";
3322 mpctx->demuxer=demux_open(mpctx->stream,mpctx->file_format,audio_id,video_id,dvdsub_id,filename);
3324 // HACK to get MOV Reference Files working
3326 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3328 unsigned char* playlist_entry;
3329 play_tree_t *list = NULL, *entry = NULL;
3331 current_module="handle_demux_playlist";
3332 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3334 char *temp, *bname;
3336 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3337 filename_recode(playlist_entry));
3339 bname=mp_basename(playlist_entry);
3340 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3341 continue;
3343 if (!strcmp(playlist_entry,filename)) // ignoring self-reference
3344 continue;
3346 entry = play_tree_new();
3348 if (filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3350 temp=malloc((strlen(filename)-strlen(mp_basename(filename))+strlen(playlist_entry)+1));
3351 if (temp)
3353 strncpy(temp, filename, strlen(filename)-strlen(mp_basename(filename)));
3354 temp[strlen(filename)-strlen(mp_basename(filename))]='\0';
3355 strcat(temp, playlist_entry);
3356 if (!strcmp(temp, filename)) {
3357 free(temp);
3358 continue;
3360 play_tree_add_file(entry,temp);
3361 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3362 free(temp);
3365 else
3366 play_tree_add_file(entry,playlist_entry);
3368 if(!list)
3369 list = entry;
3370 else
3371 play_tree_append_entry(list,entry);
3373 free_demuxer(mpctx->demuxer);
3374 mpctx->demuxer = NULL;
3376 if (list)
3378 entry = play_tree_new();
3379 play_tree_set_child(entry,list);
3380 mpctx->eof=playtree_add_playlist(entry);
3381 goto goto_next_file;
3385 if(!mpctx->demuxer)
3386 goto goto_next_file;
3387 if(dvd_chapter>1) {
3388 float pts;
3389 if (demuxer_seek_chapter(mpctx->demuxer, dvd_chapter-1, 1, &pts, NULL, NULL) >= 0 && pts > -1.0)
3390 seek(mpctx, pts, SEEK_ABSOLUTE);
3393 initialized_flags|=INITIALIZED_DEMUXER;
3395 if (mpctx->stream->type != STREAMTYPE_DVD && mpctx->stream->type != STREAMTYPE_DVDNAV) {
3396 int i;
3397 int maxid = -1;
3398 // setup global sub numbering
3399 mpctx->global_sub_indices[SUB_SOURCE_DEMUX] = mpctx->global_sub_size; // the global # of the first demux-specific sub.
3400 for (i = 0; i < MAX_S_STREAMS; i++)
3401 if (mpctx->demuxer->s_streams[i])
3402 maxid = FFMAX(maxid, ((sh_sub_t *)mpctx->demuxer->s_streams[i])->sid);
3403 mpctx->global_sub_size += maxid + 1;
3405 // Make dvdsub_id always selectable if set.
3406 if (mpctx->global_sub_size <= mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + dvdsub_id)
3407 mpctx->global_sub_size = mpctx->global_sub_indices[SUB_SOURCE_DEMUX] + dvdsub_id + 1;
3409 #ifdef CONFIG_ASS
3410 if (ass_enabled && ass_library) {
3411 for (i = 0; i < mpctx->demuxer->num_attachments; ++i) {
3412 demux_attachment_t* att = mpctx->demuxer->attachments + i;
3413 if (extract_embedded_fonts &&
3414 att->name && att->type && att->data && att->data_size &&
3415 (strcmp(att->type, "application/x-truetype-font") == 0 ||
3416 strcmp(att->type, "application/x-font") == 0))
3417 ass_add_font(ass_library, att->name, att->data, att->data_size);
3420 #endif
3422 current_module="demux_open2";
3424 //file_format=demuxer->file_format;
3426 mpctx->d_audio=mpctx->demuxer->audio;
3427 mpctx->d_video=mpctx->demuxer->video;
3428 mpctx->d_sub=mpctx->demuxer->sub;
3430 if (ts_prog) {
3431 int tmp = ts_prog;
3432 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3434 // select audio stream
3435 select_audio(mpctx->demuxer, audio_id, audio_lang);
3437 // DUMP STREAMS:
3438 if((stream_dump_type)&&(stream_dump_type<4)){
3439 FILE *f;
3440 demux_stream_t *ds=NULL;
3441 current_module="dump";
3442 // select stream to dump
3443 switch(stream_dump_type){
3444 case 1: ds=mpctx->d_audio;break;
3445 case 2: ds=mpctx->d_video;break;
3446 case 3: ds=mpctx->d_sub;break;
3448 if(!ds){
3449 mp_msg(MSGT_CPLAYER,MSGL_FATAL,MSGTR_DumpSelectedStreamMissing);
3450 exit_player(EXIT_ERROR);
3452 // disable other streams:
3453 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3454 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3455 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3456 // let's dump it!
3457 f=fopen(stream_dump_name,"wb");
3458 if(!f){
3459 mp_msg(MSGT_CPLAYER,MSGL_FATAL,MSGTR_CantOpenDumpfile);
3460 exit_player(EXIT_ERROR);
3462 while(!ds->eof){
3463 unsigned char* start;
3464 int in_size=ds_get_packet(ds,&start);
3465 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3466 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3467 if(in_size>0) fwrite(start,in_size,1,f);
3468 if(dvd_last_chapter>0) {
3469 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3470 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3471 break;
3474 fclose(f);
3475 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_CoreDumped);
3476 exit_player_with_rc(EXIT_EOF, 0);
3479 mpctx->sh_audio=mpctx->d_audio->sh;
3480 mpctx->sh_video=mpctx->d_video->sh;
3482 if(mpctx->sh_video){
3484 current_module="video_read_properties";
3485 if(!video_read_properties(mpctx->sh_video)) {
3486 mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_CannotReadVideoProperties);
3487 mpctx->sh_video=mpctx->d_video->sh=NULL;
3488 } else {
3489 mp_msg(MSGT_CPLAYER,MSGL_V,MSGTR_FilefmtFourccSizeFpsFtime,
3490 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3491 mpctx->sh_video->fps,mpctx->sh_video->frametime
3494 /* need to set fps here for output encoders to pick it up in their init */
3495 if(force_fps){
3496 mpctx->sh_video->fps=force_fps;
3497 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3499 vo_fps = mpctx->sh_video->fps;
3501 if(!mpctx->sh_video->fps && !force_fps){
3502 mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_FPSnotspecified);
3503 mpctx->sh_video=mpctx->d_video->sh=NULL;
3509 if(!mpctx->sh_video && !mpctx->sh_audio){
3510 mp_msg(MSGT_CPLAYER,MSGL_FATAL, MSGTR_NoStreamFound);
3511 #ifdef CONFIG_DVBIN
3512 if(mpctx->stream->type == STREAMTYPE_DVB)
3514 int dir;
3515 int v = mpctx->last_dvb_step;
3516 if(v > 0)
3517 dir = DVB_CHANNEL_HIGHER;
3518 else
3519 dir = DVB_CHANNEL_LOWER;
3521 if(dvb_step_channel(mpctx->stream, dir))
3522 mpctx->eof = mpctx->dvbin_reopen = 1;
3524 #endif
3525 goto goto_next_file; // exit_player(MSGTR_Exit_error);
3528 /* display clip info */
3529 demux_info_print(mpctx->demuxer);
3531 //================== Read SUBTITLES (DVD & TEXT) ==========================
3532 if(vo_spudec==NULL &&
3533 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
3534 init_vo_spudec();
3537 if(1 || mpctx->sh_video) {
3538 // after reading video params we should load subtitles because
3539 // we know fps so now we can adjust subtitle time to ~6 seconds AST
3540 // check .sub
3541 double fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
3542 current_module="read_subtitles_file";
3543 if(sub_name){
3544 for (i = 0; sub_name[i] != NULL; ++i)
3545 add_subtitles (sub_name[i], fps, 0);
3547 if(sub_auto) { // auto load sub file ...
3548 char *psub = get_path( "sub/" );
3549 char **tmp = sub_filenames((psub ? psub : ""), filename);
3550 int i = 0;
3551 free(psub); // release the buffer created by get_path() above
3552 while (tmp[i]) {
3553 add_subtitles (tmp[i], fps, 1);
3554 free(tmp[i++]);
3556 free(tmp);
3558 if (mpctx->set_of_sub_size > 0) {
3559 // setup global sub numbering
3560 mpctx->global_sub_indices[SUB_SOURCE_SUBS] = mpctx->global_sub_size; // the global # of the first sub.
3561 mpctx->global_sub_size += mpctx->set_of_sub_size;
3565 if (mpctx->global_sub_size) {
3566 select_subtitle(mpctx);
3567 if(subdata)
3568 switch (stream_dump_type) {
3569 case 3: list_sub_file(subdata); break;
3570 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
3571 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
3572 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
3573 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
3574 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
3578 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
3579 filename_recode(filename));
3580 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
3581 if (mpctx->sh_video) {
3582 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3583 if (mpctx->sh_video->format >= 0x20202020)
3584 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
3585 else
3586 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
3587 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
3588 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
3589 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
3590 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
3591 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
3593 if (mpctx->sh_audio) {
3594 /* Assume FOURCC if all bytes >= 0x20 (' ') */
3595 if (mpctx->sh_audio->format >= 0x20202020)
3596 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
3597 else
3598 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
3599 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
3600 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
3601 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
3603 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2lf\n", demuxer_get_time_length(mpctx->demuxer));
3604 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
3605 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
3606 if (mpctx->demuxer) {
3607 if (mpctx->demuxer->num_chapters == 0)
3608 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
3609 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
3612 if(!mpctx->sh_video) goto main; // audio-only
3614 if(!reinit_video_chain()) {
3615 if(!mpctx->sh_video){
3616 if(!mpctx->sh_audio) goto goto_next_file;
3617 goto main; // exit_player(MSGTR_Exit_error);
3621 if(vo_flags & 0x08 && vo_spudec)
3622 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
3624 #ifdef CONFIG_FREETYPE
3625 force_load_font = 1;
3626 #endif
3628 //================== MAIN: ==========================
3629 main:
3630 current_module="main";
3632 if(playing_msg) {
3633 char* msg = property_expand_string(mpctx, playing_msg);
3634 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
3635 free(msg);
3639 // Disable the term OSD in verbose mode
3640 if(verbose) term_osd = 0;
3643 //int frame_corr_num=0; //
3644 //float v_frame=0; // Video
3645 //float num_frames=0; // number of frames played
3647 int frame_time_remaining=0; // flag
3648 int blit_frame=0;
3649 mpctx->num_buffered_frames=0;
3651 // Make sure old OSD does not stay around,
3652 // e.g. with -fixed-vo and same-resolution files
3653 clear_osd_msgs();
3654 update_osd_msg();
3656 //================ SETUP AUDIO ==========================
3658 if(mpctx->sh_audio){
3659 reinit_audio_chain();
3660 if (mpctx->sh_audio && mpctx->sh_audio->codec)
3661 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
3664 current_module="av_init";
3666 if(mpctx->sh_video){
3667 mpctx->sh_video->timer=0;
3668 if (! ignore_start)
3669 audio_delay += mpctx->sh_video->stream_delay;
3671 if(mpctx->sh_audio){
3672 if (start_volume >= 0)
3673 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
3674 if (! ignore_start)
3675 audio_delay -= mpctx->sh_audio->stream_delay;
3676 mpctx->delay=-audio_delay;
3679 if(!mpctx->sh_audio){
3680 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_NoSound);
3681 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
3682 ds_free_packs(mpctx->d_audio); // free buffered chunks
3683 //mpctx->d_audio->id=-2; // do not read audio chunks
3684 //uninit_player(INITIALIZED_AO); // close device
3686 if(!mpctx->sh_video){
3687 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_Video_NoVideo);
3688 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
3689 ds_free_packs(mpctx->d_video);
3690 mpctx->d_video->id=-2;
3691 //if(!fixed_vo) uninit_player(INITIALIZED_VO);
3694 if (!mpctx->sh_video && !mpctx->sh_audio)
3695 goto goto_next_file;
3697 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
3698 if(force_fps && mpctx->sh_video){
3699 vo_fps = mpctx->sh_video->fps=force_fps;
3700 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
3701 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_FPSforced,mpctx->sh_video->fps,mpctx->sh_video->frametime);
3704 #ifdef CONFIG_GUI
3705 if ( use_gui ) {
3706 if ( mpctx->sh_audio ) guiIntfStruct.AudioType=mpctx->sh_audio->channels; else guiIntfStruct.AudioType=0;
3707 if ( !mpctx->sh_video && mpctx->sh_audio ) guiGetEvent( guiSetAudioOnly,(char *)1 ); else guiGetEvent( guiSetAudioOnly,(char *)0 );
3708 guiGetEvent( guiSetFileFormat,(char *)mpctx->demuxer->file_format );
3709 if ( guiGetEvent( guiSetValues,(char *)mpctx->sh_video ) ) goto goto_next_file;
3710 guiGetEvent( guiSetDemuxer,(char *)mpctx->demuxer );
3712 #endif
3714 mp_input_set_section(NULL);
3715 //TODO: add desired (stream-based) sections here
3716 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section("tv");
3717 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section("dvdnav");
3719 //==================== START PLAYING =======================
3721 if(mpctx->loop_times>1) mpctx->loop_times--; else
3722 if(mpctx->loop_times==1) mpctx->loop_times = -1;
3724 mp_msg(MSGT_CPLAYER,MSGL_INFO,MSGTR_StartPlaying);
3726 total_time_usage_start=GetTimer();
3727 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
3728 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
3729 play_n_frames=play_n_frames_mf;
3730 mpctx->startup_decode_retry = DEFAULT_STARTUP_DECODE_RETRY;
3732 if(play_n_frames==0){
3733 mpctx->eof=PT_NEXT_ENTRY; goto goto_next_file;
3736 if (seek_to_sec) {
3737 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
3738 end_at.pos += seek_to_sec;
3741 if (end_at.type == END_AT_SIZE) {
3742 mp_msg(MSGT_CPLAYER, MSGL_WARN, MSGTR_MPEndposNoSizeBased);
3743 end_at.type = END_AT_NONE;
3746 #ifdef CONFIG_DVDNAV
3747 mp_dvdnav_context_free(mpctx);
3748 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3749 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
3750 mp_dvdnav_cell_has_changed(mpctx->stream,1);
3752 #endif
3754 while(!mpctx->eof){
3755 float aq_sleep_time=0;
3757 if(dvd_last_chapter>0) {
3758 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer);
3759 if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
3760 goto goto_next_file;
3763 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
3764 mpctx->sh_audio = mpctx->d_audio->sh;
3765 mpctx->sh_audio->ds = mpctx->d_audio;
3766 reinit_audio_chain();
3769 /*========================== PLAY AUDIO ============================*/
3771 if (mpctx->sh_audio)
3772 if (!fill_audio_out_buffers())
3773 // at eof, all audio at least written to ao
3774 if (!mpctx->sh_video)
3775 mpctx->eof = PT_NEXT_ENTRY;
3778 if(!mpctx->sh_video) {
3779 // handle audio-only case:
3780 double a_pos=0;
3781 // sh_audio can be NULL due to video stream switching
3782 // TODO: handle this better
3783 if((!quiet || end_at.type == END_AT_TIME) && mpctx->sh_audio)
3784 a_pos = playing_audio_pts(mpctx->sh_audio, mpctx->d_audio, mpctx->audio_out);
3786 if(!quiet)
3787 print_status(a_pos, 0, 0);
3789 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
3790 mpctx->eof = PT_NEXT_ENTRY;
3791 update_subtitles(NULL, a_pos, mpctx->d_sub, 0);
3792 update_osd_msg();
3794 } else {
3796 /*========================== PLAY VIDEO ============================*/
3798 vo_pts=mpctx->sh_video->timer*90000.0;
3799 vo_fps=mpctx->sh_video->fps;
3801 if (!mpctx->num_buffered_frames) {
3802 double frame_time = update_video(&blit_frame);
3803 while (!blit_frame && mpctx->startup_decode_retry > 0) {
3804 double delay = mpctx->delay;
3805 // these initial decode failures are probably due to codec delay,
3806 // ignore them and also their probably nonsense durations
3807 update_video(&blit_frame);
3808 mpctx->delay = delay;
3809 mpctx->startup_decode_retry--;
3811 mpctx->startup_decode_retry = 0;
3812 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
3813 if (mpctx->sh_video->vf_initialized < 0) {
3814 mp_msg(MSGT_CPLAYER,MSGL_FATAL, MSGTR_NotInitializeVOPorVO);
3815 mpctx->eof = 1; goto goto_next_file;
3817 if (frame_time < 0)
3818 mpctx->eof = 1;
3819 else {
3820 // might return with !eof && !blit_frame if !correct_pts
3821 mpctx->num_buffered_frames += blit_frame;
3822 mpctx->time_frame += frame_time / playback_speed; // for nosound
3826 // ==========================================================================
3828 // current_module="draw_osd";
3829 // if(vo_config_count) mpctx->video_out->draw_osd();
3831 #ifdef CONFIG_GUI
3832 if(use_gui) guiEventHandling();
3833 #endif
3835 current_module="vo_check_events";
3836 if (vo_config_count) mpctx->video_out->check_events();
3838 #ifdef CONFIG_X11
3839 if (stop_xscreensaver) {
3840 current_module = "stop_xscreensaver";
3841 xscreensaver_heartbeat();
3843 #endif
3844 if (heartbeat_cmd) {
3845 static unsigned last_heartbeat;
3846 unsigned now = GetTimerMS();
3847 if (now - last_heartbeat > 30000) {
3848 last_heartbeat = now;
3849 system(heartbeat_cmd);
3853 frame_time_remaining = sleep_until_update(&mpctx->time_frame, &aq_sleep_time);
3855 //====================== FLIP PAGE (VIDEO BLT): =========================
3857 current_module="flip_page";
3858 if (!frame_time_remaining && blit_frame) {
3859 unsigned int t2=GetTimer();
3861 if(vo_config_count) mpctx->video_out->flip_page();
3862 mpctx->num_buffered_frames--;
3864 vout_time_usage += (GetTimer() - t2) * 0.000001;
3866 //====================== A-V TIMESTAMP CORRECTION: =========================
3868 adjust_sync_and_print_status(frame_time_remaining, mpctx->time_frame);
3870 //============================ Auto QUALITY ============================
3872 /*Output quality adjustments:*/
3873 if(auto_quality>0){
3874 current_module="autoq";
3875 // float total=0.000001f * (GetTimer()-aq_total_time);
3876 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
3877 if(output_quality<auto_quality && aq_sleep_time>0)
3878 ++output_quality;
3879 else
3880 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
3881 if(output_quality>1 && aq_sleep_time<0)
3882 --output_quality;
3883 else
3884 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3885 output_quality=0;
3886 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
3887 set_video_quality(mpctx->sh_video,output_quality);
3890 if (play_n_frames >= 0 && !frame_time_remaining && blit_frame) {
3891 --play_n_frames;
3892 if (play_n_frames <= 0) mpctx->eof = PT_NEXT_ENTRY;
3896 // FIXME: add size based support for -endpos
3897 if (end_at.type == END_AT_TIME &&
3898 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3899 mpctx->eof = PT_NEXT_ENTRY;
3901 } // end if(mpctx->sh_video)
3903 #ifdef CONFIG_DVDNAV
3904 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3905 nav_highlight_t hl;
3906 mp_dvdnav_get_highlight (mpctx->stream, &hl);
3907 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
3908 vo_osd_changed (OSDTYPE_DVDNAV);
3910 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3911 double ar = -1.0;
3912 if (mpctx->sh_video &&
3913 stream_control (mpctx->demuxer->stream,
3914 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3915 != STREAM_UNSUPPORTED)
3916 mpctx->sh_video->stream_aspect = ar;
3919 #endif
3921 //============================ Handle PAUSE ===============================
3923 current_module="pause";
3925 if (mpctx->osd_function == OSD_PAUSE) {
3926 mpctx->was_paused = 1;
3927 pause_loop();
3930 // handle -sstep
3931 if(step_sec>0) {
3932 mpctx->osd_function=OSD_FFW;
3933 rel_seek_secs+=step_sec;
3936 edl_update(mpctx);
3938 //================= Keyboard events, SEEKing ====================
3940 current_module="key_events";
3943 mp_cmd_t* cmd;
3944 int brk_cmd = 0;
3945 while( !brk_cmd && (cmd = mp_input_get_cmd(0,0,0)) != NULL) {
3946 brk_cmd = run_command(mpctx, cmd);
3947 mp_cmd_free(cmd);
3948 if (brk_cmd == 2)
3949 goto goto_enable_cache;
3952 mpctx->was_paused = 0;
3954 /* Looping. */
3955 if(mpctx->eof==1 && mpctx->loop_times>=0) {
3956 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d, eof = %d\n", mpctx->loop_times,mpctx->eof);
3958 if(mpctx->loop_times>1) mpctx->loop_times--; else
3959 if(mpctx->loop_times==1) mpctx->loop_times=-1;
3960 play_n_frames=play_n_frames_mf;
3961 mpctx->eof=0;
3962 abs_seek_pos=SEEK_ABSOLUTE; rel_seek_secs=seek_to_sec;
3963 loop_seek = 1;
3966 if(rel_seek_secs || abs_seek_pos){
3967 if (seek(mpctx, rel_seek_secs, abs_seek_pos) >= 0) {
3968 // Set OSD:
3969 if(!loop_seek){
3970 if( !edl_decision )
3971 set_osd_bar(0,"Position",0,100,demuxer_get_percent_pos(mpctx->demuxer));
3975 rel_seek_secs=0;
3976 abs_seek_pos=0;
3977 loop_seek=0;
3978 edl_decision = 0;
3981 #ifdef CONFIG_GUI
3982 if(use_gui){
3983 guiEventHandling();
3984 if(mpctx->demuxer->file_format==DEMUXER_TYPE_AVI && mpctx->sh_video && mpctx->sh_video->video.dwLength>2){
3985 // get pos from frame number / total frames
3986 guiIntfStruct.Position=(float)mpctx->d_video->pack_no*100.0f/mpctx->sh_video->video.dwLength;
3987 } else {
3988 guiIntfStruct.Position=demuxer_get_percent_pos(mpctx->demuxer);
3990 if ( mpctx->sh_video ) guiIntfStruct.TimeSec=mpctx->sh_video->pts;
3991 else if ( mpctx->sh_audio ) guiIntfStruct.TimeSec=playing_audio_pts(mpctx->sh_audio, mpctx->d_audio, mpctx->audio_out);
3992 guiIntfStruct.LengthInSec=demuxer_get_time_length(mpctx->demuxer);
3993 guiGetEvent( guiReDraw,NULL );
3994 guiGetEvent( guiSetVolume,NULL );
3995 if(guiIntfStruct.Playing==0) break; // STOP
3996 if(guiIntfStruct.Playing==2) mpctx->osd_function=OSD_PAUSE;
3997 if ( guiIntfStruct.DiskChanged || guiIntfStruct.NewPlay ) goto goto_next_file;
3998 #ifdef CONFIG_DVDREAD
3999 if ( mpctx->stream->type == STREAMTYPE_DVD )
4001 dvd_priv_t * dvdp = mpctx->stream->priv;
4002 guiIntfStruct.DVD.current_chapter=dvd_chapter_from_cell(dvdp,guiIntfStruct.DVD.current_title-1, dvdp->cur_cell)+1;
4004 #endif
4006 #endif /* CONFIG_GUI */
4008 } // while(!mpctx->eof)
4010 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->eof);
4012 #ifdef CONFIG_DVBIN
4013 if(mpctx->dvbin_reopen)
4015 mpctx->eof = 0;
4016 uninit_player(INITIALIZED_ALL-(INITIALIZED_GUI|INITIALIZED_STREAM|INITIALIZED_INPUT|INITIALIZED_GETCH2|(fixed_vo?INITIALIZED_VO:0)));
4017 cache_uninit(mpctx->stream);
4018 mpctx->dvbin_reopen = 0;
4019 goto goto_enable_cache;
4021 #endif
4024 goto_next_file: // don't jump here after ao/vo/getch initialization!
4026 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4028 if(benchmark){
4029 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4030 double total_time_usage;
4031 total_time_usage_start=GetTimer()-total_time_usage_start;
4032 total_time_usage = (float)total_time_usage_start*0.000001;
4033 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4034 video_time_usage,vout_time_usage,audio_time_usage,
4035 total_time_usage-tot,total_time_usage);
4036 if(total_time_usage>0.0)
4037 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4038 100.0*video_time_usage/total_time_usage,
4039 100.0*vout_time_usage/total_time_usage,
4040 100.0*audio_time_usage/total_time_usage,
4041 100.0*(total_time_usage-tot)/total_time_usage,
4042 100.0);
4043 if(total_frame_cnt && frame_dropping)
4044 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4045 total_frame_cnt-drop_frame_cnt,
4046 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4047 drop_frame_cnt,
4048 100*drop_frame_cnt/total_frame_cnt,
4049 total_frame_cnt,
4050 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4053 // time to uninit all, except global stuff:
4054 uninit_player(INITIALIZED_ALL-(INITIALIZED_GUI+INITIALIZED_INPUT+(fixed_vo?INITIALIZED_VO:0)));
4056 if(mpctx->set_of_sub_size > 0) {
4057 current_module="sub_free";
4058 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4059 sub_free(mpctx->set_of_subtitles[i]);
4060 #ifdef CONFIG_ASS
4061 if(mpctx->set_of_ass_tracks[i])
4062 ass_free_track( mpctx->set_of_ass_tracks[i] );
4063 #endif
4065 mpctx->set_of_sub_size = 0;
4067 vo_sub_last = vo_sub=NULL;
4068 subdata=NULL;
4069 #ifdef CONFIG_ASS
4070 ass_track = NULL;
4071 if(ass_library)
4072 ass_clear_fonts(ass_library);
4073 #endif
4075 if(mpctx->eof == PT_NEXT_ENTRY || mpctx->eof == PT_PREV_ENTRY) {
4076 mpctx->eof = mpctx->eof == PT_NEXT_ENTRY ? 1 : -1;
4077 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) == PLAY_TREE_ITER_ENTRY) {
4078 mpctx->eof = 1;
4079 } else {
4080 play_tree_iter_free(mpctx->playtree_iter);
4081 mpctx->playtree_iter = NULL;
4083 mpctx->play_tree_step = 1;
4084 } else if(mpctx->eof == PT_UP_NEXT || mpctx->eof == PT_UP_PREV) {
4085 mpctx->eof = mpctx->eof == PT_UP_NEXT ? 1 : -1;
4086 if(mpctx->playtree_iter) {
4087 if(play_tree_iter_up_step(mpctx->playtree_iter,mpctx->eof,0) == PLAY_TREE_ITER_ENTRY) {
4088 mpctx->eof = 1;
4089 } else {
4090 play_tree_iter_free(mpctx->playtree_iter);
4091 mpctx->playtree_iter = NULL;
4094 } else if (mpctx->eof == PT_STOP) {
4095 play_tree_iter_free(mpctx->playtree_iter);
4096 mpctx->playtree_iter = NULL;
4097 } else { // NEXT PREV SRC
4098 mpctx->eof = mpctx->eof == PT_PREV_SRC ? -1 : 1;
4101 if(mpctx->eof == 0) mpctx->eof = 1;
4103 while(mpctx->playtree_iter != NULL) {
4104 filename = play_tree_iter_get_file(mpctx->playtree_iter,mpctx->eof);
4105 if(filename == NULL) {
4106 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->eof,0) != PLAY_TREE_ITER_ENTRY) {
4107 play_tree_iter_free(mpctx->playtree_iter);
4108 mpctx->playtree_iter = NULL;
4110 } else
4111 break;
4114 #ifdef CONFIG_GUI
4115 if(use_gui && !mpctx->playtree_iter) {
4116 #ifdef CONFIG_DVDREAD
4117 if(!guiIntfStruct.DiskChanged)
4118 #endif
4119 mplEnd();
4121 #endif
4123 if(use_gui || mpctx->playtree_iter != NULL || player_idle_mode){
4124 if(!mpctx->playtree_iter) filename = NULL;
4125 mpctx->eof = 0;
4126 goto play_next_file;
4130 exit_player_with_rc(EXIT_EOF, 0);
4132 return 1;
4134 #endif /* DISABLE_MAIN */