demux_lavf: use lavf for all formats except those listed
[mplayer/glamo.git] / mplayer.c
blob77350cad7366ceeb959299a3274aef0995b9523c
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 <stdbool.h>
25 #include <math.h>
27 #include "config.h"
28 #include "talloc.h"
30 #if defined(__MINGW32__) || defined(__CYGWIN__)
31 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
32 #include <windows.h>
33 #endif
34 #include <string.h>
35 #include <unistd.h>
37 // #include <sys/mman.h>
38 #include <sys/types.h>
39 #ifndef __MINGW32__
40 #include <sys/ioctl.h>
41 #include <sys/wait.h>
42 #else
43 #define SIGHUP 1 /* hangup */
44 #define SIGQUIT 3 /* quit */
45 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
46 #define SIGBUS 10 /* bus error */
47 #define SIGPIPE 13 /* broken pipe */
48 #endif
50 #include <sys/time.h>
51 #include <sys/stat.h>
53 #include <signal.h>
54 #include <time.h>
55 #include <fcntl.h>
56 #include <limits.h>
58 #include <errno.h>
60 #include "mp_msg.h"
61 #include "av_log.h"
64 #include "m_option.h"
65 #include "m_config.h"
66 #include "mplayer.h"
67 #include "access_mpcontext.h"
68 #include "m_property.h"
70 #include "cfg-mplayer-def.h"
72 #include "libavutil/avstring.h"
74 #include "subreader.h"
76 #include "mp_osd.h"
77 #include "libvo/video_out.h"
79 #include "libvo/font_load.h"
80 #include "libvo/sub.h"
82 #ifdef CONFIG_X11
83 #include "libvo/x11_common.h"
84 #endif
86 #include "libao2/audio_out.h"
88 #include "codec-cfg.h"
90 #include "edl.h"
92 #include "spudec.h"
93 #include "vobsub.h"
95 #include "osdep/getch2.h"
96 #include "osdep/timer.h"
97 #include "osdep/findfiles.h"
99 #include "input/input.h"
101 const int under_mencoder = 0;
102 int slave_mode=0;
103 int player_idle_mode=0;
104 int quiet=0;
105 int enable_mouse_movements=0;
106 float start_volume = -1;
108 #include "osdep/priority.h"
110 char *heartbeat_cmd;
112 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
114 #ifdef HAVE_RTC
115 #ifdef __linux__
116 #include <linux/rtc.h>
117 #else
118 #include <rtc.h>
119 #define RTC_IRQP_SET RTCIO_IRQP_SET
120 #define RTC_PIE_ON RTCIO_PIE_ON
121 #endif /* __linux__ */
122 #endif /* HAVE_RTC */
124 #include "stream/tv.h"
125 #include "stream/stream_radio.h"
126 #ifdef CONFIG_DVBIN
127 #include "stream/dvbin.h"
128 #endif
129 #include "stream/cache2.h"
131 //**************************************************************************//
132 // Playtree
133 //**************************************************************************//
134 #include "playtree.h"
135 #include "playtreeparser.h"
137 //**************************************************************************//
138 // Config
139 //**************************************************************************//
140 #include "parser-cfg.h"
141 #include "parser-mpcmd.h"
143 //**************************************************************************//
144 // Config file
145 //**************************************************************************//
147 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
149 #include "path.h"
151 //**************************************************************************//
152 //**************************************************************************//
153 // Input media streaming & demultiplexer:
154 //**************************************************************************//
156 static int max_framesize=0;
158 #include "stream/stream.h"
159 #include "libmpdemux/demuxer.h"
160 #include "libmpdemux/stheader.h"
162 #ifdef CONFIG_DVDREAD
163 #include "stream/stream_dvd.h"
164 #endif
165 #include "stream/stream_dvdnav.h"
167 #include "libmpcodecs/dec_audio.h"
168 #include "libmpcodecs/dec_video.h"
169 #include "libmpcodecs/mp_image.h"
170 #include "libmpcodecs/vf.h"
171 #include "libmpcodecs/vd.h"
173 #include "mixer.h"
175 #include "mp_core.h"
176 #include "options.h"
177 #include "defaultopts.h"
179 static const char help_text[]=_(
180 "Usage: mplayer [options] [url|path/]filename\n"
181 "\n"
182 "Basic options: (complete list in the man page)\n"
183 " -vo <drv> select video output driver ('-vo help' for a list)\n"
184 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
185 #ifdef CONFIG_VCD
186 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
187 #endif
188 #ifdef CONFIG_DVDREAD
189 " dvd://<titleno> play DVD title from device instead of plain file\n"
190 #endif
191 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
192 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
193 " -nosound do not play sound\n"
194 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
195 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
196 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
197 " -playlist <file> specify playlist file\n"
198 " -vid x -aid y select video (x) and audio (y) stream to play\n"
199 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
200 " -pp <quality> enable postprocessing filter (details in the man page)\n"
201 " -framedrop enable frame dropping (for slow machines)\n"
202 "\n"
203 "Basic keys: (complete list in the man page, also check input.conf)\n"
204 " <- or -> seek backward/forward 10 seconds\n"
205 " down or up seek backward/forward 1 minute\n"
206 " pgdown or pgup seek backward/forward 10 minutes\n"
207 " < or > step backward/forward in playlist\n"
208 " p or SPACE pause movie (press any key to continue)\n"
209 " q or ESC stop playing and quit program\n"
210 " + or - adjust audio delay by +/- 0.1 second\n"
211 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
212 " * or / increase or decrease PCM volume\n"
213 " x or z adjust subtitle delay by +/- 0.1 second\n"
214 " r or t adjust subtitle position up/down, also see -vf expand\n"
215 "\n"
216 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
217 "\n");
220 #define Exit_SIGILL_RTCpuSel _(\
221 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
222 " It may be a bug in our new runtime CPU-detection code...\n"\
223 " Please read DOCS/HTML/en/bugreports.html.\n")
225 #define Exit_SIGILL _(\
226 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
227 " It usually happens when you run it on a CPU different than the one it was\n"\
228 " compiled/optimized for.\n"\
229 " Verify this!\n")
231 #define Exit_SIGSEGV_SIGFPE _(\
232 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
233 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
234 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
236 #define Exit_SIGCRASH _(\
237 "- MPlayer crashed. This shouldn't happen.\n"\
238 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
239 " gcc version. If you think it's MPlayer's fault, please read\n"\
240 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
241 " won't help unless you provide this information when reporting a possible bug.\n")
243 #define SystemTooSlow _("\n\n"\
244 " ************************************************\n"\
245 " **** Your system is too SLOW to play this! ****\n"\
246 " ************************************************\n\n"\
247 "Possible reasons, problems, workarounds:\n"\
248 "- Most common: broken/buggy _audio_ driver\n"\
249 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
250 " - Experiment with different values for -autosync, 30 is a good start.\n"\
251 "- Slow video output\n"\
252 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
253 "- Slow CPU\n"\
254 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
255 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
256 "- Broken file\n"\
257 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
258 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
259 " - Try -cache 8192.\n"\
260 "- Are you using -cache to play a non-interleaved AVI file?\n"\
261 " - Try -nocache.\n"\
262 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
263 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
266 //**************************************************************************//
267 //**************************************************************************//
269 // Common FIFO functions, and keyboard/event FIFO code
270 #include "mp_fifo.h"
271 int noconsolecontrols=0;
272 //**************************************************************************//
274 // benchmark:
275 double video_time_usage=0;
276 double vout_time_usage=0;
277 static double audio_time_usage=0;
278 static int total_time_usage_start=0;
279 static int total_frame_cnt=0;
280 static int drop_frame_cnt=0; // total number of dropped frames
281 int benchmark=0;
283 // options:
284 int auto_quality=0;
285 static int output_quality=0;
287 static int list_properties = 0;
289 int term_osd = 1;
290 static char* term_osd_esc = "\x1b[A\r\x1b[K";
291 static char* playing_msg = NULL;
292 // seek:
293 static double seek_to_sec;
294 static off_t seek_to_byte=0;
295 static off_t step_sec=0;
297 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
299 // A/V sync:
300 int autosync=0; // 30 might be a good default value.
302 // codecs:
303 char **audio_codec_list=NULL; // override audio codec
304 char **video_codec_list=NULL; // override video codec
305 char **audio_fm_list=NULL; // override audio codec family
306 char **video_fm_list=NULL; // override video codec family
308 // this dvdsub_id was selected via slang
309 // use this to allow dvdnav to follow -slang across stream resets,
310 // in particular the subtitle ID for a language changes
311 int dvdsub_lang_id;
312 int vobsub_id=-1;
313 static char* spudec_ifo=NULL;
314 int forced_subs_only=0;
315 int file_filter=1;
317 // cache2:
318 int stream_cache_size=-1;
320 // dump:
321 int stream_dump_type=0;
323 // A-V sync:
324 static float default_max_pts_correction=-1;//0.01f;
325 float audio_delay=0;
326 static int ignore_start=0;
328 static int softsleep=0;
330 double force_fps=0;
331 static int force_srate=0;
332 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
333 static int play_n_frames=-1;
334 static int play_n_frames_mf=-1;
336 // sub:
337 char *font_name=NULL;
338 char *sub_font_name=NULL;
339 extern int font_fontconfig;
340 float font_factor=0.75;
341 char **sub_name=NULL;
342 float sub_delay=0;
343 float sub_fps=0;
344 int sub_auto = 1;
345 char *vobsub_name=NULL;
346 int subcc_enabled=0;
347 int suboverlap_enabled = 1;
349 #include "ass_mp.h"
351 char* current_module=NULL; // for debugging
354 // ---
356 #ifdef CONFIG_MENU
357 #include "m_struct.h"
358 #include "libmenu/menu.h"
359 static const vf_info_t* const libmenu_vfs[] = {
360 &vf_info_menu,
361 NULL
363 static vf_instance_t* vf_menu = NULL;
364 int use_menu = 0;
365 static char* menu_cfg = NULL;
366 static char* menu_root = "main";
367 #endif
370 #ifdef HAVE_RTC
371 static int nortc = 1;
372 static char* rtc_device;
373 #endif
375 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
376 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
377 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
378 int use_filedir_conf;
379 int use_filename_title;
381 #include "mpcommon.h"
382 #include "command.h"
384 #include "metadata.h"
386 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
388 const void *mpctx_get_video_out(MPContext *mpctx)
390 return mpctx->video_out;
393 const void *mpctx_get_audio_out(MPContext *mpctx)
395 return mpctx->audio_out;
398 void *mpctx_get_demuxer(MPContext *mpctx)
400 return mpctx->demuxer;
403 void *mpctx_get_playtree_iter(MPContext *mpctx)
405 return mpctx->playtree_iter;
408 void *mpctx_get_mixer(MPContext *mpctx)
410 return &mpctx->mixer;
413 int mpctx_get_global_sub_size(MPContext *mpctx)
415 return mpctx->global_sub_size;
418 int mpctx_get_osd_function(MPContext *mpctx)
420 return mpctx->osd_function;
423 static float get_relative_time(struct MPContext *mpctx)
425 unsigned int new_time = GetTimer();
426 unsigned int delta = new_time - mpctx->last_time;
427 mpctx->last_time = new_time;
428 return delta * 0.000001;
431 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
432 switch (type)
434 /* check for valid video stream */
435 case META_VIDEO_CODEC:
436 case META_VIDEO_BITRATE:
437 case META_VIDEO_RESOLUTION:
439 if (!mpctx->sh_video)
440 return 0;
441 break;
444 /* check for valid audio stream */
445 case META_AUDIO_CODEC:
446 case META_AUDIO_BITRATE:
447 case META_AUDIO_SAMPLES:
449 if (!mpctx->sh_audio)
450 return 0;
451 break;
454 /* check for valid demuxer */
455 case META_INFO_TITLE:
456 case META_INFO_ARTIST:
457 case META_INFO_ALBUM:
458 case META_INFO_YEAR:
459 case META_INFO_COMMENT:
460 case META_INFO_TRACK:
461 case META_INFO_GENRE:
463 if (!mpctx->demuxer)
464 return 0;
465 break;
468 default:
469 break;
472 return 1;
475 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
476 char **info = mpctx->demuxer->info;
477 int n;
479 if (!info || !tag)
480 return NULL;
482 for (n = 0; info[2*n] != NULL ; n++)
483 if (!strcasecmp (info[2*n], tag))
484 break;
486 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
489 char *get_metadata(struct MPContext *mpctx, metadata_t type)
491 char *meta = NULL;
492 sh_audio_t * const sh_audio = mpctx->sh_audio;
493 sh_video_t * const sh_video = mpctx->sh_video;
495 if (!is_valid_metadata_type(mpctx, type))
496 return NULL;
498 switch (type)
500 case META_NAME:
502 return strdup (mp_basename2 (mpctx->filename));
505 case META_VIDEO_CODEC:
507 if (sh_video->format == 0x10000001)
508 meta = strdup ("mpeg1");
509 else if (sh_video->format == 0x10000002)
510 meta = strdup ("mpeg2");
511 else if (sh_video->format == 0x10000004)
512 meta = strdup ("mpeg4");
513 else if (sh_video->format == 0x10000005)
514 meta = strdup ("h264");
515 else if (sh_video->format >= 0x20202020)
517 meta = malloc (8);
518 sprintf (meta, "%.4s", (char *) &sh_video->format);
520 else
522 meta = malloc (8);
523 sprintf (meta, "0x%08X", sh_video->format);
525 return meta;
528 case META_VIDEO_BITRATE:
530 meta = malloc (16);
531 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
532 return meta;
535 case META_VIDEO_RESOLUTION:
537 meta = malloc (16);
538 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
539 return meta;
542 case META_AUDIO_CODEC:
544 if (sh_audio->codec && sh_audio->codec->name)
545 meta = strdup (sh_audio->codec->name);
546 return meta;
549 case META_AUDIO_BITRATE:
551 meta = malloc (16);
552 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
553 return meta;
556 case META_AUDIO_SAMPLES:
558 meta = malloc (16);
559 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
560 return meta;
563 /* check for valid demuxer */
564 case META_INFO_TITLE:
565 return get_demuxer_info(mpctx, "Title");
567 case META_INFO_ARTIST:
568 return get_demuxer_info(mpctx, "Artist");
570 case META_INFO_ALBUM:
571 return get_demuxer_info(mpctx, "Album");
573 case META_INFO_YEAR:
574 return get_demuxer_info(mpctx, "Year");
576 case META_INFO_COMMENT:
577 return get_demuxer_info(mpctx, "Comment");
579 case META_INFO_TRACK:
580 return get_demuxer_info(mpctx, "Track");
582 case META_INFO_GENRE:
583 return get_demuxer_info(mpctx, "Genre");
585 default:
586 break;
589 return meta;
592 static void print_file_properties(struct MPContext *mpctx, const char *filename)
594 double start_pts = MP_NOPTS_VALUE;
595 double video_start_pts = MP_NOPTS_VALUE;
596 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
597 filename_recode(filename));
598 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
599 if (mpctx->sh_video) {
600 /* Assume FOURCC if all bytes >= 0x20 (' ') */
601 if (mpctx->sh_video->format >= 0x20202020)
602 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
603 else
604 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
605 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
606 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
607 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
608 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
609 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
610 video_start_pts = ds_get_next_pts(mpctx->d_video);
612 if (mpctx->sh_audio) {
613 /* Assume FOURCC if all bytes >= 0x20 (' ') */
614 if (mpctx->sh_audio->format >= 0x20202020)
615 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
616 else
617 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
618 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
619 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
620 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
621 start_pts = ds_get_next_pts(mpctx->d_audio);
623 if (video_start_pts != MP_NOPTS_VALUE) {
624 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
625 (mpctx->sh_video && video_start_pts < start_pts))
626 start_pts = video_start_pts;
628 if (start_pts != MP_NOPTS_VALUE)
629 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
630 else
631 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
632 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
633 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
634 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
635 if (mpctx->demuxer) {
636 if (mpctx->demuxer->num_chapters == 0)
637 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
638 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
642 /// step size of mixer changes
643 int volstep = 3;
645 #ifdef CONFIG_DVDNAV
646 static void mp_dvdnav_context_free(MPContext *ctx){
647 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
648 ctx->nav_smpi = NULL;
649 free(ctx->nav_buffer);
650 ctx->nav_buffer = NULL;
651 ctx->nav_start = NULL;
652 ctx->nav_in_size = 0;
654 #endif
656 void uninit_player(struct MPContext *mpctx, unsigned int mask){
657 mask &= mpctx->initialized_flags;
659 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
661 if(mask&INITIALIZED_ACODEC){
662 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
663 current_module="uninit_acodec";
664 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
665 mpctx->sh_audio=NULL;
666 mpctx->mixer.afilter = NULL;
669 if(mask&INITIALIZED_VCODEC){
670 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
671 current_module="uninit_vcodec";
672 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
673 mpctx->sh_video=NULL;
674 #ifdef CONFIG_MENU
675 vf_menu=NULL;
676 #endif
679 if(mask&INITIALIZED_DEMUXER){
680 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
681 current_module="free_demuxer";
682 if (mpctx->num_sources) {
683 mpctx->demuxer = mpctx->sources[0].demuxer;
684 for (int i = 1; i < mpctx->num_sources; i++) {
685 free_stream(mpctx->sources[i].stream);
686 free_demuxer(mpctx->sources[i].demuxer);
689 talloc_free(mpctx->sources);
690 mpctx->sources = NULL;
691 mpctx->num_sources = 0;
692 talloc_free(mpctx->timeline);
693 mpctx->timeline = NULL;
694 mpctx->num_timeline_parts = 0;
695 talloc_free(mpctx->chapters);
696 mpctx->chapters = NULL;
697 mpctx->num_chapters = 0;
698 mpctx->video_offset = 0;
699 if(mpctx->demuxer){
700 mpctx->stream=mpctx->demuxer->stream;
701 free_demuxer(mpctx->demuxer);
703 mpctx->demuxer=NULL;
706 // kill the cache process:
707 if(mask&INITIALIZED_STREAM){
708 mpctx->initialized_flags&=~INITIALIZED_STREAM;
709 current_module="uninit_stream";
710 if(mpctx->stream) free_stream(mpctx->stream);
711 mpctx->stream=NULL;
714 if(mask&INITIALIZED_VO){
715 mpctx->initialized_flags&=~INITIALIZED_VO;
716 current_module="uninit_vo";
717 vo_destroy(mpctx->video_out);
718 mpctx->video_out=NULL;
719 #ifdef CONFIG_DVDNAV
720 mp_dvdnav_context_free(mpctx);
721 #endif
724 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
725 if(mask&INITIALIZED_GETCH2){
726 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
727 current_module="uninit_getch2";
728 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
729 // restore terminal:
730 getch2_disable();
733 if(mask&INITIALIZED_VOBSUB){
734 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
735 current_module="uninit_vobsub";
736 if(vo_vobsub) vobsub_close(vo_vobsub);
737 vo_vobsub=NULL;
740 if (mask&INITIALIZED_SPUDEC){
741 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
742 current_module="uninit_spudec";
743 spudec_free(vo_spudec);
744 vo_spudec=NULL;
747 if(mask&INITIALIZED_AO){
748 mpctx->initialized_flags&=~INITIALIZED_AO;
749 current_module="uninit_ao";
750 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
751 if (mpctx->audio_out)
752 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
753 mpctx->audio_out=NULL;
756 current_module=NULL;
759 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
761 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
762 uninit_player(mpctx, INITIALIZED_ALL);
763 #if defined(__MINGW32__) || defined(__CYGWIN__)
764 timeEndPeriod(1);
765 #endif
766 #ifdef CONFIG_X11
767 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
768 #endif
770 current_module="uninit_input";
771 mp_input_uninit(mpctx->input);
772 #ifdef CONFIG_MENU
773 if (use_menu)
774 menu_uninit();
775 #endif
777 #ifdef CONFIG_FREETYPE
778 current_module="uninit_font";
779 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
780 free_font_desc(mpctx->osd->sub_font);
781 free_font_desc(vo_font);
782 vo_font = NULL;
783 done_freetype();
784 #endif
785 osd_free(mpctx->osd);
787 #ifdef CONFIG_ASS
788 ass_library_done(ass_library);
789 ass_library = NULL;
790 #endif
792 current_module="exit_player";
794 // free mplayer config
795 if(mpctx->mconfig)
796 m_config_free(mpctx->mconfig);
797 mpctx->mconfig = NULL;
799 if(mpctx->playtree_iter)
800 play_tree_iter_free(mpctx->playtree_iter);
801 mpctx->playtree_iter = NULL;
802 if(mpctx->playtree)
803 play_tree_free(mpctx->playtree, 1);
804 mpctx->playtree = NULL;
806 talloc_free(mpctx->key_fifo);
808 free(edl_records); // free mem allocated for EDL
809 edl_records = NULL;
810 switch(how) {
811 case EXIT_QUIT:
812 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
813 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
814 break;
815 case EXIT_EOF:
816 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
817 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
818 break;
819 case EXIT_ERROR:
820 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
821 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
822 break;
823 default:
824 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
826 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
828 exit(rc);
831 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
833 exit_player_with_rc(mpctx, how, 1);
836 #ifndef __MINGW32__
837 static void child_sighandler(int x){
838 pid_t pid;
839 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
841 #endif
843 #ifdef CONFIG_CRASH_DEBUG
844 static char *prog_path;
845 static int crash_debug = 0;
846 #endif
848 static void exit_sighandler(int x){
849 static int sig_count=0;
850 #ifdef CONFIG_CRASH_DEBUG
851 if (!crash_debug || x != SIGTRAP)
852 #endif
853 ++sig_count;
854 if(sig_count==5)
856 /* We're crashing bad and can't uninit cleanly :(
857 * by popular request, we make one last (dirty)
858 * effort to restore the user's
859 * terminal. */
860 getch2_disable();
861 exit(1);
863 if(sig_count==6) exit(1);
864 if(sig_count>6){
865 // can't stop :(
866 #ifndef __MINGW32__
867 kill(getpid(),SIGKILL);
868 #endif
870 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
871 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
872 "\nMPlayer interrupted by signal %d in module: %s\n", x,
873 current_module ? current_module : "unknown");
874 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
875 if(sig_count<=1)
876 switch(x){
877 case SIGINT:
878 case SIGPIPE:
879 case SIGQUIT:
880 case SIGTERM:
881 case SIGKILL:
882 async_quit_request = 1;
883 return; // killed from keyboard (^C) or killed [-9]
884 case SIGILL:
885 #if CONFIG_RUNTIME_CPUDETECT
886 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
887 #else
888 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
889 #endif
890 case SIGFPE:
891 case SIGSEGV:
892 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
893 default:
894 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
895 #ifdef CONFIG_CRASH_DEBUG
896 if (crash_debug) {
897 int gdb_pid;
898 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
899 gdb_pid = fork();
900 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
901 if (gdb_pid == 0) { // We are the child
902 char spid[20];
903 snprintf(spid, sizeof(spid), "%i", getppid());
904 getch2_disable(); // allow terminal to work properly with gdb
905 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
906 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
907 } else if (gdb_pid < 0)
908 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
909 else {
910 waitpid(gdb_pid, NULL, 0);
912 if (x == SIGTRAP) return;
914 #endif
916 getch2_disable();
917 exit(1);
920 #include "cfg-mplayer.h"
922 static int cfg_include(m_option_t *conf, char *filename)
924 return m_config_parse_config_file(conf->priv, filename);
927 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
929 char *conffile;
930 int conffile_fd;
931 if (!disable_system_conf &&
932 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
933 exit_player(mpctx, EXIT_NONE);
934 if ((conffile = get_path("")) == NULL) {
935 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
936 } else {
937 #ifdef __MINGW32__
938 mkdir(conffile);
939 #else
940 mkdir(conffile, 0777);
941 #endif
942 free(conffile);
943 if ((conffile = get_path("config")) == NULL) {
944 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
945 } else {
946 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
947 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
948 write(conffile_fd, default_config, strlen(default_config));
949 close(conffile_fd);
951 if (!disable_user_conf &&
952 m_config_parse_config_file(conf, conffile) < 0)
953 exit_player(mpctx, EXIT_NONE);
954 free(conffile);
959 #define PROFILE_CFG_PROTOCOL "protocol."
961 static void load_per_protocol_config (m_config_t* conf, const char *const file)
963 char *str;
964 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
965 m_profile_t *p;
967 /* does filename actually uses a protocol ? */
968 str = strstr (file, "://");
969 if (!str)
970 return;
972 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
973 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
974 p = m_config_get_profile (conf, protocol);
975 if (p)
977 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
978 m_config_set_profile(conf,p);
982 #define PROFILE_CFG_EXTENSION "extension."
984 static void load_per_extension_config (m_config_t* conf, const char *const file)
986 char *str;
987 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
988 m_profile_t *p;
990 /* does filename actually have an extension ? */
991 str = strrchr (file, '.');
992 if (!str)
993 return;
995 sprintf (extension, PROFILE_CFG_EXTENSION);
996 strncat (extension, ++str, 7);
997 p = m_config_get_profile (conf, extension);
998 if (p)
1000 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
1001 m_config_set_profile(conf,p);
1005 #define PROFILE_CFG_VO "vo."
1006 #define PROFILE_CFG_AO "ao."
1008 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
1010 char profile[strlen (cfg) + strlen (out) + 1];
1011 m_profile_t *p;
1013 sprintf (profile, "%s%s", cfg, out);
1014 p = m_config_get_profile (conf, profile);
1015 if (p)
1017 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
1018 m_config_set_profile(conf,p);
1023 * Tries to load a config file
1024 * @return 0 if file was not found, 1 otherwise
1026 static int try_load_config(m_config_t *conf, const char *file)
1028 struct stat st;
1029 if (stat(file, &st))
1030 return 0;
1031 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1032 m_config_parse_config_file (conf, file);
1033 return 1;
1036 static void load_per_file_config (m_config_t* conf, const char *const file)
1038 char *confpath;
1039 char cfg[PATH_MAX];
1040 char *name;
1042 if (strlen(file) > PATH_MAX - 14) {
1043 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1044 return;
1046 sprintf (cfg, "%s.conf", file);
1048 name = strrchr(cfg, '/');
1049 if (HAVE_DOS_PATHS) {
1050 char *tmp = strrchr(cfg, '\\');
1051 if (!name || tmp > name)
1052 name = tmp;
1053 tmp = strrchr(cfg, ':');
1054 if (!name || tmp > name)
1055 name = tmp;
1057 if (!name)
1058 name = cfg;
1059 else
1060 name++;
1062 if (use_filedir_conf) {
1063 char dircfg[PATH_MAX];
1064 strcpy(dircfg, cfg);
1065 strcpy(dircfg + (name - cfg), "mplayer.conf");
1066 try_load_config(conf, dircfg);
1068 if (try_load_config(conf, cfg))
1069 return;
1072 if ((confpath = get_path (name)) != NULL)
1074 try_load_config(conf, confpath);
1076 free (confpath);
1080 /* When libmpdemux performs a blocking operation (network connection or
1081 * cache filling) if the operation fails we use this function to check
1082 * if it was interrupted by the user.
1083 * The function returns a new value for eof. */
1084 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1086 mp_cmd_t* cmd;
1087 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1088 switch(cmd->id) {
1089 case MP_CMD_QUIT:
1090 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1091 case MP_CMD_PLAY_TREE_STEP: {
1092 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1093 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1094 } break;
1095 case MP_CMD_PLAY_TREE_UP_STEP: {
1096 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1097 } break;
1098 case MP_CMD_PLAY_ALT_SRC_STEP: {
1099 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1100 } break;
1102 mp_cmd_free(cmd);
1104 return stop_play;
1107 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1109 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1111 play_tree_add_bpf(entry,mpctx->filename);
1114 if(!entry) {
1115 entry = mpctx->playtree_iter->tree;
1116 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1117 return PT_NEXT_ENTRY;
1119 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1120 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1121 return PT_NEXT_ENTRY;
1124 play_tree_remove(entry,1,1);
1125 return PT_NEXT_SRC;
1127 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1128 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1129 entry = mpctx->playtree_iter->tree;
1130 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1131 return PT_NEXT_ENTRY;
1133 play_tree_remove(entry,1,1);
1135 return PT_NEXT_SRC;
1138 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1140 struct MPOpts *opts = &mpctx->opts;
1141 sub_data *subd = NULL;
1142 struct ass_track *asst = NULL;
1144 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1145 return;
1148 #ifdef CONFIG_ASS
1149 if (opts->ass_enabled) {
1150 #ifdef CONFIG_ICONV
1151 asst = ass_read_stream(ass_library, filename, sub_cp);
1152 #else
1153 asst = ass_read_stream(ass_library, filename, 0);
1154 #endif
1155 if (!asst) {
1156 subd = sub_read_file(filename, fps);
1157 if (subd) {
1158 asst = ass_read_subdata(ass_library, subd, fps);
1159 if (asst) {
1160 sub_free(subd);
1161 subd = NULL;
1165 } else
1166 #endif
1167 subd = sub_read_file(filename, fps);
1170 if (!asst && !subd) {
1171 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1172 "Cannot load subtitles: %s\n", filename_recode(filename));
1173 return;
1176 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1177 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1178 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1179 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1180 filename_recode(filename));
1181 ++mpctx->set_of_sub_size;
1182 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1183 filename_recode(filename));
1186 void init_vo_spudec(struct MPContext *mpctx)
1188 if (vo_spudec)
1189 spudec_free(vo_spudec);
1190 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1191 vo_spudec = NULL;
1193 // we currently can't work without video stream
1194 if (!mpctx->sh_video)
1195 return;
1197 if (spudec_ifo) {
1198 unsigned int palette[16], width, height;
1199 current_module="spudec_init_vobsub";
1200 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1201 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1204 #ifdef CONFIG_DVDREAD
1205 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1206 current_module="spudec_init_dvdread";
1207 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1208 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1209 NULL, 0);
1211 #endif
1213 #ifdef CONFIG_DVDNAV
1214 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1215 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1216 current_module="spudec_init_dvdnav";
1217 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1219 #endif
1221 if (vo_spudec==NULL) {
1222 sh_sub_t *sh = mpctx->d_sub->sh;
1223 current_module="spudec_init_normal";
1224 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1225 spudec_set_font_factor(vo_spudec,font_factor);
1228 if (vo_spudec!=NULL) {
1229 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1230 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1235 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1236 * make it all work is to use the builtin SDL-bootstrap code, which
1237 * will be done automatically by replacing our main() if we include SDL.h.
1239 #if defined(__APPLE__) && defined(CONFIG_SDL)
1240 #ifdef CONFIG_SDL_SDL_H
1241 #include <SDL/SDL.h>
1242 #else
1243 #include <SDL.h>
1244 #endif
1245 #endif
1248 * \brief append a formatted string
1249 * \param buf buffer to print into
1250 * \param pos position of terminating 0 in buf
1251 * \param len maximum number of characters in buf, not including terminating 0
1252 * \param format printf format string
1254 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1256 va_list va;
1257 va_start(va, format);
1258 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1259 va_end(va);
1260 if (*pos >= len ) {
1261 buf[len] = 0;
1262 *pos = len;
1267 * \brief append time in the hh:mm:ss.f format
1268 * \param buf buffer to print into
1269 * \param pos position of terminating 0 in buf
1270 * \param len maximum number of characters in buf, not including terminating 0
1271 * \param time time value to convert/append
1273 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1274 int64_t tenths = 10 * time;
1275 int f1 = tenths % 10;
1276 int ss = (tenths / 10) % 60;
1277 int mm = (tenths / 600) % 60;
1278 int hh = tenths / 36000;
1279 if (time <= 0) {
1280 saddf(buf, pos, len, "unknown");
1281 return;
1283 if (hh > 0)
1284 saddf(buf, pos, len, "%2d:", hh);
1285 if (hh > 0 || mm > 0)
1286 saddf(buf, pos, len, "%02d:", mm);
1287 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1290 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1292 struct MPOpts *opts = &mpctx->opts;
1293 sh_video_t * const sh_video = mpctx->sh_video;
1295 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1296 a_pos = playing_audio_pts(mpctx);
1297 if (mpctx->sh_audio && sh_video && at_frame) {
1298 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1299 if (mpctx->time_frame > 0)
1300 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1301 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1302 && !mpctx->drop_message_shown) {
1303 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1304 mpctx->drop_message_shown = true;
1307 if (quiet)
1308 return;
1311 int width;
1312 char *line;
1313 unsigned pos = 0;
1314 get_screen_size();
1315 if (screen_width > 0)
1316 width = screen_width;
1317 else
1318 width = 80;
1319 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1320 /* Windows command line is broken (MinGW's rxvt works, but we
1321 * should not depend on that). */
1322 width--;
1323 #endif
1324 line = malloc(width + 1); // one additional char for the terminating null
1326 // Audio time
1327 if (mpctx->sh_audio) {
1328 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1329 if (!sh_video) {
1330 float len = get_time_length(mpctx);
1331 saddf(line, &pos, width, "(");
1332 sadd_hhmmssf(line, &pos, width, a_pos);
1333 saddf(line, &pos, width, ") of %.1f (", len);
1334 sadd_hhmmssf(line, &pos, width, len);
1335 saddf(line, &pos, width, ") ");
1339 // Video time
1340 if (sh_video)
1341 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1343 // A-V sync
1344 if (mpctx->sh_audio && sh_video)
1345 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1346 mpctx->last_av_difference, mpctx->total_avsync_change);
1348 // Video stats
1349 if (sh_video)
1350 saddf(line, &pos, width, "%3d/%3d ",
1351 (int)sh_video->num_frames,
1352 (int)sh_video->num_frames_decoded);
1354 // CPU usage
1355 if (sh_video) {
1356 if (sh_video->timer > 0.5)
1357 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1358 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1359 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1360 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1361 else
1362 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1363 } else if (mpctx->sh_audio) {
1364 if (mpctx->delay > 0.5)
1365 saddf(line, &pos, width, "%4.1f%% ",
1366 100.0*audio_time_usage/(double)mpctx->delay);
1367 else
1368 saddf(line, &pos, width, "??,?%% ");
1371 // VO stats
1372 if (sh_video)
1373 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1375 #ifdef CONFIG_STREAM_CACHE
1376 // cache stats
1377 if (stream_cache_size > 0)
1378 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1379 #endif
1381 // other
1382 if (opts->playback_speed != 1)
1383 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1385 // end
1386 if (erase_to_end_of_line) {
1387 line[pos] = 0;
1388 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1389 } else {
1390 memset(&line[pos], ' ', width - pos);
1391 line[width] = 0;
1392 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1394 free(line);
1398 * \brief build a chain of audio filters that converts the input format
1399 * to the ao's format, taking into account the current playback_speed.
1400 * \param sh_audio describes the requested input format of the chain.
1401 * \param ao_data describes the requested output format of the chain.
1403 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1405 struct MPOpts *opts = &mpctx->opts;
1406 int new_srate;
1407 int result;
1408 if (!sh_audio)
1410 mpctx->mixer.afilter = NULL;
1411 return 0;
1413 if(af_control_any_rev(sh_audio->afilter,
1414 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1415 &opts->playback_speed)) {
1416 new_srate = sh_audio->samplerate;
1417 } else {
1418 new_srate = sh_audio->samplerate * opts->playback_speed;
1419 if (new_srate != ao_data->samplerate) {
1420 // limits are taken from libaf/af_resample.c
1421 if (new_srate < 8000)
1422 new_srate = 8000;
1423 if (new_srate > 192000)
1424 new_srate = 192000;
1425 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1428 result = init_audio_filters(sh_audio, new_srate,
1429 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1430 mpctx->mixer.afilter = sh_audio->afilter;
1431 return result;
1435 typedef struct mp_osd_msg mp_osd_msg_t;
1436 struct mp_osd_msg {
1437 /// Previous message on the stack.
1438 mp_osd_msg_t* prev;
1439 /// Message text.
1440 char msg[128];
1441 int id,level,started;
1442 /// Display duration in ms.
1443 unsigned time;
1446 /// OSD message stack.
1447 static mp_osd_msg_t* osd_msg_stack = NULL;
1450 * \brief Add a message on the OSD message stack
1452 * If a message with the same id is already present in the stack
1453 * it is pulled on top of the stack, otherwise a new message is created.
1456 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1457 va_list ap)
1459 mp_osd_msg_t *msg,*last=NULL;
1460 int r;
1462 // look if the id is already in the stack
1463 for(msg = osd_msg_stack ; msg && msg->id != id ;
1464 last = msg, msg = msg->prev);
1465 // not found: alloc it
1466 if(!msg) {
1467 msg = calloc(1,sizeof(mp_osd_msg_t));
1468 msg->prev = osd_msg_stack;
1469 osd_msg_stack = msg;
1470 } else if(last) { // found, but it's not on top of the stack
1471 last->prev = msg->prev;
1472 msg->prev = osd_msg_stack;
1473 osd_msg_stack = msg;
1475 // write the msg
1476 r = vsnprintf(msg->msg, 128, fmt, ap);
1477 if(r >= 128) msg->msg[127] = 0;
1478 // set id and time
1479 msg->id = id;
1480 msg->level = level;
1481 msg->time = time;
1485 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1487 va_list ap;
1488 va_start(ap, fmt);
1489 set_osd_msg_va(id, level, time, fmt, ap);
1490 va_end(ap);
1493 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1495 va_list ap;
1496 va_start(ap, fmt);
1497 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1498 va_end(ap);
1503 * \brief Remove a message from the OSD stack
1505 * This function can be used to get rid of a message right away.
1509 void rm_osd_msg(int id) {
1510 mp_osd_msg_t *msg,*last=NULL;
1512 // Search for the msg
1513 for(msg = osd_msg_stack ; msg && msg->id != id ;
1514 last = msg, msg = msg->prev);
1515 if(!msg) return;
1517 // Detach it from the stack and free it
1518 if(last)
1519 last->prev = msg->prev;
1520 else
1521 osd_msg_stack = msg->prev;
1522 free(msg);
1526 * \brief Remove all messages from the OSD stack
1530 static void clear_osd_msgs(void) {
1531 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1532 while(msg) {
1533 prev = msg->prev;
1534 free(msg);
1535 msg = prev;
1537 osd_msg_stack = NULL;
1541 * \brief Get the current message from the OSD stack.
1543 * This function decrements the message timer and destroys the old ones.
1544 * The message that should be displayed is returned (if any).
1548 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1550 struct MPOpts *opts = &mpctx->opts;
1551 mp_osd_msg_t *msg,*prev,*last = NULL;
1552 static unsigned last_update = 0;
1553 unsigned now = GetTimerMS();
1554 unsigned diff;
1555 char hidden_dec_done = 0;
1557 if (mpctx->osd_visible) {
1558 // 36000000 means max timed visibility is 1 hour into the future, if
1559 // the difference is greater assume it's wrapped around from below 0
1560 if (mpctx->osd_visible - now > 36000000) {
1561 mpctx->osd_visible = 0;
1562 vo_osd_progbar_type = -1; // disable
1563 vo_osd_changed(OSDTYPE_PROGBAR);
1564 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1567 if (mpctx->osd_show_percentage_until - now > 36000000)
1568 mpctx->osd_show_percentage_until = 0;
1570 if(!last_update) last_update = now;
1571 diff = now >= last_update ? now - last_update : 0;
1573 last_update = now;
1575 // Look for the first message in the stack with high enough level.
1576 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1577 prev = msg->prev;
1578 if (msg->level > opts->osd_level && hidden_dec_done)
1579 continue;
1580 // The message has a high enough level or it is the first hidden one
1581 // in both cases we decrement the timer or kill it.
1582 if(!msg->started || msg->time > diff) {
1583 if(msg->started) msg->time -= diff;
1584 else msg->started = 1;
1585 // display it
1586 if (msg->level <= opts->osd_level)
1587 return msg;
1588 hidden_dec_done = 1;
1589 continue;
1591 // kill the message
1592 free(msg);
1593 if(last) {
1594 last->prev = prev;
1595 msg = last;
1596 } else {
1597 osd_msg_stack = prev;
1598 msg = NULL;
1601 // Nothing found
1602 return NULL;
1606 * \brief Display the OSD bar.
1608 * Display the OSD bar or fall back on a simple message.
1612 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1613 struct MPOpts *opts = &mpctx->opts;
1614 if (opts->osd_level < 1)
1615 return;
1617 if(mpctx->sh_video) {
1618 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1619 vo_osd_progbar_type = type;
1620 vo_osd_progbar_value = 256*(val-min)/(max-min);
1621 vo_osd_changed(OSDTYPE_PROGBAR);
1622 return;
1625 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1626 name, ROUND(100*(val-min)/(max-min)));
1630 * \brief Display text subtitles on the OSD
1632 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1634 int i;
1635 vo_sub = subs;
1636 vo_osd_changed(OSDTYPE_SUBTITLE);
1637 if (!mpctx->sh_video) {
1638 // reverse order, since newest set_osd_msg is displayed first
1639 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1640 if (!subs || i >= subs->lines || !subs->text[i])
1641 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1642 else {
1643 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1644 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1645 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1652 * \brief Update the OSD message line.
1654 * This function displays the current message on the vo OSD or on the term.
1655 * If the stack is empty and the OSD level is high enough the timer
1656 * is displayed (only on the vo OSD).
1660 static void update_osd_msg(struct MPContext *mpctx)
1662 struct MPOpts *opts = &mpctx->opts;
1663 mp_osd_msg_t *msg;
1664 struct osd_state *osd = mpctx->osd;
1665 char osd_text_timer[128];
1667 if (mpctx->add_osd_seek_info) {
1668 double percentage = get_percent_pos(mpctx);
1669 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1670 if (mpctx->sh_video)
1671 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1672 mpctx->add_osd_seek_info = false;
1675 // Look if we have a msg
1676 if((msg = get_osd_msg(mpctx))) {
1677 if (strcmp(osd->osd_text, msg->msg)) {
1678 strncpy(osd->osd_text, msg->msg, 127);
1679 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1680 if(term_osd) mp_msg(MSGT_CPLAYER,MSGL_STATUS,"%s%s\n",term_osd_esc,msg->msg);
1682 return;
1685 if(mpctx->sh_video) {
1686 // fallback on the timer
1687 if (opts->osd_level >= 2) {
1688 int len = get_time_length(mpctx);
1689 int percentage = -1;
1690 char percentage_text[10];
1691 int pts = get_current_time(mpctx);
1693 if (mpctx->osd_show_percentage_until)
1694 percentage = get_percent_pos(mpctx);
1696 if (percentage >= 0)
1697 snprintf(percentage_text, 9, " (%d%%)", percentage);
1698 else
1699 percentage_text[0] = 0;
1701 if (opts->osd_level == 3)
1702 snprintf(osd_text_timer, 63,
1703 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1704 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1705 len/3600,(len/60)%60,len%60,percentage_text);
1706 else
1707 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1708 mpctx->osd_function,pts/3600,(pts/60)%60,
1709 pts%60,percentage_text);
1710 } else
1711 osd_text_timer[0]=0;
1713 if (strcmp(osd->osd_text, osd_text_timer)) {
1714 strncpy(osd->osd_text, osd_text_timer, 63);
1715 vo_osd_changed(OSDTYPE_OSD);
1717 return;
1720 // Clear the term osd line
1721 if (term_osd && osd->osd_text[0]) {
1722 osd->osd_text[0] = 0;
1723 printf("%s\n",term_osd_esc);
1727 ///@}
1728 // OSDMsgStack
1731 void reinit_audio_chain(struct MPContext *mpctx)
1733 struct MPOpts *opts = &mpctx->opts;
1734 if (!mpctx->sh_audio)
1735 return;
1736 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1737 current_module="init_audio_codec";
1738 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1739 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1740 goto init_error;
1742 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1743 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1747 current_module="af_preinit";
1748 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1749 ao_data.samplerate=force_srate;
1750 ao_data.channels=0;
1751 ao_data.format = opts->audio_output_format;
1753 // first init to detect best values
1754 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1755 // input:
1756 mpctx->sh_audio->samplerate,
1757 // output:
1758 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1759 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1760 "pre-init!\n");
1761 exit_player(mpctx, EXIT_ERROR);
1763 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1764 current_module="ao2_init";
1765 ao_data.buffersize = opts->ao_buffersize;
1766 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1767 0, // plugin flag
1768 ao_data.samplerate,
1769 ao_data.channels,
1770 ao_data.format, 0);
1771 if(!mpctx->audio_out){
1772 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1773 goto init_error;
1775 mpctx->initialized_flags|=INITIALIZED_AO;
1776 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1777 mpctx->audio_out->info->short_name,
1778 ao_data.samplerate, ao_data.channels,
1779 af_fmt2str_short(ao_data.format),
1780 af_fmt2bits(ao_data.format)/8 );
1781 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1782 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1783 if(strlen(mpctx->audio_out->info->comment) > 0)
1784 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1787 // init audio filters:
1788 current_module="af_init";
1789 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1790 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1791 goto init_error;
1793 mpctx->mixer.audio_out = mpctx->audio_out;
1794 mpctx->mixer.volstep = volstep;
1795 mpctx->syncing_audio = true;
1796 return;
1798 init_error:
1799 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1800 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1801 mpctx->d_audio->id = -2;
1805 ///@}
1806 // Command2Property
1809 // Return pts value corresponding to the end point of audio written to the
1810 // ao so far.
1811 static double written_audio_pts(struct MPContext *mpctx)
1813 sh_audio_t *sh_audio = mpctx->sh_audio;
1814 demux_stream_t *d_audio = mpctx->d_audio;
1815 double buffered_output;
1816 // first calculate the end pts of audio that has been output by decoder
1817 double a_pts = sh_audio->pts;
1818 if (a_pts != MP_NOPTS_VALUE)
1819 // Good, decoder supports new way of calculating audio pts.
1820 // sh_audio->pts is the timestamp of the latest input packet with
1821 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1822 // the amount of bytes the decoder has written after that timestamp.
1823 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1824 else {
1825 // Decoder doesn't support new way of calculating pts (or we're
1826 // being called before it has decoded anything with known timestamp).
1827 // Use the old method of audio pts calculation: take the timestamp
1828 // of last packet with known pts the decoder has read data from,
1829 // and add amount of bytes read after the beginning of that packet
1830 // divided by input bps. This will be inaccurate if the input/output
1831 // ratio is not constant for every audio packet or if it is constant
1832 // but not accurately known in sh_audio->i_bps.
1834 a_pts = d_audio->pts;
1835 // ds_tell_pts returns bytes read after last timestamp from
1836 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1837 // it has read but not decoded
1838 if (sh_audio->i_bps)
1839 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1840 (double)sh_audio->i_bps;
1842 // Now a_pts hopefully holds the pts for end of audio from decoder.
1843 // Substract data in buffers between decoder and audio out.
1845 // Decoded but not filtered
1846 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1848 // Data buffered in audio filters, measured in bytes of "missing" output
1849 buffered_output = af_calc_delay(sh_audio->afilter);
1851 // Data that was ready for ao but was buffered because ao didn't fully
1852 // accept everything to internal buffers yet
1853 buffered_output += sh_audio->a_out_buffer_len;
1855 // Filters divide audio length by playback_speed, so multiply by it
1856 // to get the length in original units without speedup or slowdown
1857 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1859 return a_pts + mpctx->video_offset;
1862 // Return pts value corresponding to currently playing audio.
1863 double playing_audio_pts(struct MPContext *mpctx)
1865 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1866 mpctx->audio_out->get_delay();
1869 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1870 struct MPOpts *opts = &mpctx->opts;
1871 // check for frame-drop:
1872 current_module = "check_framedrop";
1873 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1874 static int dropped_frames;
1875 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1876 float d = delay-mpctx->delay;
1877 ++total_frame_cnt;
1878 // we should avoid dropping too many frames in sequence unless we
1879 // are too late. and we allow 100ms A-V delay here:
1880 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1881 && !mpctx->restart_playback) {
1882 ++drop_frame_cnt;
1883 ++dropped_frames;
1884 return frame_dropping;
1885 } else
1886 dropped_frames = 0;
1888 return 0;
1892 #ifdef HAVE_RTC
1893 int rtc_fd = -1;
1894 #endif
1896 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1898 #ifdef HAVE_RTC
1899 if (rtc_fd >= 0){
1900 // -------- RTC -----------
1901 current_module="sleep_rtc";
1902 while (time_frame > 0.000) {
1903 unsigned long rtc_ts;
1904 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1905 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1906 time_frame -= get_relative_time(mpctx);
1908 } else
1909 #endif
1911 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1912 // unnecessarily high CPU usage
1913 float margin = softsleep ? 0.011 : 0;
1914 current_module = "sleep_timer";
1915 while (time_frame > margin) {
1916 usec_sleep(1000000 * (time_frame - margin));
1917 time_frame -= get_relative_time(mpctx);
1919 if (softsleep){
1920 current_module = "sleep_soft";
1921 if (time_frame < 0)
1922 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1923 while (time_frame > 0)
1924 time_frame -= get_relative_time(mpctx); // burn the CPU
1927 return time_frame;
1930 static int select_subtitle(MPContext *mpctx)
1932 struct MPOpts *opts = &mpctx->opts;
1933 // find the best sub to use
1934 int id;
1935 int found = 0;
1936 mpctx->global_sub_pos = -1; // no subs by default
1937 if (vobsub_id >= 0) {
1938 // if user asks for a vobsub id, use that first.
1939 id = vobsub_id;
1940 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1943 if (!found && opts->sub_id >= 0) {
1944 // if user asks for a dvd sub id, use that next.
1945 id = opts->sub_id;
1946 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1949 if (!found) {
1950 // if there are text subs to use, use those. (autosubs come last here)
1951 id = 0;
1952 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1955 if (!found && opts->sub_id == -1) {
1956 // finally select subs by language and container hints
1957 if (opts->sub_id == -1)
1958 opts->sub_id =
1959 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
1960 opts->sub_lang);
1961 if (opts->sub_id >= 0) {
1962 id = opts->sub_id;
1963 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1966 return found;
1969 #ifdef CONFIG_DVDNAV
1970 #ifndef FF_B_TYPE
1971 #define FF_B_TYPE 3
1972 #endif
1973 /// store decoded video image
1974 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1975 mp_image_t *from_mpi) {
1976 mp_image_t *mpi;
1978 /// Do not store B-frames
1979 if (from_mpi->pict_type == FF_B_TYPE)
1980 return to_mpi;
1982 if (to_mpi &&
1983 to_mpi->w == from_mpi->w &&
1984 to_mpi->h == from_mpi->h &&
1985 to_mpi->imgfmt == from_mpi->imgfmt)
1986 mpi = to_mpi;
1987 else {
1988 if (to_mpi)
1989 free_mp_image(to_mpi);
1990 if (from_mpi->w == 0 || from_mpi->h == 0)
1991 return NULL;
1992 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1995 copy_mpi(mpi,from_mpi);
1996 return mpi;
1999 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2000 struct MPOpts *opts = &ctx->opts;
2001 if (ctx->sh_video) {
2002 /// clear video pts
2003 ctx->d_video->pts = 0.0f;
2004 ctx->sh_video->pts = 0.0f;
2005 ctx->sh_video->i_pts = 0.0f;
2006 ctx->sh_video->last_pts = 0.0f;
2007 ctx->sh_video->num_buffered_pts = 0;
2008 ctx->sh_video->num_frames = 0;
2009 ctx->sh_video->num_frames_decoded = 0;
2010 ctx->sh_video->timer = 0.0f;
2011 ctx->sh_video->stream_delay = 0.0f;
2012 ctx->sh_video->timer = 0;
2013 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2016 if (ctx->sh_audio) {
2017 /// free audio packets and reset
2018 ds_free_packs(ctx->d_audio);
2019 audio_delay -= ctx->sh_audio->stream_delay;
2020 ctx->delay =- audio_delay;
2021 ctx->audio_out->reset();
2022 resync_audio_stream(ctx->sh_audio);
2025 audio_delay = 0.0f;
2026 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2027 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2028 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2029 if (dvdsub_lang_id != opts->sub_id) {
2030 opts->sub_id = dvdsub_lang_id;
2031 select_subtitle(ctx);
2035 /// clear all EOF related flags
2036 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2039 /// Restore last decoded DVDNAV (still frame)
2040 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2041 int *in_size,
2042 unsigned char **start,
2043 mp_image_t *decoded_frame)
2045 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2046 return decoded_frame;
2048 /// a change occured in dvdnav stream
2049 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2050 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2051 mp_dvdnav_context_free(mpctx);
2052 mp_dvdnav_reset_stream(mpctx);
2053 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2054 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2057 if (*in_size < 0) {
2058 float len;
2060 /// Display still frame, if any
2061 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2062 decoded_frame = mpctx->nav_smpi;
2064 /// increment video frame : continue playing after still frame
2065 len = get_time_length(mpctx);
2066 if (mpctx->sh_video->pts >= len &&
2067 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2068 mp_dvdnav_skip_still(mpctx->stream);
2069 mp_dvdnav_skip_wait(mpctx->stream);
2071 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2073 if (mpctx->nav_buffer) {
2074 *start = mpctx->nav_start;
2075 *in_size = mpctx->nav_in_size;
2076 if (mpctx->nav_start)
2077 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2081 return decoded_frame;
2084 /// Save last decoded DVDNAV (still frame)
2085 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2086 unsigned char *start,
2087 mp_image_t *decoded_frame)
2089 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2090 return;
2092 free(mpctx->nav_buffer);
2094 mpctx->nav_buffer = malloc(in_size);
2095 mpctx->nav_start = start;
2096 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2097 if (mpctx->nav_buffer)
2098 memcpy(mpctx->nav_buffer,start,in_size);
2100 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2101 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2103 #endif /* CONFIG_DVDNAV */
2105 /* Modify video timing to match the audio timeline. There are two main
2106 * reasons this is needed. First, video and audio can start from different
2107 * positions at beginning of file or after a seek (MPlayer starts both
2108 * immediately even if they have different pts). Second, the file can have
2109 * audio timestamps that are inconsistent with the duration of the audio
2110 * packets, for example two consecutive timestamp values differing by
2111 * one second but only a packet with enough samples for half a second
2112 * of playback between them.
2114 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2116 current_module = "av_sync";
2118 if (!mpctx->sh_audio || mpctx->syncing_audio)
2119 return;
2121 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2122 double v_pts = mpctx->sh_video->pts;
2123 double av_delay = a_pts - v_pts;
2124 // Try to sync vo_flip() so it will *finish* at given time
2125 av_delay += mpctx->last_vo_flip_duration;
2126 av_delay -= audio_delay; // This much pts difference is desired
2128 double change = av_delay * 0.1;
2129 double max_change = default_max_pts_correction >= 0 ?
2130 default_max_pts_correction : frame_time * 0.1;
2131 if (change < -max_change)
2132 change = -max_change;
2133 else if (change > max_change)
2134 change = max_change;
2135 mpctx->delay += change;
2136 mpctx->total_avsync_change += change;
2139 #define ASYNC_PLAY_DONE -3
2140 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2142 struct MPOpts *opts = &mpctx->opts;
2143 sh_audio_t * const sh_audio = mpctx->sh_audio;
2144 int res;
2146 // Timing info may not be set without
2147 res = decode_audio(sh_audio, 1);
2148 if (res < 0)
2149 return res;
2150 double ptsdiff = written_audio_pts(mpctx) - mpctx->sh_video->pts -
2151 mpctx->delay - audio_delay;
2152 int bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2153 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2155 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2156 bytes = 0;
2158 if (bytes <= 0) {
2159 mpctx->syncing_audio = false;
2160 while (1) {
2161 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2162 int res = decode_audio(sh_audio, a);
2163 bytes += sh_audio->a_out_buffer_len;
2164 if (bytes >= 0) {
2165 memmove(sh_audio->a_out_buffer,
2166 sh_audio->a_out_buffer +
2167 sh_audio->a_out_buffer_len - bytes,
2168 bytes);
2169 sh_audio->a_out_buffer_len = bytes;
2170 if (res < 0)
2171 return res;
2172 return decode_audio(sh_audio, playsize);
2174 sh_audio->a_out_buffer_len = 0;
2175 if (res < 0)
2176 return res;
2178 } else {
2179 int fillbyte = 0;
2180 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2181 fillbyte = 0x80;
2182 if (bytes >= playsize) {
2183 /* This case could fall back to the one below with
2184 * bytes = playsize, but then silence would keep accumulating
2185 * in a_out_buffer if the AO accepts less data than it asks for
2186 * in playsize. */
2187 char *p = malloc(playsize);
2188 memset(p, fillbyte, playsize);
2189 playsize = mpctx->audio_out->play(p, playsize, 0);
2190 free(p);
2191 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2192 return ASYNC_PLAY_DONE;
2194 mpctx->syncing_audio = false;
2195 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2196 return decode_audio(sh_audio, playsize);
2200 static int fill_audio_out_buffers(struct MPContext *mpctx)
2202 struct MPOpts *opts = &mpctx->opts;
2203 unsigned int t;
2204 double tt;
2205 int playsize;
2206 int playflags=0;
2207 int audio_eof=0;
2208 bool format_change = false;
2209 sh_audio_t * const sh_audio = mpctx->sh_audio;
2211 current_module="play_audio";
2213 while (1) {
2214 int sleep_time;
2215 // all the current uses of ao_data.pts seem to be in aos that handle
2216 // sync completely wrong; there should be no need to use ao_data.pts
2217 // in get_space()
2218 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2219 playsize = mpctx->audio_out->get_space();
2220 if (mpctx->sh_video || playsize >= ao_data.outburst)
2221 break;
2223 // handle audio-only case:
2224 // this is where mplayer sleeps during audio-only playback
2225 // to avoid 100% CPU use
2226 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2227 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2228 usec_sleep(sleep_time * 1000);
2231 // Fill buffer if needed:
2232 current_module="decode_audio";
2233 t = GetTimer();
2235 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2236 mpctx->syncing_audio = false;
2238 int res;
2239 if (mpctx->syncing_audio && mpctx->sh_video)
2240 res = audio_start_sync(mpctx, playsize);
2241 else
2242 res = decode_audio(sh_audio, playsize);
2243 if (res < 0) { // EOF, error or format change
2244 if (res == -2)
2245 format_change = true;
2246 else if (res == ASYNC_PLAY_DONE)
2247 return 1;
2248 else if (mpctx->d_audio->eof) {
2249 audio_eof = 1;
2250 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2251 if (sh_audio->a_out_buffer_len < unitsize)
2252 return 0;
2255 t = GetTimer() - t;
2256 tt = t*0.000001f; audio_time_usage+=tt;
2257 if (playsize > sh_audio->a_out_buffer_len) {
2258 playsize = sh_audio->a_out_buffer_len;
2259 if (audio_eof)
2260 playflags |= AOPLAY_FINAL_CHUNK;
2262 if (!playsize)
2263 return 1;
2265 // play audio:
2266 current_module="play_audio";
2268 // Is this pts value actually useful for the aos that access it?
2269 // They're obviously badly broken in the way they handle av sync;
2270 // would not having access to this make them more broken?
2271 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2272 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2274 if (playsize > 0) {
2275 sh_audio->a_out_buffer_len -= playsize;
2276 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2277 sh_audio->a_out_buffer_len);
2278 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2280 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2281 // Sanity check to avoid hanging in case current ao doesn't output
2282 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2283 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2284 sh_audio->a_out_buffer_len = 0;
2287 /* The format change isn't handled too gracefully. A more precise
2288 * implementation would require draining buffered old-format audio
2289 * while displaying video, then doing the output format switch.
2291 if (format_change) {
2292 uninit_player(mpctx, INITIALIZED_AO);
2293 reinit_audio_chain(mpctx);
2296 return 1;
2299 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2300 float *aq_sleep_time)
2302 struct MPOpts *opts = &mpctx->opts;
2303 int frame_time_remaining = 0;
2304 current_module="calc_sleep_time";
2306 *time_frame -= get_relative_time(mpctx); // reset timer
2308 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2309 float delay = mpctx->audio_out->get_delay();
2310 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2312 if (autosync) {
2314 * Adjust this raw delay value by calculating the expected
2315 * delay for this frame and generating a new value which is
2316 * weighted between the two. The higher autosync is, the
2317 * closer to the delay value gets to that which "-nosound"
2318 * would have used, and the longer it will take for A/V
2319 * sync to settle at the right value (but it eventually will.)
2320 * This settling time is very short for values below 100.
2322 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2323 float difference = delay - predicted;
2324 delay = predicted + difference / (float)autosync;
2327 *time_frame = delay - mpctx->delay / opts->playback_speed;
2328 *time_frame -= mpctx->video_out->flip_queue_offset;
2330 // delay = amount of audio buffered in soundcard/driver
2331 if (delay > 0.25) delay=0.25; else
2332 if (delay < 0.10) delay=0.10;
2334 if (*time_frame > delay*0.6) {
2335 // sleep time too big - may cause audio drops (buffer underrun)
2336 frame_time_remaining = 1;
2337 *time_frame = delay*0.5;
2339 } else {
2340 // If we're lagging more than 200 ms behind the right playback rate,
2341 // don't try to "catch up".
2342 // If benchmark is set always output frames as fast as possible
2343 // without sleeping.
2344 if (*time_frame < -0.2 || benchmark)
2345 *time_frame = 0;
2346 *time_frame -= mpctx->video_out->flip_queue_offset;
2349 *aq_sleep_time += *time_frame;
2352 //============================== SLEEP: ===================================
2354 // flag 256 means: libvo driver does its timing (dvb card)
2355 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2356 *time_frame = timing_sleep(mpctx, *time_frame);
2357 *time_frame += mpctx->video_out->flip_queue_offset;
2358 return frame_time_remaining;
2361 int reinit_video_chain(struct MPContext *mpctx)
2363 struct MPOpts *opts = &mpctx->opts;
2364 sh_video_t * const sh_video = mpctx->sh_video;
2365 double ar=-1.0;
2366 //================== Init VIDEO (codec & libvo) ==========================
2367 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2368 current_module="preinit_libvo";
2370 //shouldn't we set dvideo->id=-2 when we fail?
2371 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2372 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2373 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2374 goto err_out;
2376 mpctx->initialized_flags|=INITIALIZED_VO;
2379 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2380 mpctx->sh_video->stream_aspect = ar;
2381 current_module="init_video_filters";
2383 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2384 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2386 #ifdef CONFIG_MENU
2387 if(use_menu) {
2388 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2389 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2390 if(!vf_menu) {
2391 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2392 use_menu = 0;
2395 if(vf_menu)
2396 sh_video->vfilter = vf_menu;
2397 #endif
2399 #ifdef CONFIG_ASS
2400 if(opts->ass_enabled) {
2401 int i;
2402 int insert = 1;
2403 if (opts->vf_settings)
2404 for (i = 0; opts->vf_settings[i].name; ++i)
2405 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2406 insert = 0;
2407 break;
2409 if (insert) {
2410 extern vf_info_t vf_info_ass;
2411 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2412 char* vf_arg[] = {"auto", "1", NULL};
2413 int retcode = 0;
2414 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2415 sh_video->vfilter,
2416 "ass", vf_arg,
2417 &retcode);
2418 if (vf_ass)
2419 sh_video->vfilter = vf_ass;
2420 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2421 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2422 else
2423 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2426 #endif
2428 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2430 #ifdef CONFIG_ASS
2431 if (opts->ass_enabled)
2432 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2433 #endif
2435 current_module="init_video_codec";
2437 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2438 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2439 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2441 if(!sh_video->initialized){
2442 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2443 goto err_out;
2446 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2448 if (sh_video->codec)
2449 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2451 sh_video->last_pts = MP_NOPTS_VALUE;
2452 sh_video->num_buffered_pts = 0;
2453 sh_video->next_frame_time = 0;
2455 if(auto_quality>0){
2456 // Auto quality option enabled
2457 output_quality=get_video_quality_max(sh_video);
2458 if(auto_quality>output_quality) auto_quality=output_quality;
2459 else output_quality=auto_quality;
2460 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2461 set_video_quality(sh_video,output_quality);
2464 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2466 current_module="init_vo";
2468 return 1;
2470 err_out:
2471 mpctx->sh_video = mpctx->d_video->sh = NULL;
2472 return 0;
2475 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2477 struct sh_video *sh_video = mpctx->sh_video;
2478 double frame_time = 0;
2479 struct vo *video_out = mpctx->video_out;
2480 while (!video_out->frame_loaded) {
2481 current_module = "filter_video";
2482 // In nocorrect-pts mode there is no way to properly time these frames
2483 if (vo_get_buffered_frame(video_out, 0) >= 0)
2484 break;
2485 if (vf_output_queued_frame(sh_video->vfilter))
2486 continue;
2487 unsigned char *packet = NULL;
2488 frame_time = sh_video->next_frame_time;
2489 if (mpctx->restart_playback)
2490 frame_time = 0;
2491 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2492 &packet, force_fps);
2493 if (in_size < 0) {
2494 #ifdef CONFIG_DVDNAV
2495 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2496 if (mp_dvdnav_is_eof(mpctx->stream))
2497 return -1;
2498 if (mpctx->d_video)
2499 mpctx->d_video->eof = 0;
2500 if (mpctx->d_audio)
2501 mpctx->d_audio->eof = 0;
2502 mpctx->stream->eof = 0;
2503 } else
2504 #endif
2505 return -1;
2507 if (in_size > max_framesize)
2508 max_framesize = in_size;
2509 sh_video->timer += frame_time;
2510 if (mpctx->sh_audio)
2511 mpctx->delay -= frame_time;
2512 // video_read_frame can change fps (e.g. for ASF video)
2513 vo_fps = sh_video->fps;
2514 int framedrop_type = check_framedrop(mpctx, frame_time);
2515 current_module = "decode video";
2517 void *decoded_frame;
2518 #ifdef CONFIG_DVDNAV
2519 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2520 if (in_size >= 0 && !decoded_frame)
2521 #endif
2522 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2523 sh_video->pts);
2524 #ifdef CONFIG_DVDNAV
2525 // Save last still frame for future display
2526 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2527 #endif
2528 if (decoded_frame) {
2529 current_module = "filter video";
2530 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2531 if (!video_out->config_ok)
2532 break;
2535 return frame_time;
2538 static void determine_frame_pts(struct MPContext *mpctx)
2540 struct sh_video *sh_video = mpctx->sh_video;
2541 struct MPOpts *opts = &mpctx->opts;
2543 if (opts->user_pts_assoc_mode) {
2544 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2545 } else if (sh_video->pts_assoc_mode == 0) {
2546 if (sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2547 sh_video->pts_assoc_mode = 1;
2548 else
2549 sh_video->pts_assoc_mode = 2;
2550 } else {
2551 int probcount1 = sh_video->num_reordered_pts_problems;
2552 int probcount2 = sh_video->num_sorted_pts_problems;
2553 if (sh_video->pts_assoc_mode == 2) {
2554 int tmp = probcount1;
2555 probcount1 = probcount2;
2556 probcount2 = tmp;
2558 if (probcount1 >= probcount2 * 1.5 + 2) {
2559 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2560 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2561 "%d.\n", sh_video->pts_assoc_mode);
2564 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2565 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2568 static double update_video(struct MPContext *mpctx)
2570 struct sh_video *sh_video = mpctx->sh_video;
2571 struct vo *video_out = mpctx->video_out;
2572 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2573 mpctx->osd); // hack for vf_expand
2574 if (!mpctx->opts.correct_pts)
2575 return update_video_nocorrect_pts(mpctx);
2577 double pts;
2579 bool hit_eof = false;
2580 while (!video_out->frame_loaded) {
2581 current_module = "filter_video";
2582 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2583 break;
2584 // XXX Time used in this call is not counted in any performance
2585 // timer now, OSD time is not updated correctly for filter-added frames
2586 if (vf_output_queued_frame(sh_video->vfilter))
2587 continue;
2588 if (hit_eof)
2589 return -1;
2590 unsigned char *packet = NULL;
2591 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2592 if (pts != MP_NOPTS_VALUE)
2593 pts += mpctx->video_offset;
2594 if (in_size < 0) {
2595 // try to extract last frames in case of decoder lag
2596 in_size = 0;
2597 pts = MP_NOPTS_VALUE;
2598 hit_eof = true;
2600 if (in_size > max_framesize)
2601 max_framesize = in_size;
2602 current_module = "decode video";
2603 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2604 void *decoded_frame = decode_video(sh_video, packet, in_size,
2605 framedrop_type, pts);
2606 if (decoded_frame) {
2607 determine_frame_pts(mpctx);
2608 current_module = "filter video";
2609 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2610 if (!video_out->config_ok)
2611 break; // We'd likely hang in this loop otherwise
2615 pts = video_out->next_pts;
2616 if (pts == MP_NOPTS_VALUE) {
2617 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2618 // Try to use decoder pts from before filters
2619 pts = sh_video->pts;
2620 if (pts == MP_NOPTS_VALUE)
2621 pts = sh_video->last_pts;
2623 sh_video->pts = pts;
2624 if (sh_video->last_pts == MP_NOPTS_VALUE)
2625 sh_video->last_pts = sh_video->pts;
2626 else if (sh_video->last_pts > sh_video->pts) {
2627 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2628 sh_video->pts, sh_video->last_pts);
2629 /* If the difference in pts is small treat it as jitter around the
2630 * right value (possibly caused by incorrect timestamp ordering) and
2631 * just show this frame immediately after the last one.
2632 * Treat bigger differences as timestamp resets and start counting
2633 * timing of later frames from the position of this one. */
2634 if (sh_video->last_pts - sh_video->pts > 0.5)
2635 sh_video->last_pts = sh_video->pts;
2636 else
2637 sh_video->pts = sh_video->last_pts;
2639 double frame_time = sh_video->pts - sh_video->last_pts;
2640 sh_video->last_pts = sh_video->pts;
2641 sh_video->timer += frame_time;
2642 if (mpctx->sh_audio)
2643 mpctx->delay -= frame_time;
2644 return frame_time;
2647 void pause_player(struct MPContext *mpctx)
2649 if (mpctx->paused)
2650 return;
2651 mpctx->paused = 1;
2652 mpctx->step_frames = 0;
2653 mpctx->time_frame -= get_relative_time(mpctx);
2655 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2656 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2658 if (mpctx->audio_out && mpctx->sh_audio)
2659 mpctx->audio_out->pause(); // pause audio, keep data if possible
2662 void unpause_player(struct MPContext *mpctx)
2664 if (!mpctx->paused)
2665 return;
2666 mpctx->paused = 0;
2668 if (mpctx->audio_out && mpctx->sh_audio)
2669 mpctx->audio_out->resume(); // resume audio
2670 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2671 && !mpctx->step_frames)
2672 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2673 (void)get_relative_time(mpctx); // ignore time that passed during pause
2676 void add_step_frame(struct MPContext *mpctx)
2678 mpctx->step_frames++;
2679 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2680 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2681 unpause_player(mpctx);
2684 static void pause_loop(struct MPContext *mpctx)
2686 mp_cmd_t* cmd;
2687 if (!quiet) {
2688 // Small hack to display the pause message on the OSD line.
2689 // The pause string is: "\n == PAUSE == \r" so we need to
2690 // take the first and the last char out
2691 if (term_osd && !mpctx->sh_video) {
2692 char msg[128] = _("\n ===== PAUSE =====\r");
2693 int mlen = strlen(msg);
2694 msg[mlen-1] = '\0';
2695 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2696 update_osd_msg(mpctx);
2697 } else
2698 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2699 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2702 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2703 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2704 if (cmd) {
2705 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2706 run_command(mpctx, cmd);
2707 mp_cmd_free(cmd);
2708 continue;
2710 if (mpctx->sh_video && mpctx->video_out)
2711 vo_check_events(mpctx->video_out);
2712 #ifdef CONFIG_MENU
2713 if (vf_menu)
2714 vf_menu_pause_update(vf_menu);
2715 #endif
2716 usec_sleep(20000);
2717 update_osd_msg(mpctx);
2718 int hack = vo_osd_changed(0);
2719 vo_osd_changed(hack);
2720 if (hack)
2721 break;
2726 // Find the right mute status and record position for new file position
2727 static void edl_seek_reset(MPContext *mpctx)
2729 mpctx->edl_muted = 0;
2730 next_edl_record = edl_records;
2732 while (next_edl_record) {
2733 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2734 break;
2736 if (next_edl_record->action == EDL_MUTE)
2737 mpctx->edl_muted = !mpctx->edl_muted;
2738 next_edl_record = next_edl_record->next;
2740 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2741 mixer_mute(&mpctx->mixer);
2745 // Execute EDL command for the current position if one exists
2746 static void edl_update(MPContext *mpctx)
2748 if (!next_edl_record)
2749 return;
2751 if (!mpctx->sh_video) {
2752 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2753 free_edl(edl_records);
2754 next_edl_record = NULL;
2755 edl_records = NULL;
2756 return;
2759 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2760 if (next_edl_record->action == EDL_SKIP) {
2761 mpctx->osd_function = OSD_FFW;
2762 mpctx->abs_seek_pos = 0;
2763 mpctx->rel_seek_secs = next_edl_record->length_sec;
2764 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2765 "[%f], length [%f]\n", next_edl_record->start_sec,
2766 next_edl_record->stop_sec, next_edl_record->length_sec);
2768 else if (next_edl_record->action == EDL_MUTE) {
2769 mpctx->edl_muted = !mpctx->edl_muted;
2770 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2771 mixer_mute(&mpctx->mixer);
2772 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2773 next_edl_record->start_sec );
2775 next_edl_record = next_edl_record->next;
2779 static void reinit_decoders(struct MPContext *mpctx)
2781 reinit_video_chain(mpctx);
2782 reinit_audio_chain(mpctx);
2783 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2786 static void seek_reset(struct MPContext *mpctx)
2788 if (mpctx->sh_video) {
2789 current_module = "seek_video_reset";
2790 resync_video_stream(mpctx->sh_video);
2791 mpctx->sh_video->timer = 0;
2792 vo_seek_reset(mpctx->video_out);
2793 mpctx->sh_video->timer = 0;
2794 mpctx->sh_video->num_buffered_pts = 0;
2795 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2796 mpctx->delay = 0;
2797 mpctx->time_frame = 0;
2798 mpctx->restart_playback = true;
2799 // Not all demuxers set d_video->pts during seek, so this value
2800 // (which is used by at least vobsub and edl code below) may
2801 // be completely wrong (probably 0).
2802 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2803 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2804 mpctx->sh_video->pts, mpctx->video_offset,
2805 mpctx->d_sub, 1);
2806 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2809 if (mpctx->sh_audio) {
2810 current_module = "seek_audio_reset";
2811 resync_audio_stream(mpctx->sh_audio);
2812 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2813 mpctx->sh_audio->a_buffer_len = 0;
2814 mpctx->sh_audio->a_out_buffer_len = 0;
2815 if (!mpctx->sh_video)
2816 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2817 mpctx->video_offset, mpctx->d_sub, 1);
2820 if (vo_vobsub && mpctx->sh_video) {
2821 current_module = "seek_vobsub_reset";
2822 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2825 edl_seek_reset(mpctx);
2827 mpctx->total_avsync_change = 0;
2828 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2829 drop_frame_cnt = 0;
2831 current_module = NULL;
2834 static bool timeline_set_part(struct MPContext *mpctx, int i)
2836 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2837 struct timeline_part *n = mpctx->timeline + i;
2838 mpctx->timeline_part = i;
2839 mpctx->video_offset = n->start - n->source_start;
2840 if (n->source == p->source)
2841 return false;
2842 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2843 mpctx->demuxer = n->source->demuxer;
2844 mpctx->d_video = mpctx->demuxer->video;
2845 mpctx->d_audio = mpctx->demuxer->audio;
2846 mpctx->d_sub = mpctx->demuxer->sub;
2847 mpctx->sh_video = mpctx->d_video->sh;
2848 mpctx->sh_audio = mpctx->d_audio->sh;
2849 return true;
2852 // Given pts, switch playback to the corresponding part.
2853 // Return offset within that part.
2854 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2855 bool *need_reset)
2857 if (pts < 0)
2858 pts = 0;
2859 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2860 struct timeline_part *p = mpctx->timeline + i;
2861 if (pts < (p+1)->start) {
2862 *need_reset = timeline_set_part(mpctx, i);
2863 return pts - p->start + p->source_start;
2866 return -1;
2870 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2871 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2872 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2873 static int seek(MPContext *mpctx, double amount, int style)
2875 current_module = "seek";
2876 if (mpctx->stop_play == AT_END_OF_FILE)
2877 mpctx->stop_play = KEEP_PLAYING;
2878 if (style & SEEK_FACTOR
2879 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2880 || amount < 0)
2881 mpctx->last_chapter_seek = -1;
2882 if (mpctx->timeline && style & SEEK_FACTOR) {
2883 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2884 style &= ~SEEK_FACTOR;
2886 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2887 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2888 style |= SEEK_ABSOLUTE;
2889 if (amount > 0)
2890 style |= SEEK_FORWARD;
2891 else
2892 style |= SEEK_BACKWARD;
2893 amount += mpctx->sh_video->pts;
2896 /* At least the liba52 decoder wants to read from the input stream
2897 * during initialization, so reinit must be done after the demux_seek()
2898 * call that clears possible stream EOF. */
2899 bool need_reset = false;
2900 if (mpctx->timeline) {
2901 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2902 if (amount == -1) {
2903 mpctx->stop_play = AT_END_OF_FILE;
2904 // Clear audio from current position
2905 if (mpctx->sh_audio) {
2906 mpctx->audio_out->reset();
2907 mpctx->sh_audio->a_buffer_len = 0;
2908 mpctx->sh_audio->a_out_buffer_len = 0;
2910 return -1;
2913 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2914 if (need_reset)
2915 reinit_decoders(mpctx);
2916 if (seekresult == 0)
2917 return -1;
2919 seek_reset(mpctx);
2920 return 0;
2924 double get_time_length(struct MPContext *mpctx)
2926 if (mpctx->timeline)
2927 return mpctx->timeline[mpctx->num_timeline_parts].start;
2929 struct demuxer *demuxer = mpctx->demuxer;
2930 double get_time_ans;
2931 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
2932 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
2933 (void *) &get_time_ans) > 0)
2934 return get_time_ans;
2936 struct sh_video *sh_video = mpctx->d_video->sh;
2937 struct sh_audio *sh_audio = mpctx->d_audio->sh;
2938 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
2939 return (double) (demuxer->movi_end - demuxer->movi_start) /
2940 (sh_video->i_bps + sh_audio->i_bps);
2941 if (sh_video && sh_video->i_bps)
2942 return (double) (demuxer->movi_end - demuxer->movi_start) /
2943 sh_video->i_bps;
2944 if (sh_audio && sh_audio->i_bps)
2945 return (double) (demuxer->movi_end - demuxer->movi_start) /
2946 sh_audio->i_bps;
2947 return 0;
2950 /* If there are timestamps from stream level then use those (for example
2951 * DVDs can have consistent times there while the MPEG-level timestamps
2952 * reset). */
2953 double get_current_time(struct MPContext *mpctx)
2955 struct demuxer *demuxer = mpctx->demuxer;
2956 if (demuxer->stream_pts != MP_NOPTS_VALUE)
2957 return demuxer->stream_pts;
2958 struct sh_video *sh_video = demuxer->video->sh;
2959 if (sh_video)
2960 return sh_video->pts;
2961 return playing_audio_pts(mpctx);
2964 int get_percent_pos(struct MPContext *mpctx)
2966 struct demuxer *demuxer = mpctx->demuxer;
2967 int ans = 0;
2968 if (mpctx->timeline)
2969 ans = get_current_time(mpctx) * 100 /
2970 mpctx->timeline[mpctx->num_timeline_parts].start;
2971 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
2973 else {
2974 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
2975 off_t pos = demuxer->filepos > 0 ?
2976 demuxer->filepos : stream_tell(demuxer->stream);
2977 if (len > 0)
2978 ans = (pos - demuxer->movi_start) / len;
2979 else
2980 ans = 0;
2982 if (ans < 0)
2983 ans = 0;
2984 if (ans > 100)
2985 ans = 100;
2986 return ans;
2989 // -2 is no chapters, -1 is before first chapter
2990 int get_current_chapter(struct MPContext *mpctx)
2992 double current_pts = get_current_time(mpctx);
2993 if (!mpctx->chapters)
2994 return FFMAX(mpctx->last_chapter_seek,
2995 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
2997 int i;
2998 for (i = 1; i < mpctx->num_chapters; i++)
2999 if (current_pts < mpctx->chapters[i].start)
3000 break;
3001 return FFMAX(mpctx->last_chapter_seek, i - 1);
3004 // currently returns a string allocated with malloc, not talloc
3005 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3007 if (!mpctx->chapters || !mpctx->sh_video)
3008 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3009 return strdup(mpctx->chapters[chapter].name);
3012 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3013 char **chapter_name)
3015 mpctx->last_chapter_seek = -1;
3016 if (!mpctx->chapters || !mpctx->sh_video) {
3017 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3018 chapter_name);
3019 if (res >= 0) {
3020 if (*seek_pts == -1)
3021 seek_reset(mpctx);
3022 else {
3023 mpctx->last_chapter_seek = res;
3024 mpctx->last_chapter_pts = *seek_pts;
3027 return res;
3030 if (chapter >= mpctx->num_chapters)
3031 return -1;
3032 if (chapter < 0)
3033 chapter = 0;
3034 *seek_pts = mpctx->chapters[chapter].start;
3035 mpctx->last_chapter_seek = chapter;
3036 mpctx->last_chapter_pts = *seek_pts;
3037 if (chapter_name)
3038 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3039 return chapter;
3042 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3043 struct content_source *sources,
3044 int num_sources,
3045 unsigned char uid_map[][16])
3047 int num_filenames = 0;
3048 char **filenames = NULL;
3049 if (num_sources > 1) {
3050 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3051 "other sources.\n");
3052 if (mpctx->stream->type != STREAMTYPE_FILE) {
3053 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3054 "normal disk file. Will not search for related files.\n");
3055 } else {
3056 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3057 "same directory to find referenced sources.\n");
3058 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3059 &num_filenames);
3063 int num_left = num_sources - 1;
3064 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3065 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3066 filename_recode(filenames[i]));
3067 int format;
3068 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3069 if (!s)
3070 continue;
3071 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3072 mpctx->opts.audio_id,
3073 mpctx->opts.video_id,
3074 mpctx->opts.sub_id, filenames[i]);
3075 if (!d) {
3076 free_stream(s);
3077 continue;
3079 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3080 for (int i = 1; i < num_sources; i++) {
3081 if (sources[i].demuxer)
3082 continue;
3083 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3084 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3085 i, filename_recode(d->filename));
3086 sources[i].stream = s;
3087 sources[i].demuxer = d;
3088 num_left--;
3089 goto match;
3093 free_demuxer(d);
3094 free_stream(s);
3095 continue;
3096 match:
3099 talloc_free(filenames);
3100 if (num_left) {
3101 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3102 "There will be parts MISSING from the video!\n");
3103 for (int i = 1, j = 1; i < num_sources; i++)
3104 if (sources[i].demuxer) {
3105 sources[j] = sources[i];
3106 memcpy(uid_map[j], uid_map[i], 16);
3107 j++;
3110 return num_sources - num_left;
3113 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3115 if (!mpctx->opts.ordered_chapters) {
3116 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3117 "you have disabled support for them. Ignoring.\n");
3118 return;
3121 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3122 "edit timeline.\n");
3124 struct demuxer *demuxer = mpctx->demuxer;
3125 struct matroska_data *m = &demuxer->matroska_data;
3127 // +1 because sources/uid_map[0] is original file even if all chapters
3128 // actually use other sources and need separate entries
3129 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3130 m->num_ordered_chapters+1);
3131 sources[0].stream = mpctx->stream;
3132 sources[0].demuxer = mpctx->demuxer;
3133 unsigned char uid_map[m->num_ordered_chapters+1][16];
3134 int num_sources = 1;
3135 memcpy(uid_map[0], m->segment_uid, 16);
3137 for (int i = 0; i < m->num_ordered_chapters; i++) {
3138 struct matroska_chapter *c = m->ordered_chapters + i;
3139 if (!c->has_segment_uid)
3140 memcpy(c->segment_uid, m->segment_uid, 16);
3142 for (int j = 0; j < num_sources; j++)
3143 if (!memcmp(c->segment_uid, uid_map[j], 16))
3144 goto found1;
3145 memcpy(uid_map[num_sources], c->segment_uid, 16);
3146 sources[num_sources] = (struct content_source){};
3147 num_sources++;
3148 found1:
3152 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3153 uid_map);
3156 // +1 for terminating chapter with start time marking end of last real one
3157 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3158 m->num_ordered_chapters + 1);
3159 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3160 m->num_ordered_chapters);
3161 uint64_t starttime = 0;
3162 uint64_t missing_time = 0;
3163 int part_count = 0;
3164 int num_chapters = 0;
3165 uint64_t prev_part_offset = 0;
3166 for (int i = 0; i < m->num_ordered_chapters; i++) {
3167 struct matroska_chapter *c = m->ordered_chapters + i;
3169 int j;
3170 for (j = 0; j < num_sources; j++) {
3171 if (!memcmp(c->segment_uid, uid_map[j], 16))
3172 goto found2;
3174 missing_time += c->end - c->start;
3175 continue;
3176 found2:;
3177 chapters[num_chapters].start = starttime / 1000.;
3178 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3179 /* Only add a separate part if the time or file actually changes.
3180 * Matroska files have chapter divisions that are redundant from
3181 * timeline point of view because the same chapter structure is used
3182 * both to specify the timeline and for normal chapter information.
3183 * Removing a missing inserted external chapter can also cause this. */
3184 if (part_count == 0 || c->start != starttime + prev_part_offset
3185 || sources + j != timeline[part_count - 1].source) {
3186 timeline[part_count].source = sources + j;
3187 timeline[part_count].start = chapters[num_chapters].start;
3188 timeline[part_count].source_start = c->start / 1000.;
3189 prev_part_offset = c->start - starttime;
3190 part_count++;
3192 starttime += c->end - c->start;
3193 num_chapters++;
3195 timeline[part_count].start = starttime / 1000.;
3197 if (!part_count) {
3198 // None of the parts come from the file itself???
3199 talloc_free(sources);
3200 talloc_free(timeline);
3201 talloc_free(chapters);
3202 return;
3205 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3206 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3207 timeline[part_count].start);
3208 if (missing_time)
3209 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3210 "from the timeline!\n", missing_time / 1000.);
3211 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3212 for (int i = 0; i < num_sources; i++)
3213 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3214 filename_recode(sources[i].demuxer->filename));
3215 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3216 "source_start, source):\n");
3217 for (int i = 0; i < part_count; i++) {
3218 struct timeline_part *p = timeline + i;
3219 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3220 p->source_start, p->source - sources);
3222 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3223 mpctx->sources = sources;
3224 mpctx->num_sources = num_sources;
3225 mpctx->timeline = timeline;
3226 mpctx->num_timeline_parts = part_count;
3227 mpctx->num_chapters = num_chapters;
3228 mpctx->chapters = chapters;
3230 mpctx->timeline_part = 0;
3231 mpctx->demuxer = timeline[0].source->demuxer;
3235 static int read_keys(void *ctx, int fd)
3237 getch2(ctx);
3238 return mplayer_get_key(ctx, 0);
3242 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3243 * file for some tools to link against. */
3244 #ifndef DISABLE_MAIN
3245 int main(int argc,char* argv[]){
3248 char * mem_ptr;
3250 // movie info:
3252 /* Flag indicating whether MPlayer should exit without playing anything. */
3253 int opt_exit = 0;
3254 int i;
3256 struct MPContext *mpctx = &(struct MPContext){
3257 .osd_function = OSD_PLAY,
3258 .begin_skip = MP_NOPTS_VALUE,
3259 .play_tree_step = 1,
3260 .global_sub_pos = -1,
3261 .set_of_sub_pos = -1,
3262 .file_format = DEMUXER_TYPE_UNKNOWN,
3263 .last_dvb_step = 1,
3266 InitTimer();
3267 srand(GetTimerMS());
3269 mp_msg_init();
3270 set_av_log_callback();
3272 #ifdef CONFIG_X11
3273 mpctx->x11_state = vo_x11_init_state();
3274 #endif
3275 struct MPOpts *opts = &mpctx->opts;
3276 set_default_mplayer_options(opts);
3277 // Create the config context and register the options
3278 mpctx->mconfig = m_config_new(opts, cfg_include);
3279 m_config_register_options(mpctx->mconfig,mplayer_opts);
3280 m_config_register_options(mpctx->mconfig, common_opts);
3281 mp_input_register_options(mpctx->mconfig);
3283 // Preparse the command line
3284 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3286 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3287 set_path_env();
3288 #endif
3290 #ifdef CONFIG_TV
3291 stream_tv_defaults.immediate = 1;
3292 #endif
3294 parse_cfgfiles(mpctx, mpctx->mconfig);
3296 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3297 if(mpctx->playtree == NULL)
3298 opt_exit = 1;
3299 else {
3300 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3301 if(mpctx->playtree) {
3302 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3303 if(mpctx->playtree_iter) {
3304 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3305 play_tree_iter_free(mpctx->playtree_iter);
3306 mpctx->playtree_iter = NULL;
3308 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3312 mpctx->key_fifo = mp_fifo_create(opts);
3314 print_version("MPlayer");
3316 #if defined(__MINGW32__) || defined(__CYGWIN__)
3318 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3319 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3320 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3321 if (kernel32) {
3322 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3323 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3325 if (setDEP) setDEP(3);
3326 if (setDllDir) setDllDir("");
3328 // stop Windows from showing all kinds of annoying error dialogs
3329 SetErrorMode(0x8003);
3330 // request 1ms timer resolution
3331 timeBeginPeriod(1);
3332 #endif
3334 #ifdef CONFIG_PRIORITY
3335 set_priority();
3336 #endif
3338 if (codec_path)
3339 set_codec_path(codec_path);
3341 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3342 list_video_out();
3343 opt_exit = 1;
3346 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3347 list_audio_out();
3348 opt_exit = 1;
3351 /* Check codecs.conf. */
3352 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3353 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3354 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3355 if(!parse_codec_cfg(NULL)){
3356 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3358 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3361 free( mem_ptr ); // release the buffer created by get_path()
3364 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3365 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3366 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3367 list_codecs(1);
3368 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3369 opt_exit = 1;
3371 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3372 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3373 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3374 list_codecs(0);
3375 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3376 opt_exit = 1;
3378 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3379 vfm_help();
3380 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3381 opt_exit = 1;
3383 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3384 afm_help();
3385 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3386 opt_exit = 1;
3388 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3389 af_help();
3390 printf("\n");
3391 opt_exit = 1;
3393 #ifdef CONFIG_X11
3394 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3395 fstype_help();
3396 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3397 opt_exit = 1;
3399 #endif
3400 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3401 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3402 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3403 demuxer_help();
3404 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3405 opt_exit = 1;
3407 if(list_properties) {
3408 property_print_help();
3409 opt_exit = 1;
3412 if(opt_exit)
3413 exit_player(mpctx, EXIT_NONE);
3415 if(!mpctx->filename && !player_idle_mode){
3416 // no file/vcd/dvd -> show HELP:
3417 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3418 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3421 /* Display what configure line was used */
3422 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3424 // Many users forget to include command line in bugreports...
3425 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3426 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3427 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3428 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3431 //------ load global data first ------
3433 mpctx->osd = osd_create();
3435 // check font
3436 #ifdef CONFIG_FREETYPE
3437 init_freetype();
3438 #endif
3439 #ifdef CONFIG_FONTCONFIG
3440 if(font_fontconfig <= 0)
3442 #endif
3443 #ifdef CONFIG_BITMAP_FONT
3444 if(font_name){
3445 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3446 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3447 filename_recode(font_name));
3448 } else {
3449 // try default:
3450 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3451 free(mem_ptr); // release the buffer created by get_path()
3452 if(!vo_font)
3453 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3455 if (sub_font_name)
3456 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3457 else
3458 mpctx->osd->sub_font = vo_font;
3459 #endif
3460 #ifdef CONFIG_FONTCONFIG
3462 #endif
3464 #ifdef CONFIG_ASS
3465 ass_library = ass_init();
3466 #endif
3468 #ifdef HAVE_RTC
3469 if(!nortc)
3471 // seteuid(0); /* Can't hurt to try to get root here */
3472 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3473 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3474 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3475 else {
3476 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3478 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3479 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3480 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3481 close (rtc_fd);
3482 rtc_fd = -1;
3483 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3484 /* variable only by the root */
3485 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3486 close (rtc_fd);
3487 rtc_fd = -1;
3488 } else
3489 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3492 if(rtc_fd<0)
3493 #endif /* HAVE_RTC */
3494 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3495 softsleep?"software":timer_name);
3497 #ifdef HAVE_TERMCAP
3498 load_termcap(NULL); // load key-codes
3499 #endif
3501 // ========== Init keyboard FIFO (connection to libvo) ============
3503 // Init input system
3504 current_module = "init_input";
3505 mpctx->input = mp_input_init(&opts->input);
3506 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3507 if(slave_mode)
3508 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3509 else if(!noconsolecontrols)
3510 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3511 // Set the libstream interrupt callback
3512 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3514 #ifdef CONFIG_MENU
3515 if(use_menu) {
3516 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3517 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3518 else {
3519 menu_cfg = get_path("menu.conf");
3520 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3521 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3522 else {
3523 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3524 MPLAYER_CONFDIR "/menu.conf"))
3525 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3526 else {
3527 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3528 use_menu = 0;
3533 #endif
3535 current_module = NULL;
3537 /// Catch signals
3538 #ifndef __MINGW32__
3539 signal(SIGCHLD,child_sighandler);
3540 #endif
3542 #ifdef CONFIG_CRASH_DEBUG
3543 prog_path = argv[0];
3544 #endif
3545 //========= Catch terminate signals: ================
3546 // terminate requests:
3547 signal(SIGTERM,exit_sighandler); // kill
3548 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3550 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3552 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3553 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3554 #ifdef CONFIG_SIGHANDLER
3555 // fatal errors:
3556 signal(SIGBUS,exit_sighandler); // bus error
3557 signal(SIGSEGV,exit_sighandler); // segfault
3558 signal(SIGILL,exit_sighandler); // illegal instruction
3559 signal(SIGFPE,exit_sighandler); // floating point exc.
3560 signal(SIGABRT,exit_sighandler); // abort()
3561 #ifdef CONFIG_CRASH_DEBUG
3562 if (crash_debug)
3563 signal(SIGTRAP,exit_sighandler);
3564 #endif
3565 #endif
3567 // ******************* Now, let's see the per-file stuff ********************
3569 play_next_file:
3571 // init global sub numbers
3572 mpctx->global_sub_size = 0;
3573 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3575 if (mpctx->filename) {
3576 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3577 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3578 load_per_file_config (mpctx->mconfig, mpctx->filename);
3581 if (opts->video_driver_list)
3582 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3583 if (opts->audio_driver_list)
3584 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3586 // We must enable getch2 here to be able to interrupt network connection
3587 // or cache filling
3588 if(!noconsolecontrols && !slave_mode){
3589 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3590 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3591 else
3592 getch2_enable(); // prepare stdin for hotkeys...
3593 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3594 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3597 // =================== GUI idle loop (STOP state) ===========================
3598 while (player_idle_mode && !mpctx->filename) {
3599 play_tree_t * entry = NULL;
3600 mp_cmd_t * cmd;
3601 if (mpctx->video_out && mpctx->video_out->config_ok)
3602 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3603 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3604 if (mpctx->video_out)
3605 vo_check_events(mpctx->video_out);
3606 usec_sleep(20000);
3608 switch (cmd->id) {
3609 case MP_CMD_LOADFILE:
3610 // prepare a tree entry with the new filename
3611 entry = play_tree_new();
3612 play_tree_add_file(entry, cmd->args[0].v.s);
3613 // The entry is added to the main playtree after the switch().
3614 break;
3615 case MP_CMD_LOADLIST:
3616 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3617 break;
3618 case MP_CMD_QUIT:
3619 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3620 break;
3621 case MP_CMD_VO_FULLSCREEN:
3622 case MP_CMD_GET_PROPERTY:
3623 case MP_CMD_SET_PROPERTY:
3624 case MP_CMD_STEP_PROPERTY:
3625 run_command(mpctx, cmd);
3626 break;
3629 mp_cmd_free(cmd);
3631 if (entry) { // user entered a command that gave a valid entry
3632 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3633 play_tree_free_list(mpctx->playtree->child, 1);
3634 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3636 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3638 play_tree_set_child(mpctx->playtree, entry);
3640 /* Make iterator start at the top the of tree. */
3641 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3642 if (!mpctx->playtree_iter) continue;
3644 // find the first real item in the tree
3645 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3646 // no items!
3647 play_tree_iter_free(mpctx->playtree_iter);
3648 mpctx->playtree_iter = NULL;
3649 continue; // wait for next command
3651 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3654 //---------------------------------------------------------------------------
3656 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3657 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3659 if (mpctx->filename) {
3660 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3661 filename_recode(mpctx->filename));
3662 if(use_filename_title && opts->vo_wintitle == NULL)
3663 opts->vo_wintitle = strdup(mp_basename2(mpctx->filename));
3666 if (edl_filename) {
3667 if (edl_records) free_edl(edl_records);
3668 next_edl_record = edl_records = edl_parse_file();
3670 if (edl_output_filename) {
3671 if (edl_fd) fclose(edl_fd);
3672 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3674 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3675 filename_recode(edl_output_filename));
3679 //==================== Open VOB-Sub ============================
3681 current_module="vobsub";
3682 if (vobsub_name){
3683 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3684 if(vo_vobsub==NULL)
3685 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3686 filename_recode(vobsub_name));
3687 } else if (sub_auto && mpctx->filename){
3688 /* try to autodetect vobsub from movie filename ::atmos */
3689 char *buf = strdup(mpctx->filename), *psub;
3690 char *pdot = strrchr(buf, '.');
3691 char *pslash = strrchr(buf, '/');
3692 #if defined(__MINGW32__) || defined(__CYGWIN__)
3693 if (!pslash) pslash = strrchr(buf, '\\');
3694 #endif
3695 if (pdot && (!pslash || pdot > pslash))
3696 *pdot = '\0';
3697 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3698 /* try from ~/.mplayer/sub */
3699 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3700 char *bname;
3701 int l;
3702 bname = strrchr(buf,'/');
3703 #if defined(__MINGW32__) || defined(__CYGWIN__)
3704 if(!bname) bname = strrchr(buf,'\\');
3705 #endif
3706 if(bname) bname++;
3707 else bname = buf;
3708 l = strlen(psub) + strlen(bname) + 1;
3709 psub = realloc(psub,l);
3710 strcat(psub,bname);
3711 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3712 free(psub);
3714 free(buf);
3716 if(vo_vobsub){
3717 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3718 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3719 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3721 // setup global sub numbering
3722 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3725 //============ Open & Sync STREAM --- fork cache2 ====================
3727 mpctx->stream=NULL;
3728 mpctx->demuxer=NULL;
3729 if (mpctx->d_audio) {
3730 //free_demuxer_stream(mpctx->d_audio);
3731 mpctx->d_audio=NULL;
3733 if (mpctx->d_video) {
3734 //free_demuxer_stream(d_video);
3735 mpctx->d_video=NULL;
3737 mpctx->sh_audio=NULL;
3738 mpctx->sh_video=NULL;
3740 current_module="open_stream";
3741 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3742 if(!mpctx->stream) { // error...
3743 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3744 goto goto_next_file;
3746 mpctx->initialized_flags|=INITIALIZED_STREAM;
3748 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3749 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3750 "playlist support will not be used automatically.\n"
3751 "MPlayer's playlist code is unsafe and should only be used with "
3752 "trusted sources.\nPlayback will probably fail.\n\n");
3753 #if 0
3754 play_tree_t* entry;
3755 // Handle playlist
3756 current_module="handle_playlist";
3757 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3758 filename_recode(mpctx->filename));
3759 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3760 mpctx->eof=playtree_add_playlist(mpctx, entry);
3761 goto goto_next_file;
3762 #endif
3764 mpctx->stream->start_pos+=seek_to_byte;
3766 if(stream_dump_type==5){
3767 unsigned char buf[4096];
3768 int len;
3769 FILE *f;
3770 current_module="dumpstream";
3771 stream_reset(mpctx->stream);
3772 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3773 f=fopen(opts->stream_dump_name,"wb");
3774 if(!f){
3775 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3776 exit_player(mpctx, EXIT_ERROR);
3778 if (opts->chapterrange[0] > 1) {
3779 int chapter = opts->chapterrange[0] - 1;
3780 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3782 while(!mpctx->stream->eof && !async_quit_request){
3783 len=stream_read(mpctx->stream,buf,4096);
3784 if(len>0) {
3785 if(fwrite(buf,len,1,f) != 1) {
3786 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3787 exit_player(mpctx, EXIT_ERROR);
3790 if (opts->chapterrange[1] > 0) {
3791 int chapter = -1;
3792 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3793 &chapter) == STREAM_OK
3794 && chapter + 1 > opts->chapterrange[1])
3795 break;
3798 if(fclose(f)) {
3799 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3800 exit_player(mpctx, EXIT_ERROR);
3802 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3803 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3806 #ifdef CONFIG_DVDREAD
3807 if(mpctx->stream->type==STREAMTYPE_DVD){
3808 current_module="dvd lang->id";
3809 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3810 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3811 // setup global sub numbering
3812 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3813 current_module=NULL;
3815 #endif
3817 #ifdef CONFIG_DVDNAV
3818 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3819 current_module="dvdnav lang->id";
3820 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3821 dvdsub_lang_id = -3;
3822 if(opts->sub_lang && opts->sub_id==-1)
3823 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3824 // setup global sub numbering
3825 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3826 current_module=NULL;
3828 #endif
3830 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3831 goto_enable_cache:
3832 if(stream_cache_size>0){
3833 int res;
3834 float stream_cache_min_percent = opts->stream_cache_min_percent;
3835 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
3836 current_module="enable_cache";
3837 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3838 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3839 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3840 if(res == 0)
3841 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3844 //============ Open DEMUXERS --- DETECT file type =======================
3845 current_module="demux_open";
3847 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3849 // HACK to get MOV Reference Files working
3851 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3853 unsigned char* playlist_entry;
3854 play_tree_t *list = NULL, *entry = NULL;
3856 current_module="handle_demux_playlist";
3857 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3859 char *temp, *bname;
3861 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3862 filename_recode(playlist_entry));
3864 bname=mp_basename(playlist_entry);
3865 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3866 continue;
3868 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3869 continue;
3871 entry = play_tree_new();
3873 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3875 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3876 if (temp)
3878 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3879 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3880 strcat(temp, playlist_entry);
3881 if (!strcmp(temp, mpctx->filename)) {
3882 free(temp);
3883 continue;
3885 play_tree_add_file(entry,temp);
3886 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3887 free(temp);
3890 else
3891 play_tree_add_file(entry,playlist_entry);
3893 if(!list)
3894 list = entry;
3895 else
3896 play_tree_append_entry(list,entry);
3898 free_demuxer(mpctx->demuxer);
3899 mpctx->demuxer = NULL;
3901 if (list)
3903 entry = play_tree_new();
3904 play_tree_set_child(entry,list);
3905 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3906 goto goto_next_file;
3910 if(!mpctx->demuxer) {
3911 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
3912 goto goto_next_file;
3915 if (mpctx->demuxer->matroska_data.ordered_chapters)
3916 build_ordered_chapter_timeline(mpctx);
3918 if (!mpctx->sources) {
3919 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3920 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3921 .demuxer = mpctx->demuxer};
3922 mpctx->num_sources = 1;
3925 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3927 #ifdef CONFIG_ASS
3928 if (opts->ass_enabled && ass_library) {
3929 for (int j = 0; j < mpctx->num_sources; j++) {
3930 struct demuxer *d = mpctx->sources[j].demuxer;
3931 for (int i = 0; i < d->num_attachments; i++) {
3932 struct demux_attachment *att = d->attachments + i;
3933 if (use_embedded_fonts && attachment_is_font(att))
3934 ass_add_font(ass_library, att->name, att->data, att->data_size);
3938 #endif
3940 current_module="demux_open2";
3942 mpctx->d_audio=mpctx->demuxer->audio;
3943 mpctx->d_video=mpctx->demuxer->video;
3944 mpctx->d_sub=mpctx->demuxer->sub;
3946 if (ts_prog) {
3947 int tmp = ts_prog;
3948 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3950 // select audio stream
3951 if (mpctx->num_sources)
3952 for (int i = 0; i < mpctx->num_sources; i++)
3953 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3954 opts->audio_lang);
3955 else
3956 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
3958 // DUMP STREAMS:
3959 if((stream_dump_type)&&(stream_dump_type<4)){
3960 FILE *f;
3961 demux_stream_t *ds=NULL;
3962 current_module="dump";
3963 // select stream to dump
3964 switch(stream_dump_type){
3965 case 1: ds=mpctx->d_audio;break;
3966 case 2: ds=mpctx->d_video;break;
3967 case 3: ds=mpctx->d_sub;break;
3969 if(!ds){
3970 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3971 exit_player(mpctx, EXIT_ERROR);
3973 // disable other streams:
3974 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3975 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3976 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3977 // let's dump it!
3978 f=fopen(opts->stream_dump_name,"wb");
3979 if(!f){
3980 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3981 exit_player(mpctx, EXIT_ERROR);
3983 while(!ds->eof){
3984 unsigned char* start;
3985 int in_size=ds_get_packet(ds,&start);
3986 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3987 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3988 if(in_size>0) fwrite(start,in_size,1,f);
3989 if (opts->chapterrange[1] > 0) {
3990 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
3991 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3992 break;
3995 fclose(f);
3996 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3997 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4000 mpctx->sh_audio=mpctx->d_audio->sh;
4001 mpctx->sh_video=mpctx->d_video->sh;
4003 if(mpctx->sh_video){
4005 current_module="video_read_properties";
4006 if(!video_read_properties(mpctx->sh_video)) {
4007 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4008 mpctx->sh_video=mpctx->d_video->sh=NULL;
4009 } else {
4010 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4011 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4012 mpctx->sh_video->fps,mpctx->sh_video->frametime
4015 /* need to set fps here for output encoders to pick it up in their init */
4016 if(force_fps){
4017 mpctx->sh_video->fps=force_fps;
4018 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4020 vo_fps = mpctx->sh_video->fps;
4022 if(!mpctx->sh_video->fps && !force_fps){
4023 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4024 mpctx->opts.correct_pts = 1;
4030 if(!mpctx->sh_video && !mpctx->sh_audio){
4031 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4032 #ifdef CONFIG_DVBIN
4033 if(mpctx->stream->type == STREAMTYPE_DVB)
4035 int dir;
4036 int v = mpctx->last_dvb_step;
4037 if(v > 0)
4038 dir = DVB_CHANNEL_HIGHER;
4039 else
4040 dir = DVB_CHANNEL_LOWER;
4042 if(dvb_step_channel(mpctx->stream, dir)) {
4043 mpctx->stop_play = PT_NEXT_ENTRY;
4044 mpctx->dvbin_reopen = 1;
4047 #endif
4048 goto goto_next_file; // exit_player(_("Fatal error"));
4051 /* display clip info */
4052 demux_info_print(mpctx->demuxer);
4054 //================== Read SUBTITLES (DVD & TEXT) ==========================
4055 if(vo_spudec==NULL &&
4056 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4057 init_vo_spudec(mpctx);
4060 // after reading video params we should load subtitles because
4061 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4062 // check .sub
4063 current_module="read_subtitles_file";
4064 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4065 if(sub_name){
4066 for (i = 0; sub_name[i] != NULL; ++i)
4067 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4069 if(sub_auto) { // auto load sub file ...
4070 char *psub = get_path( "sub/" );
4071 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4072 int i = 0;
4073 free(psub); // release the buffer created by get_path() above
4074 while (tmp[i]) {
4075 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4076 free(tmp[i++]);
4078 free(tmp);
4080 if (mpctx->set_of_sub_size > 0)
4081 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4083 if (select_subtitle(mpctx)) {
4084 if(subdata)
4085 switch (stream_dump_type) {
4086 case 3: list_sub_file(subdata); break;
4087 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
4088 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
4089 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
4090 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
4091 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
4095 print_file_properties(mpctx, mpctx->filename);
4097 if(!mpctx->sh_video) goto main; // audio-only
4099 if(!reinit_video_chain(mpctx)) {
4100 if(!mpctx->sh_video){
4101 if(!mpctx->sh_audio) goto goto_next_file;
4102 goto main; // exit_player(_("Fatal error"));
4106 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4107 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4109 #ifdef CONFIG_FREETYPE
4110 force_load_font = 1;
4111 #endif
4113 //================== MAIN: ==========================
4114 main:
4115 current_module="main";
4117 if(playing_msg) {
4118 char* msg = property_expand_string(mpctx, playing_msg);
4119 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4120 free(msg);
4124 // Disable the term OSD in verbose mode
4125 if(verbose) term_osd = 0;
4128 int frame_time_remaining=0; // flag
4129 int blit_frame=0;
4131 // Make sure old OSD does not stay around,
4132 // e.g. with -fixed-vo and same-resolution files
4133 clear_osd_msgs();
4134 update_osd_msg(mpctx);
4136 //================ SETUP AUDIO ==========================
4138 if(mpctx->sh_audio){
4139 reinit_audio_chain(mpctx);
4140 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4141 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4144 current_module="av_init";
4146 if(mpctx->sh_video){
4147 mpctx->sh_video->timer=0;
4148 if (! ignore_start)
4149 audio_delay += mpctx->sh_video->stream_delay;
4151 if(mpctx->sh_audio){
4152 if (start_volume >= 0)
4153 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4154 if (! ignore_start)
4155 audio_delay -= mpctx->sh_audio->stream_delay;
4156 mpctx->delay=-audio_delay;
4159 if(!mpctx->sh_audio){
4160 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4161 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4162 ds_free_packs(mpctx->d_audio); // free buffered chunks
4163 //mpctx->d_audio->id=-2; // do not read audio chunks
4164 //uninit_player(mpctx, INITIALIZED_AO); // close device
4166 if(!mpctx->sh_video){
4167 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4168 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4169 ds_free_packs(mpctx->d_video);
4170 mpctx->d_video->id=-2;
4171 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4174 if (!mpctx->sh_video && !mpctx->sh_audio)
4175 goto goto_next_file;
4177 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4178 if(force_fps && mpctx->sh_video){
4179 vo_fps = mpctx->sh_video->fps=force_fps;
4180 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4181 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4184 mp_input_set_section(mpctx->input, NULL);
4185 //TODO: add desired (stream-based) sections here
4186 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4187 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4189 //==================== START PLAYING =======================
4191 if(opts->loop_times>1) opts->loop_times--; else
4192 if(opts->loop_times==1) opts->loop_times = -1;
4194 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4196 total_time_usage_start=GetTimer();
4197 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4198 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4199 play_n_frames=play_n_frames_mf;
4201 if(play_n_frames==0){
4202 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4205 // If there's a timeline force an absolute seek to initialize state
4206 if (seek_to_sec || mpctx->timeline) {
4207 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4208 end_at.pos += seek_to_sec;
4210 if (opts->chapterrange[0] > 0) {
4211 double pts;
4212 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4213 && pts > -1.0)
4214 seek(mpctx, pts, SEEK_ABSOLUTE);
4217 if (end_at.type == END_AT_SIZE) {
4218 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4219 end_at.type = END_AT_NONE;
4222 #ifdef CONFIG_DVDNAV
4223 mp_dvdnav_context_free(mpctx);
4224 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4225 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4226 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4228 #endif
4230 get_relative_time(mpctx); // reset current delta
4231 mpctx->time_frame = 0;
4232 mpctx->drop_message_shown = 0;
4233 mpctx->restart_playback = true;
4234 mpctx->total_avsync_change = 0;
4235 mpctx->last_chapter_seek = -1;
4236 // Make sure VO knows current pause state
4237 if (mpctx->sh_video)
4238 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4239 NULL);
4241 while(!mpctx->stop_play){
4242 float aq_sleep_time=0;
4244 if (opts->chapterrange[1] > 0) {
4245 int cur_chapter = get_current_chapter(mpctx);
4246 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4247 goto goto_next_file;
4250 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4251 mpctx->sh_audio = mpctx->d_audio->sh;
4252 mpctx->sh_audio->ds = mpctx->d_audio;
4253 reinit_audio_chain(mpctx);
4256 /*========================== PLAY AUDIO ============================*/
4258 if (mpctx->sh_audio && !mpctx->paused
4259 && (!mpctx->restart_playback || !mpctx->sh_video))
4260 if (!fill_audio_out_buffers(mpctx))
4261 // at eof, all audio at least written to ao
4262 if (!mpctx->sh_video)
4263 mpctx->stop_play = AT_END_OF_FILE;
4266 if(!mpctx->sh_video) {
4267 // handle audio-only case:
4268 double a_pos=0;
4269 // sh_audio can be NULL due to video stream switching
4270 // TODO: handle this better
4271 if (mpctx->sh_audio)
4272 a_pos = playing_audio_pts(mpctx);
4274 print_status(mpctx, a_pos, false);
4276 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4277 mpctx->stop_play = PT_NEXT_ENTRY;
4278 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4279 mpctx->d_sub, 0);
4280 update_osd_msg(mpctx);
4282 } else {
4284 /*========================== PLAY VIDEO ============================*/
4286 vo_pts=mpctx->sh_video->timer*90000.0;
4287 vo_fps=mpctx->sh_video->fps;
4289 blit_frame = mpctx->video_out->frame_loaded;
4290 if (!blit_frame) {
4291 double frame_time = update_video(mpctx);
4292 blit_frame = mpctx->video_out->frame_loaded;
4293 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4294 if (mpctx->sh_video->vf_initialized < 0) {
4295 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4296 mpctx->stop_play = PT_NEXT_ENTRY;
4297 goto goto_next_file;
4299 if (blit_frame) {
4300 struct sh_video *sh_video = mpctx->sh_video;
4301 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4302 mpctx->video_offset, mpctx->d_sub, 0);
4303 update_teletext(sh_video, mpctx->demuxer, 0);
4304 update_osd_msg(mpctx);
4305 struct vf_instance *vf = mpctx->sh_video->vfilter;
4306 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4307 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4308 vo_osd_changed(0);
4310 if (frame_time < 0)
4311 mpctx->stop_play = AT_END_OF_FILE;
4312 else if (!mpctx->restart_playback) {
4313 mpctx->time_frame += frame_time / opts->playback_speed;
4314 adjust_sync(mpctx, frame_time);
4317 if (mpctx->timeline) {
4318 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4319 if (mpctx->sh_video->pts >= next->start
4320 || mpctx->stop_play == AT_END_OF_FILE
4321 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4322 seek(mpctx, next->start, SEEK_ABSOLUTE);
4323 continue;
4327 // ==========================================================================
4329 // current_module="draw_osd";
4330 // if(vo_config_count) mpctx->video_out->draw_osd();
4332 current_module="vo_check_events";
4333 vo_check_events(mpctx->video_out);
4335 #ifdef CONFIG_X11
4336 if (stop_xscreensaver) {
4337 current_module = "stop_xscreensaver";
4338 xscreensaver_heartbeat(mpctx->x11_state);
4340 #endif
4341 if (heartbeat_cmd) {
4342 static unsigned last_heartbeat;
4343 unsigned now = GetTimerMS();
4344 if (now - last_heartbeat > 30000) {
4345 last_heartbeat = now;
4346 system(heartbeat_cmd);
4350 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4352 //====================== FLIP PAGE (VIDEO BLT): =========================
4354 current_module="flip_page";
4355 if (!frame_time_remaining && blit_frame) {
4356 unsigned int t2=GetTimer();
4357 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4358 int duration = -1;
4359 double pts2 = mpctx->video_out->next_pts2;
4360 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
4361 && !mpctx->restart_playback) {
4362 // expected A/V sync correction is ignored
4363 double diff = (pts2 - mpctx->sh_video->pts);
4364 diff /= opts->playback_speed;
4365 if (mpctx->time_frame < 0)
4366 diff += mpctx->time_frame;
4367 if (diff < 0)
4368 diff = 0;
4369 if (diff > 10)
4370 diff = 10;
4371 duration = diff * 1e6;
4373 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4375 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4376 vout_time_usage += mpctx->last_vo_flip_duration;
4377 if (mpctx->video_out->driver->flip_page_timed) {
4378 // No need to adjust sync based on flip speed
4379 mpctx->last_vo_flip_duration = 0;
4380 // For print_status - VO call finishing early is OK for sync
4381 mpctx->time_frame -= get_relative_time(mpctx);
4383 if (mpctx->restart_playback) {
4384 mpctx->syncing_audio = true;
4385 if (mpctx->sh_audio && !mpctx->paused)
4386 fill_audio_out_buffers(mpctx);
4387 mpctx->restart_playback = false;
4388 mpctx->time_frame = 0;
4389 get_relative_time(mpctx);
4391 print_status(mpctx, MP_NOPTS_VALUE, true);
4393 else
4394 print_status(mpctx, MP_NOPTS_VALUE, false);
4396 //============================ Auto QUALITY ============================
4398 /*Output quality adjustments:*/
4399 if(auto_quality>0){
4400 current_module="autoq";
4401 // float total=0.000001f * (GetTimer()-aq_total_time);
4402 // if(output_quality<auto_quality && aq_sleep_time>0.05f*total)
4403 if(output_quality<auto_quality && aq_sleep_time>0)
4404 ++output_quality;
4405 else
4406 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4407 if(output_quality>1 && aq_sleep_time<0)
4408 --output_quality;
4409 else
4410 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4411 output_quality=0;
4412 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4413 set_video_quality(mpctx->sh_video,output_quality);
4416 if (!frame_time_remaining && blit_frame) {
4417 if (play_n_frames >= 0) {
4418 --play_n_frames;
4419 if (play_n_frames <= 0)
4420 mpctx->stop_play = PT_NEXT_ENTRY;
4422 if (mpctx->step_frames > 0) {
4423 mpctx->step_frames--;
4424 if (mpctx->step_frames == 0)
4425 pause_player(mpctx);
4430 // FIXME: add size based support for -endpos
4431 if (end_at.type == END_AT_TIME &&
4432 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4433 mpctx->stop_play = PT_NEXT_ENTRY;
4435 } // end if(mpctx->sh_video)
4437 #ifdef CONFIG_DVDNAV
4438 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4439 nav_highlight_t hl;
4440 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4441 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4442 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4443 vo_osd_changed (OSDTYPE_DVDNAV);
4444 } else {
4445 osd_set_nav_box(0, 0, 0, 0);
4446 vo_osd_changed(OSDTYPE_DVDNAV);
4447 vo_osd_changed(OSDTYPE_SPU);
4450 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4451 double ar = -1.0;
4452 if (mpctx->sh_video &&
4453 stream_control (mpctx->demuxer->stream,
4454 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4455 != STREAM_UNSUPPORTED)
4456 mpctx->sh_video->stream_aspect = ar;
4459 #endif
4461 //================= Keyboard events, SEEKing ====================
4463 current_module="key_events";
4466 while (1) {
4467 mp_cmd_t* cmd;
4468 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4469 run_command(mpctx, cmd);
4470 mp_cmd_free(cmd);
4471 if (mpctx->stop_play)
4472 break;
4473 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4474 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4475 /* Allow seek commands to be combined, but execute the real seek
4476 * before processing other commands */
4477 if (!cmd || cmd->id != MP_CMD_SEEK)
4478 break;
4481 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4482 || mpctx->abs_seek_pos)
4483 break;
4484 if (mpctx->sh_video) {
4485 update_osd_msg(mpctx);
4486 int hack = vo_osd_changed(0);
4487 vo_osd_changed(hack);
4488 if (hack) {
4489 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4490 add_step_frame(mpctx);
4491 break;
4493 else
4494 vo_osd_changed(0);
4497 pause_loop(mpctx);
4501 // handle -sstep
4502 if (step_sec > 0 && !mpctx->paused) {
4503 mpctx->osd_function=OSD_FFW;
4504 mpctx->rel_seek_secs+=step_sec;
4507 edl_update(mpctx);
4509 /* Looping. */
4510 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4511 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4513 if(opts->loop_times>1) opts->loop_times--; else
4514 if(opts->loop_times==1) opts->loop_times=-1;
4515 play_n_frames=play_n_frames_mf;
4516 mpctx->stop_play=0;
4517 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4520 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4521 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4523 mpctx->rel_seek_secs=0;
4524 mpctx->abs_seek_pos=0;
4527 } // while(!mpctx->stop_play)
4529 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4531 #ifdef CONFIG_DVBIN
4532 if(mpctx->dvbin_reopen)
4534 mpctx->stop_play = 0;
4535 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4536 cache_uninit(mpctx->stream);
4537 mpctx->dvbin_reopen = 0;
4538 goto goto_enable_cache;
4540 #endif
4543 goto_next_file: // don't jump here after ao/vo/getch initialization!
4545 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4547 if(benchmark){
4548 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4549 double total_time_usage;
4550 total_time_usage_start=GetTimer()-total_time_usage_start;
4551 total_time_usage = (float)total_time_usage_start*0.000001;
4552 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4553 video_time_usage,vout_time_usage,audio_time_usage,
4554 total_time_usage-tot,total_time_usage);
4555 if(total_time_usage>0.0)
4556 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4557 100.0*video_time_usage/total_time_usage,
4558 100.0*vout_time_usage/total_time_usage,
4559 100.0*audio_time_usage/total_time_usage,
4560 100.0*(total_time_usage-tot)/total_time_usage,
4561 100.0);
4562 if(total_frame_cnt && frame_dropping)
4563 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4564 total_frame_cnt-drop_frame_cnt,
4565 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4566 drop_frame_cnt,
4567 100*drop_frame_cnt/total_frame_cnt,
4568 total_frame_cnt,
4569 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4572 // time to uninit all, except global stuff:
4573 int uninitialize_parts = INITIALIZED_ALL;
4574 if (opts->fixed_vo)
4575 uninitialize_parts -= INITIALIZED_VO;
4576 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4577 uninitialize_parts -= INITIALIZED_AO;
4578 uninit_player(mpctx, uninitialize_parts);
4580 if(mpctx->set_of_sub_size > 0) {
4581 current_module="sub_free";
4582 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4583 sub_free(mpctx->set_of_subtitles[i]);
4584 #ifdef CONFIG_ASS
4585 if(mpctx->set_of_ass_tracks[i])
4586 ass_free_track( mpctx->set_of_ass_tracks[i] );
4587 #endif
4589 mpctx->set_of_sub_size = 0;
4591 vo_sub_last = vo_sub=NULL;
4592 subdata=NULL;
4593 #ifdef CONFIG_ASS
4594 ass_track = NULL;
4595 if(ass_library)
4596 ass_clear_fonts(ass_library);
4597 #endif
4599 if (!mpctx->stop_play) // In case some goto jumped here...
4600 mpctx->stop_play = PT_NEXT_ENTRY;
4602 int playtree_direction = 1;
4604 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4605 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4606 play_tree_iter_free(mpctx->playtree_iter);
4607 mpctx->playtree_iter = NULL;
4609 mpctx->play_tree_step = 1;
4610 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4611 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4612 if(mpctx->playtree_iter) {
4613 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4614 play_tree_iter_free(mpctx->playtree_iter);
4615 mpctx->playtree_iter = NULL;
4618 } else if (mpctx->stop_play == PT_STOP) {
4619 play_tree_iter_free(mpctx->playtree_iter);
4620 mpctx->playtree_iter = NULL;
4621 } else { // NEXT PREV SRC
4622 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4625 while(mpctx->playtree_iter != NULL) {
4626 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4627 if(mpctx->filename == NULL) {
4628 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4629 play_tree_iter_free(mpctx->playtree_iter);
4630 mpctx->playtree_iter = NULL;
4632 } else
4633 break;
4636 if(mpctx->playtree_iter != NULL || player_idle_mode){
4637 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4638 mpctx->stop_play = 0;
4639 goto play_next_file;
4643 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4645 return 1;
4647 #endif /* DISABLE_MAIN */